Live streaming improvements
This commit is contained in:
1 parent
4d047909fc
commit
7310befaaf
5 files changed
+114
-76
No files matched your search
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
- Attempt to fix low quality videos, by downgrading tv client version
|
- Attempt to fix low quality videos, by downgrading tv client version
|
||||||
|
- Live streaming improvements
|
||||||
|
|
||||||
## [0.47.2] - 2026-06-21
|
## [0.47.2] - 2026-06-21
|
||||||
|
|
||||||
|
|||||||
@@ -106,31 +106,23 @@ class DashManifest
|
|||||||
}
|
}
|
||||||
nowUtc = ""
|
nowUtc = ""
|
||||||
if isLive
|
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) / 1000.0)
|
|
||||||
if segmentSec < 1
|
|
||||||
segmentSec = 1
|
|
||||||
end if
|
|
||||||
dvrWindowSec = ValidInt(metadata.liveDvrWindowSec)
|
dvrWindowSec = ValidInt(metadata.liveDvrWindowSec)
|
||||||
mpdAttributes["profiles"] = "urn:mpeg:dash:profile:isoff-live:2011"
|
mpdAttributes["profiles"] = "urn:mpeg:dash:profile:isoff-live:2011"
|
||||||
mpdAttributes["type"] = "dynamic"
|
mpdAttributes["type"] = "dynamic"
|
||||||
' Roku won't track the live edge from wall-clock unless it's handed an
|
' Roku needs an authoritative "now" to track the live edge from wall-clock; UTCTiming +
|
||||||
' authoritative "now": without it, it anchors to the Period start
|
' publishTime carry the current UTC, restamped each refresh.
|
||||||
' (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()
|
nowUtc = CreateObject("roDateTime").ToISOString()
|
||||||
mpdAttributes["publishTime"] = nowUtc
|
mpdAttributes["publishTime"] = nowUtc
|
||||||
mpdAttributes["minimumUpdatePeriod"] = `PT${segmentSec}S`
|
' 20s: the duration SegmentTemplate extrapolates the edge between refreshes.
|
||||||
mpdAttributes["suggestedPresentationDelay"] = `PT${segmentSec * 3}S`
|
mpdAttributes["minimumUpdatePeriod"] = "PT20S"
|
||||||
if not StringUtils.IsNullOrEmpty(metadata.liveAvailabilityStartUtc)
|
' Cushion already lives in availabilityStartTime; present at minBufferTime.
|
||||||
mpdAttributes["availabilityStartTime"] = metadata.liveAvailabilityStartUtc
|
mpdAttributes["suggestedPresentationDelay"] = mpdAttributes["minBufferTime"]
|
||||||
|
if not StringUtils.IsNullOrEmpty(metadata.liveCushionedAvailabilityStartUtc)
|
||||||
|
mpdAttributes["availabilityStartTime"] = metadata.liveCushionedAvailabilityStartUtc
|
||||||
end if
|
end if
|
||||||
if dvrWindowSec > 0
|
if dvrWindowSec > 0
|
||||||
mpdAttributes["timeShiftBufferDepth"] = `PT${dvrWindowSec}S`
|
' Seekable range = window - cushion; the player's DVR floor uses the same value.
|
||||||
|
mpdAttributes["timeShiftBufferDepth"] = `PT${ValidInt(metadata.liveSeekableWindowSec)}S`
|
||||||
else
|
else
|
||||||
LogWarn("Live stream has no DVR window; omitting timeShiftBufferDepth (live seek may fail). videoId:", metadata.videoId)
|
LogWarn("Live stream has no DVR window; omitting timeShiftBufferDepth (live seek may fail). videoId:", metadata.videoId)
|
||||||
end if
|
end if
|
||||||
@@ -140,9 +132,7 @@ class DashManifest
|
|||||||
mpdAttributes["mediaPresentationDuration"] = `PT${duration}S`
|
mpdAttributes["mediaPresentationDuration"] = `PT${duration}S`
|
||||||
end if
|
end if
|
||||||
|
|
||||||
' Dynamic (live) manifests need an explicit Period start so the player can
|
' Live needs an explicit Period start to anchor the timeline against availabilityStartTime.
|
||||||
' anchor the timeline against availabilityStartTime; static keeps the
|
|
||||||
' attribute-less Period it has always used.
|
|
||||||
periodAttributes = {}
|
periodAttributes = {}
|
||||||
if isLive
|
if isLive
|
||||||
periodAttributes["start"] = "PT0S"
|
periodAttributes["start"] = "PT0S"
|
||||||
@@ -665,7 +655,7 @@ class DashManifest
|
|||||||
' The `v` (video id) lets the proxy cache the per-video format lookup.
|
' The `v` (video id) lets the proxy cache the per-video format lookup.
|
||||||
segBase = `${m.liveSegmentBaseUrl}/api/dash/live-seg?v=${metadata.videoId}&itag=${stream.itag}&backend=${m.liveBackend}`
|
segBase = `${m.liveSegmentBaseUrl}/api/dash/live-seg?v=${metadata.videoId}&itag=${stream.itag}&backend=${m.liveBackend}`
|
||||||
xml.EmptyNode("SegmentTemplate", {
|
xml.EmptyNode("SegmentTemplate", {
|
||||||
"initialization": `${segBase}&sq=init`
|
"initialization": `${segBase}&init=true`
|
||||||
"media": `${segBase}&sq=$Number$`
|
"media": `${segBase}&sq=$Number$`
|
||||||
"timescale": "1000"
|
"timescale": "1000"
|
||||||
"duration": durationMs
|
"duration": durationMs
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ import "pkg:/source/utils/UrlUtils.bs"
|
|||||||
' under INT32_MAX (~24.8 days at timescale=1000). YouTube caps live DVR at 12h.
|
' under INT32_MAX (~24.8 days at timescale=1000). YouTube caps live DVR at 12h.
|
||||||
const LIVE_MAX_DVR_WINDOW_SEC = 43200
|
const LIVE_MAX_DVR_WINDOW_SEC = 43200
|
||||||
|
|
||||||
|
' Hold the live edge this many fragments behind the head so a momentary edge-miss refetches
|
||||||
|
' instead of erroring. Baked into liveCushionedAvailabilityStartUtc. 0 = ride the head.
|
||||||
|
const LIVE_EDGE_CUSHION_SEGMENTS = 2
|
||||||
|
|
||||||
namespace Innertube
|
namespace Innertube
|
||||||
|
|
||||||
' Live streams come back with no hlsManifestUrl/dashManifestUrl, just
|
' Live streams come back with no hlsManifestUrl/dashManifestUrl, just
|
||||||
@@ -109,12 +113,6 @@ namespace Innertube
|
|||||||
windowSec = headTimeSec
|
windowSec = headTimeSec
|
||||||
end if
|
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.
|
' Effective per-fragment duration, derived from the stream's own counters.
|
||||||
' YouTube's reported targetDurationSec is unreliable for long-running streams
|
' YouTube's reported targetDurationSec is unreliable for long-running streams
|
||||||
' (observed 5s vs a real ~1.8s cadence); using it desyncs the duration-based
|
' (observed 5s vs a real ~1.8s cadence); using it desyncs the duration-based
|
||||||
@@ -122,8 +120,33 @@ namespace Innertube
|
|||||||
' (404). headTime/headSeqnum is the true average and keeps the manifest's
|
' (404). headTime/headSeqnum is the true average and keeps the manifest's
|
||||||
' wall-clock -> sq mapping anchored to the same (headTime, headSeqnum) pair
|
' wall-clock -> sq mapping anchored to the same (headTime, headSeqnum) pair
|
||||||
' that availabilityStartTime is built from.
|
' that availabilityStartTime is built from.
|
||||||
|
fragmentDurationMs = 0
|
||||||
if headSeqnum > 0
|
if headSeqnum > 0
|
||||||
parsedResponse["liveFragmentDurationMs"] = Cint((headTimeSec / headSeqnum) * 1000.0)
|
fragmentDurationMs = Cint((headTimeSec / headSeqnum) * 1000.0)
|
||||||
|
end if
|
||||||
|
|
||||||
|
astSec = nowSec - windowSec
|
||||||
|
astDate = CreateObject("roDateTime")
|
||||||
|
astDate.FromSeconds(astSec)
|
||||||
|
cushionSec = Cint(LIVE_EDGE_CUSHION_SEGMENTS * fragmentDurationMs / 1000.0)
|
||||||
|
' Younger than the cushion: shifting the anchor past now would break the edge math.
|
||||||
|
if cushionSec >= windowSec
|
||||||
|
cushionSec = 0
|
||||||
|
end if
|
||||||
|
' Shift the anchor later by the cushion so the computed edge lands a cushion behind the head.
|
||||||
|
cushionedAstDate = CreateObject("roDateTime")
|
||||||
|
cushionedAstDate.FromSeconds(astSec + cushionSec)
|
||||||
|
' Window minus the cushion; the full window would seek below startNumber.
|
||||||
|
seekableWindowSec = windowSec - cushionSec
|
||||||
|
|
||||||
|
parsedResponse["liveHeadSeqnum"] = headSeqnum
|
||||||
|
' The real (uncushioned) availabilityStartTime, kept for diagnostics.
|
||||||
|
parsedResponse["liveAvailabilityStartUtc"] = astDate.ToISOString()
|
||||||
|
parsedResponse["liveCushionedAvailabilityStartUtc"] = cushionedAstDate.ToISOString()
|
||||||
|
parsedResponse["liveDvrWindowSec"] = windowSec
|
||||||
|
parsedResponse["liveSeekableWindowSec"] = seekableWindowSec
|
||||||
|
if fragmentDurationMs > 0
|
||||||
|
parsedResponse["liveFragmentDurationMs"] = fragmentDurationMs
|
||||||
end if
|
end if
|
||||||
end function
|
end function
|
||||||
|
|
||||||
|
|||||||
@@ -1114,19 +1114,20 @@ function OnVideoContentJobDone(event as object) as void
|
|||||||
' live floor: how far back the DVR window reaches (0 = unknown -> the brain keeps the [0, edge] clamp).
|
' live floor: how far back the DVR window reaches (0 = unknown -> the brain keeps the [0, edge] clamp).
|
||||||
' The generated DASH anchors t=0 to the window start, so floor = edge - window as the session outlives it.
|
' The generated DASH anchors t=0 to the window start, so floor = edge - window as the session outlives it.
|
||||||
' The same window decides rewindability: a buffer-sized window means no live trickplay at all.
|
' The same window decides rewindability: a buffer-sized window means no live trickplay at all.
|
||||||
m.transport.SetLiveDvrWindow(ValidInt(metadata.liveDvrWindowSec) * 1000)
|
' Use the seekable depth (window - cushion) to match the manifest's timeShiftBufferDepth.
|
||||||
|
m.transport.SetLiveDvrWindow(ValidInt(metadata.liveSeekableWindowSec) * 1000)
|
||||||
m.trickPlayBar.isLive = isLive
|
m.trickPlayBar.isLive = isLive
|
||||||
m.trickPlayBar.canRewind = m.transport.CanRewindLive()
|
m.trickPlayBar.canRewind = m.transport.CanRewindLive()
|
||||||
m.bifDisplay.tileSet = invalid
|
m.bifDisplay.tileSet = invalid
|
||||||
|
|
||||||
' anchor the live edge clock at the manifest's availabilityStartTime and start the 1s heartbeat: the brain
|
' anchor the live edge clock at the cushioned availabilityStartTime and start the 1s heartbeat: the brain
|
||||||
' gets a continuous edge (OnLiveEdge) that keeps advancing through pauses, so the time-behind offset is
|
' gets a continuous edge (OnLiveEdge) that keeps advancing through pauses, so the time-behind offset is
|
||||||
' always current — including the moment the chrome reveals.
|
' always current — including the moment the chrome reveals.
|
||||||
m.liveAstSeconds = -1
|
m.liveAstSeconds = -1
|
||||||
m.liveFallbackEdgeMs = -1
|
m.liveFallbackEdgeMs = -1
|
||||||
m.liveFallbackAtSeconds = 0
|
m.liveFallbackAtSeconds = 0
|
||||||
if isLive
|
if isLive
|
||||||
ast = ValidString(metadata.liveAvailabilityStartUtc)
|
ast = ValidString(metadata.liveCushionedAvailabilityStartUtc)
|
||||||
if ast <> ""
|
if ast <> ""
|
||||||
astDate = CreateObject("roDateTime")
|
astDate = CreateObject("roDateTime")
|
||||||
astDate.FromISO8601String(ast)
|
astDate.FromISO8601String(ast)
|
||||||
|
|||||||
@@ -10,15 +10,10 @@ import "pkg:/source/utils/Types.bs"
|
|||||||
' playback; when the player asks for them the Await is short/instant. Small on
|
' playback; when the player asks for them the Await is short/instant. Small on
|
||||||
' purpose to bound concurrent roUrlTransfers (x2 representations).
|
' purpose to bound concurrent roUrlTransfers (x2 representations).
|
||||||
const LIVE_PREFETCH_SEGMENTS = 2
|
const LIVE_PREFETCH_SEGMENTS = 2
|
||||||
' Bounded retry of transient segment failures before surfacing a 502 (one 502 on an
|
' Immediate refetches (no sleep) for transient network errors (reset/5xx) before surfacing 503.
|
||||||
' init segment kills that bitrate). Retried: 204 (sq past the live edge), reset/error
|
' 204/timeout/4xx surface at once: an in-handler sleep would stall the queued audio request ~600ms
|
||||||
' (-7/-10001), 5xx. Not retried: timeout (status 0 = slow/hung; a refetch would abandon
|
' on the single thread (measured).
|
||||||
' a progressing download) and 4xx (signature/availability). Per-attempt timeout left at
|
|
||||||
' HttpClient's default; the Roku Video node's ~30s segment timeout bounds the freeze.
|
|
||||||
const LIVE_SEG_MAX_ATTEMPTS = 3
|
const LIVE_SEG_MAX_ATTEMPTS = 3
|
||||||
' Pause between attempts only on an empty (204) fragment (not yet produced), so the
|
|
||||||
' refetch doesn't busy-loop the edge. Small: the web server is single-threaded.
|
|
||||||
const LIVE_SEG_RETRY_BACKOFF_MS = 300
|
|
||||||
|
|
||||||
' Why a live-segment fetch failed. The string values double as the telemetry message
|
' Why a live-segment fetch failed. The string values double as the telemetry message
|
||||||
' and fingerprint (see ReportSegmentFailure), so they must stay stable - changing one
|
' and fingerprint (see ReportSegmentFailure), so they must stay stable - changing one
|
||||||
@@ -71,7 +66,7 @@ namespace Http
|
|||||||
m.cachedInitSeqnum = 0 ' live-edge fragment to source the init from
|
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.probeByteCount = m.INITIAL_PROBE_BYTE_COUNT ' current box-walk probe; only grows
|
||||||
m.reportedFailures = {} ' per-video telemetry dedupe (see ReportSegmentFailure)
|
m.reportedFailures = {} ' per-video telemetry dedupe (see ReportSegmentFailure)
|
||||||
' Prefetch cache: "itag|nativeSq" -> in-flight StartSegmentFetch entry,
|
' Prefetch cache: "itag|sq" -> in-flight StartSegmentFetch entry,
|
||||||
' warmed ahead of the player so awaits hit already-downloading fragments.
|
' warmed ahead of the player so awaits hit already-downloading fragments.
|
||||||
m.prefetch = {}
|
m.prefetch = {}
|
||||||
' Last itag served per media kind. When the player switches representation
|
' Last itag served per media kind. When the player switches representation
|
||||||
@@ -255,7 +250,7 @@ namespace Http
|
|||||||
'
|
'
|
||||||
' Endpoint (see DashManifest live SegmentTemplate); segments map 1:1 to native
|
' Endpoint (see DashManifest live SegmentTemplate); segments map 1:1 to native
|
||||||
' fragments, so the DASH segment number is the native sq:
|
' 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>&init=true -> ftyp+moov of the live-edge fragment
|
||||||
' /api/dash/live-seg?v=<id>&itag=<itag>&sq=<N> -> moof+mdat of fragment N
|
' /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),
|
' This is a hot path (called for every audio + video segment, continuously),
|
||||||
@@ -271,10 +266,14 @@ namespace Http
|
|||||||
|
|
||||||
v = request.query.v
|
v = request.query.v
|
||||||
itag = request.query.itag
|
itag = request.query.itag
|
||||||
sq = request.query.sq
|
isInit = ValidString(request.query.init) = "true"
|
||||||
|
sq = -1
|
||||||
|
if not isInit
|
||||||
|
sq = ValidString(request.query.sq).ToInt()
|
||||||
|
end if
|
||||||
|
|
||||||
if StringUtils.IsNullOrEmpty(itag) or StringUtils.IsNullOrEmpty(sq) or StringUtils.IsNullOrEmpty(v)
|
if StringUtils.IsNullOrEmpty(itag) or StringUtils.IsNullOrEmpty(v) or (not isInit and sq <= 0)
|
||||||
response.Default(400, "Missing v, itag or sq")
|
response.Default(400, "Missing or invalid v, itag, or sq")
|
||||||
return true
|
return true
|
||||||
end if
|
end if
|
||||||
|
|
||||||
@@ -290,7 +289,7 @@ namespace Http
|
|||||||
return true
|
return true
|
||||||
end if
|
end if
|
||||||
|
|
||||||
if sq = "init"
|
if isInit
|
||||||
' ftyp+moov, served from the per-itag cache after the first fetch.
|
' ftyp+moov, served from the per-itag cache after the first fetch.
|
||||||
output = m.cachedInit[itag]
|
output = m.cachedInit[itag]
|
||||||
if output = invalid
|
if output = invalid
|
||||||
@@ -303,8 +302,8 @@ namespace Http
|
|||||||
end if
|
end if
|
||||||
output = m.AwaitSegmentWithRetry(baseUrl, initSq, v, itag, true, invalid)
|
output = m.AwaitSegmentWithRetry(baseUrl, initSq, v, itag, true, invalid)
|
||||||
if output = invalid
|
if output = invalid
|
||||||
LogErrorNoTelemetry("[LIVE-SEG] INIT fetch failed v:", v, "itag:", itag, "-> 502")
|
LogErrorNoTelemetry("[LIVE-SEG] INIT fetch failed v:", v, "itag:", itag, "-> 503")
|
||||||
response.Default(502, "Failed to fetch live init segment")
|
response.Default(503, "Live init segment not ready")
|
||||||
return true
|
return true
|
||||||
end if
|
end if
|
||||||
m.cachedInit[itag] = output
|
m.cachedInit[itag] = output
|
||||||
@@ -313,9 +312,8 @@ namespace Http
|
|||||||
' Media DASH segment = one native YouTube fragment, reduced to moof+mdat
|
' Media DASH segment = one native YouTube fragment, reduced to moof+mdat
|
||||||
' so Roku reads the init segment only once. The manifest addresses the
|
' so Roku reads the init segment only once. The manifest addresses the
|
||||||
' proxy 1:1, so the DASH segment number is the native sq.
|
' proxy 1:1, so the DASH segment number is the native sq.
|
||||||
nativeSq = sq.ToInt()
|
if sq > m.lastSeenSq
|
||||||
if nativeSq > m.lastSeenSq
|
m.lastSeenSq = sq
|
||||||
m.lastSeenSq = nativeSq
|
|
||||||
end if
|
end if
|
||||||
|
|
||||||
' Representation switch (ABR video / audio track): the previous itag of
|
' Representation switch (ABR video / audio track): the previous itag of
|
||||||
@@ -338,14 +336,16 @@ namespace Http
|
|||||||
' (Send, no Await) BEFORE blocking here so their downloads overlap this
|
' (Send, no Await) BEFORE blocking here so their downloads overlap this
|
||||||
' fragment's await + playback; then drop entries now outside the window
|
' 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.
|
' (played past, or stranded by a seek) so the cache + temp files stay bounded.
|
||||||
entry = m.GetOrStartFetch(baseUrl, nativeSq, v, itag)
|
entry = m.GetOrStartFetch(baseUrl, sq, v, itag)
|
||||||
m.PrefetchAhead(baseUrl, v, itag, nativeSq, LIVE_PREFETCH_SEGMENTS)
|
m.PrefetchAhead(baseUrl, v, itag, sq, LIVE_PREFETCH_SEGMENTS)
|
||||||
m.EvictPrefetchOutside(itag, nativeSq + 1, nativeSq + LIVE_PREFETCH_SEGMENTS)
|
m.EvictPrefetchOutside(itag, sq + 1, sq + LIVE_PREFETCH_SEGMENTS)
|
||||||
|
|
||||||
output = m.AwaitSegmentWithRetry(baseUrl, nativeSq, v, itag, false, entry)
|
output = m.AwaitSegmentWithRetry(baseUrl, sq, v, itag, false, entry)
|
||||||
if output = invalid
|
if output = invalid
|
||||||
LogErrorNoTelemetry("[LIVE-SEG] media fragment failed v:", v, "itag:", itag, "sq:", nativeSq, "-> 502")
|
' 503 makes Roku re-request the same sq and hold the bitrate (verified); the
|
||||||
response.Default(502, "Failed to fetch live media segment")
|
' fragment will exist within ~one re-request.
|
||||||
|
LogErrorNoTelemetry("[LIVE-SEG] media fragment not ready v:", v, "itag:", itag, "sq:", sq, "-> 503")
|
||||||
|
response.Default(503, "Live media segment not ready")
|
||||||
return true
|
return true
|
||||||
end if
|
end if
|
||||||
end if
|
end if
|
||||||
@@ -513,12 +513,9 @@ namespace Http
|
|||||||
DeleteFile(entry.tmpPath)
|
DeleteFile(entry.tmpPath)
|
||||||
end function
|
end function
|
||||||
|
|
||||||
' Await `entry` (invalid -> fetch from scratch), transform to the bytes Roku
|
' Await `entry` (invalid -> fetch fresh), transform to the bytes Roku needs (wantInit ->
|
||||||
' needs (wantInit: true -> ftyp+moov, false -> moof+mdat), and retry transient
|
' ftyp+moov, else moof+mdat), retrying transient failures up to LIVE_SEG_MAX_ATTEMPTS. Each
|
||||||
' failures up to LIVE_SEG_MAX_ATTEMPTS before giving up (invalid). Each retry
|
' retry refetches the same sq, which also un-poisons a prefetched 204. Telemetry fires once.
|
||||||
' discards the entry and starts a fresh fetch for the same sq - rides an edge
|
|
||||||
' blip AND un-poisons a prefetched 204 (warmed before the edge produced it).
|
|
||||||
' Telemetry fires once, on give-up.
|
|
||||||
function AwaitSegmentWithRetry(baseUrl as string, sq as integer, v as string, itag as string, wantInit as boolean, entry as object) as dynamic
|
function AwaitSegmentWithRetry(baseUrl as string, sq as integer, v as string, itag as string, wantInit as boolean, entry as object) as dynamic
|
||||||
if entry = invalid
|
if entry = invalid
|
||||||
entry = m.StartSegmentFetch(baseUrl, sq, v, itag)
|
entry = m.StartSegmentFetch(baseUrl, sq, v, itag)
|
||||||
@@ -531,20 +528,23 @@ namespace Http
|
|||||||
return result.bytes
|
return result.bytes
|
||||||
end if
|
end if
|
||||||
|
|
||||||
if (not result.retryable) or attempt >= LIVE_SEG_MAX_ATTEMPTS
|
' 204 = sq not produced yet. Return 503 and let Roku re-ask (same sq, then resyncs);
|
||||||
m.ReportSegmentFailure(result.reason, { v: v, itag: itag, sq: sq, segUrl: entry.segUrl, response: result.response })
|
' a sleep+refetch here would stall the queued audio ~600ms on the single thread
|
||||||
return invalid
|
' (measured). Evict the warmed siblings - fetched too early, they 204'd too.
|
||||||
end if
|
|
||||||
|
|
||||||
' Empty (204) = sq not produced yet: drop the warmed siblings (also fetched
|
|
||||||
' too early) so they refetch fresh, and pause so the refetch doesn't
|
|
||||||
' busy-loop the edge. Network/5xx already spent time in the await -> no pause.
|
|
||||||
if result.reason = LiveSegFailure.EmptyFragment
|
if result.reason = LiveSegFailure.EmptyFragment
|
||||||
if not wantInit
|
if not wantInit
|
||||||
m.EvictPrefetchItag(itag)
|
m.EvictPrefetchItag(itag)
|
||||||
end if
|
end if
|
||||||
sleep(LIVE_SEG_RETRY_BACKOFF_MS)
|
m.ReportSegmentFailure(result.reason, { v: v, itag: itag, sq: sq, head: m.liveHeadSeqnum, segUrl: entry.segUrl, response: result.response })
|
||||||
|
return invalid
|
||||||
end if
|
end if
|
||||||
|
|
||||||
|
if (not result.retryable) or attempt >= LIVE_SEG_MAX_ATTEMPTS
|
||||||
|
m.ReportSegmentFailure(result.reason, { v: v, itag: itag, sq: sq, head: m.liveHeadSeqnum, segUrl: entry.segUrl, response: result.response })
|
||||||
|
return invalid
|
||||||
|
end if
|
||||||
|
|
||||||
|
' Network/5xx: transient; discard and refetch immediately (no sleep).
|
||||||
LogWarnNoTelemetry("[LIVE-SEG] retry sq", sq, "itag", itag, "(", result.reason, ") attempt", attempt + 1, "of", LIVE_SEG_MAX_ATTEMPTS)
|
LogWarnNoTelemetry("[LIVE-SEG] retry sq", sq, "itag", itag, "(", result.reason, ") attempt", attempt + 1, "of", LIVE_SEG_MAX_ATTEMPTS)
|
||||||
|
|
||||||
attempt += 1
|
attempt += 1
|
||||||
@@ -557,14 +557,15 @@ namespace Http
|
|||||||
' One fetch+transform attempt. Reads only the needed byte range from the temp
|
' One fetch+transform attempt. Reads only the needed byte range from the temp
|
||||||
' file and always deletes it. Returns:
|
' file and always deletes it. Returns:
|
||||||
' { ok: true, bytes } - the transformed segment bytes
|
' { ok: true, bytes } - the transformed segment bytes
|
||||||
' { ok: false, retryable, reason, response } - failed; `retryable` separates
|
' { ok: false, retryable, reason, response } - failed; `retryable` marks fast transient
|
||||||
' fast transient errors (204/empty, reset/-10001, 5xx) from ones a refetch
|
' NETWORK errors (reset/-10001, 5xx) worth an immediate refetch. 204/empty is handled
|
||||||
' won't fix: a plain timeout (slow/hung), 4xx, or a malformed box.
|
' specially by the caller (immediate 503); timeout/4xx/malformed are not retried.
|
||||||
function AttemptSegment(entry as object, wantInit as boolean) as object
|
function AttemptSegment(entry as object, wantInit as boolean) as object
|
||||||
tmpPath = entry.tmpPath
|
tmpPath = entry.tmpPath
|
||||||
sq = entry.sq
|
sq = entry.sq
|
||||||
|
|
||||||
response = entry.req.Await()
|
response = entry.req.Await()
|
||||||
|
m.liveHeadSeqnum = m.ReadHeadSeqnum(response)
|
||||||
if not response.IsSuccess()
|
if not response.IsSuccess()
|
||||||
status = response.StatusCode()
|
status = response.StatusCode()
|
||||||
LogErrorNoTelemetry("[LIVE-SEG] fetch sq", sq, "failed:", status)
|
LogErrorNoTelemetry("[LIVE-SEG] fetch sq", sq, "failed:", status)
|
||||||
@@ -582,7 +583,8 @@ namespace Http
|
|||||||
if fileLen <= 0
|
if fileLen <= 0
|
||||||
LogErrorNoTelemetry("[LIVE-SEG] fetch sq", sq, "empty file (status", response.StatusCode(), ")")
|
LogErrorNoTelemetry("[LIVE-SEG] fetch sq", sq, "empty file (status", response.StatusCode(), ")")
|
||||||
DeleteFile(tmpPath)
|
DeleteFile(tmpPath)
|
||||||
return { ok: false, retryable: true, reason: LiveSegFailure.EmptyFragment, response: response }
|
' 204/empty handled specially by the caller (immediate 503, no in-handler retry).
|
||||||
|
return { ok: false, retryable: false, reason: LiveSegFailure.EmptyFragment, response: response }
|
||||||
end if
|
end if
|
||||||
|
|
||||||
boxes = m.LocateBoxes(tmpPath, fileLen)
|
boxes = m.LocateBoxes(tmpPath, fileLen)
|
||||||
@@ -608,6 +610,17 @@ namespace Http
|
|||||||
return { ok: true, bytes: out }
|
return { ok: true, bytes: out }
|
||||||
end function
|
end function
|
||||||
|
|
||||||
|
' Live head sequence number from a fragment response's X-Head-Seqnum header (-1 if
|
||||||
|
' absent). Stashed (m.liveHeadSeqnum) so ReportSegmentFailure records how far ahead of
|
||||||
|
' the real edge a failed sq was (delta = sq - head) - the field signal for edge overshoot.
|
||||||
|
function ReadHeadSeqnum(response as object) as integer
|
||||||
|
headers = response.Headers()
|
||||||
|
if IsAssociativeArray(headers) and headers.DoesExist("X-Head-Seqnum")
|
||||||
|
return ValidString(headers["X-Head-Seqnum"]).ToInt()
|
||||||
|
end if
|
||||||
|
return -1
|
||||||
|
end function
|
||||||
|
|
||||||
' Read the leading boxes of a fragment temp file and return moov/moof offsets.
|
' Read the leading boxes of a fragment temp file and return moov/moof offsets.
|
||||||
' Starts with m.probeByteCount; if moof falls past the probe (a moov larger
|
' Starts with m.probeByteCount; if moof falls past the probe (a moov larger
|
||||||
' than expected), grow the probe (doubling, capped by file size and
|
' than expected), grow the probe (doubling, capped by file size and
|
||||||
@@ -677,11 +690,21 @@ namespace Http
|
|||||||
end if
|
end if
|
||||||
m.reportedFailures[dedupeKey] = true
|
m.reportedFailures[dedupeKey] = true
|
||||||
|
|
||||||
|
' Edge overshoot: how far past the live head (X-Head-Seqnum at the failing fetch, via
|
||||||
|
' info.head) the failed sq was. delta > 0 = a not-yet-produced fragment (the 503 cause).
|
||||||
|
head = ValidInt(info.head)
|
||||||
|
sqNum = ValidInt(info.sq)
|
||||||
|
deltaText = "n/a"
|
||||||
|
if head > 0 and sqNum > 0
|
||||||
|
deltaText = (sqNum - head).ToStr()
|
||||||
|
end if
|
||||||
details = [
|
details = [
|
||||||
"reason: " + reason
|
"reason: " + reason
|
||||||
"videoId: " + ValidString(info.v)
|
"videoId: " + ValidString(info.v)
|
||||||
"itag: " + ValidString(info.itag)
|
"itag: " + ValidString(info.itag)
|
||||||
"sq: " + ToString(info.sq)
|
"sq: " + ToString(info.sq)
|
||||||
|
"head: " + head.ToStr()
|
||||||
|
"delta: " + deltaText
|
||||||
"status: " + statusText
|
"status: " + statusText
|
||||||
"error: " + errorMessage
|
"error: " + errorMessage
|
||||||
"url: " + ValidString(info.segUrl)
|
"url: " + ValidString(info.segUrl)
|
||||||
|
|||||||
Reference in new issue
Block a user