From 555665488d9f0a43b81d6c6a017b9ecd81229dfd Mon Sep 17 00:00:00 2001 From: Brahim Hadriche Date: Fri, 16 Oct 2026 14:05:19 -0400 Subject: [PATCH] Live stream fixes --- CHANGELOG.md | 1 + .../components/Services/Dash/DashManifest.bs | 22 +++--- .../Services/Dash/LiveHeadCounts.bs | 3 - .../Services/Dash/LiveLoadCounts.bs | 3 + .../Services/Innertube/LiveStreamInfo.bs | 52 ++++++++----- .../Services/Innertube/PlayerEndpoint.bs | 2 +- .../Services/Innertube/PostLiveDvrInfo.bs | 77 +++++-------------- .../VideoPlayerDev/PlaybackTelemetry.bs | 11 +-- .../PlayletWebServer/Middleware/DashRouter.bs | 39 ++++++++-- .../components/Web/tests/HttpTestServer.bs | 9 ++- .../tests/Services/Dash/DashManifest.spec.bs | 18 +++++ .../Services/Innertube/LiveStreamInfo.spec.bs | 25 ++++++ .../Innertube/PostLiveDvrInfo.spec.bs | 58 +++++++++----- .../VideoPlayerDev/PlaybackTelemetry.spec.bs | 37 +++++---- .../Middleware/DashRouter.spec.bs | 57 ++++++++++++-- playlet-lib/src/source/utils/Types.bs | 4 +- playlet-lib/src/source/utils/Types.spec.bs | 10 +++ 17 files changed, 280 insertions(+), 148 deletions(-) delete mode 100644 playlet-lib/src/components/Services/Dash/LiveHeadCounts.bs create mode 100644 playlet-lib/src/components/Services/Dash/LiveLoadCounts.bs diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e9bd2ec..290ad1e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Error message when account requires age verification +- Live stream fixes ## [0.48.9] - 2026-10-14 diff --git a/playlet-lib/src/components/Services/Dash/DashManifest.bs b/playlet-lib/src/components/Services/Dash/DashManifest.bs index e9cb0e75..5915f73f 100644 --- a/playlet-lib/src/components/Services/Dash/DashManifest.bs +++ b/playlet-lib/src/components/Services/Dash/DashManifest.bs @@ -54,7 +54,6 @@ class DashManifest adaptiveFormats = m.ProxyFormatsThroughInvidious(adaptiveFormats) end if - duration = m.GetDuration(metadata) isLive = ValidBool(metadata.liveNow) groupings = m.CreateFormatGroupings(adaptiveFormats, metadata.isPostLiveDvr, isLive) @@ -119,7 +118,7 @@ class DashManifest else mpdAttributes["profiles"] = "urn:mpeg:dash:profile:full:2011" mpdAttributes["type"] = "static" - mpdAttributes["mediaPresentationDuration"] = `PT${duration}S` + mpdAttributes["mediaPresentationDuration"] = m.FormatDuration(m.GetDurationMs(metadata)) end if ' Live needs an explicit Period start to anchor the timeline against availabilityStartTime. @@ -169,17 +168,17 @@ class DashManifest return proxied end function - function GetDuration(metadata as object) as dynamic - if metadata["isPostLiveDvr"] = true and IsInt(metadata["postLiveDvrDurationMs"]) - return metadata["postLiveDvrDurationMs"] / 1000.0 + function GetDurationMs(metadata as object) as longinteger + if metadata["isPostLiveDvr"] = true and metadata["postLiveDvrDurationMs"] <> invalid + return metadata["postLiveDvrDurationMs"] end if - approxDurationMs = ValidString(ObjectUtils.Dig(metadata, ["adaptiveFormats", 0, "approxDurationMs"])).ToInt() - if approxDurationMs > 0 - return approxDurationMs / 1000.0 + approxDurationMs = StringUtils.ParseJsonSafe(ObjectUtils.Dig(metadata, ["adaptiveFormats", 0, "approxDurationMs"])) + if IsNumber(approxDurationMs) and approxDurationMs > 0 + return approxDurationMs end if - return ValidInt(metadata["lengthSeconds"]) + return ValidInt(metadata["lengthSeconds"]) * 1000& end function ' `durationRuns` ascending. @@ -246,7 +245,7 @@ class DashManifest return seqnum end function - function FormatDuration(ms as integer) as string + function FormatDuration(ms as longinteger) as string return `PT${ms \ 1000}.${Right("00" + (ms mod 1000).ToStr(), 3)}S` end function @@ -638,8 +637,7 @@ class DashManifest if not IsInt(postLiveDvrSegmentCount) xml.Comment(`[ERROR] Post-Live DVR metadata missing postLiveDvrSegmentCount for itag: ${stream.itag}`) ' We're going to guess segment count from targetDurationSec and total duration - totalDurationMs = m.GetDuration(metadata) * 1000.0 - postLiveDvrSegmentCount = MathUtils.Max(Fix(totalDurationMs / (stream.targetDurationSec * 1000)), 1) + postLiveDvrSegmentCount = MathUtils.Max(Fix(m.GetDurationMs(metadata) / (stream.targetDurationSec * 1000)), 1) xml.Comment(`[INFO] Guessing postLiveDvrSegmentCount as ${postLiveDvrSegmentCount} for itag: ${stream.itag}`) end if diff --git a/playlet-lib/src/components/Services/Dash/LiveHeadCounts.bs b/playlet-lib/src/components/Services/Dash/LiveHeadCounts.bs deleted file mode 100644 index a7665c61..00000000 --- a/playlet-lib/src/components/Services/Dash/LiveHeadCounts.bs +++ /dev/null @@ -1,3 +0,0 @@ -' The head check counts of the latest live video load, as { video_load_id, counts }. One file, -' overwritten by each live load: tmp:/ lasts as long as the app. -const LIVE_HEAD_COUNTS_PATH = "tmp:/live_head_counts.json" diff --git a/playlet-lib/src/components/Services/Dash/LiveLoadCounts.bs b/playlet-lib/src/components/Services/Dash/LiveLoadCounts.bs new file mode 100644 index 00000000..3a7f6888 --- /dev/null +++ b/playlet-lib/src/components/Services/Dash/LiveLoadCounts.bs @@ -0,0 +1,3 @@ +' The head check and timeline counts of the latest live video load, as { video_load_id, live_head, +' live_timeline }. One file, overwritten by each live load: tmp:/ lasts as long as the app. +const LIVE_LOAD_COUNTS_PATH = "tmp:/live_load_counts.json" diff --git a/playlet-lib/src/components/Services/Innertube/LiveStreamInfo.bs b/playlet-lib/src/components/Services/Innertube/LiveStreamInfo.bs index f3d608ba..b412eb19 100644 --- a/playlet-lib/src/components/Services/Innertube/LiveStreamInfo.bs +++ b/playlet-lib/src/components/Services/Innertube/LiveStreamInfo.bs @@ -33,33 +33,17 @@ namespace Innertube end if headUrl = GetLiveHeadUrl(adaptiveFormats[0]["url"], cpn) - request = CreateLiveHeadRequest(headUrl) - request.RetryCount(1) - request.RetryIf(function(response as HttpClient.Response) as string - if Innertube.ReadLiveHeadSeqnum(response) < 0 or (Innertube.ReadLiveHeadTimeMs(response) = invalid and Innertube.ReadLiveHeadTimeSecAsMs(response) = invalid) - return `no X-Head-* in the response (HTTP ${response.StatusCode()})` - end if - return "" - end function) - request.Cancellation(cancellation) - response = request.Await() - - headSeqnum = ReadLiveHeadSeqnum(response) - headTimeMs = ReadLiveHeadTimeMs(response) - averagedTimeMs = headTimeMs - if averagedTimeMs = invalid - averagedTimeMs = ReadLiveHeadTimeSecAsMs(response) - end if - if headSeqnum < 0 or averagedTimeMs = invalid + response = FetchLiveHead(headUrl, cancellation) + if not HasLiveHead(response) parsedResponse["error"] = `Live stream head check returned no X-Head-Seqnum / X-Head-Time (HTTP ${response.StatusCode()})\n${response.ErrorMessage()}` return end if now = CreateObject("roDateTime") - timeline = GetLiveTimeline(headSeqnum, averagedTimeMs, ValidInt(adaptiveFormats[0]["targetDurationSec"]), ValidInt(adaptiveFormats[0]["maxDvrDurationSec"]), chunkReadahead, now.AsSeconds(), now.GetMilliseconds()) + timeline = GetLiveTimeline(ReadLiveHeadSeqnum(response), ReadLiveHeadAnyTimeMs(response), ValidInt(adaptiveFormats[0]["targetDurationSec"]), ValidInt(adaptiveFormats[0]["maxDvrDurationSec"]), chunkReadahead, now.AsSeconds(), now.GetMilliseconds()) parsedResponse.Append(timeline) parsedResponse["liveHeadUrl"] = headUrl - parsedResponse["liveHeadTimeMs"] = headTimeMs + parsedResponse["liveHeadTimeMs"] = ReadLiveHeadTimeMs(response) end function ' The live timeline fields for a stream whose head (newest segment) is @@ -148,6 +132,25 @@ namespace Innertube return request end function + ' The head check's answer, sent once more when it lacks the head (HasLiveHead), whatever its HTTP status. + function FetchLiveHead(headUrl as string, cancellation as object) as HttpClient.Response + request = CreateLiveHeadRequest(headUrl) + request.RetryCount(1) + request.RetryIf(function(response as HttpClient.Response) as string + if not Innertube.HasLiveHead(response) + return `no X-Head-* in the response (HTTP ${response.StatusCode()})` + end if + return "" + end function) + request.Cancellation(cancellation) + return request.Await() + end function + + ' Whether a head check's answer carries the head's seqnum and time. + function HasLiveHead(response as HttpClient.Response) as boolean + return ReadLiveHeadSeqnum(response) >= 0 and ReadLiveHeadAnyTimeMs(response) <> invalid + 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). @@ -167,6 +170,15 @@ namespace Innertube return StringUtils.ParseJsonSafe(ValidString(response.Headers()["X-Head-Time-Millis"])) end function + ' X-Head-Time-Millis, else X-Head-Time-Sec in ms, invalid if neither. + function ReadLiveHeadAnyTimeMs(response as HttpClient.Response) as dynamic + timeMs = ReadLiveHeadTimeMs(response) + if timeMs = invalid + timeMs = ReadLiveHeadTimeSecAsMs(response) + end if + return timeMs + 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 HttpClient.Response) as dynamic diff --git a/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs b/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs index 814a757a..14564391 100644 --- a/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs @@ -190,7 +190,7 @@ namespace Innertube if isPostLiveDvr LogDebug("Fetching Post-Live DVR info") - GetPostLiveDvrInfo(parsedResponse, adaptiveFormats, playerRequest.cpn, client, cancellation) + GetPostLiveDvrInfo(parsedResponse, adaptiveFormats, playerRequest.cpn, cancellation) end if if isOTF diff --git a/playlet-lib/src/components/Services/Innertube/PostLiveDvrInfo.bs b/playlet-lib/src/components/Services/Innertube/PostLiveDvrInfo.bs index fac2ef4b..06b2d9cb 100644 --- a/playlet-lib/src/components/Services/Innertube/PostLiveDvrInfo.bs +++ b/playlet-lib/src/components/Services/Innertube/PostLiveDvrInfo.bs @@ -1,11 +1,11 @@ -import "pkg:/components/Services/Innertube/Context.bs" +import "pkg:/components/Services/Innertube/LiveStreamInfo.bs" import "pkg:/source/services/HttpClient.bs" import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/UrlUtils.bs" namespace Innertube - function GetPostLiveDvrInfo(parsedResponse as object, adaptiveFormats as object, cpn as dynamic, client as Innertube.ClientType, cancellation as object) as void + function GetPostLiveDvrInfo(parsedResponse as object, adaptiveFormats as object, cpn as dynamic, cancellation as object) as void if adaptiveFormats.Count() = 0 LogWarn("GetPostLiveDvrInfo: No adaptive formats available") return @@ -19,25 +19,16 @@ namespace Innertube ' Query the live edge (no sq): that response is Cache-Control: no-cache, always ' served fresh, so it carries X-Head-*. A finished stream's head is its final - ' segment, so X-Head-Seqnum is the total count and X-Head-Time-Millis the duration. - primary = FetchPostLiveDvrHead(formatUrl, invalid, cpn, client, cancellation) - headers = invalid + ' segment, so X-Head-Seqnum is the total count and X-Head-Time-* the duration. + headUrl = GetLiveHeadUrl(formatUrl, cpn) + response = FetchLiveHead(headUrl, cancellation) - if HasPostLiveDvrHead(primary) - headers = primary.headers - else - ' sq=0 is cacheable, so an edge can return it missing X-Head-* (#359); fall - ' back to it only when the live-edge query misses. - fallback = FetchPostLiveDvrHead(formatUrl, "0", cpn, client, cancellation) - diagnostics = PostLiveDvrDiagnostics(parsedResponse["videoId"], primary, fallback) - if HasPostLiveDvrHead(fallback) - headers = fallback.headers - LogTelemetryEvent({ - level: "warning" - message: `GetPostLiveDvrInfo: no-sq missing head, sq=0 fallback recovered\n${diagnostics}` - fingerprint: ["GetPostLiveDvrInfo: sq=0 fallback recovered"] - }) - else + if not HasLiveHead(response) + ' sq=0 is cacheable, so an edge can return it missing X-Head-*; fall back to it + ' only when the live-edge query misses. + fallback = FetchLiveHead(UrlUtils.AppendQueryParams(headUrl, { "sq": "0" }), cancellation) + diagnostics = PostLiveDvrDiagnostics(parsedResponse["videoId"], headUrl, response, fallback) + if not HasLiveHead(fallback) ' Warning, not error: a known transport-failure tail where playback fails regardless. LogTelemetryEvent({ level: "warning" @@ -46,10 +37,16 @@ namespace Innertube }) return end if + LogTelemetryEvent({ + level: "warning" + message: `GetPostLiveDvrInfo: no-sq missing head, sq=0 fallback recovered\n${diagnostics}` + fingerprint: ["GetPostLiveDvrInfo: sq=0 fallback recovered"] + }) + response = fallback end if - durationMs = ValidString(headers["X-Head-Time-Millis"]).ToInt() - segmentCount = ValidString(headers["X-Head-Seqnum"]).ToInt() + durationMs = ReadLiveHeadAnyTimeMs(response) + segmentCount = ReadLiveHeadSeqnum(response) if durationMs > 0 parsedResponse["postLiveDvrDurationMs"] = durationMs @@ -59,40 +56,8 @@ namespace Innertube end if end function - function FetchPostLiveDvrHead(formatUrl as string, sq as dynamic, cpn as dynamic, client as Innertube.ClientType, cancellation as object) as object - queryComponents = UrlUtils.ParseQueryComponents(formatUrl) - queryComponents["rn"] = "0" - if sq <> invalid - queryComponents["sq"] = sq - end if - if not StringUtils.IsNullOrEmpty(cpn) - queryComponents["cpn"] = cpn - end if - url = UrlUtils.SetQueryParams(formatUrl, queryComponents) - - request = HttpClient.Head(url) - requestHeaders = Innertube.CreateHeaders(client) - requestHeaders["origin"] = "https://www.youtube.com" - requestHeaders["referer"] = "https://www.youtube.com" - requestHeaders["DNT"] = "?1" - request.Headers(requestHeaders) - request.RetryCount(1) - request.Cancellation(cancellation) - response = request.Await() - - return { - url: url - statusCode: response.StatusCode() - headers: response.Headers() - } - end function - - function HasPostLiveDvrHead(result as object) as boolean - return IsAssociativeArray(result) and IsAssociativeArray(result.headers) and result.headers.DoesExist("X-Head-Time-Millis") and result.headers.DoesExist("X-Head-Seqnum") - end function - - function PostLiveDvrDiagnostics(videoId as dynamic, primary as object, fallback as object) as string - return `VideoID: ${ValidString(videoId)}` + Chr(10) + `URL (no-sq; sq=0 appends &sq=0): ${primary.url}` + Chr(10) + `no-sq HEAD status: ${primary.statusCode.ToStr()} headers: ${FormatJson(primary.headers)}` + Chr(10) + `sq=0 HEAD status: ${fallback.statusCode.ToStr()} headers: ${FormatJson(fallback.headers)}` + function PostLiveDvrDiagnostics(videoId as dynamic, headUrl as string, primary as HttpClient.Response, fallback as HttpClient.Response) as string + return `VideoID: ${ValidString(videoId)}` + Chr(10) + `URL (no-sq; sq=0 appends &sq=0): ${headUrl}` + Chr(10) + `no-sq HEAD status: ${primary.StatusCode().ToStr()} headers: ${FormatJson(primary.Headers())}` + Chr(10) + `sq=0 HEAD status: ${fallback.StatusCode().ToStr()} headers: ${FormatJson(fallback.Headers())}` end function end namespace diff --git a/playlet-lib/src/components/VideoPlayerDev/PlaybackTelemetry.bs b/playlet-lib/src/components/VideoPlayerDev/PlaybackTelemetry.bs index e7ab50dd..39400c7b 100644 --- a/playlet-lib/src/components/VideoPlayerDev/PlaybackTelemetry.bs +++ b/playlet-lib/src/components/VideoPlayerDev/PlaybackTelemetry.bs @@ -1,4 +1,4 @@ -import "pkg:/components/Services/Dash/LiveHeadCounts.bs" +import "pkg:/components/Services/Dash/LiveLoadCounts.bs" import "pkg:/components/VideoPlayerDev/VideoNode.bs" import "pkg:/source/utils/ErrorUtils.bs" import "pkg:/source/utils/Locale.bs" @@ -345,10 +345,11 @@ namespace PlaybackTelemetry "tail_resolve_samples": m.tailResolveSamples } if m.transport.isLive - liveHead = StringUtils.ParseJsonSafe(ReadAsciiFile(LIVE_HEAD_COUNTS_PATH)) - if liveHead <> invalid and liveHead["video_load_id"] = summary["video_load_id"] - summary["live_head"] = liveHead["counts"] - DeleteFile(LIVE_HEAD_COUNTS_PATH) + liveLoadCounts = StringUtils.ParseJsonSafe(ReadAsciiFile(LIVE_LOAD_COUNTS_PATH)) + if liveLoadCounts <> invalid and liveLoadCounts["video_load_id"] = summary["video_load_id"] + summary["live_head"] = liveLoadCounts["live_head"] + summary["live_timeline"] = liveLoadCounts["live_timeline"] + DeleteFile(LIVE_LOAD_COUNTS_PATH) end if summary["start_segment_bitrate_bps"] = m.startSegmentBitrateBps summary["start_measured_bitrate_bps"] = m.startMeasuredBitrateBps diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs index aa2f0caa..2cdc1d37 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs @@ -1,6 +1,6 @@ import "pkg:/components/Services/Dash/DashManifest.bs" import "pkg:/components/Services/Dash/LiveHeadChecks.bs" -import "pkg:/components/Services/Dash/LiveHeadCounts.bs" +import "pkg:/components/Services/Dash/LiveLoadCounts.bs" import "pkg:/components/Services/Dash/LiveTimeline.types.bs" import "pkg:/components/Services/Innertube/LiveStreamInfo.bs" import "pkg:/components/Services/Invidious/InvidiousService.bs" @@ -52,6 +52,7 @@ namespace Http m.liveLeadMs = 0 m.liveDriftMs = 0 m.liveLastCheckJumped = false + m.liveTimelineCounts = invalid m.reportedLiveCorrection = false m.liveManifestTemplate = "" m.liveManifestTemplateKey = invalid @@ -250,13 +251,13 @@ namespace Http newest = head end if end for - WriteAsciiFile(LIVE_HEAD_COUNTS_PATH, FormatJson({ "video_load_id": m.cachedVideoLoadId, "counts": m.liveHeadChecks.counts })) ' Listed segments can't be withdrawn: the head only moves forward. if newest <> invalid and newest.seqnum > m.liveHeadSeqnum m.AlignLiveTimeline(newest) m.liveHeadSeqnum = newest.seqnum end if + WriteAsciiFile(LIVE_LOAD_COUNTS_PATH, FormatJson({ "video_load_id": m.cachedVideoLoadId, "live_head": m.liveHeadChecks.counts, "live_timeline": m.liveTimelineCounts })) end function ' Segments are listed at the duration at load, the stream's lifetime average: off @@ -272,11 +273,23 @@ namespace Http if head.timeMs = invalid or m.liveBaseTimeMs = invalid return end if + ' The cadence since the base. + sinceBaseDurationMs = Cint((head.timeMs - m.liveBaseTimeMs) / (head.seqnum - m.liveBaseSeqnum)) + if sinceBaseDurationMs <= 0 + LogWarnNoTelemetry("Live head time went back:", head.timeMs, "ms at", head.seqnum, "after", m.liveBaseTimeMs, "ms at", m.liveBaseSeqnum) + 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 + counts = m.liveTimelineCounts + counts["timed_checks"] += 1 + counts["drift_ms_min"] = MathUtils.Min(counts["drift_ms_min"], driftMs) + counts["drift_ms_max"] = MathUtils.Max(counts["drift_ms_max"], driftMs) + counts["step_ms_min"] = MathUtils.Min(counts["step_ms_min"], stepMs) + counts["step_ms_max"] = MathUtils.Max(counts["step_ms_max"], stepMs) lastCheckJumped = m.liveLastCheckJumped m.liveLastCheckJumped = false listedDurationMs = durationRuns[durationRuns.Count() - 1].durationMs @@ -288,14 +301,9 @@ namespace Http ' 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 + durationMs = sinceBaseDurationMs 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 fromSeqnum = m.dashManifest.LiveLastListedSeqnum(durationRuns, m.liveHeadSeqnum) + 1 @@ -316,6 +324,11 @@ namespace Http durationRuns.Shift() end while durationRuns.Push({ fromSeqnum: fromSeqnum, startMs: startMs, durationMs: durationMs }) + counts["corrections"] += 1 + if isStall + counts["stall_corrections"] += 1 + end if + counts["duration_runs_max"] = MathUtils.Max(counts["duration_runs_max"], durationRuns.Count()) m.ReportLiveCorrection(head, durationMs, driftMs, stepMs, isStall) end function @@ -393,6 +406,16 @@ namespace Http m.liveLeadMs = 0 m.liveDriftMs = 0 m.liveLastCheckJumped = false + m.liveTimelineCounts = { + "timed_checks": 0 + "corrections": 0 + "stall_corrections": 0 + "drift_ms_min": 0 + "drift_ms_max": 0 + "step_ms_min": 0 + "step_ms_max": 0 + "duration_runs_max": m.liveDurationRuns.Count() + } m.reportedLiveCorrection = false m.liveManifestTemplate = "" m.liveManifestTemplateKey = invalid diff --git a/playlet-lib/src/components/Web/tests/HttpTestServer.bs b/playlet-lib/src/components/Web/tests/HttpTestServer.bs index 8a6586ab..f7f1e492 100644 --- a/playlet-lib/src/components/Web/tests/HttpTestServer.bs +++ b/playlet-lib/src/components/Web/tests/HttpTestServer.bs @@ -7,7 +7,8 @@ import "pkg:/source/utils/Types.bs" ' /delay/ 200 after ' /echo 200 with the request's { method, path, headers, body } as JSON ' /maxage// 200 with Cache-Control: max-age= -' A path in routes (its query aside) responds as its route says instead: { status, headers, body, delayMs }. +' A path in routes responds as its route says instead: { status, headers, body, delayMs }. A route keyed +' with a query answers that query only, ahead of the route keyed with the bare path. ' A route { drop: true } closes the connection without a response. ' Every response carries X-Hit, the request's count for its path. Connections are read and responded to ' without blocking each other, so a slow or abandoned one holds up nothing. @@ -162,7 +163,11 @@ function BuildResponse(item as object) as object m.top.lastRequest = request delayMs = MIN_RESPONSE_DELAY_MS - route = ValidAssociativeArray(m.top.routes)[path.Split("?")[0]] + routes = ValidAssociativeArray(m.top.routes) + route = routes[path] + if route = invalid + route = routes[path.Split("?")[0]] + end if if route <> invalid if ValidInt(route.delayMs) > delayMs delayMs = route.delayMs diff --git a/playlet-lib/src/source/tests/Services/Dash/DashManifest.spec.bs b/playlet-lib/src/source/tests/Services/Dash/DashManifest.spec.bs index 541ad504..35d923f0 100644 --- a/playlet-lib/src/source/tests/Services/Dash/DashManifest.spec.bs +++ b/playlet-lib/src/source/tests/Services/Dash/DashManifest.spec.bs @@ -140,6 +140,24 @@ namespace Tests m.assertEqual(manifest.FormatDuration(999), "PT0.999S") m.assertEqual(manifest.FormatDuration(1500), "PT1.500S") m.assertEqual(manifest.FormatDuration(10000), "PT10.000S") + m.assertEqual(manifest.FormatDuration(17900000123&), "PT17900000.123S") + end function + + @describe("DashManifest.GetDurationMs") + + @it("returns a post-live DVR duration past 32 bits") + function _() + manifest = new DashManifest("") + m.assertEqual(manifest.GetDurationMs({ isPostLiveDvr: true, postLiveDvrDurationMs: 17900000123& }), 17900000123&) + end function + + @it("falls back to the first format's approxDurationMs, then to lengthSeconds") + function _() + manifest = new DashManifest("") + m.assertEqual(manifest.GetDurationMs({ adaptiveFormats: [{ approxDurationMs: "17900000123" }], lengthSeconds: 60 }), 17900000123&) + m.assertEqual(manifest.GetDurationMs({ adaptiveFormats: [{ approxDurationMs: "0" }], lengthSeconds: 60 }), 60000&) + m.assertEqual(manifest.GetDurationMs({ adaptiveFormats: [{}], lengthSeconds: 60 }), 60000&) + m.assertEqual(manifest.GetDurationMs({ isPostLiveDvr: true, adaptiveFormats: [], lengthSeconds: 60 }), 60000&) end function end class diff --git a/playlet-lib/src/source/tests/Services/Innertube/LiveStreamInfo.spec.bs b/playlet-lib/src/source/tests/Services/Innertube/LiveStreamInfo.spec.bs index a435545e..c35b85d5 100644 --- a/playlet-lib/src/source/tests/Services/Innertube/LiveStreamInfo.spec.bs +++ b/playlet-lib/src/source/tests/Services/Innertube/LiveStreamInfo.spec.bs @@ -160,6 +160,22 @@ namespace Tests m.assertEqual(parsedResponse.error, `Live stream head check returned no X-Head-Seqnum / X-Head-Time (HTTP 200)\n`) end function + @describe("Innertube.FetchLiveHead") + + @it("sends the check once more when the answer lacks the head, whatever its status") + function _() + m.server.routes = { + "/live/failing": { status: 503 } + "/live/failingwithhead": { status: 503, headers: { "X-Head-Seqnum": "40", "X-Head-Time-Millis": "80000" } } + } + failing = Tests.HttpTestServerUrl("/live/failing?itag=1") + m.assertFalse(Innertube.HasLiveHead(Innertube.FetchLiveHead(failing, invalid))) + m.assertEqual(Tests.HttpTestServerHits(m.server, failing), 2) + failingWithHead = Tests.HttpTestServerUrl("/live/failingwithhead?itag=1") + m.assertTrue(Innertube.HasLiveHead(Innertube.FetchLiveHead(failingWithHead, invalid))) + m.assertEqual(Tests.HttpTestServerHits(m.server, failingWithHead), 1) + end function + @describe("Innertube.ReadLiveHeadSeqnum") @it("reads X-Head-Seqnum") @@ -187,6 +203,15 @@ namespace Tests m.assertInvalid(Innertube.ReadLiveHeadTimeSecAsMs(m.ResponseWithHeaders({ "X-Head-Time-Millis": "17900000123" }))) end function + @describe("Innertube.ReadLiveHeadAnyTimeMs") + + @it("reads X-Head-Time-Millis, else X-Head-Time-Sec") + function _() + m.assertEqual(Innertube.ReadLiveHeadAnyTimeMs(m.ResponseWithHeaders({ "X-Head-Time-Millis": "17900000123", "X-Head-Time-Sec": "17900000" })), 17900000123&) + m.assertEqual(Innertube.ReadLiveHeadAnyTimeMs(m.ResponseWithHeaders({ "X-Head-Time-Sec": "17900000" })), 17900000000&) + m.assertInvalid(Innertube.ReadLiveHeadAnyTimeMs(m.ResponseWithHeaders({ "X-Head-Seqnum": "40" }))) + end function + function ResponseWithHeaders(headers as object) as HttpClient.Response return new HttpClient.Response({ headers: headers }) end function diff --git a/playlet-lib/src/source/tests/Services/Innertube/PostLiveDvrInfo.spec.bs b/playlet-lib/src/source/tests/Services/Innertube/PostLiveDvrInfo.spec.bs index c643a168..97a0f5cb 100644 --- a/playlet-lib/src/source/tests/Services/Innertube/PostLiveDvrInfo.spec.bs +++ b/playlet-lib/src/source/tests/Services/Innertube/PostLiveDvrInfo.spec.bs @@ -1,6 +1,7 @@ import "pkg:/components/Services/Innertube/PostLiveDvrInfo.bs" import "pkg:/source/tests/HttpTestServer.bs" import "pkg:/source/tests/LoggingGlobals.bs" +import "pkg:/source/utils/UrlUtils.bs" namespace Tests @@ -21,37 +22,52 @@ namespace Tests m.global.telemetry.LogEvent = {} end function - @describe("Innertube.FetchPostLiveDvrHead") - - @it("reads a HEAD's status and headers") - function _() - m.server.routes = { "/dvr/head": { status: 200, headers: { "X-Head-Seqnum": "40", "X-Head-Time-Millis": "80000" } } } - result = Innertube.FetchPostLiveDvrHead(Tests.HttpTestServerUrl("/dvr/head?itag=1"), invalid, "cpn1", Innertube.ClientType.Tv, invalid) - m.assertEqual(result.statusCode, 200) - m.assertTrue(Innertube.HasPostLiveDvrHead(result)) - m.assertEqual(Tests.HttpTestServerHits(m.server, result.url), 1) - end function - - @it("sends a failed HEAD once more") - function _() - m.server.routes = { "/dvr/failing": { status: 503 } } - result = Innertube.FetchPostLiveDvrHead(Tests.HttpTestServerUrl("/dvr/failing?itag=1"), "0", invalid, Innertube.ClientType.Tv, invalid) - m.assertEqual(result.statusCode, 503) - m.assertFalse(Innertube.HasPostLiveDvrHead(result)) - m.assertEqual(Tests.HttpTestServerHits(m.server, result.url), 2) - end function - @describe("Innertube.GetPostLiveDvrInfo") @it("reads the duration and segment count from the live edge's head") function _() m.server.routes = { "/dvr/ended": { status: 200, headers: { "X-Head-Seqnum": "40", "X-Head-Time-Millis": "80000" } } } parsedResponse = {} - Innertube.GetPostLiveDvrInfo(parsedResponse, [{ url: Tests.HttpTestServerUrl("/dvr/ended?itag=1") }], invalid, Innertube.ClientType.Tv, invalid) + Innertube.GetPostLiveDvrInfo(parsedResponse, [{ url: Tests.HttpTestServerUrl("/dvr/ended?itag=1") }], invalid, invalid) m.assertEqual(parsedResponse.postLiveDvrDurationMs, 80000) m.assertEqual(parsedResponse.postLiveDvrSegmentCount, 40) end function + @it("reads a duration past 32 bits") + function _() + m.server.routes = { "/dvr/long": { status: 200, headers: { "X-Head-Seqnum": "3580000", "X-Head-Time-Millis": "17900000123" } } } + parsedResponse = {} + Innertube.GetPostLiveDvrInfo(parsedResponse, [{ url: Tests.HttpTestServerUrl("/dvr/long?itag=1") }], invalid, invalid) + m.assertEqual(parsedResponse.postLiveDvrDurationMs, 17900000123&) + m.assertEqual(parsedResponse.postLiveDvrSegmentCount, 3580000) + end function + + @it("reads the head from sq=0 when the live edge has none") + function _() + formatUrl = Tests.HttpTestServerUrl("/dvr/cached?itag=1") + fallbackUrl = UrlUtils.AppendQueryParams(Innertube.GetLiveHeadUrl(formatUrl, "cpn1"), { "sq": "0" }) + routes = { "/dvr/cached": { status: 200 } } + routes[fallbackUrl.Replace(Tests.HttpTestServerUrl(""), "")] = { status: 200, headers: { "X-Head-Seqnum": "40", "X-Head-Time-Millis": "80000" } } + m.server.routes = routes + parsedResponse = {} + Innertube.GetPostLiveDvrInfo(parsedResponse, [{ url: formatUrl }], "cpn1", invalid) + m.assertEqual(Tests.HttpTestServerHits(m.server, Innertube.GetLiveHeadUrl(formatUrl, "cpn1")), 2) + m.assertEqual(Tests.HttpTestServerHits(m.server, fallbackUrl), 1) + m.assertEqual(parsedResponse.postLiveDvrDurationMs, 80000) + m.assertEqual(parsedResponse.postLiveDvrSegmentCount, 40) + end function + + @it("sets nothing when neither the live edge nor sq=0 has a head") + function _() + m.server.routes = { "/dvr/nohead": { status: 200 } } + formatUrl = Tests.HttpTestServerUrl("/dvr/nohead?itag=1") + parsedResponse = {} + Innertube.GetPostLiveDvrInfo(parsedResponse, [{ url: formatUrl }], "cpn1", invalid) + m.assertEqual(Tests.HttpTestServerHits(m.server, UrlUtils.AppendQueryParams(Innertube.GetLiveHeadUrl(formatUrl, "cpn1"), { "sq": "0" })), 2) + m.assertFalse(parsedResponse.DoesExist("postLiveDvrDurationMs")) + m.assertFalse(parsedResponse.DoesExist("postLiveDvrSegmentCount")) + end function + end class end namespace diff --git a/playlet-lib/src/source/tests/VideoPlayerDev/PlaybackTelemetry.spec.bs b/playlet-lib/src/source/tests/VideoPlayerDev/PlaybackTelemetry.spec.bs index a17721f8..6eca0372 100644 --- a/playlet-lib/src/source/tests/VideoPlayerDev/PlaybackTelemetry.spec.bs +++ b/playlet-lib/src/source/tests/VideoPlayerDev/PlaybackTelemetry.spec.bs @@ -388,34 +388,45 @@ namespace Tests m.assertFalse(summary.DoesExist("stream_source")) end function - @it("the live head check counts of the video load, without defaults, read once") + @it("the live head check and timeline counts of the video load, without defaults, read once") function _() m.fakeTransport.isLive = true m.fakeTop.content.videoLoadId = "live1" - WriteAsciiFile(LIVE_HEAD_COUNTS_PATH, FormatJson({ "video_load_id": "live1", "counts": { "checks_sent": 6, "answered_after_wait": 1, "timed_out": 0 } })) + WriteAsciiFile(LIVE_LOAD_COUNTS_PATH, FormatJson({ + "video_load_id": "live1" + "live_head": { "checks_sent": 6, "answered_after_wait": 1, "timed_out": 0 } + "live_timeline": { "timed_checks": 3, "corrections": 1, "stall_corrections": 0, "drift_ms_min": -3425, "drift_ms_max": 0, "duration_runs_max": 2 } + })) summary = m.SendAt(1000) m.assertEqual(summary.live_head, { "checks_sent": 6, "answered_after_wait": 1 }) - m.assertFalse(CreateObject("roFileSystem").Exists(LIVE_HEAD_COUNTS_PATH), "read once") - m.assertFalse(m.SendAt(2000).DoesExist("live_head")) + m.assertEqual(summary.live_timeline, { "timed_checks": 3, "corrections": 1, "drift_ms_min": -3425, "duration_runs_max": 2 }) + m.assertFalse(CreateObject("roFileSystem").Exists(LIVE_LOAD_COUNTS_PATH), "read once") + summary = m.SendAt(2000) + m.assertFalse(summary.DoesExist("live_head")) + m.assertFalse(summary.DoesExist("live_timeline")) end function - @it("a live play without live head check counts has none") + @it("a live play without live load counts has none") function _() m.fakeTransport.isLive = true m.fakeTop.content.videoLoadId = "live1" - DeleteFile(LIVE_HEAD_COUNTS_PATH) - m.assertFalse(m.SendAt(1000).DoesExist("live_head")) + DeleteFile(LIVE_LOAD_COUNTS_PATH) + summary = m.SendAt(1000) + m.assertFalse(summary.DoesExist("live_head")) + m.assertFalse(summary.DoesExist("live_timeline")) end function - @it("leaves the live head check counts of another video load") + @it("leaves the live load counts of another video load") function _() m.fakeTransport.isLive = true m.fakeTop.content.videoLoadId = "live1" - handoff = FormatJson({ "video_load_id": "live2", "counts": { "checks_sent": 6 } }) - WriteAsciiFile(LIVE_HEAD_COUNTS_PATH, handoff) - m.assertFalse(m.SendAt(1000).DoesExist("live_head")) - m.assertEqual(ReadAsciiFile(LIVE_HEAD_COUNTS_PATH), handoff) - DeleteFile(LIVE_HEAD_COUNTS_PATH) + handoff = FormatJson({ "video_load_id": "live2", "live_head": { "checks_sent": 6 }, "live_timeline": { "corrections": 1 } }) + WriteAsciiFile(LIVE_LOAD_COUNTS_PATH, handoff) + summary = m.SendAt(1000) + m.assertFalse(summary.DoesExist("live_head")) + m.assertFalse(summary.DoesExist("live_timeline")) + m.assertEqual(ReadAsciiFile(LIVE_LOAD_COUNTS_PATH), handoff) + DeleteFile(LIVE_LOAD_COUNTS_PATH) end function @it("a live play: the first video segment's bitrate and the network's at the first playing") 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 index 454890cb..5cf1e3e6 100644 --- a/playlet-lib/src/source/tests/Web/PlayletWebServer/Middleware/DashRouter.spec.bs +++ b/playlet-lib/src/source/tests/Web/PlayletWebServer/Middleware/DashRouter.spec.bs @@ -32,7 +32,7 @@ namespace Tests end function protected override function afterEach() - DeleteFile(LIVE_HEAD_COUNTS_PATH) + DeleteFile(LIVE_LOAD_COUNTS_PATH) end function ' What VideoContentJob sets on the player's content for a video load. @@ -172,15 +172,18 @@ namespace Tests m.assertInvalid(pending["_fetch"]["_urlTransfer"]) end function - @it("writes the load's head check counts at every refresh") + @it("writes the load's head check and timeline counts at every refresh, after its correction") function _() m.LoadLive([{ seqnum: 10, timeMs: 18630 }, { seqnum: -1, timeMs: invalid }]) m.RefreshDue() + handoff = StringUtils.ParseJsonSafe(ReadAsciiFile(LIVE_LOAD_COUNTS_PATH)) + m.assertEqual(handoff["live_timeline"]["corrections"], 1) m.RefreshDue() - handoff = StringUtils.ParseJsonSafe(ReadAsciiFile(LIVE_HEAD_COUNTS_PATH)) + handoff = StringUtils.ParseJsonSafe(ReadAsciiFile(LIVE_LOAD_COUNTS_PATH)) m.assertEqual(handoff["video_load_id"], "live1") - m.assertEqual(handoff["counts"]["checks_sent"], 2) - m.assertEqual(handoff["counts"]["answered_without_head"], 1) + m.assertEqual(handoff["live_head"]["checks_sent"], 2) + m.assertEqual(handoff["live_head"]["answered_without_head"], 1) + m.assertEqual(handoff["live_timeline"], m.router.liveTimelineCounts) end function @it("gives a list behind the head the cadence since load; the load head ended where the list stays ahead") @@ -220,6 +223,16 @@ namespace Tests ' head 5: 600 ms behind, within half a segment m.RefreshDue() m.assertEqual(m.router.liveDurationRuns.Count(), 1) + m.assertEqual(m.router.liveTimelineCounts, { + "timed_checks": 1 + "corrections": 0 + "stall_corrections": 0 + "drift_ms_min": -600 + "drift_ms_max": 0 + "step_ms_min": -600 + "step_ms_max": 0 + "duration_runs_max": 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 = {} @@ -233,6 +246,17 @@ namespace Tests 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) + ' drift -600, -2600, then -2000 off the realigned list + m.assertEqual(m.router.liveTimelineCounts, { + "timed_checks": 3 + "corrections": 2 + "stall_corrections": 0 + "drift_ms_min": -2600 + "drift_ms_max": 0 + "step_ms_min": -2000 + "step_ms_max": 0 + "duration_runs_max": 2 + }) end function @it("takes a stall as a gap: the cadence stays, and the list stays on the head after it") @@ -256,6 +280,9 @@ namespace Tests end for m.assertEqual(m.router.liveDurationRuns.Count(), 2) m.assertEqual(m.router.liveLeadMs, 0) + m.assertEqual(m.router.liveTimelineCounts["corrections"], 1) + m.assertEqual(m.router.liveTimelineCounts["stall_corrections"], 1) + m.assertEqual(m.router.liveTimelineCounts["step_ms_min"], -90000) end function @it("takes a list ahead by more than the stall bound as cadence: a stall before load heals at once") @@ -264,6 +291,9 @@ namespace Tests 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) + ' head 10 ends at 36000 + 10000, listed to end at 11 x 6000 + m.assertEqual(m.router.liveTimelineCounts["drift_ms_max"], 20000) + m.assertEqual(m.router.liveTimelineCounts["step_ms_max"], 20000) m.RefreshDue() m.assertEqual(m.router.liveDurationRuns.Count(), 2) end function @@ -318,8 +348,25 @@ namespace Tests m.RefreshDue() m.assertEqual(m.router.liveHeadSeqnum, 7) m.assertEqual(m.router.liveDurationRuns.Count(), 1) + m.assertEqual(m.router.liveTimelineCounts["timed_checks"], 0) m.RefreshDue() m.assertEqual(m.router.liveDurationRuns.Count(), 2) + m.assertEqual(m.router.liveTimelineCounts["timed_checks"], 1) + end function + + @it("skips a head check whose time went back, unmeasured, and corrects at a later one") + function _() + ' the load head (2) is at 2630 ms; head 7 claims 2000 + m.LoadLive([{ seqnum: 7, timeMs: 2000 }, { seqnum: 12, timeMs: 22630 }]) + m.RefreshDue() + m.assertEqual(m.router.liveHeadSeqnum, 7) + m.assertEqual(m.router.liveDurationRuns.Count(), 1) + m.assertEqual(m.router.liveDriftMs, 0) + m.assertEqual(m.router.liveTimelineCounts["timed_checks"], 0) + m.assertEqual(m.router.liveTimelineCounts["drift_ms_max"], 0) + m.RefreshDue() + m.assertEqual(m.router.liveDurationRuns.Count(), 2) + m.assertEqual(m.router.liveTimelineCounts["timed_checks"], 1) end function @it("times the head of a stream live for 111 days (head time past 32 bits)") diff --git a/playlet-lib/src/source/utils/Types.bs b/playlet-lib/src/source/utils/Types.bs index adf610c7..27030849 100644 --- a/playlet-lib/src/source/utils/Types.bs +++ b/playlet-lib/src/source/utils/Types.bs @@ -58,9 +58,9 @@ function ValidDouble(obj as dynamic) as double end if end function -' Returns true if the given object is numeric (Integer, Float, or Double) +' Returns true if the given object is numeric (Integer, LongInteger, Float, or Double) function IsNumber(obj as dynamic) as boolean - return obj <> invalid and (GetInterface(obj, "ifInt") <> invalid or GetInterface(obj, "ifFloat") <> invalid or GetInterface(obj, "ifDouble") <> invalid) + return obj <> invalid and (GetInterface(obj, "ifInt") <> invalid or GetInterface(obj, "ifLongInt") <> invalid or GetInterface(obj, "ifFloat") <> invalid or GetInterface(obj, "ifDouble") <> invalid) end function ' Returns true if the given object is of type String, false otherwise diff --git a/playlet-lib/src/source/utils/Types.spec.bs b/playlet-lib/src/source/utils/Types.spec.bs index a3c8f84d..a2c299e8 100644 --- a/playlet-lib/src/source/utils/Types.spec.bs +++ b/playlet-lib/src/source/utils/Types.spec.bs @@ -23,6 +23,16 @@ namespace Tests m.assertEqual(ValidString(obj), expected) end function + @it("Checks if an object is a number") + function _() + m.assertTrue(IsNumber(-5)) + m.assertTrue(IsNumber(17900000123&)) + m.assertTrue(IsNumber(1.5!)) + m.assertTrue(IsNumber(1.5#)) + m.assertFalse(IsNumber("5")) + m.assertFalse(IsNumber(invalid)) + end function + end class end namespace