Additional live stream tweaks

This commit is contained in:
Brahim Hadriche committed 2026-05-26 07:13:01 -04:00
1 parent 425f4d9660
commit 0c7a3f36f8
6 files changed
+335 -148

No files matched your search

@@ -4,13 +4,6 @@ import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/UrlUtils.bs"
' Number of native YouTube live fragments (each `targetDurationSec` long) that the
' /api/dash/live-seg proxy concatenates into a single DASH segment. Roku dislikes
' the ~2s native request cadence, so we present longer segments. Used by both the
' manifest (segment duration / refresh timing) and DashRouter's live-seg handler
' (which fragments to fetch per DASH segment number).
const LIVE_SEGMENT_GROUP = 4
class DashManifest
public invidiousInstance as dynamic
@@ -18,6 +11,9 @@ class DashManifest
' 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 = ""
function new(invidiousInstance as string, disableAutoDubbed = false as boolean)
m.invidiousInstance = invidiousInstance
@@ -103,18 +99,26 @@ 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
' Dynamic (live) manifest: the player derives the current segment from
' wall-clock against availabilityStartTime, and the duration-based
' SegmentTemplate (see GenerateSegmentInformation) auto-extends as the
' stream advances. timeShiftBufferDepth exposes the DVR window.
segmentSec = Cint(m.GetLiveFragmentDurationMs(metadata) * LIVE_SEGMENT_GROUP / 1000.0)
segmentSec = Cint(m.GetLiveFragmentDurationMs(metadata) / 1000.0)
if segmentSec < 1
segmentSec = 1
end if
dvrWindowSec = ValidInt(metadata.liveDvrWindowSec)
mpdAttributes["profiles"] = "urn:mpeg:dash:profile:isoff-live:2011"
mpdAttributes["type"] = "dynamic"
' Roku won't track the live edge from wall-clock unless it's handed an
' authoritative "now": without it, it anchors to the Period start
' (availabilityStartTime) and the playhead sits ~stream-age behind. A
' direct UTCTiming + a fresh publishTime (both = current UTC, restamped on
' every refresh) give it that anchor so it computes the real live edge.
nowUtc = CreateObject("roDateTime").ToISOString()
mpdAttributes["publishTime"] = nowUtc
mpdAttributes["minimumUpdatePeriod"] = `PT${segmentSec}S`
mpdAttributes["suggestedPresentationDelay"] = `PT${segmentSec * 3}S`
if not StringUtils.IsNullOrEmpty(metadata.liveAvailabilityStartUtc)
@@ -123,9 +127,8 @@ class DashManifest
if dvrWindowSec > 0
mpdAttributes["timeShiftBufferDepth"] = `PT${dvrWindowSec}S`
else
LogWarn("[LIVE-MPD] dvrWindowSec is 0/missing -> NO timeShiftBufferDepth (live seek may fail). metadata.liveDvrWindowSec:", metadata.liveDvrWindowSec)
LogWarn("Live stream has no DVR window; omitting timeShiftBufferDepth (live seek may fail). videoId:", metadata.videoId)
end if
' LogInfo("[LIVE-MPD] live MPD attrs: availabilityStartTime:", metadata.liveAvailabilityStartUtc, "segmentSec(group-adjusted):", segmentSec, "dvrWindowSec:", dvrWindowSec, "liveHeadSeqnum:", metadata.liveHeadSeqnum, "baseUrl:", m.liveSegmentBaseUrl)
else
mpdAttributes["profiles"] = "urn:mpeg:dash:profile:full:2011"
mpdAttributes["type"] = "static"
@@ -150,6 +153,12 @@ class DashManifest
xml.End()
end if
if isLive
xml.EmptyNode("UTCTiming", {
"schemeIdUri": "urn:mpeg:dash:utc:direct:2014"
"value": nowUtc
})
end if
xml.End()
end if
return xml.ToXmlString()
@@ -168,11 +177,26 @@ class DashManifest
return ValidInt(metadata["lengthSeconds"])
end function
' Representative segment duration for a live stream, in whole seconds.
' 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
end function
' Effective per-native-fragment duration (ms) for live. Prefers the value
' derived from the live head (headTime/headSeqnum, set by GetLiveStreamInfo)
' since YouTube's reported targetDurationSec is unreliable for long-running
' streams; falls back to targetDurationSec, then to 2s.
' 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
@@ -598,22 +622,25 @@ class DashManifest
' YouTube serves no clean init or moof-only media, so Roku can't demux
' them directly (it reads the init segment once; a per-segment moov
' yields `error -36`). The /api/dash/live-seg proxy transforms them
' (init -> ftyp+moov, media -> moof+mdat) and groups LIVE_SEGMENT_GROUP
' native fragments into each DASH segment. The manifest just addresses
' the proxy by itag + DASH segment number ($Number$).
' Per-fragment duration x GROUP. NOT targetDurationSec (unreliable for
' long streams - see GetLiveFragmentDurationMs); the head-derived value
' keeps the player's wall-clock -> $Number$ -> sq mapping on the live edge.
durationMs = m.GetLiveFragmentDurationMs(metadata) * LIVE_SEGMENT_GROUP
' (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}`
' LogInfo("[LIVE-MPD] SegmentTemplate itag:", stream.itag, "targetDurationSec:", stream.targetDurationSec, "group:", LIVE_SEGMENT_GROUP, "durationMs:", durationMs)
segBase = `${m.liveSegmentBaseUrl}/api/dash/live-seg?v=${metadata.videoId}&itag=${stream.itag}&backend=${m.liveBackend}`
xml.EmptyNode("SegmentTemplate", {
"initialization": `${segBase}&sq=init`
"media": `${segBase}&sq=$Number$`
"timescale": "1000"
"duration": durationMs
"startNumber": "0"
"startNumber": startNumber.ToStr()
})
else
xml.TextNode("BaseURL", ValidString(stream.url))
@@ -0,0 +1,125 @@
import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/UrlUtils.bs"
' Hard ceiling for the exposed DVR window. availabilityStartTime is anchored this
' far back at most so the player's ms-scale presentation time (now - AST) stays well
' under INT32_MAX (~24.8 days at timescale=1000). YouTube caps live DVR at 12h.
const LIVE_MAX_DVR_WINDOW_SEC = 43200
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.
'
' 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")
return
end if
url = adaptiveFormats[0]["url"]
if StringUtils.IsNullOrEmpty(url)
LogWarn("GetLiveStreamInfo: URL is empty")
return
end if
maxDvrDurationSec = ValidInt(adaptiveFormats[0]["maxDvrDurationSec"])
queryComponents = UrlUtils.ParseQueryComponents(url)
queryComponents["rn"] = "0"
queryComponents["sq"] = "0"
if not StringUtils.IsNullOrEmpty(cpn)
queryComponents["cpn"] = cpn
end if
url = UrlUtils.SetQueryParams(url, queryComponents)
request = HttpClient.Head(url)
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)
request.TryCount(2)
request.Cancellation(cancellation)
response = request.Await()
if not response.IsSuccess()
LogError("Failed to fetch live stream info", response.ErrorMessage())
return
end if
headers = response.Headers()
if not headers.DoesExist("X-Head-Seqnum")
LogErrorNoTelemetry("[LIVE-INFO] Missing X-Head-Seqnum in headers", url, headers)
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
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.
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
end if
astDate = CreateObject("roDateTime")
astDate.FromSeconds(nowSec - windowSec)
parsedResponse["liveHeadSeqnum"] = headSeqnum
parsedResponse["liveAvailabilityStartUtc"] = astDate.ToISOString()
parsedResponse["liveDvrWindowSec"] = windowSec
' Effective per-fragment duration, derived from the stream's own counters.
' YouTube's reported targetDurationSec is unreliable for long-running streams
' (observed 5s vs a real ~1.8s cadence); using it desyncs the duration-based
' SegmentTemplate so the player requests segments far outside the DVR window
' (404). headTime/headSeqnum is the true average and keeps the manifest's
' wall-clock -> sq mapping anchored to the same (headTime, headSeqnum) pair
' that availabilityStartTime is built from.
if headSeqnum > 0
parsedResponse["liveFragmentDurationMs"] = Cint((headTimeSec / headSeqnum) * 1000.0)
end if
end function
end namespace
@@ -1,4 +1,5 @@
import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/components/Services/Innertube/LiveStreamInfo.bs"
import "pkg:/components/Services/Innertube/NodesParser.bs"
import "pkg:/components/Services/Innertube/OTFSegmentInfo.bs"
import "pkg:/source/services/HttpClient.bs"
@@ -737,85 +738,4 @@ namespace Innertube
end if
end function
' Live streams come back with no hlsManifestUrl/dashManifestUrl, just
' adaptiveFormats with a `targetDurationSec` and segments addressed by `&sq=N`
' (identical to Post-Live DVR). To build a dynamic DASH manifest we need the
' current live edge (X-Head-Seqnum) and a wall-clock anchor for the DASH
' `availabilityStartTime`. X-Head-Time-Millis is the stream-time of the head
' segment, so genesis = now - headTime.
function GetLiveStreamInfo(parsedResponse as object, adaptiveFormats as object, cpn as dynamic, client as Innertube.ClientType, cancellation as object) as void
if adaptiveFormats.Count() = 0
LogWarn("GetLiveStreamInfo: No adaptive formats available")
return
end if
url = adaptiveFormats[0]["url"]
if StringUtils.IsNullOrEmpty(url)
LogWarn("GetLiveStreamInfo: URL is empty")
return
end if
maxDvrDurationSec = ValidInt(adaptiveFormats[0]["maxDvrDurationSec"])
' LogInfo("[LIVE-INFO] GetLiveStreamInfo start. itag:", adaptiveFormats[0]["itag"], "targetDurationSec:", adaptiveFormats[0]["targetDurationSec"], "maxDvrDurationSec:", maxDvrDurationSec, "client:", client)
queryComponents = UrlUtils.ParseQueryComponents(url)
queryComponents["rn"] = "0"
queryComponents["sq"] = "0"
if not StringUtils.IsNullOrEmpty(cpn)
queryComponents["cpn"] = cpn
end if
url = UrlUtils.SetQueryParams(url, queryComponents)
request = HttpClient.Head(url)
requestHeaders = Innertube.CreateHeaders(client)
requestHeaders["origin"] = "https://www.youtube.com"
requestHeaders["referer"] = "https://www.youtube.com"
requestHeaders["DNT"] = "?1"
request.Headers(requestHeaders)
request.TryCount(2)
request.Cancellation(cancellation)
response = request.Await()
if not response.IsSuccess()
LogError("Failed to fetch live stream info", response.ErrorMessage())
return
end if
headers = response.Headers()
' LogInfo("[LIVE-INFO] HEAD response headers:", FormatJson(headers))
if not headers.DoesExist("X-Head-Time-Millis") or not headers.DoesExist("X-Head-Seqnum")
LogErrorNoTelemetry("[LIVE-INFO] Missing X-Head-Time-Millis / X-Head-Seqnum in headers", url, headers)
return
end if
' Work in seconds: wall-clock ms (~1.78e12) overflows a 32-bit integer.
headTimeSec = ValidString(headers["X-Head-Time-Millis"]).ToInt() \ 1000
headSeqnum = ValidString(headers["X-Head-Seqnum"]).ToInt()
nowSec = CreateObject("roDateTime").AsSeconds()
genesisSec = nowSec - headTimeSec
genesisDate = CreateObject("roDateTime")
genesisDate.FromSeconds(genesisSec)
parsedResponse["liveHeadSeqnum"] = headSeqnum
parsedResponse["liveAvailabilityStartUtc"] = genesisDate.ToISOString()
if maxDvrDurationSec > 0
parsedResponse["liveDvrWindowSec"] = maxDvrDurationSec
end if
' Effective per-fragment duration, derived from the stream's own counters.
' YouTube's reported targetDurationSec is unreliable for long-running streams
' (observed 5s vs a real ~1.8s cadence); using it desyncs the duration-based
' SegmentTemplate so the player requests segments far outside the DVR window
' (404). headTime/headSeqnum is the true average and keeps the manifest's
' wall-clock -> sq mapping anchored to the same (headTime, headSeqnum) pair
' that availabilityStartTime is built from.
if headSeqnum > 0
parsedResponse["liveFragmentDurationMs"] = Cint((headTimeSec / headSeqnum) * 1000.0)
end if
' LogInfo("[LIVE-INFO] computed headTimeSec:", headTimeSec, "headSeqnum:", headSeqnum, "nowSec:", nowSec, "genesisSec:", genesisSec, "availabilityStartUtc:", parsedResponse["liveAvailabilityStartUtc"], "liveDvrWindowSec:", parsedResponse["liveDvrWindowSec"])
end function
end namespace
@@ -1,5 +1,6 @@
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/components/Services/Innertube/LiveStreamInfo.bs"
import "pkg:/components/VideoFeed/PaginationType.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/CryptoUtils.bs"
@@ -162,7 +163,20 @@ namespace Invidious
}
end if
return response.Json()
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)
metadata["parser"] = "invidious"
Innertube.GetLiveStreamInfo(metadata, metadata.adaptiveFormats, invalid, invalid, cancellation)
end if
return metadata
end function
function GetPlaylist(playlistId as string, index = 0 as integer, continuation = "" as string, cancellation = invalid as object) as object
@@ -265,6 +265,7 @@ function AddDashUrls(streamUrls as object, metadata as object, preferredQuality
' dynamically generating the DASH manifest, and filter quality
dashUrl = UrlUtils.AppendQueryParams(`http://127.0.0.1:${playletServerPort}/api/dash`, {
v: metadata.videoId
backend: backend
})
dashUrlLocal = invalid
@@ -5,6 +5,12 @@ import "pkg:/source/services/HttpClient.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
namespace Http
class DashRouter extends HttpRouter
@@ -36,6 +42,7 @@ namespace Http
' 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
m.cachedMetadata = invalid
' Live-segment caches, (re)built from the same metadata dig:
m.cachedUrls = {} ' itag -> signed base url
@@ -43,13 +50,27 @@ namespace Http
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|nativeSq" -> 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
end function
' Returns the cached metadata AA for video id `v`, digging the videoQueue
' node (a render-thread rendezvous) only on a cache miss / video change. On a
' miss, also (re)builds the live-segment caches from the same copy.
function GetMetadata(v as string) as dynamic
if m.cachedVideoId = v and IsAssociativeArray(m.cachedMetadata)
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)
return m.cachedMetadata
end if
@@ -57,6 +78,7 @@ namespace Http
if IsAssociativeArray(metadata) and metadata.videoId = v
m.cachedMetadata = metadata
m.cachedVideoId = v
m.cachedBackend = backend
m.RebuildLiveCache(metadata)
end if
return metadata
@@ -82,7 +104,7 @@ namespace Http
return true
end if
metadata = m.GetMetadata(v)
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")
@@ -99,7 +121,7 @@ namespace Http
' For live streams, segments are addressed to the /api/dash/live-seg proxy
' on this same web server (the video player reaches it over 127.0.0.1).
m.dashManifest.liveSegmentBaseUrl = `http://127.0.0.1:${m.serverPort}`
' LogInfo("[LIVE-MPD] DashRouter building manifest for v:", v, "liveNow:", metadata.liveNow, "liveSegmentBaseUrl:", m.dashManifest.liveSegmentBaseUrl)
m.dashManifest.liveBackend = ValidString(request.query.backend)
qualityFilter = m.CreateQualityFilter(quality)
xmlContent = m.dashManifest.FromVideoMetadata(metadata, qualityFilter, ValidString(local) = "true")
@@ -203,11 +225,10 @@ namespace Http
' 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):
' 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=<id>&itag=<itag>&sq=init -> ftyp+moov of the live-edge fragment
' /api/dash/live-seg?v=<id>&itag=<itag>&sq=<K> -> moof+mdat of fragments
' [K*GROUP .. K*GROUP+GROUP-1]
' where GROUP = LIVE_SEGMENT_GROUP.
' /api/dash/live-seg?v=<id>&itag=<itag>&sq=<N> -> 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
@@ -231,7 +252,7 @@ namespace Http
' Warm the shared cache for this video (one node dig on a video change;
' the manifest request usually warmed it already).
m.GetMetadata(v)
m.GetMetadata(v, ValidString(request.query.backend))
baseUrl = m.cachedUrls[itag]
if StringUtils.IsNullOrEmpty(baseUrl)
@@ -256,43 +277,39 @@ namespace Http
return true
end if
else
' Media DASH segment K: concat GROUP native fragments, each reduced
' to moof+mdat so Roku reads the init segment only once.
'
' Fire all GROUP fragment fetches in parallel (Send), then await +
' transform them in order. Fetching serially here was the live
' bottleneck - segments arrived too slowly and the player dropped to
' lower bitrates. (Same Send()-then-Await() pattern as OTFSegmentInfo.)
firstFrag = sq.ToInt() * LIVE_SEGMENT_GROUP
pending = []
for i = 0 to LIVE_SEGMENT_GROUP - 1
pending.Push(m.StartSegmentFetch(baseUrl, firstFrag + i, v, itag))
end for
' 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.
nativeSq = sq.ToInt()
' Await all (so every temp file is read + deleted), then assemble the
' contiguous prefix. A failed fragment is a gap, so we stop appending
' at the first failure; trailing fragments past the live edge are
' simply dropped (partial group is valid for the live edge).
parts = []
for each entry in pending
parts.Push(m.AwaitTransformedSegment(entry, false))
end for
output = invalid
for each part in parts
if part = invalid
exit for
' 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
if output = invalid
output = part
else
output.Append(part)
m.lastAudioItag = itag
else
if IsString(m.lastVideoItag) and m.lastVideoItag <> itag
m.EvictPrefetchItag(m.lastVideoItag)
end if
end for
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, nativeSq, v, itag)
m.PrefetchAhead(baseUrl, v, itag, nativeSq, LIVE_PREFETCH_SEGMENTS)
m.EvictPrefetchOutside(itag, nativeSq + 1, nativeSq + LIVE_PREFETCH_SEGMENTS)
output = m.AwaitTransformedSegment(entry, false)
if output = invalid
' Root-cause telemetry already emitted by AwaitTransformedSegment.
LogErrorNoTelemetry("[LIVE-SEG] first media fragment failed v:", v, "itag:", itag, "sq:", firstFrag, "-> 502")
LogErrorNoTelemetry("[LIVE-SEG] media fragment failed v:", v, "itag:", itag, "sq:", nativeSq, "-> 502")
response.Default(502, "Failed to fetch live media segment")
return true
end if
@@ -310,12 +327,14 @@ namespace Http
' 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.
' Safe here because the web server handles one request at a time, so no
' live-seg fetch is in flight.
m.CleanupTempSegments()
' Re-arm the per-video telemetry dedupe (see ReportSegmentFailure).
m.reportedFailures = {}
@@ -375,6 +394,87 @@ namespace Http
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)
return
end if
if entry.req <> invalid and entry.req.urlTransfer <> invalid
entry.req.urlTransfer.AsyncCancel()
end if
DeleteFile(entry.tmpPath)
end function
' Await a fetch started by StartSegmentFetch and return just the bytes Roku
' needs:
' wantInit = true -> ftyp+moov (init segment)