Compare commits

...
10 Commits
27 changed files with 361 additions and 290 deletions

No files matched your search

+14
View File
@@ -5,6 +5,20 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.47.4] - 2026-06-25
### Fixed
- Attempt to fix `MISSING_FORMAT_FIELD` error in live videos
- Attempt to fix `No valid bitrates` error
## [0.47.3] - 2026-06-23
### Fixed
- 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
### Fixed ### Fixed
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "playlet", "name": "playlet",
"version": "0.47.2", "version": "0.47.4",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "playlet", "name": "playlet",
"version": "0.47.2", "version": "0.47.4",
"hasInstallScript": true, "hasInstallScript": true,
"devDependencies": { "devDependencies": {
"@rokucommunity/bslint": "^0.8.44", "@rokucommunity/bslint": "^0.8.44",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "playlet", "name": "playlet",
"version": "0.47.2", "version": "0.47.4",
"description": "Unofficial YouTube client for Roku", "description": "Unofficial YouTube client for Roku",
"devDependencies": { "devDependencies": {
"@rokucommunity/bslint": "^0.8.44", "@rokucommunity/bslint": "^0.8.44",
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "playlet-app", "name": "playlet-app",
"version": "0.47.2", "version": "0.47.4",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "playlet-app", "name": "playlet-app",
"version": "0.47.2" "version": "0.47.4"
} }
} }
} }
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "playlet-app", "name": "playlet-app",
"version": "0.47.2", "version": "0.47.4",
"description": "Unofficial YouTube client for Roku", "description": "Unofficial YouTube client for Roku",
"scripts": { "scripts": {
"prebuild": "node ../tools/rm.js ../build/playlet-app", "prebuild": "node ../tools/rm.js ../build/playlet-app",
+1 -1
View File
@@ -3,7 +3,7 @@ title=Playlet
# Do not update version manually, it is auto updated from package.json # Do not update version manually, it is auto updated from package.json
major_version=0 major_version=0
minor_version=47 minor_version=47
build_version=00002 build_version=00004
ui_resolutions=hd ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p uri_resolution_autosub=$$RES$$,480p,720p,1080p
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "playlet-lib", "name": "playlet-lib",
"version": "0.47.2", "version": "0.47.4",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "playlet-lib", "name": "playlet-lib",
"version": "0.47.2" "version": "0.47.4"
} }
} }
} }
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "playlet-lib", "name": "playlet-lib",
"version": "0.47.2", "version": "0.47.4",
"description": "Unofficial YouTube client for Roku", "description": "Unofficial YouTube client for Roku",
"scripts": { "scripts": {
"prebuild": "node ../tools/rm.js ../build/playlet-lib", "prebuild": "node ../tools/rm.js ../build/playlet-lib",
@@ -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
@@ -4,6 +4,7 @@ import "pkg:/components/Services/Innertube/Constants.bs"
import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/StringUtils.bs"
function Init() function Init()
m.top.observeField("requestVisitorData", FuncName(OnRequestVisitorData))
end function end function
function OnNodeReady() function OnNodeReady()
@@ -11,14 +12,14 @@ function OnNodeReady()
end function end function
function OnRequestVisitorData() as void function OnRequestVisitorData() as void
if m.innertubeSessionDataJob <> invalid if m.innertubeSessionDataJob <> invalid and not m.innertubeSessionDataJob.done
return return
end if end if
OnForceRequestVisitorData() RequestVisitorData()
end function end function
function OnForceRequestVisitorData() as void function RequestVisitorData() as void
if m.innertubeSessionDataJob <> invalid if m.innertubeSessionDataJob <> invalid
m.innertubeSessionDataJob.cancel = true m.innertubeSessionDataJob.cancel = true
m.innertubeSessionDataJob = invalid m.innertubeSessionDataJob = invalid
@@ -40,4 +41,8 @@ end function
function OnInnertubeSessionDataJobDone(event as object) as void function OnInnertubeSessionDataJobDone(event as object) as void
JobSystem.UnobserveCallback(event.getRoSGNode()) JobSystem.UnobserveCallback(event.getRoSGNode())
m.innertubeSessionDataJob = invalid m.innertubeSessionDataJob = invalid
if StringUtils.IsNullOrEmpty(m.top.visitorData)
' Trigger observers in case the job threw an error and didn't set the visitorData
m.top.visitorData = ""
end if
end function end function
@@ -1,9 +1,8 @@
<component name="Innertube" extends="Node" includes="AutoBind"> <component name="Innertube" extends="Node" includes="AutoBind">
<interface> <interface>
<field id="timestamp" type="int" /> <field id="timestamp" type="int" />
<field id="visitorData" type="string" /> <field id="visitorData" type="string" alwaysNotify="true" />
<field id="requestVisitorData" type="boolean" alwaysNotify="true" onChange="OnRequestVisitorData" /> <field id="requestVisitorData" type="boolean" alwaysNotify="true" />
<field id="forceRequestVisitorData" type="boolean" alwaysNotify="true" onChange="OnForceRequestVisitorData" />
<field id="jobQueue" type="node" /> <field id="jobQueue" type="node" />
</interface> </interface>
</component> </component>
@@ -9,13 +9,15 @@ import "pkg:/components/Services/Innertube/ResolveUrlEndpoint.bs"
import "pkg:/components/Services/Innertube/SearchEndpoint.bs" import "pkg:/components/Services/Innertube/SearchEndpoint.bs"
import "pkg:/components/Services/Innertube/SearchFilters.bs" import "pkg:/components/Services/Innertube/SearchFilters.bs"
import "pkg:/components/Services/Innertube/SubscriptionEndpoint.bs" import "pkg:/components/Services/Innertube/SubscriptionEndpoint.bs"
import "pkg:/components/Services/Innertube/TvClientDowngradeExperiment.bs"
import "pkg:/source/services/HttpClient.bs" import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/CancellationUtils.bs" import "pkg:/source/utils/CancellationUtils.bs"
import "pkg:/source/utils/ObjectUtils.bs" import "pkg:/source/utils/ObjectUtils.bs"
import "pkg:/source/utils/OptionUtils.bs" import "pkg:/source/utils/OptionUtils.bs"
import "pkg:/source/utils/TimeUtils.bs" import "pkg:/source/utils/TimeUtils.bs"
' DEBUG-only: force the SABR downgrade retry on every playable response.
#const DEBUG_FORCE_SABR_DOWNGRADE = false
namespace InnertubeService namespace InnertubeService
function GetVideoMetadata(videoId as string, options = invalid as object) as object function GetVideoMetadata(videoId as string, options = invalid as object) as object
@@ -37,17 +39,14 @@ namespace InnertubeService
end if end if
playerResponseJson = invalid playerResponseJson = invalid
client = Innertube.Experiment.InitialPlayerClient() client = Innertube.ClientType.Tv
totalPlayerRequests = 0 totalPlayerRequests = 0
triedReloadRefresh = false triedReloadRefresh = false
downgradeRetryAttempted = false
downgradeRetryArm = invalid
downgradeOutcomeReported = false
while true while true
' We shouldn't be making more than 3 requests: ' We shouldn't be making more than 3 requests:
' 1. Make request with TV client. ' 1. Make request with TV client.
' 2. Make request, but STS_MISMATCH error -> retry with new STS. ' 2. Make request, but STS_MISMATCH error -> retry with new STS.
' 3. useServerDrivenAbr -> retry with control/treatment client version to recover format URLs. ' 3. useServerDrivenAbr -> retry with downgraded TV client version to recover format URLs.
if totalPlayerRequests >= 3 if totalPlayerRequests >= 3
LogError("Too many player requests, aborting.") LogError("Too many player requests, aborting.")
return { return {
@@ -73,10 +72,6 @@ namespace InnertubeService
end if end if
if not playerResponse.IsSuccess() if not playerResponse.IsSuccess()
if downgradeRetryArm <> invalid and not downgradeOutcomeReported
downgradeOutcomeReported = true
Innertube.Experiment.ReportDowngradeOutcome(downgradeRetryArm, Innertube.Experiment.DowngradeOutcome.RetryFailed, videoId, playerRequest, playerResponse)
end if
parsedResponse = { parsedResponse = {
error: playerResponse.ErrorMessage() error: playerResponse.ErrorMessage()
} }
@@ -86,22 +81,14 @@ namespace InnertubeService
playerResponseJson = playerResponse.Json() playerResponseJson = playerResponse.Json()
if not downgradeRetryAttempted ' Under server-driven ABR the TV client can withhold every adaptive format URL (stuck
downgradePlan = Innertube.Experiment.PlanTvClientDowngradeRetry(playerResponseJson) ' at 360p); the downgraded TV client is not served SABR. Retry once with it.
if downgradePlan <> invalid if client = Innertube.ClientType.Tv and IsSabrLocked(playerResponseJson)
downgradeRetryAttempted = true LogInfo("SABR-locked response, retrying with downgraded TV client...")
downgradeRetryArm = downgradePlan.arm client = Innertube.ClientType.TvDowngraded
client = downgradePlan.client
LogInfo("[DOWNGRADE-RETRY] trigger arm=", downgradeRetryArm, " client=", client, " videoId=", videoId)
continue while continue while
end if else if client = Innertube.ClientType.TvDowngraded and not HasUsableAdaptiveUrl(playerResponseJson)
else if downgradeRetryArm <> invalid and not downgradeOutcomeReported LogError("Downgraded TV client did not recover SABR-withheld format URLs")
downgradeOutcomeReported = true
outcome = Innertube.Experiment.DowngradeOutcome.NotRecovered
if Innertube.Experiment.ResponseHasUsableAdaptive(playerResponseJson)
outcome = Innertube.Experiment.DowngradeOutcome.Recovered
end if
Innertube.Experiment.ReportDowngradeOutcome(downgradeRetryArm, outcome, videoId, playerRequest, playerResponse)
end if end if
parsedResponse = Innertube.ParseInnertubePlayerResponse(playerRequest, playerResponse, client, cancellation) parsedResponse = Innertube.ParseInnertubePlayerResponse(playerRequest, playerResponse, client, cancellation)
@@ -159,6 +146,36 @@ namespace InnertubeService
return parsedResponse return parsedResponse
end function end function
' True when the TV client's response is SABR-locked: server-driven ABR signaled with no usable
' adaptive URL.
function IsSabrLocked(playerResponseJson as object) as boolean
if not IsAssociativeArray(ObjectUtils.Dig(playerResponseJson, ["streamingData"]))
return false
end if
serverDrivenAbr = ValidBool(ObjectUtils.Dig(playerResponseJson, ["playerConfig", "mediaCommonConfig", "useServerDrivenAbr"]))
locked = serverDrivenAbr and not HasUsableAdaptiveUrl(playerResponseJson)
#if DEBUG
#if DEBUG_FORCE_SABR_DOWNGRADE
locked = true
#end if
#end if
return locked
end function
' True if any adaptive format carries a playable field (url / signatureCipher / cipher).
function HasUsableAdaptiveUrl(playerResponseJson as object) as boolean
adaptiveFormats = ObjectUtils.Dig(playerResponseJson, ["streamingData", "adaptiveFormats"])
if not IsArray(adaptiveFormats)
return false
end if
for each format in adaptiveFormats
if IsAssociativeArray(format) and (not StringUtils.IsNullOrEmpty(format["url"]) or not StringUtils.IsNullOrEmpty(format["signatureCipher"]) or not StringUtils.IsNullOrEmpty(format["cipher"]))
return true
end if
end for
return false
end function
function AwaitAndParseNextResponse(fetchNext as boolean, raw as boolean, parsedResponse as object, nextRequest as object) as object function AwaitAndParseNextResponse(fetchNext as boolean, raw as boolean, parsedResponse as object, nextRequest as object) as object
if not fetchNext if not fetchNext
return parsedResponse return parsedResponse
@@ -1,26 +1,28 @@
import "pkg:/components/Services/Innertube/SessionData.bs" import "pkg:/components/Services/Innertube/SessionData.bs"
import "pkg:/source/utils/StringUtils.bs"
@job("InnertubeSessionDataJob") @job("InnertubeSessionDataJob")
function ExecuteJob() as void function ExecuteJob() as void
input = JobGetInput() innertubeNode = JobGetInput().innertube
innertubeNode = input.innertube cached = Innertube.ReadSessionDataFromRegistry()
if cached <> invalid and not StringUtils.IsNullOrEmpty(cached.visitorData)
cancellation = JobGetCancellation() if IsInt(cached.timestamp)
sessionData = Innertube.GetSessionData(cancellation) innertubeNode.timestamp = cached.timestamp
if sessionData.error <> invalid end if
JobError(sessionData.error) innertubeNode.visitorData = cached.visitorData
if Innertube.IsSessionDataFresh(cached)
return return
end if end if
innertubeNode.queueFields(true)
if IsInt(sessionData.timestamp)
innertubeNode.timestamp = sessionData.timestamp
end if end if
if not StringUtils.IsNullOrEmpty(sessionData.visitorData) fetched = Innertube.RequestSessionData(JobGetCancellation())
innertubeNode.visitorData = sessionData.visitorData if fetched <> invalid
Innertube.SaveSessionDataToRegistry(fetched)
innertubeNode.timestamp = fetched.timestamp
innertubeNode.visitorData = fetched.visitorData
else if StringUtils.IsNullOrEmpty(innertubeNode.visitorData)
' Refresh failed and we never had an id — wake a cold waiter to fail. Never blank a valid id.
innertubeNode.visitorData = ""
end if end if
innertubeNode.queueFields(false)
end function end function
@@ -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
@@ -61,6 +61,7 @@ namespace Innertube
if not StringUtils.IsNullOrEmpty(visitorData) and not useAccessToken if not StringUtils.IsNullOrEmpty(visitorData) and not useAccessToken
request.Header("x-goog-visitor-id", visitorData) request.Header("x-goog-visitor-id", visitorData)
request.poTokenIdentity = visitorData
end if end if
request.signatureTimestamp = signatureTimestamp request.signatureTimestamp = signatureTimestamp
@@ -102,7 +103,7 @@ namespace Innertube
adaptiveFormats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "adaptiveFormats"])) adaptiveFormats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "adaptiveFormats"]))
formats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "formats"])) formats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "formats"]))
error = DecipherUrls(formats, adaptiveFormats, playerRequest.signatureTimestamp, cancellation, client) error = DecipherUrls(formats, adaptiveFormats, playerRequest.signatureTimestamp, cancellation, client, playerRequest.poTokenIdentity)
if error <> invalid if error <> invalid
parsedResponse["error"] = error.error parsedResponse["error"] = error.error
if error.DoesExist("errorCode") if error.DoesExist("errorCode")
@@ -111,6 +112,9 @@ namespace Innertube
return parsedResponse return parsedResponse
end if end if
parsedResponse["potAttached"] = HasPotParam(adaptiveFormats) or HasPotParam(formats)
LogDebug("poToken attached to deciphered urls:", parsedResponse["potAttached"])
' if isLive and adaptiveFormats.Count() > 0 ' if isLive and adaptiveFormats.Count() > 0
' LogInfo("[LIVE-INFO] post-decipher, sts:", playerRequest.signatureTimestamp, "format[0].itag:", adaptiveFormats[0]["itag"], "url:", adaptiveFormats[0]["url"]) ' LogInfo("[LIVE-INFO] post-decipher, sts:", playerRequest.signatureTimestamp, "format[0].itag:", adaptiveFormats[0]["itag"], "url:", adaptiveFormats[0]["url"])
' end if ' end if
@@ -499,7 +503,19 @@ namespace Innertube
return json["sts"] return json["sts"]
end function end function
function DecipherUrls(formats as object, adaptiveFormats as object, signatureTimestamp as dynamic, cancellation as object, client = invalid as dynamic) as object function HasPotParam(formats as object) as boolean
for each fmt in formats
url = fmt["url"]
if not StringUtils.IsNullOrEmpty(url)
if url.Instr("&pot=") <> -1
return true
end if
end if
end for
return false
end function
function DecipherUrls(formats as object, adaptiveFormats as object, signatureTimestamp as dynamic, cancellation as object, client = invalid as dynamic, poTokenIdentity = invalid as dynamic) as object
if signatureTimestamp = invalid if signatureTimestamp = invalid
' No need to decipher if signatureTimestamp is not available ' No need to decipher if signatureTimestamp is not available
return invalid return invalid
@@ -523,11 +539,16 @@ namespace Innertube
}) })
end for end for
request = HttpClient.PostJson(`${PLAYLET_SUPPORT_SERVER}/v2/decipher`, { body = {
"sts": signatureTimestamp "sts": signatureTimestamp
"formats": reqFormats "formats": reqFormats
"adaptiveFormats": reqAdaptiveFormats "adaptiveFormats": reqAdaptiveFormats
}) }
if not StringUtils.IsNullOrEmpty(poTokenIdentity)
body["identity"] = poTokenIdentity
end if
request = HttpClient.PostJson(`${PLAYLET_SUPPORT_SERVER}/v2/decipher`, body)
request.Cancellation(cancellation) request.Cancellation(cancellation)
request.LogCurlCommand(false) request.LogCurlCommand(false)
@@ -11,18 +11,12 @@ namespace Innertube
const SESSION_DATA_VERSION = 1 const SESSION_DATA_VERSION = 1
const INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS = 60 * 60 * 24 * 14 ' 14 days const INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS = 60 * 60 * 24 * 14 ' 14 days
function GetSessionData(cancellation = invalid as object) as object function IsSessionDataFresh(sessionData as object) as boolean
sessionData = ReadSessionDataFromRegistry() if sessionData = invalid or not IsInt(sessionData.timestamp)
if sessionData <> invalid return false
return sessionData
end if end if
nowSeconds = TimeUtils.Now().AsSeconds()
sessionData = RequestSessionData(cancellation) return nowSeconds - sessionData.timestamp <= INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS
if sessionData.error <> invalid
return sessionData
end if
SaveSessionDataToRegistry(sessionData)
return sessionData
end function end function
function RequestSessionData(cancellation = invalid as object) as object function RequestSessionData(cancellation = invalid as object) as object
@@ -35,12 +29,12 @@ namespace Innertube
}) })
request.Cancellation(cancellation) request.Cancellation(cancellation)
request.TryCount(2) request.TryCount(2)
request.NoCache()
response = request.Await() response = request.Await()
if not response.IsSuccess() if not response.IsSuccess()
return { LogError("Failed to fetch session data: " + response.ErrorMessage())
"error": "Failed to fetch session data: " + response.ErrorMessage() return invalid
}
end if end if
text = response.Text() text = response.Text()
@@ -48,16 +42,14 @@ namespace Innertube
json = StringUtils.ParseJsonSafe(text) json = StringUtils.ParseJsonSafe(text)
if json = invalid if json = invalid
return { LogError("Failed to parse session data: " + text)
"error": "Failed to parse session data: " + text return invalid
}
end if end if
visitorData = ObjectUtils.Dig(json, [0, 2, 0, 0, 13]) visitorData = ObjectUtils.Dig(json, [0, 2, 0, 0, 13])
if StringUtils.IsNullOrEmpty(visitorData) if StringUtils.IsNullOrEmpty(visitorData)
return { LogError("Failed to find visitorData in session data: " + text)
"error": "Failed to find visitorData in session data: " + text return invalid
}
end if end if
return { return {
@@ -84,13 +76,7 @@ namespace Innertube
return invalid return invalid
end if end if
timestamp = sessionData.timestamp
nowSeconds = TimeUtils.Now().AsSeconds()
if nowSeconds - timestamp > INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS
RegistryUtils.Delete(RegistryUtils.INNERTUBE_SESSION_DATA)
return invalid
end if
return sessionData return sessionData
end function end function
end namespace end namespace
@@ -1,108 +0,0 @@
' TV client-version downgrade experiment (recover VOD per-format URLs withheld under useServerDrivenAbr).
' Self-contained so it can be ripped out wholesale once the experiment concludes: delete this file and the
' call sites in InnertubeService.GetVideoMetadata (InitialPlayerClient, PlanTvClientDowngradeRetry,
' ResponseHasUsableAdaptive, ReportDowngradeOutcome) plus the downgradeRetry* / downgradeOutcomeReported locals,
' then drop ClientType.TvDowngraded + its branches if the downgrade isn't kept.
'
' DEBUG-only (compiled out of prod by #if DEBUG):
' DEBUG_FORCE_DOWNGRADED_CLIENT - downgrade the FIRST player request too, not just the retry.
' DEBUG_FORCE_DOWNGRADE_RETRY - force the downgrade-retry path on every non-live VOD.
#const DEBUG_FORCE_DOWNGRADE_RETRY = false
#const DEBUG_FORCE_DOWNGRADED_CLIENT = false
import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/source/utils/ObjectUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
namespace Innertube.Experiment
enum DowngradeArm
Control = "control_7x"
Treatment = "treatment_5x"
end enum
enum DowngradeOutcome
Recovered = "recovered"
NotRecovered = "not_recovered"
RetryFailed = "retry_failed"
end enum
' Client for the first player request: Tv normally, TvDowngraded only under the debug flag.
function InitialPlayerClient() as Innertube.ClientType
#if DEBUG
#if DEBUG_FORCE_DOWNGRADED_CLIENT
return Innertube.ClientType.TvDowngraded
#end if
#end if
return Innertube.ClientType.Tv
end function
' Plan a one-shot retry only when the player signals useServerDrivenAbr AND no adaptive format has a usable
' URL (the stuck-at-360p state - SABR can be signaled while URLs are still present, in which case we keep them).
' Coin-flip control (same version - intermittency baseline) vs treatment (downgrade - the fix).
' Returns invalid otherwise (URLs present, not SABR, live, or no streamingData).
function PlanTvClientDowngradeRetry(playerResponseJson as object) as object
if not IsAssociativeArray(ObjectUtils.Dig(playerResponseJson, ["streamingData"]))
return invalid
end if
if ValidBool(ObjectUtils.Dig(playerResponseJson, ["videoDetails", "isLive"]))
return invalid
end if
serverDrivenAbr = ValidBool(ObjectUtils.Dig(playerResponseJson, ["playerConfig", "mediaCommonConfig", "useServerDrivenAbr"]))
shouldRetry = serverDrivenAbr and not ResponseHasUsableAdaptive(playerResponseJson)
#if DEBUG
#if DEBUG_FORCE_DOWNGRADE_RETRY
shouldRetry = true
#end if
#end if
if not shouldRetry
return invalid
end if
arm = DowngradeArm.Control
retryClient = Innertube.ClientType.Tv
if Rnd(0) < 0.5
arm = DowngradeArm.Treatment
retryClient = Innertube.ClientType.TvDowngraded
end if
return {
arm: arm
client: retryClient
}
end function
' True if any adaptive format carries a playable field (url / signatureCipher / cipher).
function ResponseHasUsableAdaptive(playerResponseJson as object) as boolean
adaptiveFormats = ObjectUtils.Dig(playerResponseJson, ["streamingData", "adaptiveFormats"])
if not IsArray(adaptiveFormats)
return false
end if
for each format in adaptiveFormats
if IsAssociativeArray(format) and (not StringUtils.IsNullOrEmpty(format["url"]) or not StringUtils.IsNullOrEmpty(format["signatureCipher"]) or not StringUtils.IsNullOrEmpty(format["cipher"]))
return true
end if
end for
return false
end function
' One telemetry event per outcome; fingerprint splits GlitchTip into 6 buckets:
' {control_7x, treatment_5x} x {recovered, not_recovered, retry_failed}.
' Attaches the retry request + response so each bucket is diagnosable, not just a count.
function ReportDowngradeOutcome(arm as Innertube.Experiment.DowngradeArm, outcome as Innertube.Experiment.DowngradeOutcome, videoId as string, playerRequest as object, playerResponse as object) as void
LogInfo("[DOWNGRADE-RETRY] outcome arm=", arm, " outcome=", outcome, " videoId=", videoId)
LogTelemetryEvent({
level: "warning"
message: "[DOWNGRADE-RETRY] arm=" + arm + " outcome=" + outcome
fingerprint: ["downgrade-retry", arm, outcome]
attachments: [{
filename: "request.txt"
content_type: "text/plain"
data: playerRequest.ToCurlCommand()
}, {
filename: "response.json"
content_type: "application/json"
data: playerResponse.Text()
}]
})
end function
end namespace
@@ -70,6 +70,7 @@ class LoungeApi
commandHandlers[COMMAND_TYPE_SEND_DEBUG_COMMAND] = m.HandleIgnoreCommand commandHandlers[COMMAND_TYPE_SEND_DEBUG_COMMAND] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_SET_AUTOPLAY_MODE] = m.HandleIgnoreCommand commandHandlers[COMMAND_TYPE_SET_AUTOPLAY_MODE] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_GET_PARTY_GAMES_MODE] = m.HandleIgnoreCommand commandHandlers[COMMAND_TYPE_GET_PARTY_GAMES_MODE] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_SET_IMPACTED_SESSIONS_SERVER_EVENT] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_GET_NOW_PLAYING] = m.HandleGetPlayingNow commandHandlers[COMMAND_TYPE_GET_NOW_PLAYING] = m.HandleGetPlayingNow
commandHandlers[COMMAND_TYPE_SESSION_ID] = m.HandleSessionId commandHandlers[COMMAND_TYPE_SESSION_ID] = m.HandleSessionId
@@ -86,6 +87,7 @@ class LoungeApi
commandHandlers[COMMAND_TYPE_STOP_VIDEO] = m.HandleStopVideo commandHandlers[COMMAND_TYPE_STOP_VIDEO] = m.HandleStopVideo
commandHandlers[COMMAND_TYPE_SEEK_TO] = m.HandleSeekTo commandHandlers[COMMAND_TYPE_SEEK_TO] = m.HandleSeekTo
commandHandlers[COMMAND_TYPE_SET_PLAYBACK_SPEED] = m.HandleSetPlaybackSpeed commandHandlers[COMMAND_TYPE_SET_PLAYBACK_SPEED] = m.HandleSetPlaybackSpeed
commandHandlers[COMMAND_TYPE_GET_PLAYBACK_SPEED] = m.HandleGetPlaybackSpeed
for each key in commandHandlers for each key in commandHandlers
m[COMMAND_HANDLER_PREFIX + key] = commandHandlers[key] m[COMMAND_HANDLER_PREFIX + key] = commandHandlers[key]
@@ -508,6 +510,11 @@ class LoungeApi
speed = 1.0 speed = 1.0
end if end if
content = player.content
if content <> invalid and content.live = true
return
end if
currentSpeed = ValidFloat(player.playbackSpeed) currentSpeed = ValidFloat(player.playbackSpeed)
if Abs(currentSpeed - speed) < 0.001 if Abs(currentSpeed - speed) < 0.001
@@ -534,6 +541,27 @@ class LoungeApi
messagesToSend.Push(LoungeMessages.OnPlaybackSpeedChanged(speed, true)) messagesToSend.Push(LoungeMessages.OnPlaybackSpeedChanged(speed, true))
end function end function
function HandleGetPlaybackSpeed(commandId as integer, _commandType as string, _commandArgs as object, messagesToSend as object) as void
player = m.videoQueueNode.player
if player = invalid
return
end if
if not player.hasField("playbackSpeed")
LogWarn("Video node does not support 'playbackSpeed' field on this device, ignoring getPlaybackSpeed command")
return
end if
speed = ValidFloat(player.playbackSpeed)
if speed <= 0
speed = 1.0
end if
message = LoungeMessages.OnPlaybackSpeedChanged(speed)
message["commandId"] = commandId
messagesToSend.Push(message)
end function
function SendMessages(messages as object, loungeData = invalid as object) as void function SendMessages(messages as object, loungeData = invalid as object) as void
if messages.Count() = 0 if messages.Count() = 0
return return
@@ -34,6 +34,8 @@ const COMMAND_TYPE_GET_RECEIVER_STATUS = "getReceiverStatus"
const COMMAND_TYPE_SEND_DEBUG_COMMAND = "sendDebugCommand" const COMMAND_TYPE_SEND_DEBUG_COMMAND = "sendDebugCommand"
const COMMAND_TYPE_SET_AUTOPLAY_MODE = "setAutoplayMode" const COMMAND_TYPE_SET_AUTOPLAY_MODE = "setAutoplayMode"
const COMMAND_TYPE_SET_PLAYBACK_SPEED = "setPlaybackSpeed" const COMMAND_TYPE_SET_PLAYBACK_SPEED = "setPlaybackSpeed"
const COMMAND_TYPE_GET_PLAYBACK_SPEED = "getPlaybackSpeed"
const COMMAND_TYPE_SET_IMPACTED_SESSIONS_SERVER_EVENT = "setImpactedSessionsServerEvent"
' Special commands ' Special commands
const COMMAND_TYPE_SESSION_ID = "c" const COMMAND_TYPE_SESSION_ID = "c"
const COMMAND_TYPE_G_SESSION_ID = "S" const COMMAND_TYPE_G_SESSION_ID = "S"
@@ -15,16 +15,18 @@ namespace LoungeMessages
return message return message
end function end function
function OnPlaybackSpeedChanged(speed as float, isContentSupportVSP as boolean) as object function OnPlaybackSpeedChanged(speed as float, isContentSupportVSP = invalid as dynamic) as object
message = { message = {
commandType: COMMAND_ON_PLAYBACK_SPEED_CHANGED commandType: COMMAND_ON_PLAYBACK_SPEED_CHANGED
} }
commandArgs = {} commandArgs = {}
commandArgs[FIELD_PLAYBACK_SPEED] = speed commandArgs[FIELD_PLAYBACK_SPEED] = speed
if isContentSupportVSP <> invalid
commandArgs[FIELD_PLAYBACK_SPEED_INFO] = FormatJson({ commandArgs[FIELD_PLAYBACK_SPEED_INFO] = FormatJson({
"playbackSpeed": speed "playbackSpeed": speed
"isContentSupportVSP": isContentSupportVSP "isContentSupportVSP": isContentSupportVSP
}) })
end if
message.commandArgs = commandArgs message.commandArgs = commandArgs
return message return message
end function end function
@@ -16,8 +16,9 @@ namespace Lounge
overrides[FIELD_VIDEO_ID] = videoId overrides[FIELD_VIDEO_ID] = videoId
end if end if
nowPlayingMsg = LoungeMessages.NowPlaying(m.top, overrides) nowPlayingMsg = LoungeMessages.NowPlaying(m.top, overrides)
' Sending playback speed to indicate that we will reset it to 1.0 when the content starts playing ' Reset the displayed speed to 1.0 on load. The content's live status (which decides VSP support)
playbackSpeedMsg = LoungeMessages.OnPlaybackSpeedChanged(playbackSpeed, true) ' isn't known yet here, so report only the speed, as the real receiver does for non-change updates.
playbackSpeedMsg = LoungeMessages.OnPlaybackSpeedChanged(playbackSpeed)
m.loungeService.outgoingMessages = [nowPlayingMsg, loungeStateMsg, playbackSpeedMsg] m.loungeService.outgoingMessages = [nowPlayingMsg, loungeStateMsg, playbackSpeedMsg]
end function end function
@@ -1,5 +1,7 @@
import "pkg:/components/Services/Innertube/InnertubeService.bs" import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs" import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/source/utils/CancellationUtils.bs"
import "pkg:/source/utils/MessagePortUtils.bs"
@job("VideoContentJob") @job("VideoContentJob")
function ExecuteJob() as void function ExecuteJob() as void
@@ -32,19 +34,15 @@ function ExecuteJob() as void
if not IsAssociativeArray(metadata) if not IsAssociativeArray(metadata)
cancellation = JobGetCancellation() cancellation = JobGetCancellation()
if backend = "playlet" if backend = "playlet"
visitorData = innertubeNode.visitorData
if StringUtils.IsNullOrEmpty(visitorData) visitorData = GetVisitorData(innertubeNode, cancellation)
messagePort = CreateObject("roMessagePort") if visitorData.cancel = true
MessagePortUtils.ObserveFieldScopedExSafe(innertubeNode, "visitorData", messagePort) JobCancel()
innertubeNode.requestVisitorData = true
message = wait(20000, messagePort)
innertubeNode.unobserveFieldScoped("visitorData")
if message = invalid
innertubeNode.forceRequestVisitorData = true
JobError("Failed to get visitor data. Please try again later.")
return return
end if end if
visitorData = message.getData() if visitorData.error <> invalid
JobError(visitorData.error)
return
end if end if
accessToken = invalid accessToken = invalid
@@ -58,10 +56,16 @@ function ExecuteJob() as void
metadata = InnertubeService.GetVideoMetadata(contentNode.videoId, { metadata = InnertubeService.GetVideoMetadata(contentNode.videoId, {
"cancellation": cancellation "cancellation": cancellation
"credentialTransferToken": loungeServiceNode.credentialTransferToken "credentialTransferToken": loungeServiceNode.credentialTransferToken
"visitorData": visitorData "visitorData": visitorData.visitorData
"accessToken": accessToken "accessToken": accessToken
"onBehalfOfUser": onBehalfOfUser "onBehalfOfUser": onBehalfOfUser
}) })
if IsAssociativeArray(metadata)
contentNode.addFields({
potAttached: ValidBool(metadata.potAttached)
loggedIn: not StringUtils.IsNullOrEmpty(accessToken)
})
end if
else else
metadata = service.GetVideoMetadata(contentNode.videoId, { cancellation: m.top.cancellation }) metadata = service.GetVideoMetadata(contentNode.videoId, { cancellation: m.top.cancellation })
end if end if
@@ -154,6 +158,48 @@ function ExecuteJob() as void
end if end if
end function end function
function GetVisitorData(innertubeNode as object, cancellation as object) as object
port = CreateObject("roMessagePort")
MessagePortUtils.ObserveFieldScopedExSafe(innertubeNode, "visitorData", port)
CancellationUtils.ObserveCancellationScoped(cancellation, port)
visitorData = innertubeNode.visitorData
if not StringUtils.IsNullOrEmpty(visitorData)
innertubeNode.unobserveFieldScoped("visitorData")
CancellationUtils.UnobserveCancellationScoped(cancellation)
return {
visitorData: visitorData
}
end if
innertubeNode.requestVisitorData = true
message = wait(30000, port)
innertubeNode.unobserveFieldScoped("visitorData")
CancellationUtils.UnobserveCancellationScoped(cancellation)
if message <> invalid
if CancellationUtils.IsCancellationEvent(cancellation, message)
return {
cancel: true
}
end if
visitorData = message.getData()
end if
if StringUtils.IsNullOrEmpty(visitorData)
return {
error: "Failed to get visitor data. Please try again later."
}
end if
return {
visitorData: visitorData
}
end function
function CreateStreamUrls(metadata as object, service as Invidious.InvidiousService, preferences as object, backend as string, playletServerPort as integer) as object function CreateStreamUrls(metadata as object, service as Invidious.InvidiousService, preferences as object, backend as string, playletServerPort as integer) as object
instance = service.GetInstance() instance = service.GetInstance()
proxyVideos = preferences["invidious.proxy_videos"] proxyVideos = preferences["invidious.proxy_videos"]
@@ -342,6 +388,10 @@ function SetCaptions(metadata as object, service as object, contentNode as objec
end if end if
isoLanguageList = StringUtils.ParseJsonSafe(ReadAsciiFile("libpkg:/config/ISO-639-1-to-ISO-639-2T.json5")) isoLanguageList = StringUtils.ParseJsonSafe(ReadAsciiFile("libpkg:/config/ISO-639-1-to-ISO-639-2T.json5"))
if not IsAssociativeArray(isoLanguageList)
LogError("Failed to load ISO-639 language map; skipping captions")
return
end if
instance = service.GetInstance() instance = service.GetInstance()
subtitleTracks = [] subtitleTracks = []
@@ -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)
@@ -1403,6 +1404,17 @@ function ReportVideoError(errorData as object, url as dynamic, urls as object, u
data: ValidString(ReadAsciiFile("cachefs:/last_player_response.json")) data: ValidString(ReadAsciiFile("cachefs:/last_player_response.json"))
}] }]
end if end if
potAttached = "false"
loggedIn = "false"
content = m.top.content
if content <> invalid
if ValidBool(content.potAttached)
potAttached = "true"
end if
if ValidBool(content.loggedIn)
loggedIn = "true"
end if
end if
message = [ message = [
errorData.title errorData.title
errorData.body errorData.body
@@ -1412,8 +1424,12 @@ function ReportVideoError(errorData as object, url as dynamic, urls as object, u
`Url: ${url}` `Url: ${url}`
"Urls: " + FormatJson(urls) "Urls: " + FormatJson(urls)
`Url index: ${urlIndex}` `Url index: ${urlIndex}`
`pot_attached: ${potAttached}`
`logged_in: ${loggedIn}`
].Join(Chr(10)) ].Join(Chr(10))
errorData.fingerprint.Push(shownInDialog) errorData.fingerprint.Push(shownInDialog)
errorData.fingerprint.Push(potAttached)
errorData.fingerprint.Push(loggedIn)
if shownInDialog if shownInDialog
level = "error" level = "error"
else else
@@ -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)
+1 -1
View File
@@ -3,7 +3,7 @@ title=PlayletLib
# Do not update version manually, it is auto updated from package.json # Do not update version manually, it is auto updated from package.json
major_version=0 major_version=0
minor_version=47 minor_version=47
build_version=00002 build_version=00004
ui_resolutions=hd ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p uri_resolution_autosub=$$RES$$,480p,720p,1080p
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "playlet-web", "name": "playlet-web",
"version": "0.47.2", "version": "0.47.4",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "playlet-web", "name": "playlet-web",
"version": "0.47.2", "version": "0.47.4",
"devDependencies": { "devDependencies": {
"@sveltejs/vite-plugin-svelte": "^7.1.2", "@sveltejs/vite-plugin-svelte": "^7.1.2",
"@tailwindcss/postcss": "^4.3.1", "@tailwindcss/postcss": "^4.3.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "playlet-web", "name": "playlet-web",
"version": "0.47.2", "version": "0.47.4",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",