Various Live stream improvements, streamed directly without local proxy, attempt to reduce errors and stutters.

This commit is contained in:
Brahim Hadriche committed 2026-10-07 17:59:50 -04:00
1 parent 2dbd5840c0
commit 2bdcd0007d
27 files changed
+1360 -946

No files matched your search

+27 -23
View File
@@ -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
@@ -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
@@ -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, <S> 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", "<S t=.(\d+). d=.(\d+). r=.(\d+). />", "").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
@@ -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
@@ -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
@@ -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.
' =========================================================================================
@@ -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
@@ -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 <S> 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