import "pkg:/components/Services/Dash/LiveTimeline.types.bs" import "pkg:/components/Web/WebServer/Http/HttpUtils.bs" import "pkg:/source/services/XmlObject.bs" import "pkg:/source/utils/CodecCapabilities.bs" import "pkg:/source/utils/Logging.bs" import "pkg:/source/utils/MathUtils.bs" import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/UrlUtils.bs" ' Placeholders in a live manifest, filled on every refresh. const LIVE_NOW_TOKEN = "{{now}}" const LIVE_START_NUMBER_TOKEN = "{{startNumber}}" const LIVE_SEGMENTS_TOKEN = "{{segments}}" ' How often the player re-fetches a live manifest. Between fetches the listed end ' trails the live head by up to this, and the player plays on from its buffer. const LIVE_MANIFEST_REFRESH_MS = 10000 class DashManifest public invidiousInstance as dynamic public disableAutoDubbed as boolean private canDecodeAv1Cache as dynamic function new(invidiousInstance as string, disableAutoDubbed = false as boolean) m.invidiousInstance = invidiousInstance m.disableAutoDubbed = disableAutoDubbed m.utils = new Http.Utils() ' https://github.com/LuanRT/YouTube.js/blob/6082b4a52ee07a622735e6e9128a0531a5ae3bfb/src/utils/StreamingInfo.ts#L332-L349 m.colorInfo = { primaries: { "COLOR_PRIMARIES_BT709": "1" "COLOR_PRIMARIES_BT2020": "9" } transferCharacteristics: { "COLOR_TRANSFER_CHARACTERISTICS_BT709": "1" "COLOR_TRANSFER_CHARACTERISTICS_BT2020_10": "14" "COLOR_TRANSFER_CHARACTERISTICS_SMPTEST2084": "16" "COLOR_TRANSFER_CHARACTERISTICS_ARIB_STD_B67": "18" } matrixCoefficients: { "COLOR_MATRIX_COEFFICIENTS_BT709": "1" "COLOR_MATRIX_COEFFICIENTS_BT2020_NCL": "14" } } end function function FromVideoMetadata(metadata as object, qualityFilter as object, local as boolean) as string adaptiveFormats = [] adaptiveFormats.Append(metadata.adaptiveFormats) if local and m.invidiousInstance <> Invidious.PLAYLET_BUILT_IN_INSTANCE adaptiveFormats = m.ProxyFormatsThroughInvidious(adaptiveFormats) end if duration = m.GetDuration(metadata) isLive = ValidBool(metadata.liveNow) groupings = m.CreateFormatGroupings(adaptiveFormats, metadata.isPostLiveDvr, isLive) audioGroups = groupings.audio videoGroups = groupings.video filteredVideoGroups = m.FilterVideoGroups(videoGroups, qualityFilter) ' The player skips video sets it can't play (webm container, undecodable codec). ' A filter that leaves only such sets - e.g. 2160p-only when the 4K streams are ' VP9/webm - would play audio with no video, so fall back to all streams. if not m.HasPlayableVideoGroup(filteredVideoGroups) and videoGroups.Count() > 0 LogWarnNoTelemetry("No playable video streams using quality filter:", qualityFilter, "Falling back to all video streams") filteredVideoGroups = videoGroups end if if filteredVideoGroups.Count() = 0 lastPlayerResponse = ValidString(ReadAsciiFile("cachefs:/last_player_response.json")) LogTelemetryEvent({ level: "error" message: "No video streams found in metadata for Dash." fingerprint: ["No video streams found in metadata for Dash."] attachments: [{ filename: "metadata.json" content_type: "application/json" data: FormatJson(metadata) }, { filename: "last_player_response.json" content_type: "application/json" data: lastPlayerResponse }] }) end if storyboards = metadata.storyboards xml = new XmlObject() xml.Comment(`Generated by Playlet - Video ID: ${metadata.videoId}`) xml.Comment(`Parser: ${ValidString(metadata.parser)}`) mpdAttributes = { "xmlns": "urn:mpeg:dash:schema:mpd:2011" "minBufferTime": "PT1.5S" "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance" "xsi:schemaLocation": "urn:mpeg:dash:schema:mpd:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd" } if isLive mpdAttributes["profiles"] = "urn:mpeg:dash:profile:isoff-live:2011" mpdAttributes["type"] = "dynamic" mpdAttributes["publishTime"] = LIVE_NOW_TOKEN segmentDurationMs = ValidInt(metadata.liveSegmentDurationMs) windowSegments = ValidInt(metadata.liveWindowSegments) if windowSegments > 0 and segmentDurationMs > 0 mpdAttributes["availabilityStartTime"] = metadata.liveAvailabilityStartUtc mpdAttributes["minimumUpdatePeriod"] = m.FormatDuration(MathUtils.Max(LIVE_MANIFEST_REFRESH_MS, segmentDurationMs)) ' The whole window, also while the listed timeline grows into it: Roku renumbers ' segments listed beyond timeShiftBufferDepth, and takes no seek in a live stream ' whose timeShiftBufferDepth started short (measured). mpdAttributes["timeShiftBufferDepth"] = m.FormatDuration(windowSegments * segmentDurationMs) else xml.Comment(`[ERROR] Live stream metadata has no timeline (liveWindowSegments / liveSegmentDurationMs) for video: ${metadata.videoId}`) end if else mpdAttributes["profiles"] = "urn:mpeg:dash:profile:full:2011" mpdAttributes["type"] = "static" mpdAttributes["mediaPresentationDuration"] = `PT${duration}S` end if ' Live needs an explicit Period start to anchor the timeline against availabilityStartTime. periodAttributes = {} if isLive periodAttributes["start"] = "PT0S" end if if xml.Node("MPD", mpdAttributes) if xml.Node("Period", periodAttributes) id = 0 id = m.GenerateAudioAdaptationSets(xml, audioGroups, id, metadata) id = m.GenerateVideoAdaptationSets(xml, filteredVideoGroups, id, metadata) m.GenerateImageAdaptationSets(xml, storyboards, id) xml.End() end if if isLive xml.EmptyNode("UTCTiming", { "schemeIdUri": "urn:mpeg:dash:utc:direct:2014" "value": LIVE_NOW_TOKEN }) end if xml.End() end if return xml.ToXmlString() end function ' The formats with their urls routed through the Invidious instance, as copies: the ' metadata outlives this manifest (cached across manifest requests), and rewriting a ' url twice would route it through the instance as its own host. function ProxyFormatsThroughInvidious(formats as object) as object parsedInvidiousUrl = UrlUtils.ParseUrl(m.invidiousInstance) proxied = [] for each format in formats if not StringUtils.IsNullOrEmpty(format.url) parsedUrl = UrlUtils.ParseUrl(format.url) parsedInvidiousUrl.path = UrlUtils.AppendQueryParams(parsedUrl.path, { host: parsedUrl.host }) proxiedFormat = {} proxiedFormat.Append(format) proxiedFormat.url = UrlUtils.BuildUrlFromParts(parsedInvidiousUrl) format = proxiedFormat end if proxied.Push(format) end for return proxied end function function GetDuration(metadata as object) as dynamic if metadata["isPostLiveDvr"] = true and IsInt(metadata["postLiveDvrDurationMs"]) return metadata["postLiveDvrDurationMs"] / 1000.0 end if approxDurationMs = ValidString(ObjectUtils.Dig(metadata, ["adaptiveFormats", 0, "approxDurationMs"])).ToInt() if approxDurationMs > 0 return approxDurationMs / 1000.0 end if return ValidInt(metadata["lengthSeconds"]) end function ' `durationRuns` ascending. function FillLiveManifest(template as string, headSeqnum as integer, durationRuns as LiveDurationRun[], windowMs as integer) as string lastSeqnum = m.LiveLastListedSeqnum(durationRuns, headSeqnum) ' S@t keeps each listed segment at its place on the timeline. startNumber = m.LiveFirstListedSeqnum(durationRuns, lastSeqnum, windowMs) segments = "" for i = 0 to durationRuns.Count() - 1 durationRun = durationRuns[i] runLast = lastSeqnum if i + 1 < durationRuns.Count() runLast = MathUtils.Min(runLast, durationRuns[i + 1].fromSeqnum - 1) end if runFirst = MathUtils.Max(durationRun.fromSeqnum, startNumber) if runFirst <= runLast segments += `` end if end for ' Roku needs an authoritative "now" to track the live edge from wall-clock: ' UTCTiming + publishTime carry the current UTC. nowUtc = CreateObject("roDateTime").ToISOString() return template.Replace(LIVE_NOW_TOKEN, nowUtc).Replace(LIVE_START_NUMBER_TOKEN, startNumber.ToStr()).Replace(LIVE_SEGMENTS_TOKEN, segments) end function ' The newest segment may not have reached every edge server yet, and Roku ' retries a segment answered 204 only 20-100s later (measured), stalling. function LiveLastListedSeqnum(durationRuns as LiveDurationRun[], headSeqnum as integer) as integer return MathUtils.Max(headSeqnum - 1, durationRuns[0].fromSeqnum) end function ' The list grows from the first segment at load until it spans the window, then ' slides with the head. function LiveFirstListedSeqnum(durationRuns as LiveDurationRun[], lastSeqnum as integer, windowMs as integer) as integer return m.LiveSegmentAtOrAfter(durationRuns, m.LiveSegmentStartMs(durationRuns, lastSeqnum + 1) - windowMs) end function function LiveSegmentStartMs(durationRuns as LiveDurationRun[], seqnum as integer) as integer durationRun = durationRuns[0] for each candidate in durationRuns if candidate.fromSeqnum <= seqnum durationRun = candidate end if end for return durationRun.startMs + (seqnum - durationRun.fromSeqnum) * durationRun.durationMs end function ' The first segment starting at or after `timeMs` on the live timeline, or the ' first run's first segment if `timeMs` is before it. function LiveSegmentAtOrAfter(durationRuns as LiveDurationRun[], timeMs as integer) as integer seqnum = durationRuns[0].fromSeqnum for i = 0 to durationRuns.Count() - 1 durationRun = durationRuns[i] if timeMs <= durationRun.startMs return durationRun.fromSeqnum end if seqnum = durationRun.fromSeqnum + (timeMs - durationRun.startMs + durationRun.durationMs - 1) \ durationRun.durationMs if i + 1 < durationRuns.Count() and seqnum < durationRuns[i + 1].fromSeqnum exit for end if end for return seqnum end function function FormatDuration(ms as integer) as string return `PT${ms \ 1000}.${Right("00" + (ms mod 1000).ToStr(), 3)}S` end function function CreateFormatGroupings(formats as object, isPostLiveDvr as boolean, isLive as boolean) as object groupInfo = {} for each format in formats isOtf = format.isTypeOTF = true hasInit = not StringUtils.IsNullOrEmpty(format.init) hasIndex = not StringUtils.IsNullOrEmpty(format.index) ' Live formats (like Post-Live DVR / OTF) have no init/index ranges; ' they are segmented via `&sq=N`. isValid = (hasInit and hasIndex) or isOtf or isPostLiveDvr or isLive if not isValid continue for end if if not IsString(format.type) continue for end if if (format.width = invalid or format.height = invalid) and not StringUtils.IsNullOrEmpty(format.size) if format.size.instr("x") > 0 parts = format.size.Tokenize("x") if parts.Count() = 2 format.width = ValidInt(parts[0].toInt()) format.height = ValidInt(parts[1].toInt()) end if end if end if codecs = "" mimeType = format.type.Tokenize(";")[0] if format.type.inStr("codecs=") <> -1 codecs = format.type.split("codecs=")[1] if codecs.startsWith(`"`) codecs = codecs.mid(1) end if if codecs.endsWith(`"`) codecs = codecs.left(codecs.len() - 1) end if end if justCodec = codecs.split(".")[0] colorInfo = "" if IsAssociativeArray(format.colorInfo) colorInfo = `${format.colorInfo.primaries}-${format.colorInfo.transferCharacteristics}-${format.colorInfo.matrixCoefficients}` end if if format.type.startsWith("audio") xtagsInfo = m.GetXtagsInfo(format) format.xtagsInfo = xtagsInfo format.isDrc = xtagsInfo.isDrc format.isVoiceBoost = xtagsInfo.isVoiceBoost format.isDubbed = xtagsInfo.isDubbed format.isAutoDubbed = xtagsInfo.isAutoDubbed format.isDescriptive = xtagsInfo.isDescriptive format.isSecondary = xtagsInfo.isSecondary format.isOriginal = xtagsInfo.isOriginal ' Some sources (e.g. Invidious) don't provide an `audioTrack` object the ' way Innertube does; the language only lives in the URL's xtags. Without ' an audioTrack, every language collapses into a single AdaptationSet and ' the device labels each track "Other". Synthesize a minimal audioTrack ' from xtags so tracks group per language and carry a `lang` attribute the ' device maps to a real name. if not IsAssociativeArray(format.audioTrack) and not StringUtils.IsNullOrEmpty(xtagsInfo.lang) format.audioTrack = m.SynthesizeAudioTrack(xtagsInfo) end if end if audioTrackId = "" if IsAssociativeArray(format.audioTrack) and IsString(format.audioTrack.id) audioTrackId = format.audioTrack.id end if groupId = `${mimeType}-${justCodec}-${colorInfo}-${audioTrackId}${m.GetAudioVariantSuffix(format)}` if groupInfo[groupId] = invalid groupInfo[groupId] = [] end if groupInfo[groupId].Push(format) end for audioGroups = [] videoGroups = [] for each key in groupInfo group = groupInfo[key] if group[0].type.startsWith("audio") audioGroups.Push(group) else if group[0].type.startsWith("video") videoGroups.Push(group) end if end for return { audio: audioGroups, video: videoGroups } end function function FilterVideoGroups(videoGroups as object, qualityFilter as object) as object if qualityFilter.Count() = 0 return videoGroups end if filteredGroups = [] for each group in videoGroups filteredStreams = [] for each stream in group if m.IsVideoFormatIncluded(stream, qualityFilter) filteredStreams.Push(stream) end if end for if filteredStreams.Count() > 0 filteredGroups.Push(filteredStreams) end if end for return filteredGroups end function function HasPlayableVideoGroup(videoGroups as object) as boolean for each group in videoGroups mimeType = ValidString(group[0].type) ' DASH chunks must be fragmented MP4: the player never picks webm sets. if not mimeType.startsWith("video/mp4") continue for end if if mimeType.inStr("avc1") <> -1 return true end if if mimeType.inStr("av01") <> -1 and m.CanDecodeAv1() return true end if end for return false end function function CanDecodeAv1() as boolean if m.canDecodeAv1Cache = invalid m.canDecodeAv1Cache = CodecCapabilities.CanDecodeAv1() end if return m.canDecodeAv1Cache end function function IsVideoFormatIncluded(stream as object, qualityFilter as object) as boolean if qualityFilter.Count() = 0 return true end if qualityLabel = stream.qualityLabel if not StringUtils.IsNullOrEmpty(qualityLabel) pIndex = qualityLabel.InStr("p") if pIndex <> -1 qualityLabel = qualityLabel.Mid(0, pIndex) end if if qualityFilter[qualityLabel] = true return true end if end if if stream.height <> invalid if qualityFilter[ToString(stream.height)] = true return true end if end if resolution = stream.resolution if not StringUtils.IsNullOrEmpty(resolution) pIndex = resolution.InStr("p") if pIndex <> -1 resolution = resolution.Mid(0, pIndex) end if if qualityFilter[resolution] = true return true end if end if size = stream.size if not StringUtils.IsNullOrEmpty(size) sizeParts = size.Split("x") if sizeParts.Count() = 2 if qualityFilter[sizeParts[1]] = true return true end if end if end if return false end function function GenerateAudioAdaptationSets(xml as object, audioGroups as object, id as integer, metadata as object) as integer for each group in audioGroups firstFormat = group[0] if m.disableAutoDubbed and ValidBool(firstFormat.isAutoDubbed) continue for end if hoisted = {} adaptationSetAttributes = { "id": `${id}` "mimeType": firstFormat.type.Tokenize(";")[0] "startWithSAP": "1" "subsegmentAlignment": "true" "contentType": "audio" } if IsAssociativeArray(firstFormat.audioTrack) if IsString(firstFormat.audioTrack.languageCode) adaptationSetAttributes["lang"] = firstFormat.audioTrack.languageCode else if IsString(firstFormat.audioTrack.id) ' ID is in the format "CODE.DIGIT" e.g. "en.4" adaptationSetAttributes["lang"] = firstFormat.audioTrack.id.split(".")[0] end if end if ' Hoist common attributes codecs = m.HoistCodecs(group, hoisted) if IsString(codecs) adaptationSetAttributes["codecs"] = codecs end if audioSampleRate = m.HoistNumberAttribute(group, "audioSampleRate", hoisted) if IsInt(audioSampleRate) adaptationSetAttributes["audioSamplingRate"] = audioSampleRate end if if xml.Node("AdaptationSet", adaptationSetAttributes) if IsArray(firstFormat.drmFamilies) for each drmFamily in firstFormat.drmFamilies systemId = m.GetDrmSystemId(drmFamily) if IsString(systemId) xml.EmptyNode("ContentProtection", { "schemeIdUri": `urn:uuid:${systemId}` }) end if end for end if if IsAssociativeArray(firstFormat.audioTrack) or firstFormat.isDrc = true or firstFormat.isVoiceBoost = true ' Roles roles = m.GetTrackRoles(firstFormat) for each role in roles xml.EmptyNode("Role", { "schemeIdUri": "urn:mpeg:dash:role:2011", "value": role }) end for ' Label if IsAssociativeArray(firstFormat.audioTrack) and IsString(firstFormat.audioTrack.displayName) displayName = firstFormat.audioTrack.displayName if firstFormat.isDrc = true displayName = `${displayName} (Stable Volume)` end if xml.Node("Label", { "id": id }) xml.Text(displayName) xml.End() end if end if ' AudioChannelConfiguration channels = m.HoistAudioChannels(group, hoisted) if IsInt(channels) xml.EmptyNode("AudioChannelConfiguration", { "schemeIdUri": "urn:mpeg:dash:23003:3:audio_channel_configuration:2011" "value": channels }) end if for each stream in group representationId = stream.itag if IsAssociativeArray(stream.audioTrack) and IsString(stream.audioTrack.id) representationId = `${representationId}-${stream.audioTrack.id}` end if representationId = `${representationId}${m.GetAudioVariantSuffix(stream)}` representationAttributes = { "id": representationId "bandwidth": stream.bitrate } if hoisted["codecs"] = invalid and (stream.type.inStr("codecs=") <> -1) representationAttributes["codecs"] = stream.type.split("codecs=")[1].replace(`"`, "").replace(`"`, "") end if if hoisted["audioSampleRate"] = invalid representationAttributes["audioSamplingRate"] = stream.audioSampleRate end if if xml.Node("Representation", representationAttributes) if hoisted["AudioChannelConfiguration"] = invalid and IsInt(stream.audioChannels) xml.EmptyNode("AudioChannelConfiguration", { "schemeIdUri": "urn:mpeg:dash:23003:3:audio_channel_configuration:2011" "value": stream.audioChannels }) end if m.GenerateSegmentInformation(xml, stream, metadata) xml.End() end if end for xml.End() end if id += 1 end for return id end function function GenerateVideoAdaptationSets(xml as object, videoGroups as object, id as integer, metadata as object) as integer for each group in videoGroups firstFormat = group[0] hoisted = {} adaptationSetAttributes = { "id": `${id}` "mimeType": firstFormat.type.Tokenize(";")[0] "startWithSAP": "1" "subsegmentAlignment": "true" "maxPlayoutRate": "1" "contentType": "video" } ' Hoist common attributes codecs = m.HoistCodecs(group, hoisted) if IsString(codecs) adaptationSetAttributes["codecs"] = codecs end if fps = m.HoistNumberAttribute(group, "fps", hoisted) if fps <> invalid adaptationSetAttributes["frameRate"] = fps end if if xml.Node("AdaptationSet", adaptationSetAttributes) if IsArray(firstFormat.drmFamilies) for each drmFamily in firstFormat.drmFamilies systemId = m.GetDrmSystemId(drmFamily) if IsString(systemId) xml.EmptyNode("ContentProtection", { "schemeIdUri": `urn:uuid:${systemId}` }) end if end for end if m.AddColorInfo(firstFormat, xml) for each stream in group representationAttributes = { "id": stream.itag "bandwidth": stream.bitrate } if stream.width <> invalid representationAttributes["width"] = stream.width end if if stream.height <> invalid representationAttributes["height"] = stream.height end if if hoisted["codecs"] = invalid and (stream.type.inStr("codecs=") <> -1) representationAttributes["codecs"] = stream.type.split("codecs=")[1].replace(`"`, "").replace(`"`, "") end if if hoisted["fps"] = invalid representationAttributes["frameRate"] = stream.fps end if if xml.Node("Representation", representationAttributes) m.GenerateSegmentInformation(xml, stream, metadata) xml.End() end if end for xml.End() end if id += 1 end for return id end function function GenerateSegmentInformation(xml as object, stream as object, metadata as object) as void if StringUtils.IsNullOrEmpty(stream.url) xml.Comment(`[ERROR] Stream.url is null or empty for itag: ${stream.itag}`) end if if metadata.isPostLiveDvr = true if not IsInt(stream.targetDurationSec) xml.Comment(`[ERROR] Post-Live DVR stream missing targetDurationSec for itag: ${stream.itag}`) return end if if stream.targetDurationSec < 1 xml.Comment(`[ERROR] Post-Live DVR stream has invalid targetDurationSec (${stream.targetDurationSec}) for itag: ${stream.itag}`) return end if postLiveDvrSegmentCount = metadata.postLiveDvrSegmentCount if not IsInt(postLiveDvrSegmentCount) xml.Comment(`[ERROR] Post-Live DVR metadata missing postLiveDvrSegmentCount for itag: ${stream.itag}`) ' We're going to guess segment count from targetDurationSec and total duration totalDurationMs = m.GetDuration(metadata) * 1000.0 postLiveDvrSegmentCount = MathUtils.Max(Fix(totalDurationMs / (stream.targetDurationSec * 1000)), 1) xml.Comment(`[INFO] Guessing postLiveDvrSegmentCount as ${postLiveDvrSegmentCount} for itag: ${stream.itag}`) end if duration = stream.targetDurationSec * 1000 repeatCount = postLiveDvrSegmentCount - 1 if xml.Node("SegmentTemplate", { "initialization": `${stream.url}&sq=0`, "media": `${stream.url}&sq=$Number$`, "timescale": "1000" }) if xml.Node("SegmentTimeline") xml.EmptyNode("S", { "d": duration, "r": repeatCount }) xml.End() end if xml.End() end if else if stream.isTypeOTF = true segmentDurations = stream.otfSegmentDurations if not IsArray(segmentDurations) xml.Comment(`[ERROR] OTF stream missing otfSegmentDurations for itag: ${stream.itag}`) return end if if xml.Node("SegmentTemplate", { "initialization": `${stream.url}&sq=0`, "media": `${stream.url}&sq=$Number$`, "timescale": "1000" }) if xml.Node("SegmentTimeline") if segmentDurations.Count() = 0 xml.Comment(`[ERROR] OTF stream has empty otfSegmentDurations for itag: ${stream.itag}`) end if for each segment in segmentDurations xml.EmptyNode("S", segment) end for xml.End() end if xml.End() end if else if metadata.liveNow = true ' Live: list only the segments that exist - a SegmentTimeline over the DVR ' window, ending just behind the newest produced segment (see ' FillLiveManifest). Roku never requests past the listed end, so a stream ' that produces slower than the wall clock, or stalls, holds the player at ' the list end instead of sending it after segments that don't exist yet. ' Segments are `&sq=N` fragments fetched straight from googlevideo. They are ' self-initializing (ftyp+moov+emsg+moof+mdat), so one doubles as the init, as ' for OTF: one listed at load, which googlevideo keeps past the signed url's ' expiry (measured ~12h back, even with DVR off). if xml.Node("SegmentTemplate", { "initialization": `${stream.url}&sq=${MathUtils.Max(ValidInt(metadata.liveHeadSeqnum) - 1, 0)}` "media": `${stream.url}&sq=$Number$` "timescale": "1000" "startNumber": LIVE_START_NUMBER_TOKEN }) if xml.Node("SegmentTimeline") xml.Text(LIVE_SEGMENTS_TOKEN) xml.End() end if xml.End() end if else xml.TextNode("BaseURL", ValidString(stream.url)) if StringUtils.IsNullOrEmpty(stream.index) or StringUtils.IsNullOrEmpty(stream.init) xml.Comment(`[ERROR] Stream index: ${stream.index}, init: ${stream.init} is invalid for itag: ${stream.itag}`) end if if xml.Node("SegmentBase", { "indexRange": stream.index }) xml.EmptyNode("Initialization", { "range": stream.init }) xml.End() end if end if end function function HoistCodecs(formats as object, hoisted as object) as dynamic if formats.Count() < 2 return invalid end if firstCodec = formats[0].type.split("codecs=")[1] for i = 1 to formats.Count() - 1 currentCodec = formats[i].type.split("codecs=")[1] if firstCodec <> currentCodec return invalid end if end for hoisted["codecs"] = true return firstCodec.replace(`"`, "").replace(`"`, "") end function function HoistNumberAttribute(formats as object, property as string, hoisted as object) as dynamic if formats.Count() < 2 return invalid end if firstFormat = formats[0] if firstFormat[property] = invalid return invalid end if firstValue = firstFormat[property] for i = 1 to formats.Count() - 1 otherValue = formats[i][property] if type(otherValue) <> type(firstValue) or otherValue <> firstValue return invalid end if end for hoisted[property] = true return firstValue end function function HoistAudioChannels(formats as object, hoisted as object) as dynamic if formats.Count() < 2 return invalid end if firstValue = formats[0].audioChannels if firstValue = invalid firstValue = 2 end if for i = 1 to formats.Count() - 1 currentValue = formats[i].audioChannels if currentValue = invalid currentValue = 2 end if if currentValue <> firstValue return invalid end if end for hoisted["AudioChannelConfiguration"] = true return firstValue end function function GetTrackRoles(format as object) as object roles = [] ' Within the preferred language, the device defaults to a "main" track (a set ' without a Role counts as main) regardless of bitrate or manifest order. ' Stable Volume and Voice Boost are opt-in re-mixes of the original. if format.isOriginal = true and format.isDrc <> true and format.isVoiceBoost <> true roles.Push("main") else roles.Push("alternate") end if if format.isDubbed = true or format.isAutoDubbed = true roles.Push("dub") end if if format.isDescriptive = true roles.Push("description") end if ' The device's audio menu ignores Label: it lists tracks by language, and this ' role is what shows a same-language variant separately, as "Enhanced audio". if format.isVoiceBoost = true roles.Push("enhanced-audio-intelligibility") end if return roles end function ' Stable Volume and Voice Boost are re-mixes of the same itag: without the suffix ' they share an AdaptationSet (and Representation ids) with the regular mix. function GetAudioVariantSuffix(format as object) as string suffix = "" if format.isDrc = true suffix = `${suffix}-drc` end if if format.isVoiceBoost = true suffix = `${suffix}-vb` end if return suffix end function function GenerateImageAdaptationSets(xml as object, storyboards as object, id as integer) as integer ' https://developer.roku.com/en-ca/docs/developer-program/media-playback/trick-mode/hls-and-dash.md#dash-standard-thumbnail-tiles for i = storyboards.Count() - 1 to 0 step -1 storyboard = storyboards[i] interval = ValidInt(storyboard.interval) if interval = 0 LogWarnNoTelemetry("Invalid storyboard interval:", storyboard.interval) continue for end if storyboardWidth = storyboard.storyboardWidth storyboardHeight = storyboard.storyboardHeight storyboardCount = storyboard.storyboardCount tileWidthInPixels = storyboard.width tileHeightInPixels = storyboard.height totalTileCount = storyboard.count ' For the last page, the image height might be smaller than the storyboard height if storyboardCount = 1 storyboardHeight = totalTileCount \ storyboardWidth if totalTileCount mod storyboardWidth > 0 storyboardHeight += 1 end if end if intervalInSeconds = interval / 1000.0 ' YouTube template uses the var $M for tile pages ' DASH-IF uses $Number$ in the SegmentTemplate ' https://dashif.org/docs/DASH-IF-IOP-v4.3.pdf url = storyboard.templateUrl.replace("$M", "$Number$") tilesPerPage = storyboardWidth * storyboardHeight duration = tilesPerPage * intervalInSeconds storyboardWidthInPixels = tileWidthInPixels * storyboardWidth storyboardHeightInPixels = tileHeightInPixels * storyboardHeight ' The OS exposes the image representation with the LOWEST @bandwidth in Video.thumbnailTiles ' (ties resolve by document order), so a size-derived estimate would hand apps the blurriest ' level. Declare the same value for every level instead: the tie makes the first-written set win, ' and this loop writes the sharpest first - that ordering is load-bearing. bandwidth = 1000 if xml.Node("AdaptationSet", { "id": `${id}` "mimeType": "image/jpeg" "contentType": "image" }) xml.EmptyNode("SegmentTemplate", { "media": url "duration": duration "startNumber": 0 }) if xml.Node("Representation", { "id": `thumbnails_${id}` "bandwidth": bandwidth "width": storyboardWidthInPixels "height": storyboardHeightInPixels }) xml.EmptyNode("EssentialProperty", { "schemeIdUri": "http://dashif.org/guidelines/thumbnail_tile" "value": `${storyboardWidth}x${storyboardHeight}` }) xml.End() end if xml.End() end if id += 1 end for return id end function function AddColorInfo(videoStream as object, xml as object) as void if videoStream.colorInfo = invalid return end if if videoStream.colorInfo.primaries <> invalid primaries = m.colorInfo.primaries[videoStream.colorInfo.primaries] if primaries <> invalid xml.EmptyNode("SupplementalProperty", { "schemeIdUri": "urn:mpeg:mpegB:cicp:ColourPrimaries" "value": primaries }) else LogWarn("Unknown colorInfo.primaries:", videoStream.colorInfo.primaries) end if end if if videoStream.colorInfo.transferCharacteristics <> invalid transferCharacteristics = m.colorInfo.transferCharacteristics[videoStream.colorInfo.transferCharacteristics] if transferCharacteristics <> invalid xml.EmptyNode("SupplementalProperty", { "schemeIdUri": "urn:mpeg:mpegB:cicp:TransferCharacteristics" "value": transferCharacteristics }) else LogWarn("Unknown colorInfo.transferCharacteristics:", videoStream.colorInfo.transferCharacteristics) end if end if if videoStream.colorInfo.matrixCoefficients <> invalid matrixCoefficients = m.colorInfo.matrixCoefficients[videoStream.colorInfo.matrixCoefficients] if matrixCoefficients <> invalid xml.EmptyNode("SupplementalProperty", { "schemeIdUri": "urn:mpeg:mpegB:cicp:MatrixCoefficients" "value": matrixCoefficients }) else LogWarn("Unknown colorInfo.matrixCoefficients:", videoStream.colorInfo.matrixCoefficients) end if end if end function function GetXtagsInfo(format as object) as object result = { lang: "" acont: "" isDrc: false isVoiceBoost: false isDubbed: false isAutoDubbed: false isDescriptive: false isSecondary: false isOriginal: false } if StringUtils.IsNullOrEmpty(format.url) return result end if ' Technically format.xtags can be used, but it is protobuf encoded ' so this is simpler. Also, this is consistent for both local ' Innertube and Invidious. queryParams = UrlUtils.ParseQueryComponents(format.url) xtagsString = queryParams["xtags"] if StringUtils.IsNullOrEmpty(xtagsString) return result end if tags = {} xtagsList = xtagsString.split(":") for each xtag in xtagsList pair = xtag.split("=") if pair.Count() = 2 tags[pair[0]] = pair[1] end if end for for each key in tags if key = "lang" result.lang = tags[key] else if key = "acont" result.acont = tags[key] else if key = "drc" and tags[key] = "1" result.isDrc = true else if key = "vb" and tags[key] = "1" result.isVoiceBoost = true end if end for if format.isDrc = true result.isDrc = true end if if result.acont = "dubbed" result.isDubbed = true else if result.acont = "dubbed-auto" result.isAutoDubbed = true else if result.acont = "descriptive" result.isDescriptive = true else if result.acont = "secondary" result.isSecondary = true end if if result.acont = "original" or (not result.isDubbed and not result.isAutoDubbed and not result.isDescriptive and not result.isSecondary) result.isOriginal = true end if return result end function ' Builds a minimal audioTrack for sources that only encode the language in the ' stream URL's xtags (e.g. Invidious), mirroring the shape Innertube provides. ' The id keeps each language + content variant (original/dubbed/...) in its own ' group; languageCode is the base ISO code (e.g. "en" from "en-US") that the ' device maps to a display name. No displayName is set on purpose: without a ' Label, the device derives the name from `lang` ("English") rather than echoing ' the raw code. function SynthesizeAudioTrack(xtagsInfo as object) as object lang = xtagsInfo.lang id = lang if not StringUtils.IsNullOrEmpty(xtagsInfo.acont) id = `${lang}.${xtagsInfo.acont}` end if return { "id": id "languageCode": lang.Tokenize("-")[0] } end function function GetDrmSystemId(drmFamily as dynamic) as dynamic if not IsString(drmFamily) return invalid end if if drmFamily = "WIDEVINE" return "edef8ba9-79d6-4ace-a3c8-27dcd51d21ed" else if drmFamily = "PLAYREADY" return "9a04f079-9840-4286-ab92-e65be0885f95" end if return invalid end function end class