Live stream fixes, http client rewrite, telemetry improvements

This commit is contained in:
Brahim Hadriche committed 2026-10-13 17:13:12 -04:00
1 parent df4e16b846
commit 9200bd1c74
63 files changed
+4382 -1157

No files matched your search

@@ -1,4 +1,6 @@
import "pkg:/components/Services/Dash/DashManifest.bs"
import "pkg:/components/Services/Dash/LiveHeadChecks.bs"
import "pkg:/components/Services/Dash/LiveHeadCounts.bs"
import "pkg:/components/Services/Dash/LiveTimeline.types.bs"
import "pkg:/components/Services/Innertube/LiveStreamInfo.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs"
@@ -10,8 +12,6 @@ import "pkg:/source/utils/Types.bs"
' Manifest requests closer together than this (Roku re-fetching after an error) share one live head check.
const LIVE_HEAD_MIN_INTERVAL_MS = 500
' The manifest response waits on the head check; past this it lists the last known head.
const LIVE_HEAD_TIMEOUT_SECONDS = 2
' Head time leaping this far past the listed timeline within one head check is a stall.
const LIVE_STALL_JUMP_MS = 10000
@@ -40,6 +40,7 @@ namespace Http
m.cachedMetadata = invalid
m.liveHeadUrl = ""
m.liveHeadTimer = invalid ' since the last head check; invalid = never checked
m.liveHeadChecks = invalid
m.liveHeadSeqnum = 0
m.liveLoadHeadSeqnum = 0
m.liveLoadHeadTimeMs = invalid
@@ -175,8 +176,7 @@ namespace Http
return true
end if
dashRequest = HttpClient.Get(url)
dashResponse = dashRequest.Await()
dashResponse = HttpClient.Get(url).Await()
if not dashResponse.IsSuccess()
LogError("Failed to fetch DASH manifest from URL", dashResponse.ErrorMessage())
@@ -184,7 +184,7 @@ namespace Http
return true
end if
dashContent = ValidString(dashResponse.Text())
dashContent = dashResponse.Text()
storyboardIndex = dashContent.InStr("</Period>")
if storyboardIndex = -1
response.Redirect(url)
@@ -229,8 +229,8 @@ namespace Http
return xmlContent
end function
' Raise the live head to the stream's newest segment. On failure the timeline
' keeps its end, and the player holds at it until a later check succeeds.
' Raise the live head to the newest one answered. Until a check answers with a newer head, the
' timeline keeps its end and the player holds at it.
function RefreshLiveHead() as void
if StringUtils.IsNullOrEmpty(m.liveHeadUrl)
return
@@ -242,28 +242,21 @@ namespace Http
end if
m.liveHeadTimer.Mark()
head = m.CheckLiveHead()
if head.seqnum < 0
m.ReportLiveHeadFailure(head.response)
return
end if
' Listed segments can't be withdrawn: the head only moves forward.
if head.seqnum > m.liveHeadSeqnum
m.AlignLiveTimeline(head)
m.liveHeadSeqnum = head.seqnum
end if
end function
newest = invalid
for each head in m.liveHeadChecks.Refresh()
if head.seqnum < 0
m.ReportLiveHeadFailure(head.response)
else if newest = invalid or head.seqnum > newest.seqnum
newest = head
end if
end for
WriteAsciiFile(LIVE_HEAD_COUNTS_PATH, FormatJson({ "video_load_id": m.cachedVideoLoadId, "counts": m.liveHeadChecks.counts }))
' A no-sq HEAD: googlevideo answers at once with the X-Head-* headers.
function CheckLiveHead() as LiveHeadReading
request = Innertube.CreateLiveHeadRequest(m.liveHeadUrl)
request.TimeoutSeconds(LIVE_HEAD_TIMEOUT_SECONDS)
response = request.Await()
return {
seqnum: Innertube.ReadLiveHeadSeqnum(response)
timeMs: Innertube.ReadLiveHeadTimeMs(response)
response: response
}
' Listed segments can't be withdrawn: the head only moves forward.
if newest <> invalid and newest.seqnum > m.liveHeadSeqnum
m.AlignLiveTimeline(newest)
m.liveHeadSeqnum = newest.seqnum
end if
end function
' Segments are listed at the duration at load, the stream's lifetime average: off
@@ -353,11 +346,10 @@ namespace Http
})
end function
' Until a head check succeeds, the listed timeline stops growing and the player
' holds at its end. Telemetry once per video load.
function ReportLiveHeadFailure(response as object) as void
' Telemetry once per video load.
function ReportLiveHeadFailure(response as HttpClient.Response) as void
statusText = Str(response.StatusCode()).Trim()
LogWarnNoTelemetry("Live head check returned no X-Head-Seqnum (HTTP", statusText, "); head stays at", m.liveHeadSeqnum)
LogWarnNoTelemetry("Live head check returned no X-Head-Seqnum (HTTP", statusText, ")")
if m.reportedLiveHeadFailure
return
end if
@@ -375,7 +367,7 @@ namespace Http
`video_load_id: ${ValidString(m.cachedVideoLoadId)}`
`head: ${m.liveHeadSeqnum}`
`status: ${statusText}`
`error: ${response.ErrorMessage(false)}`
`error: ${response.ErrorMessage()}`
`url: ${m.liveHeadUrl}`
].Join(`\n`)
}]
@@ -384,6 +376,10 @@ namespace Http
function ResetLiveState(metadata as object) as void
m.liveHeadUrl = ValidString(metadata.liveHeadUrl)
if m.liveHeadChecks <> invalid
m.liveHeadChecks.Cancel()
end if
m.liveHeadChecks = new LiveHeadChecks(m.liveHeadUrl)
m.liveHeadTimer = invalid
m.liveHeadSeqnum = ValidInt(metadata.liveHeadSeqnum)
m.liveLoadHeadSeqnum = m.liveHeadSeqnum
@@ -81,8 +81,8 @@ namespace Http
end if
end if
req = HttpClient.Post("https://www.youtube.com/api/lounge/pairing/register_pairing_code", "")
req.UrlEncodedForm({
req = HttpClient.Post("https://www.youtube.com/api/lounge/pairing/register_pairing_code")
req.FormBody({
"pairing_code": pairingCode
"screen_id": m.loungeService.screenId
"screen_name": m.deviceName
@@ -128,8 +128,23 @@ namespace Http
requestHeaders["User-Agent"] = VIDEO_PLAYER_USER_AGENT
end if
httpReq = HttpClient.FromObject(requestArgs)
httpRes = httpReq.Await()
method = "GET"
if requestArgs.Method <> invalid
method = requestArgs.Method
end if
proxyRequest = new HttpClient.Request(method, requestArgs.Url)
proxyRequest.Headers(requestHeaders)
if requestArgs.Body <> invalid
proxyRequest.TextBody(requestArgs.Body)
end if
if requestArgs.CacheSeconds <> invalid
if requestArgs.CacheSeconds > 0
proxyRequest.CacheForSeconds(requestArgs.CacheSeconds)
else
proxyRequest.NoCache()
end if
end if
httpRes = proxyRequest.Await()
result = {
"status": httpRes.StatusCode()
@@ -0,0 +1,13 @@
import "pkg:/source/services/HttpClient.bs"
' Awaits url on this task's thread, as a job does, cancellable through cancellationNode.cancel.
function Init()
m.top.functionName = "AwaitUrl"
end function
function AwaitUrl() as void
cancellation = CancellationUtils.CreateCancellation(m.top.cancellationNode, "cancel", true)
pending = HttpClient.Get(m.top.url).Cancellation(cancellation).Send()
m.top.sending = true
m.top.cancelled = pending.Await().IsCancelled()
end function
@@ -0,0 +1,9 @@
<component name="AwaitInTask" extends="Task">
<interface>
<field id="url" type="string" />
<!-- owned by the thread that made it, so cancelling it reaches this task from another thread -->
<field id="cancellationNode" type="node" />
<field id="sending" type="boolean" />
<field id="cancelled" type="boolean" />
</interface>
</component>
@@ -0,0 +1,17 @@
' Sets cancellationNode.cancel cancelAfterMs after that field is set, while the caller's thread blocks.
function Init()
m.top.functionName = "CancelLater"
end function
function CancelLater() as void
node = CreateObject("roSGNode", "Node")
node.addField("cancel", "boolean", false)
port = CreateObject("roMessagePort")
m.top.ObserveField("cancelAfterMs", port)
m.top.cancellationNode = node
' Waiting on the port lets other threads rendezvous with this one.
while type(wait(0, port)) <> "roSGNodeEvent"
end while
wait(m.top.cancelAfterMs, port)
node.cancel = true
end function
@@ -0,0 +1,7 @@
<component name="CancelLaterTask" extends="Task">
<interface>
<!-- owned by this task's thread, so setting its cancel field needs no other thread -->
<field id="cancellationNode" type="node" />
<field id="cancelAfterMs" type="integer" alwaysNotify="true" />
</interface>
</component>
@@ -0,0 +1,220 @@
import "pkg:/source/utils/Types.bs"
' Responds to one request per connection, by path:
' /status/<code> the status
' /seq/<id>/<code>,<code>,... the next status in the list for that path, then its last one;
' <code>@<ms> responds after <ms>
' /delay/<ms> 200 after <ms>
' /echo 200 with the request's { method, path, headers, body } as JSON
' /maxage/<seconds>/<id> 200 with Cache-Control: max-age=<seconds>
' A path in routes (its query aside) responds as its route says instead: { status, headers, body, delayMs }.
' A route { drop: true } closes the connection without a response.
' Every response carries X-Hit, the request's count for its path. Connections are read and responded to
' without blocking each other, so a slow or abandoned one holds up nothing.
' The last request read is in lastRequest: { method, path, headers, body }.
' Roku's roUrlTransfer sometimes never completes when the whole response and the close reach it over
' loopback within a millisecond of its request (9 of 8000 such requests; 0 of 16000 at 5ms or 20ms).
const MIN_RESPONSE_DELAY_MS = 5
' A connection whose request isn't complete by then is dropped.
const READ_TIMEOUT_MS = 2000
function Init()
m.top.functionName = "Serve"
end function
function Serve() as void
messagePort = CreateObject("roMessagePort")
listener = CreateObject("roStreamSocket")
listener.SetReuseAddr(true)
address = CreateObject("roSocketAddress")
address.SetAddress(`127.0.0.1:${m.top.port}`)
listener.SetAddress(address)
listener.SetMessagePort(messagePort)
listener.NotifyReadable(true)
if not listener.Listen(8)
return
end if
m.top.ObserveField("shouldQuit", messagePort)
m.hits = {}
m.clock = CreateObject("roTimespan")
reading = []
responses = []
m.top.isRunning = true
while true
' 0: no deadline, wait for the next socket event.
waitMs = 0
for each item in reading
waitMs = ShorterWaitMs(waitMs, item.sinceMs + READ_TIMEOUT_MS)
end for
for each response in responses
waitMs = ShorterWaitMs(waitMs, response.sendAtMs)
end for
message = wait(waitMs, messagePort)
if type(message) = "roSGNodeEvent"
exit while
end if
if listener.IsReadable()
connection = listener.Accept()
while connection <> invalid
connection.SetMessagePort(messagePort)
connection.NotifyReadable(true)
reading.Push({ connection: connection, data: "", byteCount: 0, sinceMs: m.clock.TotalMilliseconds() })
connection = listener.Accept()
end while
end if
stillReading = []
for each item in reading
connection = item.connection
closed = false
if connection.IsReadable()
count = connection.GetCountRcvBuf()
if count > 0
' ReceiveStr ends at a NUL byte; a binary body is counted in bytes, read as text up to its first NUL.
bytes = CreateObject("roByteArray")
bytes[count - 1] = 0
item.byteCount += connection.Receive(bytes, 0, count)
item.data += bytes.ToAsciiString()
else
' Readable with nothing to read: the peer closed.
closed = true
end if
end if
response = BuildResponse(item)
if response <> invalid
connection.NotifyReadable(false)
responses.Push(response)
else if closed or m.clock.TotalMilliseconds() - item.sinceMs >= READ_TIMEOUT_MS
connection.Close()
else
stillReading.Push(item)
end if
end for
reading = stillReading
unsent = []
for each response in responses
if response.sendAtMs <= m.clock.TotalMilliseconds()
response.connection.SendStr(response.text)
response.connection.Close()
else
unsent.Push(response)
end if
end for
responses = unsent
end while
for each item in reading
item.connection.Close()
end for
for each response in responses
response.connection.Close()
end for
listener.Close()
m.top.isRunning = false
end function
' The wait until deadlineMs, or waitMs if that is shorter; 0 means no wait limit yet.
function ShorterWaitMs(waitMs as integer, deadlineMs as integer) as integer
untilDeadlineMs = deadlineMs - m.clock.TotalMilliseconds()
if untilDeadlineMs < 1
untilDeadlineMs = 1
end if
if waitMs = 0 or untilDeadlineMs < waitMs
return untilDeadlineMs
end if
return waitMs
end function
' The response to the connection's request and when to send it, or invalid until the request is complete.
function BuildResponse(item as object) as object
headEnd = item.data.InStr(`\r\n\r\n`)
if headEnd = -1
return invalid
end if
head = item.data.Left(headEnd)
headers = {}
for each line in head.Split(`\r\n`)
colon = line.InStr(":")
if colon > 0
headers[LCase(line.Left(colon))] = line.Mid(colon + 1).Trim()
end if
end for
requestBody = item.data.Mid(headEnd + 4)
if item.byteCount - headEnd - 4 < ValidString(headers["content-length"]).ToInt()
return invalid
end if
requestLine = head.Split(`\r\n`)[0].Split(" ")
if requestLine.Count() < 2
return invalid
end if
method = requestLine[0]
path = requestLine[1]
m.hits[path] = ValidInt(m.hits[path]) + 1
hit = m.hits[path]
m.top.hits = m.hits
request = { method: method, path: path, headers: headers, body: requestBody }
m.top.lastRequest = request
delayMs = MIN_RESPONSE_DELAY_MS
route = ValidAssociativeArray(m.top.routes)[path.Split("?")[0]]
if route <> invalid
if ValidInt(route.delayMs) > delayMs
delayMs = route.delayMs
end if
if route.drop = true
return { connection: item.connection, text: "", sendAtMs: m.clock.TotalMilliseconds() + delayMs }
end if
text = `HTTP/1.1 ${route.status} Test\r\nContent-Length: ${ValidString(route.body).Len()}\r\nX-Hit: ${hit}\r\nConnection: close\r\n`
for each name in ValidAssociativeArray(route.headers)
text += `${name}: ${route.headers[name]}\r\n`
end for
text += `\r\n`
if method <> "HEAD"
text += ValidString(route.body)
end if
return { connection: item.connection, text: text, sendAtMs: m.clock.TotalMilliseconds() + delayMs }
end if
status = 404
segments = path.Split("?")[0].Split("/")
if segments.Count() = 3 and segments[1] = "status"
status = segments[2].ToInt()
else if segments.Count() = 4 and segments[1] = "seq"
codes = segments[3].Split(",")
index = hit - 1
if index >= codes.Count()
index = codes.Count() - 1
end if
entry = codes[index].Split("@")
status = entry[0].ToInt()
if entry.Count() > 1
delayMs = entry[1].ToInt()
end if
else if segments.Count() = 3 and segments[1] = "delay"
delayMs = segments[2].ToInt()
status = 200
else if segments.Count() = 2 and segments[1] = "echo"
status = 200
else if segments.Count() = 4 and segments[1] = "maxage"
status = 200
end if
body = `hit ${hit}`
extraHeaders = ""
if segments[1] = "echo"
body = FormatJson(request)
else if segments[1] = "maxage"
extraHeaders = `Cache-Control: max-age=${segments[2]}\r\n`
end if
text = `HTTP/1.1 ${status} Test\r\nContent-Type: text/plain\r\nContent-Length: ${body.Len()}\r\nX-Hit: ${hit}\r\n${extraHeaders}Connection: close\r\n\r\n`
if method <> "HEAD"
text += body
end if
return { connection: item.connection, text: text, sendAtMs: m.clock.TotalMilliseconds() + delayMs }
end function
@@ -0,0 +1,11 @@
<component name="HttpTestServer" extends="Task">
<interface>
<field id="port" type="integer" value="54124" />
<field id="isRunning" type="boolean" />
<!-- request count per /seq id -->
<field id="hits" type="assocarray" />
<field id="routes" type="assocarray" />
<field id="lastRequest" type="assocarray" />
<field id="shouldQuit" type="boolean" alwaysNotify="true" />
</interface>
</component>
@@ -0,0 +1,19 @@
import "pkg:/source/services/HttpClient.bs"
' Polls url's response on this task's thread without ever waiting on a port, cancellable through cancellationNode.cancel.
function Init()
m.top.functionName = "PollUrl"
end function
function PollUrl() as void
cancellation = CancellationUtils.CreateCancellation(m.top.cancellationNode, "cancel", true)
pending = HttpClient.Get(m.top.url).Cancellation(cancellation).Send()
m.top.sending = true
response = invalid
timer = CreateObject("roTimespan")
while response = invalid and timer.TotalMilliseconds() < 5000
response = pending.Poll()
sleep(10)
end while
m.top.cancelled = response <> invalid and response.IsCancelled()
end function
@@ -0,0 +1,9 @@
<component name="PollInTask" extends="Task">
<interface>
<field id="url" type="string" />
<!-- owned by the thread that made it, so cancelling it reaches this task from another thread -->
<field id="cancellationNode" type="node" />
<field id="sending" type="boolean" />
<field id="cancelled" type="boolean" />
</interface>
</component>