From 425f4d9660b1b543e2a1e31ea16d6922b026a98e Mon Sep 17 00:00:00 2001 From: Brahim Hadriche Date: Mon, 25 May 2026 17:01:03 -0400 Subject: [PATCH] Fix/live videos (#877) * Initial fix * Optimize * changelog, move hls down in priority * Fix for audio track names when using Invidious * comments * comment * comment --- CHANGELOG.md | 7 + .../components/Services/Dash/DashManifest.bs | 157 ++++++- .../Services/Innertube/InnertubeService.bs | 29 +- .../Services/Innertube/PlayerEndpoint.bs | 128 ++++-- .../components/VideoPlayer/VideoContentJob.bs | 6 +- .../PlayletWebServer/Middleware/DashRouter.bs | 412 +++++++++++++++++- 6 files changed, 663 insertions(+), 76 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 075978bf..55982cb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Fixed + +- Live stream videos +- Audio track names when using Invidious + ## [0.45.0] - 2026-05-25 ### Added diff --git a/playlet-lib/src/components/Services/Dash/DashManifest.bs b/playlet-lib/src/components/Services/Dash/DashManifest.bs index e1061545..39617dcf 100644 --- a/playlet-lib/src/components/Services/Dash/DashManifest.bs +++ b/playlet-lib/src/components/Services/Dash/DashManifest.bs @@ -4,10 +4,20 @@ import "pkg:/source/utils/Logging.bs" import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/UrlUtils.bs" +' Number of native YouTube live fragments (each `targetDurationSec` long) that the +' /api/dash/live-seg proxy concatenates into a single DASH segment. Roku dislikes +' the ~2s native request cadence, so we present longer segments. Used by both the +' manifest (segment duration / refresh timing) and DashRouter's live-seg handler +' (which fragments to fetch per DASH segment number). +const LIVE_SEGMENT_GROUP = 4 + class DashManifest public invidiousInstance as dynamic public disableAutoDubbed as boolean + ' Base URL (scheme://host:port) of Playlet's local web server, so live + ' SegmentTemplate URLs can address the /api/dash/live-seg proxy. Set by DashRouter. + public liveSegmentBaseUrl as string = "" function new(invidiousInstance as string, disableAutoDubbed = false as boolean) m.invidiousInstance = invidiousInstance @@ -51,8 +61,9 @@ class DashManifest end if duration = m.GetDuration(metadata) + isLive = ValidBool(metadata.liveNow) - groupings = m.CreateFormatGroupings(adaptiveFormats, metadata.isPostLiveDvr) + groupings = m.CreateFormatGroupings(adaptiveFormats, metadata.isPostLiveDvr, isLive) audioGroups = groupings.audio videoGroups = groupings.video @@ -86,16 +97,51 @@ class DashManifest xml.Comment(`Generated by Playlet - Video ID: ${metadata.videoId}`) xml.Comment(`Parser: ${ValidString(metadata.parser)}`) - if xml.Node("MPD", { - "xmlns": "urn:mpeg:dash:schema:mpd:2011" - "profiles": "urn:mpeg:dash:profile:full:2011" - "minBufferTime": "PT1.5S" - "type": "static" - "mediaPresentationDuration": `PT${duration}S` - "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 xml.Node("Period") + 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 + ' Dynamic (live) manifest: the player derives the current segment from + ' wall-clock against availabilityStartTime, and the duration-based + ' SegmentTemplate (see GenerateSegmentInformation) auto-extends as the + ' stream advances. timeShiftBufferDepth exposes the DVR window. + segmentSec = Cint(m.GetLiveFragmentDurationMs(metadata) * LIVE_SEGMENT_GROUP / 1000.0) + if segmentSec < 1 + segmentSec = 1 + end if + dvrWindowSec = ValidInt(metadata.liveDvrWindowSec) + mpdAttributes["profiles"] = "urn:mpeg:dash:profile:isoff-live:2011" + mpdAttributes["type"] = "dynamic" + mpdAttributes["minimumUpdatePeriod"] = `PT${segmentSec}S` + mpdAttributes["suggestedPresentationDelay"] = `PT${segmentSec * 3}S` + if not StringUtils.IsNullOrEmpty(metadata.liveAvailabilityStartUtc) + mpdAttributes["availabilityStartTime"] = metadata.liveAvailabilityStartUtc + end if + if dvrWindowSec > 0 + mpdAttributes["timeShiftBufferDepth"] = `PT${dvrWindowSec}S` + else + LogWarn("[LIVE-MPD] dvrWindowSec is 0/missing -> NO timeShiftBufferDepth (live seek may fail). metadata.liveDvrWindowSec:", metadata.liveDvrWindowSec) + end if + ' LogInfo("[LIVE-MPD] live MPD attrs: availabilityStartTime:", metadata.liveAvailabilityStartUtc, "segmentSec(group-adjusted):", segmentSec, "dvrWindowSec:", dvrWindowSec, "liveHeadSeqnum:", metadata.liveHeadSeqnum, "baseUrl:", m.liveSegmentBaseUrl) + else + mpdAttributes["profiles"] = "urn:mpeg:dash:profile:full:2011" + mpdAttributes["type"] = "static" + mpdAttributes["mediaPresentationDuration"] = `PT${duration}S` + end if + + ' Dynamic (live) manifests need an explicit Period start so the player can + ' anchor the timeline against availabilityStartTime; static keeps the + ' attribute-less Period it has always used. + 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) @@ -122,14 +168,33 @@ class DashManifest return ValidInt(metadata["lengthSeconds"]) end function - function CreateFormatGroupings(formats as object, isPostLiveDvr as boolean) as object + ' Representative segment duration for a live stream, in whole seconds. + ' Effective per-native-fragment duration (ms) for live. Prefers the value + ' derived from the live head (headTime/headSeqnum, set by GetLiveStreamInfo) + ' since YouTube's reported targetDurationSec is unreliable for long-running + ' streams; falls back to targetDurationSec, then to 2s. + function GetLiveFragmentDurationMs(metadata as object) as integer + fragMs = ValidInt(metadata.liveFragmentDurationMs) + if fragMs > 0 + return fragMs + end if + targetSec = ValidInt(ObjectUtils.Dig(metadata, ["adaptiveFormats", 0, "targetDurationSec"])) + if targetSec < 1 + targetSec = 2 + end if + return targetSec * 1000 + 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) - isValid = (hasInit and hasIndex) or isOtf or isPostLiveDvr + ' 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 @@ -167,11 +232,6 @@ class DashManifest colorInfo = `${format.colorInfo.primaries}-${format.colorInfo.transferCharacteristics}-${format.colorInfo.matrixCoefficients}` end if - audioTrackId = "" - if IsAssociativeArray(format.audioTrack) and IsString(format.audioTrack.id) - audioTrackId = format.audioTrack.id - end if - if format.type.startsWith("audio") xtagsInfo = m.GetXtagsInfo(format) format.xtagsInfo = xtagsInfo @@ -181,6 +241,21 @@ class DashManifest 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 drc = "" @@ -513,6 +588,33 @@ class DashManifest end if xml.End() end if + else if metadata.liveNow = true + ' Live: segments are `&sq=N` with the live edge advancing over time. A + ' duration-based SegmentTemplate (no fixed SegmentTimeline) lets the + ' player compute the current segment from availabilityStartTime and keep + ' extending as the stream grows. + + ' Live segments are self-initializing (ftyp+moov+emsg+moof+mdat) and + ' YouTube serves no clean init or moof-only media, so Roku can't demux + ' them directly (it reads the init segment once; a per-segment moov + ' yields `error -36`). The /api/dash/live-seg proxy transforms them + ' (init -> ftyp+moov, media -> moof+mdat) and groups LIVE_SEGMENT_GROUP + ' native fragments into each DASH segment. The manifest just addresses + ' the proxy by itag + DASH segment number ($Number$). + ' Per-fragment duration x GROUP. NOT targetDurationSec (unreliable for + ' long streams - see GetLiveFragmentDurationMs); the head-derived value + ' keeps the player's wall-clock -> $Number$ -> sq mapping on the live edge. + durationMs = m.GetLiveFragmentDurationMs(metadata) * LIVE_SEGMENT_GROUP + ' The `v` (video id) lets the proxy cache the per-video format lookup. + segBase = `${m.liveSegmentBaseUrl}/api/dash/live-seg?v=${metadata.videoId}&itag=${stream.itag}` + ' LogInfo("[LIVE-MPD] SegmentTemplate itag:", stream.itag, "targetDurationSec:", stream.targetDurationSec, "group:", LIVE_SEGMENT_GROUP, "durationMs:", durationMs) + xml.EmptyNode("SegmentTemplate", { + "initialization": `${segBase}&sq=init` + "media": `${segBase}&sq=$Number$` + "timescale": "1000" + "duration": durationMs + "startNumber": "0" + }) else xml.TextNode("BaseURL", ValidString(stream.url)) @@ -794,6 +896,25 @@ class DashManifest 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 diff --git a/playlet-lib/src/components/Services/Innertube/InnertubeService.bs b/playlet-lib/src/components/Services/Innertube/InnertubeService.bs index bb4aa44d..534e1aa7 100644 --- a/playlet-lib/src/components/Services/Innertube/InnertubeService.bs +++ b/playlet-lib/src/components/Services/Innertube/InnertubeService.bs @@ -35,20 +35,14 @@ namespace InnertubeService nextRequest.Send() end if - ' For LIVE videos, we will need to fallback to iOS for HLS streams for now. - ' Also, since we might have tracking urls in the player response (if logged in), - ' we can keep them to avoid an extra request later. - ' TODO:P0 figure out how to get DASH to work for live videos. - playbackTrackingUrls = invalid playerResponseJson = invalid client = Innertube.ClientType.Tv totalPlayerRequests = 0 while true - ' We shouldn't be making more that 3 requests: - ' 1. Make request with TV client, but turns out to be live -> fallback to iOS - ' 2. Make request, but STS_MISMATCH error -> retry with new STS - ' 3. Make request, it either succeeds or fails. - if totalPlayerRequests > 3 + ' We shouldn't be making more than 2 requests: + ' 1. Make request with TV client. + ' 2. Make request, but STS_MISMATCH error -> retry with new STS. + if totalPlayerRequests >= 2 LogError("Too many player requests, aborting.") return { error: "Too many player requests" @@ -81,14 +75,6 @@ namespace InnertubeService end if playerResponseJson = playerResponse.Json() - notDashSupported = Innertube.IsLiveStream(playerResponseJson) - if notDashSupported and client = Innertube.ClientType.Tv - LogDebug("Falling back to iOS client for live video.") - isLoggedIn = Innertube.ParseIsLoggedIn(playerResponseJson) - playbackTrackingUrls = Innertube.ParsePlaybackTrackingUrls(playerResponseJson, isLoggedIn) - client = Innertube.ClientType.IOS - continue while - end if parsedResponse = Innertube.ParseInnertubePlayerResponse(playerRequest, playerResponse, client, cancellation) @@ -136,13 +122,6 @@ namespace InnertubeService parsedResponse["videoId"] = videoId end if - ' If we did capture tracking urls when we did the TV request, but now we're - ' missing them because we switched to iOS, add them back. - if playbackTrackingUrls <> invalid and parsedResponse.playbackTrackingUrls = invalid - LogDebug("Adding playback tracking URLs from TV player response.") - parsedResponse["playbackTrackingUrls"] = playbackTrackingUrls - end if - return parsedResponse end function diff --git a/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs b/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs index ff4de5e2..69c100b3 100644 --- a/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs @@ -98,17 +98,19 @@ namespace Innertube adaptiveFormats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "adaptiveFormats"])) formats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "formats"])) - if not isLive - error = DecipherUrls(formats, adaptiveFormats, playerRequest.signatureTimestamp, cancellation) - if error <> invalid - parsedResponse["error"] = error.error - if error.DoesExist("errorCode") - parsedResponse["errorCode"] = error.errorCode - end if - return parsedResponse + error = DecipherUrls(formats, adaptiveFormats, playerRequest.signatureTimestamp, cancellation) + if error <> invalid + parsedResponse["error"] = error.error + if error.DoesExist("errorCode") + parsedResponse["errorCode"] = error.errorCode end if + return parsedResponse end if + ' if isLive and adaptiveFormats.Count() > 0 + ' LogInfo("[LIVE-INFO] post-decipher, sts:", playerRequest.signatureTimestamp, "format[0].itag:", adaptiveFormats[0]["itag"], "url:", adaptiveFormats[0]["url"]) + ' end if + hasLiveStreamingData = FormatsHaveLiveStreamingData(adaptiveFormats) or FormatsHaveLiveStreamingData(formats) isOTF = FormatsHasTypeOTF(adaptiveFormats) hasDrm = (not StringUtils.IsNullOrEmpty(streamingData.drmParams)) or IsArray(streamingData.licenseInfos) @@ -168,6 +170,11 @@ namespace Innertube OTFGetSegmentInfo(adaptiveFormats, client, cancellation) end if + if isLive + LogDebug("Fetching live stream info") + GetLiveStreamInfo(parsedResponse, adaptiveFormats, playerRequest.cpn, client, cancellation) + end if + return parsedResponse end function @@ -415,6 +422,9 @@ namespace Innertube if fmt["targetDurationSec"] <> invalid result["targetDurationSec"] = fmt["targetDurationSec"] end if + if fmt["maxDvrDurationSec"] <> invalid + result["maxDvrDurationSec"] = fmt["maxDvrDurationSec"] + end if if ValidString(fmt["type"]) = "FORMAT_STREAM_TYPE_OTF" result["isTypeOTF"] = true @@ -640,27 +650,6 @@ namespace Innertube } end function - function IsLiveStream(payload as object) as boolean - if ValidBool(ObjectUtils.Dig(payload, ["videoDetails", "isLive"])) - return true - end if - - if ValidBool(ObjectUtils.Dig(payload, ["videoDetails", "isPostLiveDvr"])) - return false - end if - - adaptiveFormats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "adaptiveFormats"])) - if FormatsHaveLiveStreamingData(adaptiveFormats) - return true - end if - - formats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "formats"])) - if FormatsHaveLiveStreamingData(formats) - return true - end if - return false - end function - function FormatsHaveLiveStreamingData(formats as object) as boolean if not IsArray(formats) return false @@ -748,4 +737,85 @@ namespace Innertube end if end function + ' Live streams come back with no hlsManifestUrl/dashManifestUrl, just + ' adaptiveFormats with a `targetDurationSec` and segments addressed by `&sq=N` + ' (identical to Post-Live DVR). To build a dynamic DASH manifest we need the + ' current live edge (X-Head-Seqnum) and a wall-clock anchor for the DASH + ' `availabilityStartTime`. X-Head-Time-Millis is the stream-time of the head + ' segment, so genesis = now - headTime. + function GetLiveStreamInfo(parsedResponse as object, adaptiveFormats as object, cpn as dynamic, client as Innertube.ClientType, cancellation as object) as void + if adaptiveFormats.Count() = 0 + LogWarn("GetLiveStreamInfo: No adaptive formats available") + return + end if + + url = adaptiveFormats[0]["url"] + if StringUtils.IsNullOrEmpty(url) + LogWarn("GetLiveStreamInfo: URL is empty") + return + end if + + maxDvrDurationSec = ValidInt(adaptiveFormats[0]["maxDvrDurationSec"]) + ' LogInfo("[LIVE-INFO] GetLiveStreamInfo start. itag:", adaptiveFormats[0]["itag"], "targetDurationSec:", adaptiveFormats[0]["targetDurationSec"], "maxDvrDurationSec:", maxDvrDurationSec, "client:", client) + + queryComponents = UrlUtils.ParseQueryComponents(url) + queryComponents["rn"] = "0" + queryComponents["sq"] = "0" + if not StringUtils.IsNullOrEmpty(cpn) + queryComponents["cpn"] = cpn + end if + + url = UrlUtils.SetQueryParams(url, queryComponents) + + request = HttpClient.Head(url) + requestHeaders = Innertube.CreateHeaders(client) + requestHeaders["origin"] = "https://www.youtube.com" + requestHeaders["referer"] = "https://www.youtube.com" + requestHeaders["DNT"] = "?1" + request.Headers(requestHeaders) + + request.TryCount(2) + request.Cancellation(cancellation) + response = request.Await() + + if not response.IsSuccess() + LogError("Failed to fetch live stream info", response.ErrorMessage()) + return + end if + + headers = response.Headers() + ' LogInfo("[LIVE-INFO] HEAD response headers:", FormatJson(headers)) + + if not headers.DoesExist("X-Head-Time-Millis") or not headers.DoesExist("X-Head-Seqnum") + LogErrorNoTelemetry("[LIVE-INFO] Missing X-Head-Time-Millis / X-Head-Seqnum in headers", url, headers) + return + end if + + ' Work in seconds: wall-clock ms (~1.78e12) overflows a 32-bit integer. + headTimeSec = ValidString(headers["X-Head-Time-Millis"]).ToInt() \ 1000 + headSeqnum = ValidString(headers["X-Head-Seqnum"]).ToInt() + nowSec = CreateObject("roDateTime").AsSeconds() + genesisSec = nowSec - headTimeSec + + genesisDate = CreateObject("roDateTime") + genesisDate.FromSeconds(genesisSec) + + parsedResponse["liveHeadSeqnum"] = headSeqnum + parsedResponse["liveAvailabilityStartUtc"] = genesisDate.ToISOString() + if maxDvrDurationSec > 0 + parsedResponse["liveDvrWindowSec"] = maxDvrDurationSec + end if + ' Effective per-fragment duration, derived from the stream's own counters. + ' YouTube's reported targetDurationSec is unreliable for long-running streams + ' (observed 5s vs a real ~1.8s cadence); using it desyncs the duration-based + ' SegmentTemplate so the player requests segments far outside the DVR window + ' (404). headTime/headSeqnum is the true average and keeps the manifest's + ' wall-clock -> sq mapping anchored to the same (headTime, headSeqnum) pair + ' that availabilityStartTime is built from. + if headSeqnum > 0 + parsedResponse["liveFragmentDurationMs"] = Cint((headTimeSec / headSeqnum) * 1000.0) + end if + ' LogInfo("[LIVE-INFO] computed headTimeSec:", headTimeSec, "headSeqnum:", headSeqnum, "nowSec:", nowSec, "genesisSec:", genesisSec, "availabilityStartUtc:", parsedResponse["liveAvailabilityStartUtc"], "liveDvrWindowSec:", parsedResponse["liveDvrWindowSec"]) + end function + end namespace diff --git a/playlet-lib/src/components/VideoPlayer/VideoContentJob.bs b/playlet-lib/src/components/VideoPlayer/VideoContentJob.bs index 5673c63d..4e727134 100644 --- a/playlet-lib/src/components/VideoPlayer/VideoContentJob.bs +++ b/playlet-lib/src/components/VideoPlayer/VideoContentJob.bs @@ -166,9 +166,6 @@ function CreateStreamUrls(metadata as object, service as Invidious.InvidiousServ url: metadata.dashUrl }) streamUrls.push(dashUrl) - else if SupportsHls(metadata) - metadata.hlsUrl = AddInstanceToUrlIfNeeded(metadata.hlsUrl, instance) - AddHlsUrls(streamUrls, metadata, preferredQuality, backend, proxyVideos, playletServerPort) else if SupportsDash(metadata) AddDashUrls(streamUrls, metadata, preferredQuality, backend, proxyVideos, playletServerPort) else if SupportsMuxedFormats(metadata) @@ -179,6 +176,9 @@ function CreateStreamUrls(metadata as object, service as Invidious.InvidiousServ stream.url = AddInstanceToUrlIfNeeded(stream.url, instance) streamUrls.push(stream.url) end for + else if SupportsHls(metadata) + metadata.hlsUrl = AddInstanceToUrlIfNeeded(metadata.hlsUrl, instance) + AddHlsUrls(streamUrls, metadata, preferredQuality, backend, proxyVideos, playletServerPort) end if return streamUrls diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs index eea866ff..56f62a7f 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs @@ -1,22 +1,65 @@ import "pkg:/components/Services/Dash/DashManifest.bs" import "pkg:/components/Services/Invidious/InvidiousService.bs" import "pkg:/components/Web/WebServer/Http/HttpRouter.bs" +import "pkg:/source/services/HttpClient.bs" import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/Types.bs" namespace Http class DashRouter extends HttpRouter + ' Starting probe size for the live-segment box walk (see LocateBoxes): + ' ftyp+moov+emsg sit well within this (observed ~920 bytes), so we never read + ' the (large) mdat just to find where moof starts. + private INITIAL_PROBE_BYTE_COUNT = 2048 + ' Hard ceiling on the probe so a fragment that genuinely has no moof (corrupt) + ' can't make us slurp a whole multi-hundred-KB mdat into memory while growing. + private MAX_PROBE_BYTE_COUNT = 65536 + function new(server as object) super() m.videoQueueNode = server.sceneNodes.videoQueue m.invidiousNode = server.sceneNodes.invidious m.preferencesNode = server.sceneNodes.preferences + m.serverPort = server.settings.Port m.invidiousService = new Invidious.InvidiousService(m.invidiousNode) ' No need to pass the invidious instance here, we will refresh it for ' each request to make sure we are using the latest one m.dashManifest = new DashManifest("") + m.fs = CreateObject("roFileSystem") + + ' Live manifests are re-fetched every `minimumUpdatePeriod` (~20s), and + ' reading metadata off the videoQueue node is a cross-thread rendezvous + ' that deep-copies the whole (~39 KB) metadata AA. The metadata is + ' immutable for a given videoId, so cache it and only dig the node when + ' the video changes. The same dig also feeds the live-segment lookups + ' below, so /api/dash and /api/dash/live-seg share one dig + one copy. + m.cachedVideoId = invalid + m.cachedMetadata = invalid + ' Live-segment caches, (re)built from the same metadata dig: + m.cachedUrls = {} ' itag -> signed base url + m.cachedTypes = {} ' itag -> "audio/mp4" | "video/mp4" + m.cachedInitSeqnum = 0 ' live-edge fragment to source the init from + m.probeByteCount = m.INITIAL_PROBE_BYTE_COUNT ' current box-walk probe; only grows + m.reportedFailures = {} ' per-video telemetry dedupe (see ReportSegmentFailure) + end function + + ' Returns the cached metadata AA for video id `v`, digging the videoQueue + ' node (a render-thread rendezvous) only on a cache miss / video change. On a + ' miss, also (re)builds the live-segment caches from the same copy. + function GetMetadata(v as string) as dynamic + if m.cachedVideoId = v and IsAssociativeArray(m.cachedMetadata) + return m.cachedMetadata + end if + + metadata = ObjectUtils.DigUnsafe(m.videoQueueNode, ["player", "content", "metadata"]) + if IsAssociativeArray(metadata) and metadata.videoId = v + m.cachedMetadata = metadata + m.cachedVideoId = v + m.RebuildLiveCache(metadata) + end if + return metadata end function @get("/api/dash") @@ -39,7 +82,7 @@ namespace Http return true end if - metadata = ObjectUtils.DigUnsafe(m.videoQueueNode, ["player", "content", "metadata"]) + metadata = m.GetMetadata(v) if not IsAssociativeArray(metadata) response.Default(500, "videoQueue.player.content.metadata is invalid") WriteAsciiFile("cachefs:/last_generated_dash.xml", "500 videoQueue.player.content.metadata is invalid") @@ -53,6 +96,10 @@ namespace Http m.dashManifest.invidiousInstance = m.invidiousService.GetInstance() m.dashManifest.disableAutoDubbed = ValidBool(m.preferencesNode["playback.disable_auto_dubbed"]) + ' For live streams, segments are addressed to the /api/dash/live-seg proxy + ' on this same web server (the video player reaches it over 127.0.0.1). + m.dashManifest.liveSegmentBaseUrl = `http://127.0.0.1:${m.serverPort}` + ' LogInfo("[LIVE-MPD] DashRouter building manifest for v:", v, "liveNow:", metadata.liveNow, "liveSegmentBaseUrl:", m.dashManifest.liveSegmentBaseUrl) qualityFilter = m.CreateQualityFilter(quality) xmlContent = m.dashManifest.FromVideoMetadata(metadata, qualityFilter, ValidString(local) = "true") @@ -145,6 +192,369 @@ namespace Http return true end function + ' ------------------------------------------------------------------------ + ' Live segment proxy + ' + ' Proxies YouTube live segments so Roku can demux them as DASH. YouTube live + ' fragments (`&sq=N`) are self-initializing: every fragment is + ' `ftyp+moov+emsg+moof+mdat`. Standard DASH (and Roku) want the init segment to + ' be `ftyp+moov` only and media segments to be `moof+mdat` only; a per-fragment + ' moov makes Roku fail with `Cannot seek to video: error -36`. YouTube serves + ' no clean init or moof-only media directly (`&range=` -> 400, the HTTP Range + ' header is ignored), so this transform is unavoidable. + ' + ' Endpoint (see DashManifest live SegmentTemplate): + ' /api/dash/live-seg?v=&itag=&sq=init -> ftyp+moov of the live-edge fragment + ' /api/dash/live-seg?v=&itag=&sq= -> moof+mdat of fragments + ' [K*GROUP .. K*GROUP+GROUP-1] + ' where GROUP = LIVE_SEGMENT_GROUP. + ' + ' This is a hot path (called for every audio + video segment, continuously), + ' so it is written to minimize per-request work: the itag -> url/type lookups + ' and live-edge seqnum are resolved once per video id (shared with /api/dash via + ' GetMetadata), the segment URL is a plain string concat (no URL parse/encode), + ' and the moof/moov split reads only the needed byte ranges from the temp file. + ' ------------------------------------------------------------------------ + @get("/api/dash/live-seg") + function GetLiveSegment(context as object) as boolean + request = context.request + response = context.response + + v = request.query.v + itag = request.query.itag + sq = request.query.sq + + if StringUtils.IsNullOrEmpty(itag) or StringUtils.IsNullOrEmpty(sq) or StringUtils.IsNullOrEmpty(v) + response.Default(400, "Missing v, itag or sq") + return true + end if + + ' Warm the shared cache for this video (one node dig on a video change; + ' the manifest request usually warmed it already). + m.GetMetadata(v) + + baseUrl = m.cachedUrls[itag] + if StringUtils.IsNullOrEmpty(baseUrl) + LogErrorNoTelemetry("[LIVE-SEG] no live format url for v:", v, "itag:", itag, "-> 404") + m.ReportSegmentFailure("no live format url", { v: v, itag: itag, sq: sq }) + response.Default(404, "No live format url for itag " + itag) + return true + end if + + if sq = "init" + ' Init segment: ftyp+moov. We must NOT use fragment 0 - for a + ' long-running live stream (e.g. a 24/7 channel up for weeks) sq=0 is + ' far outside the DVR window and googlevideo 404s it. Every live + ' fragment is self-initializing with an identical moov (constant + ' codec config), so we source the init from the live-edge fragment + ' (cachedInitSeqnum), which is always within the DVR window. + output = m.AwaitTransformedSegment(m.StartSegmentFetch(baseUrl, m.cachedInitSeqnum, v, itag), true) + if output = invalid + ' Root-cause telemetry already emitted by AwaitTransformedSegment. + LogErrorNoTelemetry("[LIVE-SEG] INIT fetch failed v:", v, "itag:", itag, "-> 502") + response.Default(502, "Failed to fetch live init segment") + return true + end if + else + ' Media DASH segment K: concat GROUP native fragments, each reduced + ' to moof+mdat so Roku reads the init segment only once. + ' + ' Fire all GROUP fragment fetches in parallel (Send), then await + + ' transform them in order. Fetching serially here was the live + ' bottleneck - segments arrived too slowly and the player dropped to + ' lower bitrates. (Same Send()-then-Await() pattern as OTFSegmentInfo.) + firstFrag = sq.ToInt() * LIVE_SEGMENT_GROUP + pending = [] + for i = 0 to LIVE_SEGMENT_GROUP - 1 + pending.Push(m.StartSegmentFetch(baseUrl, firstFrag + i, v, itag)) + end for + + ' Await all (so every temp file is read + deleted), then assemble the + ' contiguous prefix. A failed fragment is a gap, so we stop appending + ' at the first failure; trailing fragments past the live edge are + ' simply dropped (partial group is valid for the live edge). + parts = [] + for each entry in pending + parts.Push(m.AwaitTransformedSegment(entry, false)) + end for + + output = invalid + for each part in parts + if part = invalid + exit for + end if + if output = invalid + output = part + else + output.Append(part) + end if + end for + + if output = invalid + ' Root-cause telemetry already emitted by AwaitTransformedSegment. + LogErrorNoTelemetry("[LIVE-SEG] first media fragment failed v:", v, "itag:", itag, "sq:", firstFrag, "-> 502") + response.Default(502, "Failed to fetch live media segment") + return true + end if + end if + + response.http_code = 200 + response.headers["Content-Type"] = m.cachedTypes[itag] + response.headers["Cache-Control"] = "no-cache, must-revalidate" + response.headers["Cross-Origin-Resource-Policy"] = "cross-origin" + response.SetBodyDataBuffer(output) + return true + end function + + ' (Re)build the live-segment lookups (itag -> url/type, live-edge seqnum) from + ' an already-dug metadata AA - NO second node dig. Called from GetMetadata on a + ' video change. Also sweeps orphaned temp files and re-arms the telemetry guard. + function RebuildLiveCache(metadata as object) as void + ' Video changed: sweep any orphaned segment temp files. Each request + ' deletes its own temp files on every path, so this is only a safety net + ' for an unexpected error that skipped a delete - without it, tmp:/ + ' (RAM-backed, never reaped by the OS) could grow across a long session. + ' Safe here because the web server handles one request at a time, so no + ' live-seg fetch is in flight. + m.CleanupTempSegments() + ' Re-arm the per-video telemetry dedupe (see ReportSegmentFailure). + m.reportedFailures = {} + + urls = {} + types = {} + adaptiveFormats = ObjectUtils.DigUnsafe(metadata, ["adaptiveFormats"]) + if IsArray(adaptiveFormats) + for each format in adaptiveFormats + if IsString(format.itag) and not StringUtils.IsNullOrEmpty(format.url) + urls[format.itag] = format.url + if IsString(format.type) and format.type.StartsWith("audio") + types[format.itag] = "audio/mp4" + else + types[format.itag] = "video/mp4" + end if + end if + end for + else + LogErrorNoTelemetry("[LIVE-SEG] RebuildLiveCache: adaptiveFormats not an array for v:", metadata.videoId) + m.ReportSegmentFailure("adaptiveFormats not an array", { v: ValidString(metadata.videoId) }) + end if + + m.cachedUrls = urls + m.cachedTypes = types + ' Live-edge fragment to source the init segment from. Falls back to 0 if + ' absent - fine for young streams where sq=0 is still inside the DVR window. + m.cachedInitSeqnum = ValidInt(ObjectUtils.DigUnsafe(metadata, ["liveHeadSeqnum"])) + end function + + ' Delete any leftover `tmp:/live-seg-*.m4s` files. Only our segment temp + ' files match the prefix, so this never touches other tmp: data. + function CleanupTempSegments() as void + listing = m.fs.GetDirectoryListing("tmp:/") + if not IsArray(listing) + return + end if + for each name in listing + if IsString(name) and name.StartsWith("live-seg-") + DeleteFile(`tmp:/${name}`) + end if + end for + end function + + ' Start an async fetch of one YouTube live fragment (`&sq=N`) to a unique + ' temp file. Returns the in-flight request plus the context the failure + ' telemetry needs (v, itag, segUrl). The request is already sent (Send), so + ' callers can start a whole group before awaiting any of them. + function StartSegmentFetch(baseUrl as string, sq as integer, v as string, itag as string) as object + ' Plain concat: the base url is already a fully signed googlevideo url + ' (it has a query string), so appending &sq/&rn is safe. Must NOT route + ' through UrlUtils here - re-parsing/re-encoding the query breaks the + ' signature (sig/n) and googlevideo returns 403; it is also far slower. + segUrl = `${baseUrl}&sq=${sq}&rn=0` + tmpPath = `tmp:/live-seg-${StringUtils.RandomId()}.m4s` + req = HttpClient.Get(segUrl).ToFile(tmpPath).NoCache().Send() + return { req: req, tmpPath: tmpPath, sq: sq, v: v, itag: itag, segUrl: segUrl } + end function + + ' Await a fetch started by StartSegmentFetch and return just the bytes Roku + ' needs: + ' wantInit = true -> ftyp+moov (init segment) + ' wantInit = false -> moof+mdat (media segment) + ' Reads only the required byte range from the temp file and always deletes + ' it. Returns invalid on failure. + function AwaitTransformedSegment(entry as object, wantInit as boolean) as dynamic + tmpPath = entry.tmpPath + sq = entry.sq + + response = entry.req.Await() + if not response.IsSuccess() + LogErrorNoTelemetry("[LIVE-SEG] fetch sq", sq, "failed:", response.StatusCode()) + m.ReportSegmentFailure("fragment fetch failed", { v: entry.v, itag: entry.itag, sq: sq, segUrl: entry.segUrl, response: response }) + DeleteFile(tmpPath) + return invalid + end if + + stat = m.fs.Stat(tmpPath) + fileLen = 0 + if IsAssociativeArray(stat) + fileLen = ValidInt(stat.size) + end if + if fileLen <= 0 + LogErrorNoTelemetry("[LIVE-SEG] fetch sq", sq, "empty file") + m.ReportSegmentFailure("empty fragment file", { v: entry.v, itag: entry.itag, sq: sq, segUrl: entry.segUrl, response: response }) + DeleteFile(tmpPath) + return invalid + end if + + boxes = m.LocateBoxes(tmpPath, fileLen) + + out = CreateObject("roByteArray") + if wantInit + if boxes.moovEnd <= 0 or boxes.moovEnd > fileLen + LogErrorNoTelemetry("[LIVE-SEG] no moov in fragment sq", sq, "(moovEnd:", boxes.moovEnd, ")") + m.ReportSegmentFailure("no moov in fragment", { v: entry.v, itag: entry.itag, sq: sq, segUrl: entry.segUrl, response: response }) + DeleteFile(tmpPath) + return invalid + end if + out.ReadFile(tmpPath, 0, boxes.moovEnd) + else + if boxes.moofStart <= 0 or boxes.moofStart >= fileLen + LogErrorNoTelemetry("[LIVE-SEG] no moof in fragment sq", sq, "(moofStart:", boxes.moofStart, ")") + m.ReportSegmentFailure("no moof in fragment", { v: entry.v, itag: entry.itag, sq: sq, segUrl: entry.segUrl, response: response }) + DeleteFile(tmpPath) + return invalid + end if + out.ReadFile(tmpPath, boxes.moofStart, fileLen - boxes.moofStart) + end if + + DeleteFile(tmpPath) + return out + end function + + ' Read the leading boxes of a fragment temp file and return moov/moof offsets. + ' Starts with m.probeByteCount; if moof falls past the probe (a moov larger + ' than expected), grow the probe (doubling, capped by file size and + ' MAX_PROBE_BYTE_COUNT) and re-walk. A successful grow persists to + ' m.probeByteCount so the rest of the session reads the larger window in one + ' shot - the common (small-moov) case still does a single 2 KB read. + function LocateBoxes(tmpPath as string, fileLen as integer) as object + probeByteCount = m.probeByteCount + if probeByteCount > fileLen + probeByteCount = fileLen + end if + + boxes = {} + while true + head = CreateObject("roByteArray") + head.ReadFile(tmpPath, 0, probeByteCount) + boxes = m.WalkBoxes(head) + + ' Self-initializing fragment = ftyp+moov+emsg+moof+mdat, so both + ' offsets are present once the probe reaches moof. If the probe already + ' covers the whole file (or we've hit the ceiling), stop regardless - + ' a still-missing box is a genuine "no moof/moov", reported by caller. + foundBoth = boxes.moovEnd > 0 and boxes.moofStart > 0 + if foundBoth or probeByteCount >= fileLen or probeByteCount >= m.MAX_PROBE_BYTE_COUNT + exit while + end if + + nextByteCount = probeByteCount * 2 + if nextByteCount > fileLen + nextByteCount = fileLen + end if + if nextByteCount > m.MAX_PROBE_BYTE_COUNT + nextByteCount = m.MAX_PROBE_BYTE_COUNT + end if + ' Persist the grown probe for subsequent fragments this session. + probeByteCount = nextByteCount + m.probeByteCount = probeByteCount + LogWarnNoTelemetry("[LIVE-SEG] moof past probe; grew probe to", probeByteCount, "bytes") + end while + + return boxes + end function + + ' Emit a rich, actionable telemetry event for a live-segment failure. The + ' per-failure console logs above stay terse; this carries the detail needed to + ' diagnose a YouTube-side break: video id, itag, sq, status code, error message, + ' and the (signed) segment url. + ' + ' `info` keys (all optional): v, itag, sq, segUrl, response. + ' + ' Deduped to one event per (reason, status) per video session: enough to + ' capture a transient blip and a later persistent failure separately, without + ' flooding identical failures every few seconds (Sentry quota). Re-armed per + ' video in RebuildLiveCache. + function ReportSegmentFailure(reason as string, info as object) as void + statusText = "n/a" + errorMessage = "" + response = info.response + if response <> invalid + statusText = Str(response.StatusCode()).Trim() + errorMessage = ValidString(response.ErrorMessage(false)) + end if + + dedupeKey = `${reason}:${statusText}` + if m.reportedFailures.DoesExist(dedupeKey) + return + end if + m.reportedFailures[dedupeKey] = true + + details = [ + "reason: " + reason + "videoId: " + ValidString(info.v) + "itag: " + ValidString(info.itag) + "sq: " + ToString(info.sq) + "status: " + statusText + "error: " + errorMessage + "url: " + ValidString(info.segUrl) + ] + + LogTelemetryEvent({ + level: "error" + message: `[LIVE-SEG] ${reason} (status ${statusText})` + fingerprint: ["live-seg fetch failure", reason] + attachments: [{ + filename: "live-seg-failure.txt" + content_type: "text/plain" + data: details.Join(Chr(10)) + }] + }) + end function + + ' Walk top-level ISO-BMFF boxes from the front, returning the byte offset + ' where moov ends and where moof starts. Stops at moof, so it only ever + ' reads the small leading boxes - never the large mdat. + function WalkBoxes(bytes as object) as object + moovEnd = 0 + moofStart = 0 + count = bytes.Count() + i = 0 + while i + 8 <= count + ' 32-bit big-endian box size. Leading boxes are small, so this + ' arithmetic is overflow-safe. + size = (bytes[i] * 16777216) + (bytes[i + 1] * 65536) + (bytes[i + 2] * 256) + bytes[i + 3] + if size <= 0 + exit while + end if + ' Box type chars: 'm'=109 'o'=111 'v'=118 'f'=102. Compare the raw + ' bytes (cheaper than building a string per box). + b4 = bytes[i + 4] + b5 = bytes[i + 5] + b6 = bytes[i + 6] + b7 = bytes[i + 7] + if b4 = 109 and b5 = 111 and b6 = 111 ' "moo*" + if b7 = 118 ' "moov" + moovEnd = i + size + else if b7 = 102 ' "moof" + moofStart = i + exit while + end if + end if + i += size + end while + return { moovEnd: moovEnd, moofStart: moofStart } + end function + end class end namespace