diff --git a/CHANGELOG.md b/CHANGELOG.md index de4ba39d..4c8eadd6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Backend changes from Invidious to Playlet if no instance url is set. This is to avoid playback errors. +### Fixed + +- Various Live stream improvements, streamed directly without local proxy, attempt to reduce errors and stutters. + ## [0.48.7] - 2026-10-05 ### Added diff --git a/integration-tests/vpd-player-live.ts b/integration-tests/vpd-player-live.ts index 0cae1753..66b9fa96 100644 --- a/integration-tests/vpd-player-live.ts +++ b/integration-tests/vpd-player-live.ts @@ -1,6 +1,6 @@ // VideoPlayerDev live e2e: on the trackbar, OK toggles the HUD without pausing (stock live faithfulness); -// Rewind enters the live-DVR ladder. Live streams are unstable, so this skips cleanly when none is available -// and the DVR-ladder checks are soft (a stream may expose no DVR window). +// Rewind enters the live-DVR ladder: every live stream rewinds (the generated DASH lists everything since the +// stream's start, up to 12h). Live streams are unstable, so this skips cleanly when none is available. // // cd references/playlet-legacy && npx tsx ./integration-tests/vpd-player-live.ts // PLAYER_LIVE_ID= npx tsx ./integration-tests/vpd-player-live.ts # override the stream @@ -40,9 +40,9 @@ import { getLiveVideoId } from './live-id'; await expectField('#Chrome.opacity', 0); await expectField('#VideoPlayer.state', 'playing'); - group('Rewind enters the live-DVR ladder (soft — needs a DVR window)'); + group('Rewind enters the live-DVR ladder'); await press(Key.Rewind); - await expectSoft('#trickPlayBar.transportMode', (v) => v === Mode.liveDvr, 'rewind -> liveDvr'); + await expectField('#trickPlayBar.transportMode', Mode.liveDvr); await expectSoft('#trickPlayBar.glyph', (v) => v !== Glyph.none, 'rewind glyph present'); await expectSoft('#bifDisplay.visible', (v) => v === true, 'bif shows in liveDvr'); @@ -53,8 +53,8 @@ import { getLiveVideoId } from './live-id'; // Pause a live stream, let the edge run on, resume -> you're behind the edge, so the badge swaps "● LIVE" for // the time-behind offset. The brain drops off the edge the moment the device reports the user pause // (pausing live IS falling behind); the offset reads out once the post-resume duration catch-up lands. - // Soft: needs a real DVR/pause window and a few seconds of wall clock. - group('pause -> resume drops off the live edge and shows the offset (soft — needs DVR window)'); + // Soft: the pause keypress can race the device. + group('pause -> resume drops off the live edge and shows the offset'); await waitFor('#VideoPlayer.state', (v) => v === 'playing', 'settle the commit-to-live seek before pausing'); const durBefore = Number(await field('#VideoPlayer.duration')); // verified toggle: a single ECP Play can land out of phase (eaten/raced), inverting every check after it. diff --git a/playlet-lib/src/components/Logger/Logger.bs b/playlet-lib/src/components/Logger/Logger.bs index 38cbbad3..da864457 100644 --- a/playlet-lib/src/components/Logger/Logger.bs +++ b/playlet-lib/src/components/Logger/Logger.bs @@ -154,7 +154,7 @@ function GetSysLogUrlType(url as dynamic) as string if url.InStr("/api/timedtext") <> -1 or url.InStr("/api/v1/captions/") <> -1 return SysLogUrlType.Captions end if - if url.InStr("/videoplayback") <> -1 or url.InStr("/api/dash/live-seg") <> -1 + if url.InStr("/videoplayback") <> -1 return SysLogUrlType.VideoPlayback end if if url.InStr("/api/manifest/") <> -1 or url.InStr("/api/dash") <> -1 or url.InStr("/api/hls") <> -1 diff --git a/playlet-lib/src/components/Services/Dash/DashManifest.bs b/playlet-lib/src/components/Services/Dash/DashManifest.bs index fc844ece..e9cb0e75 100644 --- a/playlet-lib/src/components/Services/Dash/DashManifest.bs +++ b/playlet-lib/src/components/Services/Dash/DashManifest.bs @@ -1,20 +1,24 @@ +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 - ' 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 = "" - ' Backend the metadata came from, echoed onto every live-seg URL so the - ' DashRouter cache keys on it without reading the prefs node. Set by DashRouter. - public liveBackend as string = "" private canDecodeAv1Cache as dynamic function new(invidiousInstance as string, disableAutoDubbed = false as boolean) @@ -47,15 +51,7 @@ class DashManifest adaptiveFormats.Append(metadata.adaptiveFormats) if local and m.invidiousInstance <> Invidious.PLAYLET_BUILT_IN_INSTANCE - parsedInvidiousUrl = UrlUtils.ParseUrl(m.invidiousInstance) - for i = 0 to adaptiveFormats.Count() - 1 - if StringUtils.IsNullOrEmpty(adaptiveFormats[i].url) - continue for - end if - parsedUrl = UrlUtils.ParseUrl(adaptiveFormats[i].url) - parsedInvidiousUrl.path = UrlUtils.AppendQueryParams(parsedUrl.path, { host: parsedUrl.host }) - adaptiveFormats[i].url = UrlUtils.BuildUrlFromParts(parsedInvidiousUrl) - end for + adaptiveFormats = m.ProxyFormatsThroughInvidious(adaptiveFormats) end if duration = m.GetDuration(metadata) @@ -104,27 +100,21 @@ class DashManifest "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" } - nowUtc = "" if isLive - dvrWindowSec = ValidInt(metadata.liveDvrWindowSec) mpdAttributes["profiles"] = "urn:mpeg:dash:profile:isoff-live:2011" mpdAttributes["type"] = "dynamic" - ' Roku needs an authoritative "now" to track the live edge from wall-clock; UTCTiming + - ' publishTime carry the current UTC, restamped each refresh. - nowUtc = CreateObject("roDateTime").ToISOString() - mpdAttributes["publishTime"] = nowUtc - ' 20s: the duration SegmentTemplate extrapolates the edge between refreshes. - mpdAttributes["minimumUpdatePeriod"] = "PT20S" - ' Cushion already lives in availabilityStartTime; present at minBufferTime. - mpdAttributes["suggestedPresentationDelay"] = mpdAttributes["minBufferTime"] - if not StringUtils.IsNullOrEmpty(metadata.liveCushionedAvailabilityStartUtc) - mpdAttributes["availabilityStartTime"] = metadata.liveCushionedAvailabilityStartUtc - end if - if dvrWindowSec > 0 - ' Seekable range = window - cushion; the player's DVR floor uses the same value. - mpdAttributes["timeShiftBufferDepth"] = `PT${ValidInt(metadata.liveSeekableWindowSec)}S` + 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 - LogWarn("Live stream has no DVR window; omitting timeShiftBufferDepth (live seek may fail). videoId:", metadata.videoId) + 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" @@ -151,7 +141,7 @@ class DashManifest if isLive xml.EmptyNode("UTCTiming", { "schemeIdUri": "urn:mpeg:dash:utc:direct:2014" - "value": nowUtc + "value": LIVE_NOW_TOKEN }) end if xml.End() @@ -159,6 +149,26 @@ class DashManifest 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 @@ -172,36 +182,72 @@ class DashManifest return ValidInt(metadata["lengthSeconds"]) end function - ' DASH segment number at availabilityStartTime (the DVR-window anchor, not - ' genesis). The segments map 1:1 to native fragments, so it's the live-edge - ' fragment (headSeqnum) minus the window's worth of fragments. Clamped to 0 for - ' young streams whose history is shorter than the window. - function GetLiveStartNumber(metadata as object, durationMs as integer) as integer - headSeqnum = ValidInt(metadata.liveHeadSeqnum) - windowSec = ValidInt(metadata.liveDvrWindowSec) - if headSeqnum <= 0 or durationMs <= 0 - return 0 - end if - startNumber = headSeqnum - (windowSec * 1000 \ durationMs) - if startNumber < 0 - return 0 - end if - return startNumber + ' `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 - ' Effective per-native-fragment duration (ms) for live. Prefers the value - ' derived from the live head (headTime/headSeqnum, set by GetLiveStreamInfo); - ' 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 + ' 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 @@ -626,35 +672,27 @@ class DashManifest 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) one native fragment per DASH - ' segment, addressed by itag + DASH segment number ($Number$, == native sq). - ' Per-fragment duration. 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) - ' availabilityStartTime is anchored to the DVR window, not genesis (see - ' GetLiveStreamInfo), so segment 0 is no longer the live edge's ancestor. - ' Shift startNumber to the segment at that anchor (live-edge fragment minus - ' the window) so the wall-clock -> $Number$ -> sq mapping stays on the edge. - startNumber = m.GetLiveStartNumber(metadata, durationMs) - ' 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}&backend=${m.liveBackend}` - xml.EmptyNode("SegmentTemplate", { - "initialization": `${segBase}&init=true` - "media": `${segBase}&sq=$Number$` - "timescale": "1000" - "duration": durationMs - "startNumber": startNumber.ToStr() - }) + ' 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)) diff --git a/playlet-lib/src/components/Services/Dash/LiveTimeline.types.bs b/playlet-lib/src/components/Services/Dash/LiveTimeline.types.bs new file mode 100644 index 00000000..aef9c84d --- /dev/null +++ b/playlet-lib/src/components/Services/Dash/LiveTimeline.types.bs @@ -0,0 +1,14 @@ +' Segments fromSeqnum up to the next run's fromSeqnum, each durationMs long, the first +' starting at startMs on the live timeline. A run starts at or after the previous one's end. +interface LiveDurationRun + fromSeqnum as integer + startMs as integer + durationMs as integer +end interface + +' A live head check: seqnum -1 and timeMs invalid when the response lacks them. +interface LiveHeadReading + seqnum as integer + timeMs as dynamic + response as object +end interface diff --git a/playlet-lib/src/components/Services/Innertube/LiveStreamInfo.bs b/playlet-lib/src/components/Services/Innertube/LiveStreamInfo.bs index aec75933..343e1003 100644 --- a/playlet-lib/src/components/Services/Innertube/LiveStreamInfo.bs +++ b/playlet-lib/src/components/Services/Innertube/LiveStreamInfo.bs @@ -1,5 +1,5 @@ -import "pkg:/components/Services/Innertube/Context.bs" import "pkg:/source/services/HttpClient.bs" +import "pkg:/source/utils/MathUtils.bs" import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/UrlUtils.bs" @@ -8,146 +8,175 @@ import "pkg:/source/utils/UrlUtils.bs" ' under INT32_MAX (~24.8 days at timescale=1000). YouTube caps live DVR at 12h. const LIVE_MAX_DVR_WINDOW_SEC = 43200 -' Hold the live edge this many fragments behind the head so a momentary edge-miss refetches -' instead of erroring. Baked into liveCushionedAvailabilityStartUtc. 0 = ride the head. -const LIVE_EDGE_CUSHION_SEGMENTS = 3 +' videoDetails.liveChunkReadahead when /player omits it: what YouTube sends for normal +' and low latency streams. +const LIVE_DEFAULT_CHUNK_READAHEAD = 3 +' liveChunkReadahead is clamped to at least 3 seconds' worth and at most this many segments. +const LIVE_MAX_CHUNK_READAHEAD = 8 namespace Innertube ' 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. + ' adaptiveFormats with a `targetDurationSec` and segments addressed by `&sq=N`. + ' The generated dynamic DASH manifest lists the segments that exist (a + ' SegmentTimeline ending behind the live head, see DashManifest), anchored here once + ' per video load: availabilityStartTime and the segment numbering must not change + ' across manifest refreshes. ' - ' Backend-agnostic: works off the signed `adaptiveFormats[0].url` alone. The - ' innertube path passes its `client`/`cpn` (so the HEAD carries innertube - ' headers); the Invidious path passes invalid for both - the url is already - ' signed and googlevideo returns the X-Head-* headers regardless. - function GetLiveStreamInfo(parsedResponse as object, adaptiveFormats as object, cpn as dynamic, client as dynamic, cancellation as object) as void - if adaptiveFormats.Count() = 0 - LogWarn("GetLiveStreamInfo: No adaptive formats available") + ' Works off the signed `adaptiveFormats[0].url` alone: googlevideo answers the head + ' check with the X-Head-* headers whatever the backend. Without them there is no + ' timeline to list, so the load fails with the cause in parsedResponse.error. + function GetLiveStreamInfo(parsedResponse as object, adaptiveFormats as object, chunkReadahead as integer, cpn as dynamic, cancellation as object) as void + if adaptiveFormats.Count() = 0 or StringUtils.IsNullOrEmpty(adaptiveFormats[0]["url"]) + parsedResponse["error"] = "Live stream has no format url to read its head from" return end if - url = adaptiveFormats[0]["url"] - if StringUtils.IsNullOrEmpty(url) - LogWarn("GetLiveStreamInfo: URL is empty") - return - end if - - maxDvrDurationSec = ValidInt(adaptiveFormats[0]["maxDvrDurationSec"]) - - ' HEAD the base url with NO `sq`: that queries the stream's live edge and - ' returns the X-Head-* headers (X-Head-Seqnum / X-Head-Time-Sec). Pinning - ' `sq=0` instead makes googlevideo answer about segment 0 specifically, and for - ' some streams (observed targetDurationSec=5) it then omits X-Head-* entirely - ' (only X-Sequence-Num/X-Walltime-Ms) - which left availabilityStartTime unset - ' and Roku failed with "availabilityStartTime not available for live stream". - queryComponents = UrlUtils.ParseQueryComponents(url) - queryComponents["rn"] = "0" - if not StringUtils.IsNullOrEmpty(cpn) - queryComponents["cpn"] = cpn - end if - - url = UrlUtils.SetQueryParams(url, queryComponents) - - request = HttpClient.Head(url) - if client <> invalid - requestHeaders = Innertube.CreateHeaders(client) - else - requestHeaders = {} - end if - requestHeaders["origin"] = "https://www.youtube.com" - requestHeaders["referer"] = "https://www.youtube.com" - requestHeaders["DNT"] = "?1" - request.Headers(requestHeaders) - + headUrl = GetLiveHeadUrl(adaptiveFormats[0]["url"], cpn) + request = CreateLiveHeadRequest(headUrl) request.TryCount(2) + request.RetryCallback(function(context as object) as boolean + response = context.response + return Innertube.ReadLiveHeadSeqnum(response) < 0 or (Innertube.ReadLiveHeadTimeMs(response) = invalid and Innertube.ReadLiveHeadTimeSecAsMs(response) = invalid) + end function) request.Cancellation(cancellation) response = request.Await() - ' Do NOT gate on HTTP status. A no-sq HEAD that queries the live edge can come - ' back non-2xx yet still carry the X-Head-* headers we need (observed: one - ' stream returns 500, another 200; both include them). Read the headers - ' regardless and only bail if they're genuinely absent (e.g. a network error - ' with no response at all). - headers = response.Headers() - - if not headers.DoesExist("X-Head-Seqnum") - LogErrorNoTelemetry("[LIVE-INFO] No X-Head-Seqnum in response (HTTP " + ValidInt(response.StatusCode()).ToStr() + ")", url, headers) + headSeqnum = ReadLiveHeadSeqnum(response) + headTimeMs = ReadLiveHeadTimeMs(response) + averagedTimeMs = headTimeMs + if averagedTimeMs = invalid + averagedTimeMs = ReadLiveHeadTimeSecAsMs(response) + end if + if headSeqnum < 0 or averagedTimeMs = invalid + parsedResponse["error"] = `Live stream head check returned no X-Head-Seqnum / X-Head-Time (HTTP ${response.StatusCode()})\n${response.ErrorMessage(false)}` return end if - headSeqnum = ValidString(headers["X-Head-Seqnum"]).ToInt() - ' Head time: NEVER parse X-Head-Time-Millis with .ToInt(). For a long-running - ' 24/7 stream (e.g. 76 days = 6.58e9 ms) it overflows BrightScript's 32-bit - ' int, corrupting both the genesis anchor AND the derived fragment duration - ' (seen as a bogus 327ms vs the real 1000ms). Prefer X-Head-Time-Sec - ' (~6.58e6, fits int32, equals X-Head-Seqnum here at 1 fragment/second); if - ' only millis is present, ParseJson decodes it as a 64-bit double untruncated. - if headers.DoesExist("X-Head-Time-Sec") - headTimeSec = ValidString(headers["X-Head-Time-Sec"]).ToInt() - else if headers.DoesExist("X-Head-Time-Millis") - headTimeSec = Cint(StringUtils.ParseJsonSafe(ValidString(headers["X-Head-Time-Millis"])) / 1000.0) - else - LogErrorNoTelemetry("[LIVE-INFO] Missing X-Head-Time-Sec / -Millis in headers", url, headers) - return + now = CreateObject("roDateTime") + timeline = GetLiveTimeline(headSeqnum, averagedTimeMs, ValidInt(adaptiveFormats[0]["targetDurationSec"]), ValidInt(adaptiveFormats[0]["maxDvrDurationSec"]), chunkReadahead, now.AsSeconds(), now.GetMilliseconds()) + parsedResponse.Append(timeline) + parsedResponse["liveHeadUrl"] = headUrl + parsedResponse["liveHeadTimeMs"] = headTimeMs + end function + + ' The live timeline fields for a stream whose head (newest segment) is + ' `headSeqnum`, `headTimeMs` into the stream, observed at `nowSec`.`nowMs`. + function GetLiveTimeline(headSeqnum as integer, headTimeMs as dynamic, targetDurationSec as integer, maxDvrDurationSec as integer, chunkReadahead as integer, nowSec as integer, nowMs as integer) as object + ' Media time per segment: the head's stream time over its seqnum, the fragments' + ' cadence whatever targetDurationSec declares. + segmentDurationMs = 0 + if headSeqnum > 0 + segmentDurationMs = Cint(headTimeMs / headSeqnum) + end if + if segmentDurationMs <= 0 + segmentDurationMs = MathUtils.Max(targetDurationSec, 1) * 1000 end if - nowSec = CreateObject("roDateTime").AsSeconds() - ' Anchor availabilityStartTime to the DVR window, NOT the true stream genesis. - ' A 24/7 channel can be live for weeks; with timescale=1000 the player's - ' (now - availabilityStartTime) presentation time in ms then exceeds INT32_MAX - ' (~24.8 days) and the live-edge segment math wraps - the playhead falls back - ' near the period start, hours/days behind real time. Segments older than the - ' DVR window 404 anyway, so the window IS the real availability start. - ' DashManifest shifts startNumber to match this anchor. + ' The DVR window, in segments ending at the head: a 24/7 channel is anchored at the + ' window, not its genesis (see LIVE_MAX_DVR_WINDOW_SEC). A young stream has less + ' history than the window: it is anchored at its first segment (sq 0), and the + ' listed timeline grows into the window. windowSec = maxDvrDurationSec if windowSec <= 0 or windowSec > LIVE_MAX_DVR_WINDOW_SEC windowSec = LIVE_MAX_DVR_WINDOW_SEC end if - ' A young stream has less history than the DVR window. - if headTimeSec > 0 and windowSec > headTimeSec - windowSec = headTimeSec + windowSegments = MathUtils.Max(windowSec * 1000 \ segmentDurationMs, 1) + firstSeqnum = MathUtils.Max(headSeqnum - windowSegments + 1, 0) + + ' Distance the player stays behind the head: liveChunkReadahead segments of the + ' measured duration. A momentary head miss is absorbed instead of stalling at the + ' list end. + chunks = chunkReadahead + if chunks <= 0 + chunks = LIVE_DEFAULT_CHUNK_READAHEAD + end if + minChunks = MathUtils.Max((3000 + segmentDurationMs - 1) \ segmentDurationMs, 1) + chunks = MathUtils.Clamp(chunks, minChunks, LIVE_MAX_CHUNK_READAHEAD) + cushionMs = chunks * segmentDurationMs + ' A stream younger than the cushion plays at its head: a cushion reaching back to its + ' first segment fails the start (demux.dash -36, 2 of 4 starts, measured). + if cushionMs >= (headSeqnum - firstSeqnum + 1) * segmentDurationMs + cushionMs = 0 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. - fragmentDurationMs = 0 - if headSeqnum > 0 - fragmentDurationMs = Cint((headTimeSec / headSeqnum) * 1000.0) - end if - - astSec = nowSec - windowSec + ' Anchor: the head segment ends at (now - availabilityStartTime) + cushion, so the + ' player's clock edge sits a cushion behind the head. availabilityStartTime is + ' whole seconds; the sub-second remainder shifts the timeline instead. The window + ' never exceeds LIVE_MAX_DVR_WINDOW_SEC, so offsetting by it keeps `\` and `mod` + ' on a non-negative operand. + shiftedMs = LIVE_MAX_DVR_WINDOW_SEC * 1000 + nowMs + cushionMs - (headSeqnum - firstSeqnum + 1) * segmentDurationMs astDate = CreateObject("roDateTime") - astDate.FromSeconds(astSec) - cushionSec = Cint(LIVE_EDGE_CUSHION_SEGMENTS * fragmentDurationMs / 1000.0) - ' Younger than the cushion: shifting the anchor past now would break the edge math. - if cushionSec >= windowSec - cushionSec = 0 - end if - ' Shift the anchor later by the cushion so the computed edge lands a cushion behind the head. - cushionedAstDate = CreateObject("roDateTime") - cushionedAstDate.FromSeconds(astSec + cushionSec) - ' Window minus the cushion; the full window would seek below startNumber. - seekableWindowSec = windowSec - cushionSec + astDate.FromSeconds(nowSec - LIVE_MAX_DVR_WINDOW_SEC + shiftedMs \ 1000) - parsedResponse["liveHeadSeqnum"] = headSeqnum - ' The real (uncushioned) availabilityStartTime, kept for diagnostics. - parsedResponse["liveAvailabilityStartUtc"] = astDate.ToISOString() - parsedResponse["liveCushionedAvailabilityStartUtc"] = cushionedAstDate.ToISOString() - parsedResponse["liveDvrWindowSec"] = windowSec - parsedResponse["liveSeekableWindowSec"] = seekableWindowSec - if fragmentDurationMs > 0 - parsedResponse["liveFragmentDurationMs"] = fragmentDurationMs + return { + "liveHeadSeqnum": headSeqnum + "liveFirstSeqnum": firstSeqnum + "liveWindowSegments": windowSegments + "liveSegmentDurationMs": segmentDurationMs + "liveTimelineOffsetMs": shiftedMs mod 1000 + "liveAvailabilityStartUtc": astDate.ToISOString() + ' The player's seek floor: the window less the cushion, and less a segment for + ' the listed timeline's alignment (DashRouter.AlignLiveTimeline). + "liveSeekableWindowSec": MathUtils.Max((windowSegments - 1) * segmentDurationMs - cushionMs, 0) \ 1000 + } + end function + + ' The format url with NO `sq` queries the stream's live head: googlevideo answers + ' at once with the X-Head-* headers (X-Head-Seqnum = newest available segment). + ' Pinning `sq=0` instead makes googlevideo answer about segment 0 specifically, and for + ' some streams (observed targetDurationSec=5) it then omits X-Head-* entirely + ' (only X-Sequence-Num/X-Walltime-Ms). + function GetLiveHeadUrl(formatUrl as string, cpn as dynamic) as string + queryComponents = UrlUtils.ParseQueryComponents(formatUrl) + queryComponents["rn"] = "0" + if not StringUtils.IsNullOrEmpty(cpn) + queryComponents["cpn"] = cpn end if + return UrlUtils.SetQueryParams(formatUrl, queryComponents) + end function + + function CreateLiveHeadRequest(headUrl as string) as object + request = HttpClient.Head(headUrl) + request.Headers({ + "origin": "https://www.youtube.com" + "referer": "https://www.youtube.com" + "DNT": "?1" + }) + return request + end function + + ' X-Head-Seqnum of a live head response, -1 if absent. Not gated on HTTP status: a + ' head check can come back non-2xx yet still carry the X-Head-* headers + ' (observed: one stream returns 500, another 200; both include them). + function ReadLiveHeadSeqnum(response as object) as integer + headers = response.Headers() + if not IsAssociativeArray(headers) or not headers.DoesExist("X-Head-Seqnum") + return -1 + end if + return ValidString(headers["X-Head-Seqnum"]).ToInt() + end function + + ' How far into the stream the head is (ms, X-Head-Time-Millis), invalid if absent. A + ' long-running stream's (e.g. 207 days = 1.79e10 ms) overflows BrightScript's 32-bit + ' int: ParseJson keeps it as a LongInteger, which .ToInt() and Cdbl() would truncate + ' (measured). + function ReadLiveHeadTimeMs(response as object) as dynamic + headers = response.Headers() + if not IsAssociativeArray(headers) + return invalid + end if + return StringUtils.ParseJsonSafe(ValidString(headers["X-Head-Time-Millis"])) + end function + + ' X-Head-Time-Sec in ms, invalid if absent: whole seconds, too coarse to average a + ' young stream's few segments or to time the head between checks. + function ReadLiveHeadTimeSecAsMs(response as object) as dynamic + headers = response.Headers() + if not IsAssociativeArray(headers) or not headers.DoesExist("X-Head-Time-Sec") + return invalid + end if + return ValidString(headers["X-Head-Time-Sec"]).ToInt() * 1000& end function end namespace diff --git a/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs b/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs index ef94d7e1..60c75be2 100644 --- a/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs @@ -200,7 +200,7 @@ namespace Innertube if isLive LogDebug("Fetching live stream info") - GetLiveStreamInfo(parsedResponse, adaptiveFormats, playerRequest.cpn, client, cancellation) + GetLiveStreamInfo(parsedResponse, adaptiveFormats, ValidInt(videoDetails["liveChunkReadahead"]), playerRequest.cpn, cancellation) end if return parsedResponse diff --git a/playlet-lib/src/components/Services/Invidious/InvidiousService.bs b/playlet-lib/src/components/Services/Invidious/InvidiousService.bs index 6036485d..5e7df7de 100644 --- a/playlet-lib/src/components/Services/Invidious/InvidiousService.bs +++ b/playlet-lib/src/components/Services/Invidious/InvidiousService.bs @@ -170,16 +170,18 @@ namespace Invidious end if metadata = response.Json() - ' Live videos need the same X-Head-* enrichment the innertube path does - ' (liveHeadSeqnum / liveAvailabilityStartUtc / liveDvrWindowSec / ...), - ' or the generated dynamic DASH manifest has no availabilityStartTime and - ' Roku fails with "availabilityStartTime not available for live stream". - ' The Invidious adaptiveFormats urls are already signed googlevideo urls, - ' so the shared helper works with no client/cpn. parser is set so the - ' manifest's diagnostic comment reflects the real source. - if IsAssociativeArray(metadata) and ValidBool(metadata.liveNow) and IsArray(metadata.adaptiveFormats) + if not IsAssociativeArray(metadata) + return metadata + end if + ' Playlet's built-in instance answers with innertube metadata, parser and live + ' timeline included; an Invidious server sends neither. + if StringUtils.IsNullOrEmpty(metadata["parser"]) metadata["parser"] = "invidious" - Innertube.GetLiveStreamInfo(metadata, metadata.adaptiveFormats, invalid, invalid, cancellation) + end if + ' The Invidious adaptiveFormats urls are already signed googlevideo urls; + ' Invidious sends no chunk readahead or cpn. + if Invidious.NeedsLiveStreamInfo(metadata) + Innertube.GetLiveStreamInfo(metadata, metadata.adaptiveFormats, 0, invalid, cancellation) end if return metadata @@ -812,4 +814,10 @@ namespace Invidious end function end class + ' Whether a /videos response is a live video still missing the live timeline the + ' innertube path gets: the built-in instance's responses carry it already. + function NeedsLiveStreamInfo(metadata as object) as boolean + return ValidBool(metadata.liveNow) and IsArray(metadata.adaptiveFormats) and StringUtils.IsNullOrEmpty(metadata.liveHeadUrl) + end function + end namespace diff --git a/playlet-lib/src/components/VideoPlayer/VideoContentJob.bs b/playlet-lib/src/components/VideoPlayer/VideoContentJob.bs index 86df4a56..1e63973b 100644 --- a/playlet-lib/src/components/VideoPlayer/VideoContentJob.bs +++ b/playlet-lib/src/components/VideoPlayer/VideoContentJob.bs @@ -122,17 +122,19 @@ function ExecuteJob() as void end if contentNode.live = metadata.liveNow + ' Identifies this video load (one metadata fetch). + videoLoadId = StringUtils.RandomId() if metadata.error <> invalid ' Adding metadata allows us to play next recommended video after displaying the error - contentNode.addFields({ metadata: metadata }) + contentNode.addFields({ metadata: metadata, videoLoadId: videoLoadId }) JobError(metadata.error) return end if streamSource = SelectStreamSource(metadata) - streamUrls = CreateStreamUrls(streamSource, metadata, service, preferencesNode, backend, playletServerPort) + streamUrls = CreateStreamUrls(streamSource, metadata, videoLoadId, service, preferencesNode, backend, playletServerPort) if streamUrls.Count() = 0 - contentNode.addFields({ metadata: metadata }) + contentNode.addFields({ metadata: metadata, videoLoadId: videoLoadId }) error = "No playable streams found for this video." lastPlayerResponse = ValidString(ReadAsciiFile("cachefs:/last_player_response.json")) LogTelemetryEvent({ @@ -170,6 +172,7 @@ function ExecuteJob() as void contentNode.ForwardQueryStringParams = false contentNode.addFields({ metadata: metadata + videoLoadId: videoLoadId ' StreamUrls is taken playletStreamUrls: streamUrls playletStreamUrlIndex: 0 @@ -279,7 +282,7 @@ function SelectStreamSource(metadata as object) as string return StreamSource.None end function -function CreateStreamUrls(source as string, metadata as object, service as Invidious.InvidiousService, preferences as object, backend as string, playletServerPort as integer) as object +function CreateStreamUrls(source as string, metadata as object, videoLoadId as string, service as Invidious.InvidiousService, preferences as object, backend as string, playletServerPort as integer) as object instance = service.GetInstance() proxyVideos = preferences["invidious.proxy_videos"] preferredQuality = preferences["playback.preferred_quality"] @@ -292,7 +295,7 @@ function CreateStreamUrls(source as string, metadata as object, service as Invid }) streamUrls.push(dashUrl) else if source = StreamSource.AdaptiveFormats - AddDashUrls(streamUrls, metadata, preferredQuality, backend, proxyVideos, playletServerPort) + AddDashUrls(streamUrls, metadata, videoLoadId, preferredQuality, backend, proxyVideos, playletServerPort) else if source = StreamSource.FormatStreams for each stream in metadata.formatStreams if StringUtils.IsNullOrEmpty(stream.url) @@ -385,12 +388,12 @@ function AddHlsUrls(streamUrls as object, metadata as object, preferredQuality a AddUrls(streamUrls, hlsUrl, hlsUrlLocal, hlsUrlFiltered, hlsUrlFilteredLocal, proxyVideos) end function -function AddDashUrls(streamUrls as object, metadata as object, preferredQuality as string, backend as string, proxyVideos as string, playletServerPort as integer) as void +function AddDashUrls(streamUrls as object, metadata as object, videoLoadId as string, preferredQuality as string, backend as string, proxyVideos as string, playletServerPort as integer) as void ' Redirect to Playet's local web server, where will will be ' dynamically generating the DASH manifest, and filter quality dashUrl = UrlUtils.AppendQueryParams(`http://127.0.0.1:${playletServerPort}/api/dash`, { v: metadata.videoId - backend: backend + "videoLoadId": videoLoadId }) dashUrlLocal = invalid diff --git a/playlet-lib/src/components/VideoPlayer/VideoPlayer.bs b/playlet-lib/src/components/VideoPlayer/VideoPlayer.bs index 32177fec..147cb6b7 100644 --- a/playlet-lib/src/components/VideoPlayer/VideoPlayer.bs +++ b/playlet-lib/src/components/VideoPlayer/VideoPlayer.bs @@ -607,6 +607,11 @@ function ReportVideoError(errorData as object, url as dynamic, urls as object, u position = m.top.position duration = m.top.duration + videoLoadId = "" + content = m.top.content + if content <> invalid + videoLoadId = ValidString(content.videoLoadId) + end if message = [ errorData.title errorData.body @@ -616,6 +621,7 @@ function ReportVideoError(errorData as object, url as dynamic, urls as object, u `Url: ${url}` `Urls: ` + ToString(urls) `Url index: ${urlIndex}` + `video_load_id: ${videoLoadId}` ].Join(`\n`) errorData.fingerprint.push(shownInDialog) diff --git a/playlet-lib/src/components/VideoPlayerDev/PlaybackTelemetry.bs b/playlet-lib/src/components/VideoPlayerDev/PlaybackTelemetry.bs index 1879ba02..1c8f9fa6 100644 --- a/playlet-lib/src/components/VideoPlayerDev/PlaybackTelemetry.bs +++ b/playlet-lib/src/components/VideoPlayerDev/PlaybackTelemetry.bs @@ -32,6 +32,13 @@ namespace PlaybackTelemetry return "unknown" end function + function ContentVideoLoadId(content as object) as string + if content = invalid + return "" + end if + return ValidString(content.videoLoadId) + end function + ' The summary's wire rule: false, 0, "", [] and invalid are omitted, at every depth; a reader takes an absent ' field as that default. function OmitDefaults(value as dynamic) as dynamic @@ -254,6 +261,7 @@ namespace PlaybackTelemetry `logged_in: ${loggedIn}` `backend: ${backend}` `is_live: ${isLive}` + `video_load_id: ${PlaybackTelemetry.ContentVideoLoadId(content)}` ].Join(Chr(10)) fingerprint = [ Locale.VideoPlayer.ErrorPlayingVideo @@ -300,6 +308,7 @@ namespace PlaybackTelemetry summary = { "live": m.transport.isLive "backend": PlaybackTelemetry.ContentBackend(content) + "video_load_id": PlaybackTelemetry.ContentVideoLoadId(content) "outcome": m.outcome "metadata_done_at_ms": m.metadataDoneAtMs "first_playing_at_ms": m.firstPlayingAtMs diff --git a/playlet-lib/src/components/VideoPlayerDev/TransportController.bs b/playlet-lib/src/components/VideoPlayerDev/TransportController.bs index 27839973..7b7af75f 100644 --- a/playlet-lib/src/components/VideoPlayerDev/TransportController.bs +++ b/playlet-lib/src/components/VideoPlayerDev/TransportController.bs @@ -94,9 +94,6 @@ namespace TransportController ' not a seek into the last instants (which just re-buffers and fights the device's EOF auto-resume). ' Matches the SponsorBlock finish rule (SkipTargetForSegment). const FINISH_EPSILON_MS = 2000 - ' Live streams whose DVR window is under this are treated as NOT rewindable (a ~30s window is just the - ' buffer): the rewind/scan/replay commands are ignored and the bar drops the "Rewind live TV" label. - const LIVE_REWIND_MIN_WINDOW_MS = 60000 const REPLAY_TOAST_MS = 700 ' how long the transient InstantReplay icon stays before it self-clears ' "● LIVE" shows while the offset is within this jitter band of the inherent latency; beyond it the bar ' shows the time-behind. The clock-anchored edge advances smoothly, so this only needs to absorb position @@ -130,8 +127,7 @@ namespace TransportController isLive as boolean = false private hasStoryboards as boolean = false storyboardStepMs as integer = 2000 ' VOD per-tap step + scan base (storyboard L2 interval) - ' Live DVR window length (0 = unknown). The generated DASH anchors t=0 to the window start, so the - ' rewind floor is edge - window once the session outlives the window (content below it has expired). + ' Live DVR window length (0 = unknown); see LiveFloorMs. private dvrWindowMs as integer = 0 ' ---- inputs pushed by the coordinator (OnPosition / OnDuration / OnReady) ---- @@ -211,22 +207,9 @@ namespace TransportController end if end function - ' Whether this live stream is rewindable at all. The DVR window we receive is the same value the - ' generated DASH advertises as timeShiftBufferDepth, so this IS the manifest's signal: a tiny window - ' (~30s) is just the buffer, not a rewind feature. Unknown (0) assumes rewindable. - function CanRewindLive() as boolean - if not m.isLive - return false - end if - if m.dvrWindowMs <= 0 - return true - end if - return m.dvrWindowMs >= TransportController.LIVE_REWIND_MIN_WINDOW_MS - end function - - ' The rewind FLOOR: the oldest still-available position. t=0 is the window start at manifest build - ' time, so as the session outlives the window the floor advances (edge - window); 0 while unknown or - ' while the stream is younger than its window. + ' The rewind FLOOR: the oldest still-available position. t=0 is the oldest segment at manifest build + ' time (the stream's start on a stream younger than the window), so as the session outlives the window + ' the floor advances (edge - window); 0 while unknown or until then. function LiveFloorMs() as integer if m.dvrWindowMs <= 0 return 0 @@ -404,10 +387,6 @@ namespace TransportController return end if if m.isLive - ' a non-rewindable live stream (DVR window is just the buffer) takes no transport input. - if not m.CanRewindLive() - return - end if if command = TransportController.Command.Left m.LiveStep(-1) else if command = TransportController.Command.Right @@ -714,10 +693,7 @@ namespace TransportController function Replay() as void ' InstantReplay works from ANY state. From a transport (frozen) it cancels it and RESUMES from ' cursor-20s; from idle it just seeks -20s and keeps the play state. Reference is the cursor (= position - ' while idle). A non-rewindable live stream takes no replay either. - if m.isLive and not m.CanRewindLive() - return - end if + ' while idle). wasTransport = (m.transportMode <> TransportController.Mode.Idle) ' spamming InstantReplay must ACCUMULATE: while a prior replay seek is still in flight, base off the ' LAST target so each press goes another -20s, not off the stale position (all presses landing together). diff --git a/playlet-lib/src/components/VideoPlayerDev/TrickPlayBar/TrickPlayBar.bs b/playlet-lib/src/components/VideoPlayerDev/TrickPlayBar/TrickPlayBar.bs index 15363a9c..4b41dda8 100644 --- a/playlet-lib/src/components/VideoPlayerDev/TrickPlayBar/TrickPlayBar.bs +++ b/playlet-lib/src/components/VideoPlayerDev/TrickPlayBar/TrickPlayBar.bs @@ -26,7 +26,7 @@ function Init() ' language — "EN DIRECT" is far wider than "LIVE"); measured lazily, once. m.liveBadgeLaidOut = false - for each field in ["transportMode", "positionMs", "durationMs", "cursorMs", "isLive", "canRewind", "liveOffsetMs", "atLiveEdge", "forceLiveBadge"] + for each field in ["transportMode", "positionMs", "durationMs", "cursorMs", "isLive", "liveOffsetMs", "liveFloorMs", "atLiveEdge", "forceLiveBadge"] m.top.ObserveField(field, FuncName(Repaint)) end for m.top.ObserveField("focused", FuncName(OnFocusChange)) @@ -84,12 +84,13 @@ function RenderLiveBar() as void ' moved yet at entry, so atLiveEdge alone would keep the badge up. showBadge = (m.top.atLiveEdge or m.top.forceLiveBadge) and not transportActive - ' Fill + playhead are proportional to the cursor's place in the DVR window [0, effEdge], where + ' Fill + playhead are proportional to the cursor's place in the reachable range [floor, effEdge], where ' effEdge = cursor + offset; at the edge the playhead sits at the right end and the fill clips rightward. - effEdge = m.top.cursorMs + m.top.liveOffsetMs + floor = m.top.liveFloorMs + span = m.top.cursorMs + m.top.liveOffsetMs - floor frac = 1.0 - if effEdge > 0 - frac = m.top.cursorMs / (effEdge * 1.0) + if span > 0 + frac = (m.top.cursorMs - floor) / (span * 1.0) end if if frac < 0 frac = 0 @@ -106,12 +107,7 @@ function RenderLiveBar() as void ' Handle raised for the bif while rewinding, resting at the edge otherwise. PositionHandle(transportActive) - ' the rewind hint only when the stream actually rewinds (a buffer-sized DVR window doesn't count). - if m.top.canRewind - m.currentLabel.text = m.rewindLiveText - else - m.currentLabel.text = "" - end if + m.currentLabel.text = m.rewindLiveText if showBadge m.remainingLabel.text = "" diff --git a/playlet-lib/src/components/VideoPlayerDev/TrickPlayBar/TrickPlayBar.spec.bs b/playlet-lib/src/components/VideoPlayerDev/TrickPlayBar/TrickPlayBar.spec.bs index f12ee6eb..87730676 100644 --- a/playlet-lib/src/components/VideoPlayerDev/TrickPlayBar/TrickPlayBar.spec.bs +++ b/playlet-lib/src/components/VideoPlayerDev/TrickPlayBar/TrickPlayBar.spec.bs @@ -150,17 +150,6 @@ namespace Tests m.assertFalse(m.top.findNode("liveLabel").visible) end function - @it("a NON-rewindable live stream (buffer-sized DVR window) drops the rewind label") - function _() - m.top.isLive = true - m.top.transportMode = TransportController.Mode.Idle - m.top.canRewind = false - m.assertEqual(m.top.findNode("currentLabel").text, "") - ' rewindable again (e.g. next content) -> the label returns - m.top.canRewind = true - m.assertEqual(m.top.findNode("currentLabel").text, Tr(Locale.VideoPlayer.RewindLiveTv)) - end function - @it("AT the edge: frac=1 -> playhead at 1130.87 (the exact at-edge stock pin) + ● LIVE") function _() m.top.isLive = true @@ -189,6 +178,21 @@ namespace Tests m.assertTrue(moved > 85 and moved < 105) ' ~1136.87/12 ≈ 95px end function + @it("starts the bar at the floor once the session outlives the window") + function _() + m.top.isLive = true + m.top.transportMode = TransportController.Mode.LiveDvr + m.top.atLiveEdge = false + m.top.liveFloorMs = 3600000 ' 1h into the session: the first hour has expired + m.top.cursorMs = 25200000 ' 7h + m.top.liveOffsetMs = 21600000 ' 6h behind -> edge 13h, halfway through [1h, 13h] + fill = m.top.findNode("trackFill") + m.assertTrue(Abs(fill.clippingRect.x - 0.5 * 1136.8679) < 0.5) + m.top.cursorMs = 3600000 ' at the floor + m.top.liveOffsetMs = 43200000 + m.assertEqual(fill.clippingRect.x, 0.0) + end function + @it("shows the ● LIVE badge only at the edge") function _() m.top.isLive = true diff --git a/playlet-lib/src/components/VideoPlayerDev/TrickPlayBar/TrickPlayBar.xml b/playlet-lib/src/components/VideoPlayerDev/TrickPlayBar/TrickPlayBar.xml index d95766bc..d0bbb3a2 100644 --- a/playlet-lib/src/components/VideoPlayerDev/TrickPlayBar/TrickPlayBar.xml +++ b/playlet-lib/src/components/VideoPlayerDev/TrickPlayBar/TrickPlayBar.xml @@ -1,16 +1,16 @@ + the bif. Left label = "Rewind live TV" on live; right label = offset M:SS when behind, or "● LIVE" + at the edge. --> - + diff --git a/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.bs b/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.bs index ed82ac7c..e2439619 100644 --- a/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.bs +++ b/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.bs @@ -289,6 +289,7 @@ function PushTransportToRenderers() as void m.trickPlayBar.durationMs = m.transport.durationMs if mode <> TransportController.Mode.Idle or isLive + m.trickPlayBar.liveFloorMs = m.transport.LiveFloorMs() m.trickPlayBar.cursorMs = m.transport.cursorMs m.trickPlayBar.liveOffsetMs = m.transport.liveOffsetMs m.trickPlayBar.atLiveEdge = m.transport.atLiveEdge @@ -1151,13 +1152,9 @@ function OnVideoContentJobDone(event as object) as void ' fill them in for VOD. isLive = content <> invalid and content.Live = true m.transport.SetContent(isLive, 2000, false) - ' live floor: how far back the DVR window reaches (0 = unknown -> the brain keeps the [0, edge] clamp). - ' The generated DASH anchors t=0 to the window start, so floor = edge - window as the session outlives it. - ' The same window decides rewindability: a buffer-sized window means no live trickplay at all. - ' Use the seekable depth (window - cushion) to match the manifest's timeShiftBufferDepth. + ' The seekable depth keeps the rewind floor on the manifest's listed segments (see Innertube.GetLiveTimeline). m.transport.SetLiveDvrWindow(ValidInt(metadata.liveSeekableWindowSec) * 1000) m.trickPlayBar.isLive = isLive - m.trickPlayBar.canRewind = m.transport.CanRewindLive() m.bifDisplay.tileSet = invalid ' anchor the live edge clock at the cushioned availabilityStartTime and start the 1s heartbeat: the brain @@ -1167,7 +1164,7 @@ function OnVideoContentJobDone(event as object) as void m.liveFallbackEdgeMs = -1 m.liveFallbackAtSeconds = 0 if isLive - ast = ValidString(metadata.liveCushionedAvailabilityStartUtc) + ast = ValidString(metadata.liveAvailabilityStartUtc) if ast <> "" astDate = CreateObject("roDateTime") astDate.FromISO8601String(ast) diff --git a/playlet-lib/src/components/VideoPlayerDev/tests/PlaybackTelemetryWiring.spec.bs b/playlet-lib/src/components/VideoPlayerDev/tests/PlaybackTelemetryWiring.spec.bs index 7d37f843..361939d9 100644 --- a/playlet-lib/src/components/VideoPlayerDev/tests/PlaybackTelemetryWiring.spec.bs +++ b/playlet-lib/src/components/VideoPlayerDev/tests/PlaybackTelemetryWiring.spec.bs @@ -24,6 +24,7 @@ namespace Tests content.addField("playletStreamUrls", "array", false) content.addField("playletStreamUrlIndex", "integer", false) content.addField("playletStreamSource", "string", false) + content.addField("videoLoadId", "string", false) content.setFields({ videoId: "vid1" backend: "playlet" @@ -31,6 +32,7 @@ namespace Tests playletStreamUrls: urls playletStreamUrlIndex: 0 playletStreamSource: "adaptiveFormats" + videoLoadId: "load1" }) m.top.content = content end function @@ -107,7 +109,7 @@ namespace Tests m.State(VideoState.Error) report = m.global.telemetry.LogEvent m.assertEqual(report.level, "warning", "retried: not shown to the viewer") - m.assertTrue(report.message.InStr("Url: http://a") > 0 and report.message.InStr("Url index: 0") > 0, "got: " + report.message) + m.assertTrue(report.message.InStr("Url: http://a") > 0 and report.message.InStr("Url index: 0") > 0, `got: ${report.message}`) m.State(VideoState.Playing) summary = m.Close() m.assertEqual(summary.error_count, 1) @@ -115,6 +117,17 @@ namespace Tests m.assertEqual(summary.outcome, "closed") end function + @it("the video load id joins the error report to the summary") + function _() + m.SetContent(["http://stream"]) + m.HttpError() + m.State(VideoState.Error) + report = m.global.telemetry.LogEvent + m.assertTrue(report.message.InStr("video_load_id: load1") > 0, `got: ${report.message}`) + summary = m.Close() + m.assertEqual(summary.video_load_id, "load1") + end function + @it("an error with no retry left ends in error") function _() m.SetContent(["http://stream"]) diff --git a/playlet-lib/src/components/VideoPlayerDev/tests/VideoPlayerDevMock.bs b/playlet-lib/src/components/VideoPlayerDev/tests/VideoPlayerDevMock.bs index 51311c15..fb41295d 100644 --- a/playlet-lib/src/components/VideoPlayerDev/tests/VideoPlayerDevMock.bs +++ b/playlet-lib/src/components/VideoPlayerDev/tests/VideoPlayerDevMock.bs @@ -115,13 +115,12 @@ function TestSetControl(value as string) as void m.top.control = value end function -' TestSetLive — flip the loaded content to a rewindable live stream with a known edge: what +' TestSetLive — flip the loaded content to a live stream with a known edge: what ' OnVideoContentJobDone does for real live content (SetContent + DVR window + bar fields), minus the job. function TestSetLive(edgeMs as integer) as void m.transport.SetContent(true, 2000, false) - m.transport.SetLiveDvrWindow(4 * 3600 * 1000) ' 4h window -> rewindable + m.transport.SetLiveDvrWindow(4 * 3600 * 1000) m.trickPlayBar.isLive = true - m.trickPlayBar.canRewind = m.transport.CanRewindLive() m.transport.OnLiveEdge(edgeMs) m.transport.OnPosition(edgeMs) end function diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs index 8e391ea6..ac824dbe 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs @@ -1,42 +1,23 @@ import "pkg:/components/Services/Dash/DashManifest.bs" +import "pkg:/components/Services/Dash/LiveTimeline.types.bs" +import "pkg:/components/Services/Innertube/LiveStreamInfo.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/MathUtils.bs" import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/Types.bs" -' How many DASH segments ahead to warm per representation. On a request for segment -' N we Send (without Await) the next few so their downloads overlap N's await + -' playback; when the player asks for them the Await is short/instant. Small on -' purpose to bound concurrent roUrlTransfers (x2 representations). -const LIVE_PREFETCH_SEGMENTS = 2 -' Immediate refetches (no sleep) for transient network errors (reset/5xx) before surfacing 503. -' 204/timeout/4xx surface at once: an in-handler sleep would stall the queued audio request ~600ms -' on the single thread (measured). -const LIVE_SEG_MAX_ATTEMPTS = 3 - -' Why a live-segment fetch failed. The string values double as the telemetry message -' and fingerprint (see ReportSegmentFailure), so they must stay stable - changing one -' forks its Bugsink issue and orphans the history. -enum LiveSegFailure - NoFormatUrl = "no live format url" - FormatsNotArray = "adaptiveFormats not an array" - FetchFailed = "fragment fetch failed" - EmptyFragment = "empty fragment file" - NoMoov = "no moov in fragment" - NoMoof = "no moof in fragment" -end enum +' Manifest requests closer together than this (Roku re-fetching after an error) share one live head check. +const LIVE_HEAD_MIN_INTERVAL_MS = 500 +' The manifest response waits on the head check; past this it lists the last known head. +const LIVE_HEAD_TIMEOUT_SECONDS = 2 +' Head time leaping this far past the listed timeline within one head check is a stall. +const LIVE_STALL_JUMP_MS = 10000 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() @@ -44,66 +25,53 @@ namespace Http 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.cachedBackend = invalid + ' Live manifests are re-fetched every `minimumUpdatePeriod`, and reading + ' metadata off the player's content is a cross-thread rendezvous that + ' deep-copies the whole (~39 KB) metadata AA. The metadata is immutable for a + ' video load, so it is cached per load, not per video: replaying a video (or + ' switching backends) pushes fresh metadata with re-signed urls for the same + ' video id. + m.cachedVideoLoadId = 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) - ' Prefetch cache: "itag|sq" -> in-flight StartSegmentFetch entry, - ' warmed ahead of the player so awaits hit already-downloading fragments. - m.prefetch = {} - ' Last itag served per media kind. When the player switches representation - ' (ABR video / audio track), the previous itag's warmed entries are evicted - ' so they don't leak until the next video change. - m.lastVideoItag = invalid - m.lastAudioItag = invalid - ' itag -> transformed init bytes (ftyp+moov). moov is constant per - ' representation, so fetch once and serve later init requests from memory. - ' Cleared per video in RebuildLiveCache. - m.cachedInit = {} - ' Highest native sq requested; sources the init from a current fragment (the - ' load-time live edge ages out of the DVR window over a long session). - m.lastSeenSq = 0 + m.liveHeadUrl = "" + m.liveHeadTimer = invalid ' since the last head check; invalid = never checked + m.liveHeadSeqnum = 0 + m.liveLoadHeadSeqnum = 0 + m.liveLoadHeadTimeMs = invalid + m.liveBaseSeqnum = 0 + m.liveBaseTimeMs = invalid + m.liveBaseEndMs = 0 + m.liveWindowMs = 0 + m.liveDurationRuns = [] ' LiveDurationRun[] + m.liveLeadMs = 0 + m.liveDriftMs = 0 + m.liveLastCheckJumped = false + m.reportedLiveCorrection = false + m.liveManifestTemplate = "" + m.liveManifestTemplateKey = invalid + m.reportedLiveHeadFailure = false 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, backend as string) as dynamic - ' Key on backend too, not just videoId: switching backends replays the - ' same videoId but pushes fresh metadata onto the content node (different - ' parser, different live fields). Keyed on videoId alone we'd keep serving - ' the previous backend's stale copy. The backend is carried on the request - ' query (set when the stream urls are built) so we never read the prefs - ' node on this hot path. - if m.cachedVideoId = v and m.cachedBackend = backend and IsAssociativeArray(m.cachedMetadata) + ' Returns the metadata of video load `videoLoadId`, or invalid when the player holds + ' another load. A new load also resets the live state. + function GetMetadata(videoLoadId as string) as dynamic + if m.cachedVideoLoadId = videoLoadId 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.cachedBackend = backend - m.RebuildLiveCache(metadata) + content = ObjectUtils.DigUnsafe(m.videoQueueNode, ["player", "content"]) + if content = invalid or ValidString(content.videoLoadId) <> videoLoadId + return invalid end if + metadata = content.metadata + m.cachedMetadata = metadata + m.cachedVideoLoadId = videoLoadId + m.ResetLiveState(metadata) return metadata end function @@ -117,65 +85,63 @@ namespace Http return m.GenerateDashManifestAppendStoryboards(context) end if - v = request.query.v + videoLoadId = ValidString(request.query.videoLoadId) local = request.query.local quality = request.query.quality - if StringUtils.IsNullOrEmpty(v) - response.Default(400, "Missing video id") - WriteAsciiFile("cachefs:/last_generated_dash.xml", "400 Missing video id") + if videoLoadId = "" + response.Default(400, "Missing video load id") + WriteAsciiFile("cachefs:/last_generated_dash.xml", "400 Missing video load id") return true end if - metadata = m.GetMetadata(v, ValidString(request.query.backend)) - 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") - return true - end if - if metadata.videoId <> v - response.Default(400, "videoQueue.player.content.metadata.videoId does not match the requested video id") - WriteAsciiFile("cachefs:/last_generated_dash.xml", "400 videoQueue.player.content.metadata.videoId does not match the requested video id") + metadata = m.GetMetadata(videoLoadId) + if metadata = invalid + response.Default(400, "videoQueue.player.content holds no metadata for the requested video load id") + WriteAsciiFile("cachefs:/last_generated_dash.xml", "400 videoQueue.player.content holds no metadata for the requested video load id") return true end if 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}` - m.dashManifest.liveBackend = ValidString(request.query.backend) + isLocal = ValidString(local) = "true" - qualityFilter = m.CreateQualityFilter(quality) - xmlContent = m.dashManifest.FromVideoMetadata(metadata, qualityFilter, ValidString(local) = "true") - - if xmlContent.InStr("[ERROR]") <> -1 - LogErrorNoTelemetry("Dash manifest generated with errors") - lastPlayerResponse = ValidString(ReadAsciiFile("cachefs:/last_player_response.json")) - LogTelemetryEvent({ - level: "error" - message: "Dash manifest generated with errors" - attachments: [{ - filename: "dash.xml" - content_type: "text/plain" - data: xmlContent - }, { - filename: "last_player_response.json" - content_type: "application/json" - data: lastPlayerResponse - }] - }) + if ValidBool(metadata.liveNow) + xmlContent = m.GetLiveManifest(metadata, videoLoadId, ValidString(quality), isLocal) + else + xmlContent = m.dashManifest.FromVideoMetadata(metadata, m.CreateQualityFilter(quality), isLocal) + m.ReportManifestErrors(xmlContent, videoLoadId) + WriteAsciiFile("cachefs:/last_generated_dash.xml", xmlContent) end if response.http_code = 200 response.SetBodyDataString(xmlContent) response.ContentType("application/dash+xml") - - WriteAsciiFile("cachefs:/last_generated_dash.xml", xmlContent) - return true end function + function ReportManifestErrors(xmlContent as string, videoLoadId as string) as void + if xmlContent.InStr("[ERROR]") = -1 + return + end if + LogErrorNoTelemetry("Dash manifest generated with errors") + lastPlayerResponse = ValidString(ReadAsciiFile("cachefs:/last_player_response.json")) + LogTelemetryEvent({ + level: "error" + message: `Dash manifest generated with errors\nvideo_load_id: ${videoLoadId}` + fingerprint: ["Dash manifest generated with errors"] + attachments: [{ + filename: "dash.xml" + content_type: "text/plain" + data: xmlContent + }, { + filename: "last_player_response.json" + content_type: "application/json" + data: lastPlayerResponse + }] + }) + end function + function CreateQualityFilter(quality as dynamic) as object qualityFilter = {} if not IsString(quality) @@ -238,522 +204,203 @@ namespace Http 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); segments map 1:1 to native - ' fragments, so the DASH segment number is the native sq: - ' /api/dash/live-seg?v=&itag=&init=true -> ftyp+moov of the live-edge fragment - ' /api/dash/live-seg?v=&itag=&sq= -> moof+mdat of fragment N - ' - ' 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. + ' The live manifest lists the segments that exist, so its timeline ends at + ' the stream's live head, re-read on every manifest request (RefreshLiveHead). + ' The player fetches the segments (`&sq=N` fragments) straight from + ' googlevideo, init included (see DashManifest.GenerateSegmentInformation). ' ------------------------------------------------------------------------ - @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 - isInit = ValidString(request.query.init) = "true" - sq = -1 - if not isInit - sq = ValidString(request.query.sq).ToInt() + ' Between live manifest requests only the live head and the clock change: the + ' manifest is built once per video load and output options, then filled in per request. + function GetLiveManifest(metadata as object, videoLoadId as string, quality as string, isLocal as boolean) as string + templateKey = `${quality}|${isLocal}|${m.dashManifest.invidiousInstance}|${m.dashManifest.disableAutoDubbed}` + isNewTemplate = m.liveManifestTemplateKey <> templateKey + if isNewTemplate + m.liveManifestTemplate = m.dashManifest.FromVideoMetadata(metadata, m.CreateQualityFilter(quality), isLocal) + m.liveManifestTemplateKey = templateKey end if - if StringUtils.IsNullOrEmpty(itag) or StringUtils.IsNullOrEmpty(v) or (not isInit and sq <= 0) - response.Default(400, "Missing or invalid v, itag, or sq") - return true + m.RefreshLiveHead() + xmlContent = m.dashManifest.FillLiveManifest(m.liveManifestTemplate, m.liveHeadSeqnum, m.liveDurationRuns, m.liveWindowMs) + if isNewTemplate + m.ReportManifestErrors(xmlContent, videoLoadId) 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, ValidString(request.query.backend)) - - baseUrl = m.cachedUrls[itag] - if StringUtils.IsNullOrEmpty(baseUrl) - LogErrorNoTelemetry("[LIVE-SEG] no live format url for v:", v, "itag:", itag, "-> 404") - m.ReportSegmentFailure(LiveSegFailure.NoFormatUrl, { v: v, itag: itag, sq: sq }) - response.Default(404, "No live format url for itag " + itag) - return true - end if - - if isInit - ' ftyp+moov, served from the per-itag cache after the first fetch. - output = m.cachedInit[itag] - if output = invalid - ' Source from a current fragment: sq=0 is outside the DVR window (404) - ' and the load-time edge ages out, so prefer lastSeenSq; fall back to - ' the load-time seqnum only before any media segment is served. - initSq = m.cachedInitSeqnum - if m.lastSeenSq > 0 - initSq = m.lastSeenSq - end if - output = m.AwaitSegmentWithRetry(baseUrl, initSq, v, itag, true, invalid) - if output = invalid - LogErrorNoTelemetry("[LIVE-SEG] INIT fetch failed v:", v, "itag:", itag, "-> 503") - response.Default(503, "Live init segment not ready") - return true - end if - m.cachedInit[itag] = output - end if - else - ' Media DASH segment = one native YouTube fragment, reduced to moof+mdat - ' so Roku reads the init segment only once. The manifest addresses the - ' proxy 1:1, so the DASH segment number is the native sq. - if sq > m.lastSeenSq - m.lastSeenSq = sq - end if - - ' Representation switch (ABR video / audio track): the previous itag of - ' this kind stops being requested, so evict its warmed fragments now - - ' EvictPrefetchOutside is itag-scoped and would never reach them, so - ' they'd otherwise leak (temp files + idle transfers) until video change. - if m.cachedTypes[itag] = "audio/mp4" - if IsString(m.lastAudioItag) and m.lastAudioItag <> itag - m.EvictPrefetchItag(m.lastAudioItag) - end if - m.lastAudioItag = itag - else - if IsString(m.lastVideoItag) and m.lastVideoItag <> itag - m.EvictPrefetchItag(m.lastVideoItag) - end if - m.lastVideoItag = itag - end if - - ' Reuse a warmed fetch if present, else start one. Warm the next few - ' (Send, no Await) BEFORE blocking here so their downloads overlap this - ' fragment's await + playback; then drop entries now outside the window - ' (played past, or stranded by a seek) so the cache + temp files stay bounded. - entry = m.GetOrStartFetch(baseUrl, sq, v, itag) - m.PrefetchAhead(baseUrl, v, itag, sq, LIVE_PREFETCH_SEGMENTS) - m.EvictPrefetchOutside(itag, sq + 1, sq + LIVE_PREFETCH_SEGMENTS) - - output = m.AwaitSegmentWithRetry(baseUrl, sq, v, itag, false, entry) - if output = invalid - ' 503 makes Roku re-request the same sq and hold the bitrate (verified); the - ' fragment will exist within ~one re-request. - LogErrorNoTelemetry("[LIVE-SEG] media fragment not ready v:", v, "itag:", itag, "sq:", sq, "-> 503") - response.Default(503, "Live media segment not ready") - 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 + WriteAsciiFile("cachefs:/last_generated_dash.xml", xmlContent) + return xmlContent 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 - ' Prefetched fetches from the previous video may still be in flight (they - ' outlive the request that started them), so cancel them first - otherwise - ' they'd race the sweep below (and keep writing temp files). - m.ClearPrefetch() - ' 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. - m.CleanupTempSegments() - ' Re-arm the per-video telemetry dedupe (see ReportSegmentFailure). - m.reportedFailures = {} - ' Init bytes and the sq high-water mark belong to the previous video. - m.cachedInit = {} - m.lastSeenSq = 0 - - 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(LiveSegFailure.FormatsNotArray, { 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) + ' Raise the live head to the stream's newest segment. On failure the timeline + ' keeps its end, and the player holds at it until a later check succeeds. + function RefreshLiveHead() as void + if StringUtils.IsNullOrEmpty(m.liveHeadUrl) 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 - - ' Return a warmed (prefetched) fetch for this native fragment if present, - ' consuming it from the cache; otherwise start a fresh one. - function GetOrStartFetch(baseUrl as string, sq as integer, v as string, itag as string) as object - key = `${itag}|${sq}` - if m.prefetch.DoesExist(key) - entry = m.prefetch[key] - m.prefetch.Delete(key) - return entry - end if - return m.StartSegmentFetch(baseUrl, sq, v, itag) - end function - - ' Send (without awaiting) the next `count` native fragments after `fromSq` so - ' their downloads overlap the current segment. Already-warmed ones are left be. - function PrefetchAhead(baseUrl as string, v as string, itag as string, fromSq as integer, count as integer) as void - for i = 1 to count - key = `${itag}|${fromSq + i}` - if not m.prefetch.DoesExist(key) - m.prefetch[key] = m.StartSegmentFetch(baseUrl, fromSq + i, v, itag) - end if - end for - end function - - ' Drop warmed fragments for `itag` whose sq is outside [lowSq, highSq] - played - ' past or stranded by a seek - cancelling the in-flight transfer and deleting - ' its temp file so the cache and tmp:/ stay bounded. - function EvictPrefetchOutside(itag as string, lowSq as integer, highSq as integer) as void - prefix = `${itag}|` - stale = [] - for each key in m.prefetch - if key.StartsWith(prefix) - sq = key.Mid(prefix.Len()).ToInt() - if sq < lowSq or sq > highSq - stale.Push(key) - end if - end if - end for - for each key in stale - m.DiscardFetch(m.prefetch[key]) - m.prefetch.Delete(key) - end for - end function - - ' Cancel and drop every warmed fragment belonging to `itag` (used when the - ' player switches away from a representation). - function EvictPrefetchItag(itag as string) as void - prefix = `${itag}|` - stale = [] - for each key in m.prefetch - if key.StartsWith(prefix) - stale.Push(key) - end if - end for - for each key in stale - m.DiscardFetch(m.prefetch[key]) - m.prefetch.Delete(key) - end for - end function - - ' Cancel every warmed fetch and clear the cache. Called on a video change - ' before the temp-file sweep so in-flight prefetch transfers don't race it. - function ClearPrefetch() as void - for each key in m.prefetch - m.DiscardFetch(m.prefetch[key]) - end for - m.prefetch = {} - m.lastVideoItag = invalid - m.lastAudioItag = invalid - end function - - ' Abort an in-flight fetch and delete its temp file (non-blocking). - function DiscardFetch(entry as object) as void - if not IsAssociativeArray(entry) + if m.liveHeadTimer = invalid + m.liveHeadTimer = CreateObject("roTimespan") + else if m.liveHeadTimer.TotalMilliseconds() < LIVE_HEAD_MIN_INTERVAL_MS return end if - if entry.req <> invalid and entry.req.urlTransfer <> invalid - entry.req.urlTransfer.AsyncCancel() + m.liveHeadTimer.Mark() + + head = m.CheckLiveHead() + if head.seqnum < 0 + m.ReportLiveHeadFailure(head.response) + return + end if + ' Listed segments can't be withdrawn: the head only moves forward. + if head.seqnum > m.liveHeadSeqnum + m.AlignLiveTimeline(head) + m.liveHeadSeqnum = head.seqnum end if - DeleteFile(entry.tmpPath) end function - ' Await `entry` (invalid -> fetch fresh), transform to the bytes Roku needs (wantInit -> - ' ftyp+moov, else moof+mdat), retrying transient failures up to LIVE_SEG_MAX_ATTEMPTS. Each - ' retry refetches the same sq, which also un-poisons a prefetched 204. Telemetry fires once. - function AwaitSegmentWithRetry(baseUrl as string, sq as integer, v as string, itag as string, wantInit as boolean, entry as object) as dynamic - if entry = invalid - entry = m.StartSegmentFetch(baseUrl, sq, v, itag) + ' A no-sq HEAD: googlevideo answers at once with the X-Head-* headers. + function CheckLiveHead() as LiveHeadReading + request = Innertube.CreateLiveHeadRequest(m.liveHeadUrl) + request.TimeoutSeconds(LIVE_HEAD_TIMEOUT_SECONDS) + response = request.Await() + return { + seqnum: Innertube.ReadLiveHeadSeqnum(response) + timeMs: Innertube.ReadLiveHeadTimeMs(response) + response: response + } + end function + + ' Segments are listed at the duration at load, the stream's lifetime average: off + ' by a young stream's short first segment and by any change of cadence. Roku plays + ' at its clock edge, so a list behind the stream skips segments for the rest of the + ' load (measured), and one ahead holds the player further from live. The base is a + ' head whose place on the timeline is known (the load head, then the last stall): + ' head time since it says where the head ends. Off by more than half a segment + ' (within the cushion, at least a segment), segments not yet listed take the cadence + ' since the base, or after a stall keep theirs and move the base. Listed segments + ' keep their place, so a list ahead stays ahead by liveLeadMs. + function AlignLiveTimeline(head as LiveHeadReading) as void + if head.timeMs = invalid or m.liveBaseTimeMs = invalid + return + end if + durationRuns = m.liveDurationRuns + headEndMs = m.liveBaseEndMs + Cint(head.timeMs - m.liveBaseTimeMs) + driftMs = m.dashManifest.LiveSegmentStartMs(durationRuns, head.seqnum + 1) - headEndMs - m.liveLeadMs + stepMs = driftMs - m.liveDriftMs + m.liveDriftMs = driftMs + lastCheckJumped = m.liveLastCheckJumped + m.liveLastCheckJumped = false + listedDurationMs = durationRuns[durationRuns.Count() - 1].durationMs + if Abs(driftMs) * 2 <= listedDurationMs + return end if - attempt = 1 - while true - result = m.AttemptSegment(entry, wantInit) - if result.ok - return result.bytes + ' A cadence error builds up across checks; a stall leaps forward within one. A + ' large cadence error can leap too (a young stream between sparse checks): the + ' next check measures it. + isStall = stepMs < -LIVE_STALL_JUMP_MS and not lastCheckJumped + if isStall + durationMs = listedDurationMs + else + durationMs = Cint((head.timeMs - m.liveBaseTimeMs) / (head.seqnum - m.liveBaseSeqnum)) + if durationMs <= 0 + LogWarnNoTelemetry("Live head time went back:", head.timeMs, "ms at", head.seqnum, "after", m.liveBaseTimeMs, "ms at", m.liveBaseSeqnum) + return end if + end if - ' 204 = sq not produced yet. Return 503 and let Roku re-ask (same sq, then resyncs); - ' a sleep+refetch here would stall the queued audio ~600ms on the single thread - ' (measured). Evict the warmed siblings - fetched too early, they 204'd too. - if result.reason = LiveSegFailure.EmptyFragment - if not wantInit - m.EvictPrefetchItag(itag) - end if - m.ReportSegmentFailure(result.reason, { v: v, itag: itag, sq: sq, head: m.liveHeadSeqnum, segUrl: entry.segUrl, response: result.response }) - return invalid - end if + fromSeqnum = m.dashManifest.LiveLastListedSeqnum(durationRuns, m.liveHeadSeqnum) + 1 + alignedStartMs = headEndMs - (head.seqnum + 1 - fromSeqnum) * durationMs + startMs = MathUtils.Max(m.dashManifest.LiveSegmentStartMs(durationRuns, fromSeqnum), alignedStartMs) + m.liveLeadMs = startMs - alignedStartMs + m.liveDriftMs = 0 + if isStall + m.liveBaseSeqnum = head.seqnum + m.liveBaseTimeMs = head.timeMs + m.liveBaseEndMs = headEndMs + m.liveLastCheckJumped = true + end if + LogInfo("Live timeline", driftMs, "ms off the head, stall:", isStall, "; segments from", fromSeqnum, "take", durationMs, "ms from", startMs, "ms, lead", m.liveLeadMs, "ms") - if (not result.retryable) or attempt >= LIVE_SEG_MAX_ATTEMPTS - m.ReportSegmentFailure(result.reason, { v: v, itag: itag, sq: sq, head: m.liveHeadSeqnum, segUrl: entry.segUrl, response: result.response }) - return invalid - end if - - ' Network/5xx: transient; discard and refetch immediately (no sleep). - LogWarnNoTelemetry("[LIVE-SEG] retry sq", sq, "itag", itag, "(", result.reason, ") attempt", attempt + 1, "of", LIVE_SEG_MAX_ATTEMPTS) - - attempt += 1 - entry = m.StartSegmentFetch(baseUrl, sq, v, itag) + firstListed = m.dashManifest.LiveFirstListedSeqnum(durationRuns, m.dashManifest.LiveLastListedSeqnum(durationRuns, m.liveHeadSeqnum), m.liveWindowMs) + while durationRuns.Count() > 1 and durationRuns[1].fromSeqnum <= firstListed + durationRuns.Shift() end while + durationRuns.Push({ fromSeqnum: fromSeqnum, startMs: startMs, durationMs: durationMs }) - return invalid + m.ReportLiveCorrection(head, durationMs, driftMs, stepMs, isStall) end function - ' One fetch+transform attempt. Reads only the needed byte range from the temp - ' file and always deletes it. Returns: - ' { ok: true, bytes } - the transformed segment bytes - ' { ok: false, retryable, reason, response } - failed; `retryable` marks fast transient - ' NETWORK errors (reset/-10001, 5xx) worth an immediate refetch. 204/empty is handled - ' specially by the caller (immediate 503); timeout/4xx/malformed are not retried. - function AttemptSegment(entry as object, wantInit as boolean) as object - tmpPath = entry.tmpPath - sq = entry.sq - - response = entry.req.Await() - m.liveHeadSeqnum = m.ReadHeadSeqnum(response) - if not response.IsSuccess() - status = response.StatusCode() - LogErrorNoTelemetry("[LIVE-SEG] fetch sq", sq, "failed:", status) - DeleteFile(tmpPath) - ' status<0 = active error event (reset/-10001), 5xx = server error: both - ' transient -> retried. status 0 = timeout (slow/hung) -> not retried. - return { ok: false, retryable: status < 0 or status >= 500, reason: LiveSegFailure.FetchFailed, response: response } - 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 (status", response.StatusCode(), ")") - DeleteFile(tmpPath) - ' 204/empty handled specially by the caller (immediate 503, no in-handler retry). - return { ok: false, retryable: false, reason: LiveSegFailure.EmptyFragment, response: response } - 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, ")") - DeleteFile(tmpPath) - return { ok: false, retryable: false, reason: LiveSegFailure.NoMoov, response: response } - 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, ")") - DeleteFile(tmpPath) - return { ok: false, retryable: false, reason: LiveSegFailure.NoMoof, response: response } - end if - out.ReadFile(tmpPath, boxes.moofStart, fileLen - boxes.moofStart) - end if - - DeleteFile(tmpPath) - return { ok: true, bytes: out } - end function - - ' Live head sequence number from a fragment response's X-Head-Seqnum header (-1 if - ' absent). Stashed (m.liveHeadSeqnum) so ReportSegmentFailure records how far ahead of - ' the real edge a failed sq was (delta = sq - head) - the field signal for edge overshoot. - function ReadHeadSeqnum(response as object) as integer - headers = response.Headers() - if IsAssociativeArray(headers) and headers.DoesExist("X-Head-Seqnum") - return ValidString(headers["X-Head-Seqnum"]).ToInt() - end if - return -1 - 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 LiveSegFailure, 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) + ' Telemetry once per video load. + function ReportLiveCorrection(head as LiveHeadReading, durationMs as integer, driftMs as integer, stepMs as integer, isStall as boolean) as void + if m.reportedLiveCorrection return end if - m.reportedFailures[dedupeKey] = true + m.reportedLiveCorrection = true - ' Edge overshoot: how far past the live head (X-Head-Seqnum at the failing fetch, via - ' info.head) the failed sq was. delta > 0 = a not-yet-produced fragment (the 503 cause). - head = ValidInt(info.head) - sqNum = ValidInt(info.sq) - deltaText = "n/a" - if head > 0 and sqNum > 0 - deltaText = (sqNum - head).ToStr() + LogTelemetryEvent({ + level: "info" + message: FormatJson({ + "video_load_id": ValidString(m.cachedVideoLoadId) + "video_id": ValidString(ObjectUtils.Dig(m.cachedMetadata, ["videoId"])) + "target_duration_ms": ValidInt(ObjectUtils.Dig(m.cachedMetadata, ["adaptiveFormats", 0, "targetDurationSec"])) * 1000 + "load_head_seqnum": m.liveLoadHeadSeqnum + "load_duration_ms": ValidInt(ObjectUtils.Dig(m.cachedMetadata, ["liveSegmentDurationMs"])) + "duration_ms": durationMs + "drift_ms": driftMs + "step_ms": stepMs + "stall": isStall + "segments_since_load": head.seqnum - m.liveLoadHeadSeqnum + "ms_since_load": Cint(head.timeMs - m.liveLoadHeadTimeMs) + }) + fingerprint: ["live timeline correction"] + }) + end function + + ' Until a head check succeeds, the listed timeline stops growing and the player + ' holds at its end. Telemetry once per video load. + function ReportLiveHeadFailure(response as object) as void + statusText = Str(response.StatusCode()).Trim() + LogWarnNoTelemetry("Live head check returned no X-Head-Seqnum (HTTP", statusText, "); head stays at", m.liveHeadSeqnum) + if m.reportedLiveHeadFailure + return end if - details = [ - "reason: " + reason - "videoId: " + ValidString(info.v) - "itag: " + ValidString(info.itag) - "sq: " + ToString(info.sq) - "head: " + head.ToStr() - "delta: " + deltaText - "status: " + statusText - "error: " + errorMessage - "url: " + ValidString(info.segUrl) - ] + m.reportedLiveHeadFailure = true LogTelemetryEvent({ level: "error" - message: `[LIVE-SEG] ${reason} (status ${statusText})` - fingerprint: ["live-seg fetch failure", reason] + message: `Live head check failed (status ${statusText})` + fingerprint: ["live head check failure", statusText] attachments: [{ - filename: "live-seg-failure.txt" + filename: "live-head-failure.txt" content_type: "text/plain" - data: details.Join(Chr(10)) + data: [ + `videoId: ${ValidString(ObjectUtils.Dig(m.cachedMetadata, ["videoId"]))}` + `video_load_id: ${ValidString(m.cachedVideoLoadId)}` + `head: ${m.liveHeadSeqnum}` + `status: ${statusText}` + `error: ${response.ErrorMessage(false)}` + `url: ${m.liveHeadUrl}` + ].Join(`\n`) }] }) 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 } + function ResetLiveState(metadata as object) as void + m.liveHeadUrl = ValidString(metadata.liveHeadUrl) + m.liveHeadTimer = invalid + m.liveHeadSeqnum = ValidInt(metadata.liveHeadSeqnum) + m.liveLoadHeadSeqnum = m.liveHeadSeqnum + m.liveLoadHeadTimeMs = metadata.liveHeadTimeMs + segmentDurationMs = ValidInt(metadata.liveSegmentDurationMs) + m.liveDurationRuns = [{ fromSeqnum: ValidInt(metadata.liveFirstSeqnum), startMs: ValidInt(metadata.liveTimelineOffsetMs), durationMs: segmentDurationMs }] + m.liveBaseSeqnum = m.liveHeadSeqnum + m.liveBaseTimeMs = m.liveLoadHeadTimeMs + m.liveBaseEndMs = m.dashManifest.LiveSegmentStartMs(m.liveDurationRuns, m.liveHeadSeqnum + 1) + m.liveWindowMs = ValidInt(metadata.liveWindowSegments) * segmentDurationMs + m.liveLeadMs = 0 + m.liveDriftMs = 0 + m.liveLastCheckJumped = false + m.reportedLiveCorrection = false + m.liveManifestTemplate = "" + m.liveManifestTemplateKey = invalid + m.reportedLiveHeadFailure = false end function end class diff --git a/playlet-lib/src/source/services/HttpClient.bs b/playlet-lib/src/source/services/HttpClient.bs index 2527dc23..5e9a48fd 100644 --- a/playlet-lib/src/source/services/HttpClient.bs +++ b/playlet-lib/src/source/services/HttpClient.bs @@ -468,9 +468,32 @@ namespace HttpClient triesLeft -= 1 while triesLeft > 0 - backoffMs = 1000 + Rnd(2000) tryNumber = m._tryCount - triesLeft + 1 - LogWarnNoTelemetry("Request failed ID:", m.urlTransfer.GetIdentity(), "ErrorMessage:", response.ErrorMessage(), `\nRetrying: (`, tryNumber, "/", m._tryCount, ") in", backoffMs, "ms") + shouldRetry = true + if IsFunction(m._retryCallback) + try + callbackResult = m._retryCallback({ + tryNumber: tryNumber + tryCount: m._tryCount + request: m + response: response + }) + shouldRetry = not IsBool(callbackResult) or callbackResult + catch error + #if DEBUG + throw error + #else + LogError("Retry callback failed:", ErrorUtils.Format(error)) + #end if + end try + end if + + backoffMs = 1000 + Rnd(2000) + if shouldRetry + LogWarnNoTelemetry("Request failed ID:", m.urlTransfer.GetIdentity(), "ErrorMessage:", response.ErrorMessage(), `\nRetrying: (`, tryNumber, "/", m._tryCount, ") in", backoffMs, "ms") + else + LogWarnNoTelemetry("Request failed ID:", m.urlTransfer.GetIdentity(), "ErrorMessage:", response.ErrorMessage(), `\nNot retrying: the retry callback declined`) + end if LogTelemetryEvent({ level: "warning" message: response.ErrorMessage() @@ -480,27 +503,8 @@ namespace HttpClient data: m.ToCurlCommand() }] }) - - if IsFunction(m._retryCallback) - try - shouldRetry = m._retryCallback({ - tryNumber: tryNumber - tryCount: m._tryCount - request: m - response: response - }) - - if IsBool(shouldRetry) and not shouldRetry - LogInfo("Retry callback returned false. Not retrying.") - return response - end if - catch error - #if DEBUG - throw error - #else - LogError("Retry callback failed:", ErrorUtils.Format(error)) - #end if - end try + if not shouldRetry + return response end if m.urlTransfer = invalid diff --git a/playlet-lib/src/source/services/HttpClient.spec.bs b/playlet-lib/src/source/services/HttpClient.spec.bs new file mode 100644 index 00000000..c5646934 --- /dev/null +++ b/playlet-lib/src/source/services/HttpClient.spec.bs @@ -0,0 +1,64 @@ +import "pkg:/source/services/HttpClient.bs" + +namespace Tests + + @suite + class HttpClientTests extends Rooibos.BaseTestSuite + + protected override function beforeEach() + ' the logger plugin reads m.global.logger; LogTelemetryEvent writes m.global.telemetry.LogEvent. + if m.global.logger = invalid + m.global.addField("logger", "node", false) + m.global.logger = CreateObject("roSGNode", "Logger") + end if + if m.global.telemetry = invalid + m.global.addField("telemetry", "node", false) + telemetry = CreateObject("roSGNode", "Node") + telemetry.addField("LogEvent", "assocarray", false) + m.global.telemetry = telemetry + end if + m.global.telemetry.LogEvent = {} + end function + + ' Nothing listens on port 1: the connection is refused, a failure that is not a timeout. + function RefusedRequest(retryCallback as function) as HttpClient.HttpRequest + return HttpClient.Head("http://127.0.0.1:1/").NoCache().TryCount(2).RetryCallback(retryCallback) + end function + + @describe("HttpClient.HttpRequest.Await") + + @it("reports a failed attempt the retry callback declines, without retrying") + function _() + request = m.RefusedRequest(function(context as object) as boolean + context.request.declinedError = context.response.ErrorMessage() + return false + end function) + timer = CreateObject("roTimespan") + response = request.Await() + ' A retry waits at least 1000 ms before its second attempt. + m.assertTrue(timer.TotalMilliseconds() < 1000, `took ${timer.TotalMilliseconds()} ms`) + m.assertFalse(response.IsSuccess()) + event = m.global.telemetry.LogEvent + m.assertEqual(event.level, "warning") + m.assertEqual(event.message, request.declinedError) + m.assertEqual(event.attachments[0].filename, "request.txt") + end function + + @it("reports a failed attempt before retrying it") + function _() + request = m.RefusedRequest(function(context as object) as boolean + context.request.retriedError = context.response.ErrorMessage() + return true + end function) + timer = CreateObject("roTimespan") + request.Await() + m.assertTrue(timer.TotalMilliseconds() >= 1000, `took ${timer.TotalMilliseconds()} ms`) + event = m.global.telemetry.LogEvent + m.assertEqual(event.level, "warning") + m.assertEqual(event.message, request.retriedError) + m.assertEqual(event.attachments[0].filename, "request.txt") + end function + + end class + +end namespace diff --git a/playlet-lib/src/source/tests/Services/Dash/DashManifest.spec.bs b/playlet-lib/src/source/tests/Services/Dash/DashManifest.spec.bs new file mode 100644 index 00000000..541ad504 --- /dev/null +++ b/playlet-lib/src/source/tests/Services/Dash/DashManifest.spec.bs @@ -0,0 +1,147 @@ +import "pkg:/components/Services/Dash/DashManifest.bs" + +namespace Tests + + @suite + class DashManifestTests extends Rooibos.BaseTestSuite + + @describe("DashManifest.ProxyFormatsThroughInvidious") + + @it("routes each url through the instance, keeping the original host as a param") + function _() + manifest = new DashManifest("https://inv.example") + proxied = manifest.ProxyFormatsThroughInvidious([{ itag: "137", url: "https://rr1.googlevideo.com/videoplayback?id=abc" }]) + m.assertEqual(proxied[0].url, "https://inv.example/videoplayback?id=abc&host=rr1.googlevideo.com") + m.assertEqual(proxied[0].itag, "137") + end function + + @it("leaves the source formats untouched, so a second pass routes the same") + function _() + manifest = new DashManifest("https://inv.example") + formats = [{ itag: "137", url: "https://rr1.googlevideo.com/videoplayback?id=abc" }] + first = manifest.ProxyFormatsThroughInvidious(formats) + second = manifest.ProxyFormatsThroughInvidious(formats) + m.assertEqual(formats[0].url, "https://rr1.googlevideo.com/videoplayback?id=abc") + m.assertEqual(second[0].url, first[0].url) + end function + + @it("passes formats without a url through") + function _() + manifest = new DashManifest("https://inv.example") + proxied = manifest.ProxyFormatsThroughInvidious([{ itag: "140" }]) + m.assertEqual(proxied.Count(), 1) + m.assertEqual(proxied[0].itag, "140") + m.assertInvalid(proxied[0].url) + end function + + @describe("DashManifest.FillLiveManifest") + + ' The filled startNumber, entries ({ t, d, r }) and now. + function FillTemplate(headSeqnum as integer, firstSeqnum = 100 as integer, windowSegments = 10 as integer, durationRuns = invalid as dynamic) as object + if durationRuns = invalid + durationRuns = [{ fromSeqnum: firstSeqnum, startMs: 250, durationMs: 5000 }] + end if + manifest = new DashManifest("") + template = `${LIVE_START_NUMBER_TOKEN}|${LIVE_SEGMENTS_TOKEN}|${LIVE_NOW_TOKEN}` + parts = manifest.FillLiveManifest(template, headSeqnum, durationRuns, windowSegments * durationRuns[0].durationMs).Split("|") + entries = [] + for each match in CreateObject("roRegex", "", "").MatchAll(parts[1]) + entries.Push({ t: match[1].ToInt(), d: match[2].ToInt(), r: match[3].ToInt() }) + end for + return { startNumber: parts[0].ToInt(), s: entries, now: parts[2] } + end function + + @it("grows a young stream's list from its first segment") + function _() + atLoad = m.FillTemplate(3, 0, 8640) + m.assertEqual(atLoad.startNumber, 0) + m.assertEqual(atLoad.s[0].r, 2) + later = m.FillTemplate(50, 0, 8640) + m.assertEqual(later.startNumber, 0) + m.assertEqual(later.s[0].t, 250) + m.assertEqual(later.s[0].r, 49) + end function + + @it("lists the window behind the head at load: from the first segment to head - 1") + function _() + filled = m.FillTemplate(109) + m.assertEqual(filled.startNumber, 100) + m.assertEqual(filled.s, [{ t: 250, d: 5000, r: 8 }]) + end function + + @it("slides startNumber and S@t together as the head advances") + function _() + filled = m.FillTemplate(115) + m.assertEqual(filled.startNumber, 105) + m.assertEqual(filled.s, [{ t: 5 * 5000 + 250, d: 5000, r: 9 }]) + end function + + @it("still lists the head when it is the first segment: an empty timeline isn't expressible") + function _() + filled = m.FillTemplate(100) + m.assertEqual(filled.startNumber, 100) + m.assertEqual(filled.s[0].r, 0) + end function + + @it("starts sliding exactly when a young stream's list fills the window") + function _() + full = m.FillTemplate(10, 0, 10) + m.assertEqual(full.startNumber, 0) + m.assertEqual(full.s[0].r, 9) + sliding = m.FillTemplate(11, 0, 10) + m.assertEqual(sliding.startNumber, 1) + m.assertEqual(sliding.s, [{ t: 5000 + 250, d: 5000, r: 9 }]) + end function + + @it("lists segments past a re-measured duration with it, keeping the earlier ones' times") + function _() + filled = m.FillTemplate(20, 0, 33230, [{ fromSeqnum: 0, startMs: 250, durationMs: 1300 }, { fromSeqnum: 10, startMs: 13250, durationMs: 2000 }]) + m.assertEqual(filled.startNumber, 0) + m.assertEqual(filled.s, [{ t: 250, d: 1300, r: 9 }, { t: 13250, d: 2000, r: 9 }]) + end function + + @it("keeps a gap before a run that starts past the previous one's end") + function _() + ' segments 0-9 end at 13250; segment 10 realigned to 20250 + runs = [{ fromSeqnum: 0, startMs: 250, durationMs: 1300 }, { fromSeqnum: 10, startMs: 20250, durationMs: 2000 }] + filled = m.FillTemplate(15, 0, 33230, runs) + m.assertEqual(filled.s, [{ t: 250, d: 1300, r: 9 }, { t: 20250, d: 2000, r: 4 }]) + ' a time inside the gap (13250-20250) maps to the run after it + manifest = new DashManifest("") + m.assertEqual(manifest.LiveSegmentAtOrAfter(runs, 18250), 10) + m.assertEqual(manifest.LiveSegmentAtOrAfter(runs, 13000), 10) + m.assertEqual(manifest.LiveSegmentAtOrAfter(runs, 11000), 9) + end function + + @it("slides by time over mixed durations: the list never spans more than the window") + function _() + ' window 10 x 1000 ms; segments 0-4 at 1000, 5+ at 2000; head 12 lists up to 11 + filled = m.FillTemplate(12, 0, 10, [{ fromSeqnum: 0, startMs: 250, durationMs: 1000 }, { fromSeqnum: 5, startMs: 5250, durationMs: 2000 }]) + m.assertEqual(filled.startNumber, 7) + m.assertEqual(filled.s, [{ t: 250 + 5 * 1000 + 2 * 2000, d: 2000, r: 4 }]) + end function + + @it("fills every placeholder, with the current time as now") + function _() + filled = m.FillTemplate(109) + m.assertEqual(filled.now.Instr("{{"), -1) + now = CreateObject("roDateTime") + stamped = CreateObject("roDateTime") + stamped.FromISO8601String(filled.now) + m.assertTrue(Abs(now.AsSeconds() - stamped.AsSeconds()) <= 1) + end function + + @describe("DashManifest.FormatDuration") + + @it("formats milliseconds as an xs:duration") + function _() + manifest = new DashManifest("") + m.assertEqual(manifest.FormatDuration(0), "PT0.000S") + m.assertEqual(manifest.FormatDuration(999), "PT0.999S") + m.assertEqual(manifest.FormatDuration(1500), "PT1.500S") + m.assertEqual(manifest.FormatDuration(10000), "PT10.000S") + end function + + end class + +end namespace diff --git a/playlet-lib/src/source/tests/Services/Innertube/LiveStreamInfo.spec.bs b/playlet-lib/src/source/tests/Services/Innertube/LiveStreamInfo.spec.bs new file mode 100644 index 00000000..779463e8 --- /dev/null +++ b/playlet-lib/src/source/tests/Services/Innertube/LiveStreamInfo.spec.bs @@ -0,0 +1,158 @@ +import "pkg:/components/Services/Innertube/LiveStreamInfo.bs" + +namespace Tests + + @suite + class LiveStreamInfoTests extends Rooibos.BaseTestSuite + + ' availabilityStartTime + the timeline offset place the first segment's start so that the head + ' segment ends a cushion behind now. + function AssertAnchored(timeline as object, nowSec as integer, nowMs as integer, cushionMs as integer) + ast = CreateObject("roDateTime") + ast.FromISO8601String(timeline.liveAvailabilityStartUtc) + anchorMs = (ast.AsSeconds() - nowSec) * 1000 + timeline.liveTimelineOffsetMs + segmentCount = timeline.liveHeadSeqnum - timeline.liveFirstSeqnum + 1 + m.assertEqual(anchorMs, nowMs + cushionMs - segmentCount * timeline.liveSegmentDurationMs) + m.assertTrue(timeline.liveTimelineOffsetMs >= 0 and timeline.liveTimelineOffsetMs < 1000) + end function + + @describe("Innertube.GetLiveTimeline") + + @it("anchors a 12h window on a stream live for 111 days (head time past 32 bits)") + function _() + timeline = Innertube.GetLiveTimeline(1923180, 9615900000&, 5, 43200, 3, 2000000000, 250) + m.assertEqual(timeline.liveSegmentDurationMs, 5000) + m.assertEqual(timeline.liveWindowSegments, 8640) + m.assertEqual(timeline.liveFirstSeqnum, 1923180 - 8640 + 1) + m.assertEqual(timeline.liveSeekableWindowSec, 43200 - 15 - 5) + m.AssertAnchored(timeline, 2000000000, 250, 15000) + end function + + @it("averages the segment duration over the head time, not targetDurationSec") + function _() + timeline = Innertube.GetLiveTimeline(10000, 18000000, 5, 43200, 3, 2000000000, 0) + m.assertEqual(timeline.liveSegmentDurationMs, 1800) + end function + + @it("falls back to targetDurationSec at head 0, with no cushion") + function _() + timeline = Innertube.GetLiveTimeline(0, 0, 2, 43200, 3, 2000000000, 0) + m.assertEqual(timeline.liveSegmentDurationMs, 2000) + m.assertEqual(timeline.liveFirstSeqnum, 0) + m.AssertAnchored(timeline, 2000000000, 0, 0) + end function + + @it("anchors a young stream at its first segment, with the full window to grow into and no cushion") + function _() + timeline = Innertube.GetLiveTimeline(2, 10000, 5, 43200, 3, 2000000000, 999) + m.assertEqual(timeline.liveWindowSegments, 8640) + m.assertEqual(timeline.liveFirstSeqnum, 0) + m.assertEqual(timeline.liveSeekableWindowSec, 43200 - 5) + ' younger than its 3-segment cushion: plays at the head + m.AssertAnchored(timeline, 2000000000, 999, 0) + end function + + @it("keeps the cushion once the stream is older than it") + function _() + ' 4 segments (0..3) of 5s against a 3-segment cushion + timeline = Innertube.GetLiveTimeline(3, 15000, 5, 43200, 3, 2000000000, 0) + m.AssertAnchored(timeline, 2000000000, 0, 15000) + end function + + ' The player's rewind floor: (now - availabilityStartTime) - the seekable window, from 0. + function FloorMs(timeline as object) as integer + ast = CreateObject("roDateTime") + ast.FromISO8601String(timeline.liveAvailabilityStartUtc) + return MathUtils.Max((2000000000 - ast.AsSeconds()) * 1000 - timeline.liveSeekableWindowSec * 1000, 0) + end function + + @it("puts the player's rewind floor a segment into the listed window") + function _() + timeline = Innertube.GetLiveTimeline(1923180, 9615900000&, 5, 43200, 3, 2000000000, 250) + ' the first listed segment starts at the timeline offset; whole seconds round the floor + secondStartMs = timeline.liveTimelineOffsetMs + timeline.liveSegmentDurationMs + floorMs = m.FloorMs(timeline) + m.assertTrue(floorMs > secondStartMs - 1000 and floorMs < secondStartMs + 1000, `floor ${floorMs} vs second segment at ${secondStartMs}`) + end function + + @it("puts a young stream's rewind floor at its start") + function _() + m.assertEqual(m.FloorMs(Innertube.GetLiveTimeline(40, 200000, 5, 43200, 3, 2000000000, 700)), 0) + end function + + @it("caps the window at maxDvrDurationSec") + function _() + timeline = Innertube.GetLiveTimeline(100000, 500000000, 5, 3600, 3, 2000000000, 0) + m.assertEqual(timeline.liveWindowSegments, 720) + end function + + @it("caps the window at 12h when maxDvrDurationSec is missing") + function _() + timeline = Innertube.GetLiveTimeline(100000, 500000000, 5, 0, 3, 2000000000, 0) + m.assertEqual(timeline.liveWindowSegments, 8640) + end function + + @it("raises the readahead to 3 seconds' worth (ultra low latency: 2 chunks of 1s)") + function _() + timeline = Innertube.GetLiveTimeline(100000, 100000000, 1, 43200, 2, 2000000000, 0) + m.AssertAnchored(timeline, 2000000000, 0, 3000) + end function + + @it("raises the readahead to 3 seconds of the measured duration, not targetDurationSec") + function _() + ' declared 5s, measured 1.8s: 1 chunk would be 1.8s + timeline = Innertube.GetLiveTimeline(10000, 18000000, 5, 43200, 1, 2000000000, 0) + m.AssertAnchored(timeline, 2000000000, 0, 2 * 1800) + end function + + @it("defaults a missing readahead to 3 chunks and caps it at 8") + function _() + m.AssertAnchored(Innertube.GetLiveTimeline(100000, 500000000, 5, 43200, 0, 2000000000, 0), 2000000000, 0, 15000) + m.AssertAnchored(Innertube.GetLiveTimeline(100000, 500000000, 5, 43200, 20, 2000000000, 0), 2000000000, 0, 40000) + end function + + @it("carries the sub-second remainder into the timeline offset") + function _() + timeline = Innertube.GetLiveTimeline(10000, 18000000, 2, 43200, 3, 2000000000, 900) + m.AssertAnchored(timeline, 2000000000, 900, 5400) + end function + + @describe("Innertube.ReadLiveHeadSeqnum") + + @it("reads X-Head-Seqnum") + function _() + m.assertEqual(Innertube.ReadLiveHeadSeqnum(m.FakeResponse({ "X-Head-Seqnum": "9059091" })), 9059091) + end function + + @it("returns -1 without the header") + function _() + m.assertEqual(Innertube.ReadLiveHeadSeqnum(m.FakeResponse({ "X-Walltime-Ms": "1791305190669" })), -1) + m.assertEqual(Innertube.ReadLiveHeadSeqnum(m.FakeResponse(invalid)), -1) + end function + + @describe("Innertube.ReadLiveHeadTimeMs") + + @it("reads X-Head-Time-Millis past 32 bits") + function _() + m.assertEqual(Innertube.ReadLiveHeadTimeMs(m.FakeResponse({ "X-Head-Time-Millis": "17900000123", "X-Head-Time-Sec": "17900000" })), 17900000123&) + end function + + @it("returns invalid without X-Head-Time-Millis, X-Head-Time-Sec or not") + function _() + m.assertInvalid(Innertube.ReadLiveHeadTimeMs(m.FakeResponse({ "X-Head-Time-Sec": "17900000" }))) + m.assertEqual(Innertube.ReadLiveHeadTimeSecAsMs(m.FakeResponse({ "X-Head-Time-Sec": "17900000" })), 17900000000&) + m.assertInvalid(Innertube.ReadLiveHeadTimeSecAsMs(m.FakeResponse({ "X-Head-Time-Millis": "17900000123" }))) + end function + + function FakeResponse(headers as dynamic) as object + return { + headerData: headers + Headers: function() as dynamic + return m.headerData + end function + } + end function + + end class + +end namespace diff --git a/playlet-lib/src/source/tests/Services/Invidious/InvidiousService.spec.bs b/playlet-lib/src/source/tests/Services/Invidious/InvidiousService.spec.bs new file mode 100644 index 00000000..bb36bb9f --- /dev/null +++ b/playlet-lib/src/source/tests/Services/Invidious/InvidiousService.spec.bs @@ -0,0 +1,27 @@ +import "pkg:/components/Services/Invidious/InvidiousService.bs" + +namespace Tests + + @suite + class InvidiousServiceTests extends Rooibos.BaseTestSuite + + @describe("Invidious.NeedsLiveStreamInfo") + + @it("needs the live timeline for a live response from an Invidious server") + function _() + m.assertTrue(Invidious.NeedsLiveStreamInfo({ liveNow: true, adaptiveFormats: [{ url: "https://example.googlevideo.com/videoplayback" }] })) + end function + + @it("keeps the live timeline the built-in instance's response carries") + function _() + m.assertFalse(Invidious.NeedsLiveStreamInfo({ liveNow: true, adaptiveFormats: [{ url: "https://example.googlevideo.com/videoplayback" }], liveHeadUrl: "https://example.googlevideo.com/videoplayback?rn=0" })) + end function + + @it("needs nothing for a video that isn't live") + function _() + m.assertFalse(Invidious.NeedsLiveStreamInfo({ liveNow: false, adaptiveFormats: [{ url: "https://example.googlevideo.com/videoplayback" }] })) + end function + + end class + +end namespace diff --git a/playlet-lib/src/source/tests/VideoPlayerDev/TransportController.spec.bs b/playlet-lib/src/source/tests/VideoPlayerDev/TransportController.spec.bs index 9e4da9ab..75a6c646 100644 --- a/playlet-lib/src/source/tests/VideoPlayerDev/TransportController.spec.bs +++ b/playlet-lib/src/source/tests/VideoPlayerDev/TransportController.spec.bs @@ -1129,8 +1129,8 @@ namespace Tests end function ' ========================================================================================= - ' LIVE DVR FLOOR — the generated DASH anchors t=0 to the window start, so once the session - ' outlives the window the oldest available position is edge - window, not 0. + ' LIVE DVR FLOOR — once the session outlives the window, the oldest available position is + ' edge - window, not 0. ' ========================================================================================= @describe("live dvr floor") @@ -1319,36 +1319,6 @@ namespace Tests m.assertEqual(t.edgeMs, 305000) end function - ' ========================================================================================= - ' LIVE REWINDABILITY — a buffer-sized DVR window (the manifest's timeShiftBufferDepth) is not - ' a rewind feature: the brain takes no live transport input and the bar drops its label. - ' ========================================================================================= - @describe("live rewindability") - - @it("a buffer-sized window is not rewindable; a real window or an unknown one is") - function _() - t = m.LiveWindowed() ' 60s window = exactly the threshold - m.assertTrue(t.CanRewindLive()) - t.SetLiveDvrWindow(30000) - m.assertFalse(t.CanRewindLive()) - t.SetLiveDvrWindow(0) ' unknown -> assume rewindable - m.assertTrue(t.CanRewindLive()) - ' VOD is never "live-rewindable" - m.assertFalse(m.t.CanRewindLive()) - end function - - @it("a non-rewindable live stream ignores every transport command (incl. InstantReplay)") - function _() - t = m.LiveWindowed() - t.SetLiveDvrWindow(30000) - for each cmd in [TransportController.Command.Left, TransportController.Command.Right, TransportController.Command.Rev, TransportController.Command.Fwd, TransportController.Command.Replay] - t.HandleCommand(cmd) - m.assertEqual(t.transportMode, TransportController.Mode.Idle, "cmd=" + cmd.ToStr() + " must be ignored") - m.assertInvalid(t.TakeVideoIntent()) - end for - m.assertTrue(t.atLiveEdge) - end function - ' ========================================================================================= ' VOD COMMIT AT THE END — finish (PlayNext/close), don't seek into the last instants. ' ========================================================================================= diff --git a/playlet-lib/src/source/tests/VideoPlayerDev/TransportControllerCompleteness.spec.bs b/playlet-lib/src/source/tests/VideoPlayerDev/TransportControllerCompleteness.spec.bs index da9663d7..a8c32e3a 100644 --- a/playlet-lib/src/source/tests/VideoPlayerDev/TransportControllerCompleteness.spec.bs +++ b/playlet-lib/src/source/tests/VideoPlayerDev/TransportControllerCompleteness.spec.bs @@ -15,7 +15,7 @@ namespace Tests ' ---------- brain builders / snapshot ---------- ' a fresh brain at rest (idle, ready) with realistic content facts. windowMs = the live DVR window - ' (0 = unknown), the axis that decides the rewind floor and live rewindability. + ' (0 = unknown), the axis that decides the rewind floor. function Fresh(isLive as boolean, windowMs = 0 as integer) as object t = new TransportController.Controller() t.SetContent(isLive, 2000, true) @@ -31,12 +31,12 @@ namespace Tests end function ' the content variants the exhaustive matrix + fuzz sweep: VOD, live with an unknown window, live with - ' a buffer-sized (non-rewindable) window, and live with a real window (active rewind floor). + ' a window shorter than the session (floor near the edge), and live with a longer window. function Variants() as object return [ { isLive: false, windowMs: 0, tag: " [vod] " } { isLive: true, windowMs: 0, tag: " [live] " } - { isLive: true, windowMs: 30000, tag: " [live no-dvr] " } + { isLive: true, windowMs: 30000, tag: " [live short window] " } { isLive: true, windowMs: 90000, tag: " [live windowed] " } ] end function diff --git a/playlet-lib/src/source/tests/Web/PlayletWebServer/Middleware/DashRouter.spec.bs b/playlet-lib/src/source/tests/Web/PlayletWebServer/Middleware/DashRouter.spec.bs new file mode 100644 index 00000000..a14c7c94 --- /dev/null +++ b/playlet-lib/src/source/tests/Web/PlayletWebServer/Middleware/DashRouter.spec.bs @@ -0,0 +1,301 @@ +import "pkg:/components/Web/PlayletWebServer/Middleware/DashRouter.bs" + +namespace Tests + + @suite + class DashRouterTests extends Rooibos.BaseTestSuite + + protected override function beforeEach() + ' the logger plugin reads m.global.logger; LogTelemetryEvent writes m.global.telemetry.LogEvent. + if m.global.logger = invalid + m.global.addField("logger", "node", false) + m.global.logger = CreateObject("roSGNode", "Logger") + end if + if m.global.telemetry = invalid + m.global.addField("telemetry", "node", false) + telemetry = CreateObject("roSGNode", "Node") + telemetry.addField("LogEvent", "assocarray", false) + m.global.telemetry = telemetry + end if + m.content = CreateObject("roSGNode", "Node") + m.content.addFields({ metadata: {}, videoLoadId: "" }) + player = CreateObject("roSGNode", "Node") + player.addFields({ content: m.content }) + queueNode = CreateObject("roSGNode", "Node") + queueNode.addFields({ player: player }) + m.router = new Http.DashRouter({ + sceneNodes: { videoQueue: queueNode, invidious: invalid, preferences: invalid } + settings: { Port: 8888 } + }) + end function + + ' What VideoContentJob sets on the player's content for a video load. + function PushLoad(videoLoadId as string, metadata as object) + m.content.metadata = metadata + m.content.videoLoadId = videoLoadId + end function + + function PushMetadata(videoLoadId as string, videoId as string) + m.PushLoad(videoLoadId, { videoId: videoId, adaptiveFormats: [] }) + end function + + @describe("DashRouter.GetMetadata") + + @it("digs the node once per video load") + function _() + m.PushMetadata("load1", "first") + m.assertEqual(m.router.GetMetadata("load1").videoId, "first") + m.PushMetadata("load1", "pushed later") + m.assertEqual(m.router.GetMetadata("load1").videoId, "first") + end function + + @it("re-digs on a new video load, even for the same video") + function _() + m.PushMetadata("load1", "same") + m.router.GetMetadata("load1") + m.PushLoad("load2", { videoId: "same", adaptiveFormats: [], title: "re-signed" }) + m.assertEqual(m.router.GetMetadata("load2").title, "re-signed") + end function + + @it("returns invalid for a load the node doesn't hold, keeping the cached one") + function _() + m.PushMetadata("load1", "first") + m.router.GetMetadata("load1") + m.PushMetadata("load2", "second") + m.assertInvalid(m.router.GetMetadata("stale")) + m.assertEqual(m.router.GetMetadata("load1").videoId, "first") + end function + + @describe("DashRouter.RefreshLiveHead") + + ' A live load whose head was 2 at 2630 ms (a 0.63s first segment, then 2s: the + ' load-time average is 1315 ms), with `overrides` on its metadata and head checks + ' answering `heads` in order ({ seqnum, timeMs }) and always due. + function LoadLive(heads as object, overrides = {} as object) + metadata = { + videoId: "v" + adaptiveFormats: [{ targetDurationSec: 2 }] + liveHeadUrl: "https://example.googlevideo.com/videoplayback?rn=0" + liveHeadSeqnum: 2 + liveHeadTimeMs: 2630 + liveFirstSeqnum: 0 + liveSegmentDurationMs: 1315 + liveTimelineOffsetMs: 0 + liveWindowSegments: 8640 + } + metadata.Append(overrides) + m.PushLoad("live1", metadata) + m.router.GetMetadata("live1") + m.router.heads = heads + m.router.headChecks = 0 + m.router.CheckLiveHead = function() as object + m.headChecks += 1 + head = m.heads.Shift() + head.response = { + StatusCode: function() as integer + return 403 + end function + ErrorMessage: function(_includeBody = true as boolean) as string + return "Reason:Forbidden" + end function + } + return head + end function + end function + + function RefreshDue() + m.router.liveHeadTimer = invalid + m.router.RefreshLiveHead() + end function + + ' The listed entries at the router's head. + function ListedSegments() as string + return m.router.dashManifest.FillLiveManifest(LIVE_SEGMENTS_TOKEN, m.router.liveHeadSeqnum, m.router.liveDurationRuns, m.router.liveWindowMs) + end function + + @it("only moves the head forward") + function _() + m.LoadLive([{ seqnum: 10, timeMs: 18630 }, { seqnum: 8, timeMs: 14630 }]) + m.RefreshDue() + m.RefreshDue() + m.assertEqual(m.router.liveHeadSeqnum, 10) + end function + + @it("shares one head check between manifest requests closer than LIVE_HEAD_MIN_INTERVAL_MS") + function _() + m.LoadLive([{ seqnum: 10, timeMs: 18630 }, { seqnum: 11, timeMs: 20630 }]) + m.router.RefreshLiveHead() + m.router.RefreshLiveHead() + m.assertEqual(m.router.headChecks, 1) + m.assertEqual(m.router.liveHeadSeqnum, 10) + end function + + @it("keeps the head on a failed check, reporting the first failure of a video load only") + function _() + m.LoadLive([{ seqnum: -1, timeMs: invalid }, { seqnum: -1, timeMs: invalid }, { seqnum: -1, timeMs: invalid }]) + m.global.telemetry.LogEvent = {} + m.RefreshDue() + m.assertEqual(m.router.liveHeadSeqnum, 2) + m.assertEqual(m.global.telemetry.LogEvent.fingerprint, ["live head check failure", "403"]) + m.global.telemetry.LogEvent = {} + m.RefreshDue() + m.assertEmpty(m.global.telemetry.LogEvent) + ' a new video load reports again + m.PushLoad("live2", { videoId: "v", adaptiveFormats: [], liveHeadUrl: "https://example.googlevideo.com/videoplayback?rn=0" }) + m.router.GetMetadata("live2") + m.RefreshDue() + m.assertNotEmpty(m.global.telemetry.LogEvent) + end function + + @it("gives a list behind the head the cadence since load; the load head ended where the list stays ahead") + function _() + ' the load head (2) ended at 3 x 1315; head 7 ends 10000 ms later, at 13945, but is + ' listed to end at 8 x 1315 = 10520. Segments from 2 take 2000 ms; placed to end + ' head 7 at 13945 they'd start at 1945, before segment 1 ends (2630): contiguous, + ' the list 685 ms ahead. + m.LoadLive([{ seqnum: 7, timeMs: 12630 }, { seqnum: 20, timeMs: 38630 }]) + m.global.telemetry.LogEvent = {} + m.RefreshDue() + m.assertEqual(m.router.liveDurationRuns, [{ fromSeqnum: 0, startMs: 0, durationMs: 1315 }, { fromSeqnum: 2, startMs: 2630, durationMs: 2000 }]) + m.assertEqual(m.router.liveLeadMs, 685) + m.assertEqual(m.global.telemetry.LogEvent.fingerprint, ["live timeline correction"]) + m.assertEqual(StringUtils.ParseJsonSafe(m.global.telemetry.LogEvent.message), { + "video_load_id": "live1" + "video_id": "v" + "target_duration_ms": 2000 + "load_head_seqnum": 2 + "load_duration_ms": 1315 + "duration_ms": 2000 + "drift_ms": -3425 + "step_ms": -3425 + "stall": false + "segments_since_load": 5 + "ms_since_load": 10000 + }) + ' still 685 ms ahead at head 20: no new run + m.RefreshDue() + m.assertEqual(m.router.liveDurationRuns.Count(), 2) + end function + + @it("realigns past a gap when the list falls behind, then drops runs the list slid past, reporting once") + function _() + ' 2000 ms at load, 2200 ms real; a 20 s window. The load head (2) ends at 6000. + m.LoadLive([{ seqnum: 5, timeMs: 4000 + 3 * 2200 }, { seqnum: 15, timeMs: 4000 + 13 * 2200 }, { seqnum: 40, timeMs: 89600 }], { liveHeadTimeMs: 4000, liveSegmentDurationMs: 2000, liveWindowSegments: 10 }) + ' head 5: 600 ms behind, within half a segment + m.RefreshDue() + m.assertEqual(m.router.liveDurationRuns.Count(), 1) + ' head 15 ends at 6000 + 28600 = 34600, listed at 32000: 5 onwards (4 is the last + ' listed) take 2200 ms, placed to end 15 there: from 10400, past 4's end (10000) + m.global.telemetry.LogEvent = {} + m.RefreshDue() + m.assertEqual(m.router.liveDurationRuns, [{ fromSeqnum: 0, startMs: 0, durationMs: 2000 }, { fromSeqnum: 5, startMs: 10400, durationMs: 2200 }]) + m.assertEqual(m.router.liveLeadMs, 0) + m.assertNotEmpty(m.global.telemetry.LogEvent) + ' head 40 ends at 91600, listed at 89600: 15 onwards take 85600 / 38 = 2253 ms, + ' from 91600 - 26 x 2253. The list starts at 6 by then: the first run is dropped. + m.global.telemetry.LogEvent = {} + m.RefreshDue() + m.assertEqual(m.router.liveDurationRuns, [{ fromSeqnum: 5, startMs: 10400, durationMs: 2200 }, { fromSeqnum: 15, startMs: 91600 - 26 * 2253, durationMs: 2253 }]) + m.assertEmpty(m.global.telemetry.LogEvent) + end function + + @it("takes a stall as a gap: the cadence stays, and the list stays on the head after it") + function _() + ' 2000 ms exact; head time leaps 90 s between heads 7 and 12, then runs on + heads = [{ seqnum: 7, timeMs: 4000 + 5 * 2000 }, { seqnum: 12, timeMs: 4000 + 10 * 2000 + 90000 }] + for i = 1 to 360 + heads.Push({ seqnum: 12 + 5 * i, timeMs: 4000 + (10 + 5 * i) * 2000 + 90000 }) + end for + m.LoadLive(heads, { liveHeadTimeMs: 4000, liveSegmentDurationMs: 2000 }) + m.RefreshDue() + m.global.telemetry.LogEvent = {} + m.RefreshDue() + ' head 12 ends at 6000 + 110000, listed at 26000: from 7 (unlisted), placed to end 12 there + m.assertEqual(m.router.liveDurationRuns, [{ fromSeqnum: 0, startMs: 0, durationMs: 2000 }, { fromSeqnum: 7, startMs: 116000 - 6 * 2000, durationMs: 2000 }]) + event = StringUtils.ParseJsonSafe(m.global.telemetry.LogEvent.message) + m.assertTrue(event.stall) + m.assertEqual(event.step_ms, -90000) + for i = 1 to 360 + m.RefreshDue() + end for + m.assertEqual(m.router.liveDurationRuns.Count(), 2) + m.assertEqual(m.router.liveLeadMs, 0) + end function + + @it("takes a list ahead by more than the stall bound as cadence: a stall before load heals at once") + function _() + ' head 5 at 30 s: a 20 s stall before load averages 6000 ms; real 2000 + m.LoadLive([{ seqnum: 10, timeMs: 40000 }, { seqnum: 15, timeMs: 50000 }], { liveHeadSeqnum: 5, liveHeadTimeMs: 30000, liveSegmentDurationMs: 6000 }) + m.RefreshDue() + m.assertEqual(m.router.liveDurationRuns[1].durationMs, 2000) + m.RefreshDue() + m.assertEqual(m.router.liveDurationRuns.Count(), 2) + end function + + @it("takes a second leap on the next check as cadence") + function _() + m.LoadLive([{ seqnum: 12, timeMs: 4000 + 10 * 2000 + 90000 }, { seqnum: 17, timeMs: 4000 + 15 * 2000 + 180000 }], { liveHeadTimeMs: 4000, liveSegmentDurationMs: 2000 }) + m.RefreshDue() + m.assertTrue(m.router.liveLastCheckJumped) + m.RefreshDue() + m.assertFalse(m.router.liveLastCheckJumped) + ' the cadence since the stall's base (head 12): 100000 ms over 5 segments + m.assertEqual(m.router.liveDurationRuns[2].durationMs, 20000) + end function + + @it("measures a young stream's cadence on the check after one that leapt past the stall bound") + function _() + ' head 1 at load after a 0.63 s first segment (630 ms average), 2000 ms real, checks + ' 20 s apart: 10 segments x 1370 ms behind per check + m.LoadLive([{ seqnum: 11, timeMs: 630 + 10 * 2000 }, { seqnum: 21, timeMs: 630 + 20 * 2000 }, { seqnum: 31, timeMs: 630 + 30 * 2000 }], { liveHeadSeqnum: 1, liveHeadTimeMs: 630, liveSegmentDurationMs: 630 }) + m.RefreshDue() + m.assertTrue(m.router.liveLastCheckJumped) + m.RefreshDue() + m.assertEqual(m.router.liveDurationRuns[m.router.liveDurationRuns.Count() - 1].durationMs, 2000) + runCount = m.router.liveDurationRuns.Count() + m.RefreshDue() + m.assertEqual(m.router.liveDurationRuns.Count(), runCount) + end function + + @it("keeps the listed segments' times across a correction") + function _() + m.LoadLive([{ seqnum: 5, timeMs: 4000 + 3 * 2200 }, { seqnum: 15, timeMs: 4000 + 13 * 2200 }], { liveHeadTimeMs: 4000, liveSegmentDurationMs: 2000 }) + m.RefreshDue() + before = m.ListedSegments() + m.RefreshDue() + m.assertEqual(m.router.liveDurationRuns.Count(), 2) + after = m.ListedSegments() + m.assertEqual(after.Left(before.Len()), before) + end function + + @it("leaves a list within half a segment of the head") + function _() + ' 1318 ms real against 1315 listed: 114 ms behind at head 40 + m.LoadLive([{ seqnum: 40, timeMs: 2630 + 38 * 1318 }]) + m.RefreshDue() + m.assertEqual(m.router.liveDurationRuns, [{ fromSeqnum: 0, startMs: 0, durationMs: 1315 }]) + end function + + @it("skips a head check without a time, and corrects at a later one") + function _() + m.LoadLive([{ seqnum: 7, timeMs: invalid }, { seqnum: 12, timeMs: 22630 }]) + m.RefreshDue() + m.assertEqual(m.router.liveHeadSeqnum, 7) + m.assertEqual(m.router.liveDurationRuns.Count(), 1) + m.RefreshDue() + m.assertEqual(m.router.liveDurationRuns.Count(), 2) + end function + + @it("times the head of a stream live for 111 days (head time past 32 bits)") + function _() + ' 5000 ms at load, 5300 real: head +10 ends 53000 ms later, listed 50000 later + m.LoadLive([{ seqnum: 1923190, timeMs: 9615900000& + 53000 }], { liveHeadSeqnum: 1923180, liveHeadTimeMs: 9615900000&, liveFirstSeqnum: 1914541, liveSegmentDurationMs: 5000, liveTimelineOffsetMs: 250 }) + m.RefreshDue() + ' the load head ends at 250 + 8640 x 5000; 1923180 onwards stay contiguous, 300 ms ahead + m.assertEqual(m.router.liveDurationRuns[1], { fromSeqnum: 1923180, startMs: 250 + 8639 * 5000, durationMs: 5300 }) + m.assertEqual(m.router.liveLeadMs, 300) + end function + + end class + +end namespace