Compare commits

..
23 Commits
Author SHA1 Message Date
Brahim Hadriche 6c9c87ce50 Release v0.48.7 (#951) 2026-10-05 17:19:53 -04:00
Brahim Hadriche 684295c405 [skip ci] ES translations 2026-10-05 17:14:40 -04:00
Weblate (bot)andAdrian Vargas edb28abb60 Translated using Weblate (Spanish) (#950)
Currently translated at 100.0% (354 of 354 strings)

Translation: Playlet/Playlet
Translate-URL: https://hosted.weblate.org/projects/playlet/playlet/es/

Co-authored-by: Adrian Vargas <adrian18175@gmail.com>
2026-10-05 17:12:30 -04:00
Brahim Hadriche 332e1e7ef6 Playback telemetry 2026-10-05 16:57:49 -04:00
Brahim Hadriche 6e964fa2e5 telemetry fix 2026-10-03 21:11:16 -04:00
Brahim Hadriche 55bdf2855b Release v0.48.6 (#948) 2026-10-03 17:12:05 -04:00
Brahim Hadriche 725c427eb7 [skip ci] Add telemetry fallback 2026-10-03 17:07:03 -04:00
Brahim Hadriche d453730e3b [skip ci] capture caption and manifest syslog errors separately 2026-10-02 22:09:53 -04:00
sekuso 8be85f2dd0 when invidious returns 403 on authenticated request, inspect error be… (#944)
* when invidious returns 403 on authenticated request, inspect error before determining if it's fatal for the user token

* simplifying with ibicha's !945 edits - no more followup request to subs endpoint to verify token, just pass if 403 fails for some unk reason
2026-10-02 21:51:43 -04:00
Brahim Hadriche 3dab7b5069 Fixed missing shows, seasons, courses and stations (except paid ones) 2026-10-01 08:37:14 -04:00
Brahim Hadriche e93f9a02c2 [chore] update dependencies (#938)
* update dependencies

* no message
2026-09-29 14:47:11 -04:00
Brahim Hadriche 37a1fffb8d Release v0.48.5 (#943) 2026-09-29 14:06:52 -04:00
Brahim Hadriche 6ae6f6cb68 Fixed issue with start up tasks that might have caused "Failed to fetch session data" errors. 2026-09-26 20:03:51 -04:00
Brahim Hadriche 510d81b872 Release v0.48.4 (#942) 2026-09-24 18:55:56 -04:00
Brahim Hadriche ebabb6ca99 Audio track fix 2026-09-24 16:37:42 -04:00
Brahim Hadriche 1678bee3b5 [chore] update dependencies (#927)
* update dependencies

* Few updates
2026-09-09 15:36:51 -04:00
Brahim Hadriche c055260023 [skip ci] License related fixes
remove wrong license comment - https://github.com/FortAwesome/Font-Awesome/issues/19191
Add MIT notice for qrcode
2026-08-25 20:32:47 -04:00
Brahim Hadriche e0f5c9691b Filter out search tiles 2026-08-19 11:53:58 -04:00
Brahim Hadriche 9da9bdf06f [skip ci] ci fix 2026-08-15 10:24:54 -04:00
Brahim Hadriche fea1c22aa9 [skip ci] prevent crashes on older pinned versions of playlet-lib 2026-08-12 18:47:59 -04:00
Brahim Hadriche 48b10e8618 [skip ci] small fixes 2026-08-02 09:42:41 -04:00
Brahim Hadriche 7286c099a0 http client telemetry fix 2026-07-30 15:30:54 -04:00
Brahim Hadriche f29b0f0af8 [skip ci] onkeyevent test for player 2026-07-30 14:00:20 -04:00
51 changed files with 3451 additions and 2761 deletions

No files matched your search

+1
View File
@@ -8,6 +8,7 @@ on:
jobs:
update_wiki_stats:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- name: Checkout
uses: actions/checkout@v4
+29
View File
@@ -5,6 +5,35 @@ 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/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.48.7] - 2026-10-05
### Added
- Spanish translations
### Fixed
- Playback telemetry: capture baseline buffering states, to be able to optimize in future versions
## [0.48.6] - 2026-10-03
### Fixed
- Missing shows, seasons, courses and stations (except paid ones)
- Keep Invidious profiles signed in when a 403 does not report a known authentication error
## [0.48.5] - 2026-09-29
### Fixed
- Issue with start up tasks that might have caused "Failed to fetch session data" errors.
## [0.48.4] - 2026-09-24
### Fixed
- Default audio track is now the regular audio instead of "Voice Boost" or "Stable Volume", which are now separate tracks
## [0.48.3] - 2026-07-28
### Fixed
+1
View File
@@ -15,6 +15,7 @@
1010
],
"diagnosticLevel": "hint",
"minFirmwareVersion": "11.5.0",
// The validation regex rules are validated using the validation-plugin.ts plugin
"validation": [
{
+379 -1950
View File
File diff suppressed because it is too large. Load diff
+15 -21
View File
@@ -1,39 +1,37 @@
{
"name": "playlet",
"version": "0.48.3",
"version": "0.48.7",
"description": "Unofficial YouTube client for Roku",
"devDependencies": {
"@rokucommunity/bslint": "^0.8.44",
"@rokucommunity/bslint": "^0.8.46",
"@types/crypto-js": "^4.2.2",
"@types/fs-extra": "^11.0.4",
"@types/node": "^26.1.1",
"@types/node": "^26.6.3",
"@types/xml2js": "^0.4.14",
"argparse": "^3.0.0",
"brighterscript": "0.73.0",
"brighterscript-formatter": "^1.8.1",
"argparse": "^3.0.2",
"brighterscript": "0.73.5",
"brighterscript-formatter": "^1.8.3",
"convert-svg-to-png": "^0.7.1",
"crypto-js": "^4.2.0",
"dotenv": "^17.4.2",
"fs-extra": "^11.4.0",
"dotenv": "^18.0.4",
"fs-extra": "^11.4.1",
"glob": "^13.0.6",
"imap": "^0.8.19",
"ip": "^2.0.1",
"json5": "^2.2.3",
"mailparser": "^3.9.14",
"mailparser": "^3.9.28",
"protocol-buffers-schema": "^3.6.1",
"puppeteer": "^25.3.0",
"roku-deploy": "^3.18.2",
"roku-deploy": "^3.18.4",
"roku-test-automation": "^2.2.2",
"rooibos-roku": "5.16.4",
"rounded-rect-9patch": "^1.1.2",
"rooibos-roku": "5.16.5",
"semver": "^7.8.5",
"shelljs": "^0.10.0",
"telnet-client": "^2.2.13",
"telnet-client": "^2.2.14",
"ts-node": "^10.9.2",
"typescript": "6.0.3",
"xml2js": "^0.6.2",
"yaml": "^2.9.0",
"youtubei.js": "^17.2.0"
"yaml": "^2.9.1",
"youtubei.js": "^18.1.0"
},
"engines": {
"node": "22"
@@ -68,20 +66,16 @@
"test:integration:player": "npx tsx ./integration-tests/vpd-run-player.ts",
"version-sync": "node tools/version-sync.js",
"manifest-git-hash": "node tools/update-manifest-git-hash.js",
"sign-released-package": "node tools/sign-released-package.js",
"screenshot": "node tools/screenshot.js",
"convert-images": "node tools/convert-images.js",
"update-rale-component": "cd tools/RALE && rm TrackerTask.xml && curl -o TrackerTask.zip https://devtools.web.roku.com/roku-advanced-layout-editor/app/TrackerTask.zip && unzip TrackerTask.zip && rm TrackerTask.zip",
"postinstall": "cd playlet-lib && npm install && cd ../playlet-app && npm install && cd ../playground && npm install && cd ../playlet-web && npm install",
"update-deps": "npx npm-check-updates --deep --upgrade --install always --reject typescript,svelte-preprocess",
"update-deps": "npx npm-check-updates --deep --upgrade --install always --reject typescript",
"registry:write": "node tools/registry.js --input registry.json",
"registry:read": "node tools/registry.js --output registry.json",
"registry:clear": "node tools/registry.js --clear",
"restart-app": "node tools/restart-app.js",
"check-for-updates": "node tools/check-for-updates.js",
"shutdown": "node tools/shutdown.js"
},
"optionalDependencies": {
"@rollup/rollup-linux-x64-gnu": "^4.62.2"
}
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-app",
"version": "0.48.3",
"version": "0.48.7",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-app",
"version": "0.48.3"
"version": "0.48.7"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-app",
"version": "0.48.3",
"version": "0.48.7",
"description": "Unofficial YouTube client for Roku",
"scripts": {
"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
major_version=0
minor_version=48
build_version=00003
build_version=00007
ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p
+1
View File
@@ -23,6 +23,7 @@ function Main(args as object) as void
Registry.ClearPlayletLibUrlsIfNeeded(args)
Registry.ClearRegistryIfNeeded(args)
Registry.ClearUnsupportedPlayletLibUrls()
scene = screen.CreateScene("BootstrapScene")
screen.show()
+37
View File
@@ -0,0 +1,37 @@
namespace PlayletLibUrls
const RELEASE_URL_PATTERN = "^https://github\.com/iBicha/playlet/releases/download/v(\d+\.\d+\.\d+)/"
' v0.11.0 is the first release without HomeGridScreen, which still crashes on the devices
' pinned to v0.7.0 - v0.10.3.
const MIN_VERSION = "0.11.0"
function IsUnsupported(entry as object) as boolean
matches = CreateObject("roRegex", RELEASE_URL_PATTERN, "").Match(entry.link)
if matches.Count() <> 2
return false
end if
return CompareVersions(matches[1], MIN_VERSION) < 0
end function
function CompareVersions(left as string, right as string) as integer
leftParts = left.Tokenize(".")
rightParts = right.Tokenize(".")
for i = 0 to leftParts.Count() - 1
leftPart = leftParts[i].ToInt()
rightPart = rightParts[i].ToInt()
if leftPart < rightPart
return -1
end if
if leftPart > rightPart
return 1
end if
end for
return 0
end function
end namespace
@@ -0,0 +1,61 @@
namespace Tests
@suite
class PlayletLibUrlsTests extends Rooibos.BaseTestSuite
@describe("PlayletLibUrls.IsUnsupported")
@it("reports a tagged release below the minimum version")
@params("https://github.com/iBicha/playlet/releases/download/v0.7.0/playlet-lib.zip")
@params("https://github.com/iBicha/playlet/releases/download/v0.9.0/playlet-lib.zip")
@params("https://github.com/iBicha/playlet/releases/download/v0.10.3/playlet-lib.zip")
@params("https://github.com/iBicha/playlet/releases/download/v0.10.3/playlet-lib.squashfs.pkg")
function _(link as string)
m.assertTrue(PlayletLibUrls.IsUnsupported({ type: "custom", link: link }))
end function
@it("reports nothing for a tagged release at or above the minimum version")
@params("https://github.com/iBicha/playlet/releases/download/v0.11.0/playlet-lib.zip")
@params("https://github.com/iBicha/playlet/releases/download/v0.11.1/playlet-lib.zip")
@params("https://github.com/iBicha/playlet/releases/download/v0.48.3/playlet-lib.squashfs.pkg")
@params("https://github.com/iBicha/playlet/releases/download/v1.0.0/playlet-lib.zip")
function _(link as string)
m.assertFalse(PlayletLibUrls.IsUnsupported({ type: "custom", link: link }))
end function
@it("reports nothing for a url that carries no version")
@params("https://github.com/iBicha/playlet/releases/latest/download/playlet-lib.zip")
@params("https://github.com/iBicha/playlet/releases/download/canary/playlet-lib.zip")
@params("https://github.com/iBicha/playlet/releases/download/0.10.3/playlet-lib.zip")
@params("http://192.168.1.10:8888/playlet-lib.zip")
@params("pkg:/lib/playlet-lib.zip")
@params("")
function _(link as string)
m.assertFalse(PlayletLibUrls.IsUnsupported({ type: "custom", link: link }))
end function
@describe("PlayletLibUrls.CompareVersions")
@it("reports the same version as equal")
function _()
m.assertEqual(PlayletLibUrls.CompareVersions("0.11.0", "0.11.0"), 0)
end function
@it("orders by the first part that differs")
@params("0.10.3", "0.11.0")
@params("0.11.0", "0.11.1")
@params("0.11.0", "1.0.0")
function _(older as string, newer as string)
m.assertEqual(PlayletLibUrls.CompareVersions(older, newer), -1)
m.assertEqual(PlayletLibUrls.CompareVersions(newer, older), 1)
end function
@it("compares parts as numbers, not text")
function _()
m.assertEqual(PlayletLibUrls.CompareVersions("0.9.0", "0.11.0"), -1)
m.assertEqual(PlayletLibUrls.CompareVersions("0.11.0", "0.9.0"), 1)
end function
end class
end namespace
+19
View File
@@ -1,3 +1,5 @@
import "pkg:/source/PlayletLibUrls.bs"
namespace Registry
function ReadKey(key as string, section as string) as dynamic
@@ -41,6 +43,23 @@ namespace Registry
Logger.Log("Cleared key playlet_lib_urls from registry")
end function
' BootstrapScene's load-failure fallback never reaches a pinned lib that loads and then
' crashes, so the device stays on it across every channel update.
function ClearUnsupportedPlayletLibUrls() as void
urls = GetPlayletLibUrlsFromRegistry()
if urls = invalid
return
end if
for each entry in urls
if PlayletLibUrls.IsUnsupported(entry)
DeleteKey("playlet_lib_urls", "Playlet")
Logger.Log(`Cleared key playlet_lib_urls from registry: ${entry.link} is no longer supported`)
return
end if
end for
end function
function ClearRegistryIfNeeded(launchArgs as object) as void
if launchArgs = invalid or launchArgs.clearRegistry = invalid
return
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-lib",
"version": "0.48.3",
"version": "0.48.7",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-lib",
"version": "0.48.3"
"version": "0.48.7"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-lib",
"version": "0.48.3",
"version": "0.48.7",
"description": "Unofficial YouTube client for Roku",
"scripts": {
"prebuild": "node ../tools/rm.js ../build/playlet-lib",
@@ -2,51 +2,20 @@ import "pkg:/source/utils/MessagePortUtils.bs"
import "pkg:/source/utils/Types.bs"
function Init()
m.jobQueueTaskReady = false
m.jobQueueTask = CreateObject("roSGNode", "JobQueueTask")
m.jobQueueTask.observeFieldScoped("ready", FuncName(OnJobQueueTaskReady))
m.jobQueueTask.control = "run"
m.top.observeField("shutdown", FuncName(OnShutdown))
m.top.observeField("request", FuncName(OnRequest))
end function
function OnJobQueueTaskReady(event as object) as void
jobQueueTask = event.getRoSGNode()
jobQueueTask.unobserveFieldScoped("ready")
m.jobQueueTaskReady = true
pendingRequestEvents = m.pendingRequestEvents
if pendingRequestEvents = invalid
return
end if
m.pendingRequestEvents = invalid
for each requestEvent in pendingRequestEvents
OnRequest(requestEvent)
end for
m.jobQueueTask.control = "run"
end function
function OnShutdown() as void
m.top.unobserveField("shutdown")
m.top.unobserveField("request")
m.jobQueueTaskReady = false
m.jobQueueTask.unobserveField("ready")
m.jobQueueTask.shutdown = true
m.jobQueueTask = invalid
m.pendingRequestEvents = invalid
end function
function OnRequest(event as object) as void
if not m.jobQueueTaskReady
if m.pendingRequestEvents = invalid
m.pendingRequestEvents = []
end if
m.pendingRequestEvents.push(event)
LogWarnNoTelemetry("JobQueue: Job queue task is not ready, request will be queued")
return
end if
request = event.getData()
if not IsAssociativeArray(request)
LogError("JobQueue: Invalid request data", request)
@@ -9,65 +9,57 @@ import "pkg:/source/utils/StringUtils.bs"
const MAX_JOB_TASK_COUNT = 30
' Minimum number of JobTasks that will be kept alive
const MIN_JOB_TASK_COUNT = 2
' Time in milliseconds to wait before scaling down JobTasks
' Time in milliseconds without a message before scaling down JobTasks
const SCALE_DOWN_THRESHOLD_MS = 10000
' wait() sometimes isn't woken by a new message (seen on device); the next wait() returns it
const POLL_MS = 1000
' Missed requests cluster right after start (measured): check the port more often then
const STARTUP_WINDOW_MS = 2000
const STARTUP_POLL_MS = 100
function Init()
m.top.functionName = "JobQueueTaskLoop"
m.port = CreateObject("roMessagePort")
m.top.observeField("shutdown", m.port)
m.top.observeField("request", m.port)
end function
function JobQueueTaskLoop() as void
messagePort = CreateObject("roMessagePort")
m.top.observeField("shutdown", messagePort)
m.top.observeField("request", messagePort)
m.top.ready = true
port = m.port
m.busyJobTasks = {}
m.idleJobTasks = []
requests = []
startup = CreateObject("roTimespan")
scaleDownTimer = CreateObject("roTimespan")
while true
while requests.count() > 0
if m.idleJobTasks.Count() > 0
ScheduleRequest(requests.Shift(), m.idleJobTasks.Pop())
continue while
end if
if m.idleJobTasks.Count() + m.busyJobTasks.Count() < MAX_JOB_TASK_COUNT
LogDebug("Creating a new JobTask. Idle:", m.idleJobTasks.Count(), ", Busy:", m.busyJobTasks.Count())
jobTask = CreateObject("roSGNode", "JobTask")
jobTaskId = "JobTask-" + StringUtils.RandomId()
jobTask.id = jobTaskId
jobTaskObject = {
id: jobTaskId
node: jobTask
}
m.busyJobTasks[jobTaskId] = jobTaskObject
MessagePortUtils.ObserveFieldScopedExSafe(jobTask, "ready", messagePort)
jobTask.control = "run"
else
#if DEBUG
LogWarnNoTelemetry("Cannot create new JobTask. Idle:", m.idleJobTasks.Count(), ", Busy:", m.busyJobTasks.Count())
#end if
end if
exit while
while requests.Count() > 0 and m.idleJobTasks.Count() > 0
ScheduleRequest(requests.Shift(), m.idleJobTasks.Pop())
end while
scaleDownThresholdMs = m.idleJobTasks.Count() > MIN_JOB_TASK_COUNT ? SCALE_DOWN_THRESHOLD_MS : 0
message = wait(scaleDownThresholdMs, messagePort)
if requests.Count() > 0 and m.idleJobTasks.Count() + m.busyJobTasks.Count() < MAX_JOB_TASK_COUNT
StartJobTask(requests.Shift(), port)
end if
waitMs = POLL_MS
if startup.TotalMilliseconds() < STARTUP_WINDOW_MS
waitMs = STARTUP_POLL_MS
end if
message = wait(waitMs, port)
if message = invalid
if m.idleJobTasks.Count() > 0
if m.idleJobTasks.Count() > MIN_JOB_TASK_COUNT and scaleDownTimer.TotalMilliseconds() >= SCALE_DOWN_THRESHOLD_MS
jobTaskObject = m.idleJobTasks.Pop()
jobTaskObject.node.UnobserveFieldScoped("ready")
jobTaskObject.node.shutdown = true
LogDebug("Scaled down JobTasks. Idle:", m.idleJobTasks.Count(), ", Busy:", m.busyJobTasks.Count())
scaleDownTimer.Mark()
end if
continue while
end if
scaleDownTimer.Mark()
messageType = Type(message)
if messageType = "roSGNodeEvent"
@@ -89,16 +81,32 @@ function JobQueueTaskLoop() as void
end while
end function
function StartJobTask(request as object, port as object) as void
LogDebug("Creating a new JobTask. Idle:", m.idleJobTasks.Count(), ", Busy:", m.busyJobTasks.Count())
jobTask = CreateObject("roSGNode", "JobTask")
jobTaskId = "JobTask-" + StringUtils.RandomId()
jobTask.id = jobTaskId
jobTaskObject = {
id: jobTaskId
node: jobTask
}
MessagePortUtils.ObserveFieldScopedExSafe(jobTask, "ready", port)
' Set the request before starting the task: its first wait() then returns it right away,
' with no wakeup to miss.
ScheduleRequest(request, jobTaskObject)
jobTask.control = "run"
end function
function ScheduleRequest(request as dynamic, jobTaskObject as dynamic)
m.busyJobTasks[jobTaskObject.id] = jobTaskObject
jobTaskObject.node.request = request
end function
function Shutdown()
m.top.UnobserveFieldScoped("request")
m.top.UnobserveFieldScoped("shutdown")
m.top.UnobserveField("request")
m.top.UnobserveField("shutdown")
m.top.request = invalid
m.top.ready = false
for each jobTaskId in m.busyJobTasks
jobTask = m.busyJobTasks[jobTaskId]
@@ -2,6 +2,5 @@
<interface>
<field id="request" type="assocarray" />
<field id="shutdown" type="boolean" />
<field id="ready" type="boolean" />
</interface>
</component>
@@ -2,20 +2,21 @@ import "pkg:/components/JobSystem/JobRequest.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/StringUtils.bs"
' wait() sometimes isn't woken by a new message (seen on device); the next wait() returns it
const POLL_MS = 1000
function Init()
m.top.functionName = "JobTaskLoop"
m.port = CreateObject("roMessagePort")
m.top.observeField("shutdown", m.port)
m.top.observeField("request", m.port)
end function
function JobTaskLoop() as void
msgPort = CreateObject("roMessagePort")
m.top.observeField("shutdown", msgPort)
m.top.observeField("request", msgPort)
m.top.ready = true
port = m.port
while true
msg = wait(0, msgPort)
msg = wait(POLL_MS, port)
msgType = type(msg)
if msgType = "roSGNodeEvent"
+27 -2
View File
@@ -8,6 +8,13 @@ const FILENAME = "app_logs.txt"
const FILENAME_PREVIOUS = "app_logs_previous.txt"
const FILENAME_STARTUP = "cachefs:/playlet_startup_logs.txt"
enum SysLogUrlType
Captions = "captions"
VideoPlayback = "videoplayback"
Manifest = "manifest"
Other = "other"
end enum
function Init()
m.top.functionName = "LoggerLoop"
@@ -125,9 +132,10 @@ function OnLineSysLog(event as object, dateTime as object, logsFile as string, b
buffer.FromAsciiString(line + `\n`)
buffer.AppendFile(logsFile)
fingerprint = `SysLog${info.Status}${info.LogType}${httpCode}${info.Method}`
urlType = GetSysLogUrlType(info.OrigUrl)
fingerprint = `SysLog-${urlType}-${info.Status}-${info.LogType}-${httpCode}-${info.Method}`
if ThrottleEvent("SysLogError", fingerprint, 60)
if ThrottleEvent("SysLogError" + urlType, fingerprint, 60)
return
end if
@@ -138,6 +146,23 @@ function OnLineSysLog(event as object, dateTime as object, logsFile as string, b
})
end function
function GetSysLogUrlType(url as dynamic) as string
if not IsString(url)
return SysLogUrlType.Other
end if
if url.InStr("/api/timedtext") <> -1 or url.InStr("/api/v1/captions/") <> -1
return SysLogUrlType.Captions
end if
if url.InStr("/videoplayback") <> -1 or url.InStr("/api/dash/live-seg") <> -1
return SysLogUrlType.VideoPlayback
end if
if url.InStr("/api/manifest/") <> -1 or url.InStr("/api/dash") <> -1 or url.InStr("/api/hls") <> -1
return SysLogUrlType.Manifest
end if
return SysLogUrlType.Other
end function
function OnLineLogMonitorMemoryWarning(event as object, dateTime as object, logsFile as string, buffer as object) as void
info = event.getInfo()
message = "[WARN][AppMonitorMemory] " + ToString(info)
@@ -255,6 +255,7 @@ class DashManifest
xtagsInfo = m.GetXtagsInfo(format)
format.xtagsInfo = xtagsInfo
format.isDrc = xtagsInfo.isDrc
format.isVoiceBoost = xtagsInfo.isVoiceBoost
format.isDubbed = xtagsInfo.isDubbed
format.isAutoDubbed = xtagsInfo.isAutoDubbed
format.isDescriptive = xtagsInfo.isDescriptive
@@ -277,12 +278,7 @@ class DashManifest
audioTrackId = format.audioTrack.id
end if
drc = ""
if format.isDrc = true
drc = "drc"
end if
groupId = `${mimeType}-${justCodec}-${colorInfo}-${audioTrackId}-${drc}`
groupId = `${mimeType}-${justCodec}-${colorInfo}-${audioTrackId}${m.GetAudioVariantSuffix(format)}`
if groupInfo[groupId] = invalid
groupInfo[groupId] = []
@@ -441,7 +437,7 @@ class DashManifest
end for
end if
if IsAssociativeArray(firstFormat.audioTrack) or firstFormat.isDrc = true
if IsAssociativeArray(firstFormat.audioTrack) or firstFormat.isDrc = true or firstFormat.isVoiceBoost = true
' Roles
roles = m.GetTrackRoles(firstFormat)
for each role in roles
@@ -474,9 +470,7 @@ class DashManifest
if IsAssociativeArray(stream.audioTrack) and IsString(stream.audioTrack.id)
representationId = `${representationId}-${stream.audioTrack.id}`
end if
if stream.isDrc = true
representationId = `${representationId}-drc`
end if
representationId = `${representationId}${m.GetAudioVariantSuffix(stream)}`
representationAttributes = {
"id": representationId
@@ -739,7 +733,10 @@ class DashManifest
function GetTrackRoles(format as object) as object
roles = []
if format.isOriginal = true
' Within the preferred language, the device defaults to a "main" track (a set
' without a Role counts as main) regardless of bitrate or manifest order.
' Stable Volume and Voice Boost are opt-in re-mixes of the original.
if format.isOriginal = true and format.isDrc <> true and format.isVoiceBoost <> true
roles.Push("main")
else
roles.Push("alternate")
@@ -753,13 +750,28 @@ class DashManifest
roles.Push("description")
end if
if format.isDrc = true
' The device's audio menu ignores Label: it lists tracks by language, and this
' role is what shows a same-language variant separately, as "Enhanced audio".
if format.isVoiceBoost = true
roles.Push("enhanced-audio-intelligibility")
end if
return roles
end function
' Stable Volume and Voice Boost are re-mixes of the same itag: without the suffix
' they share an AdaptationSet (and Representation ids) with the regular mix.
function GetAudioVariantSuffix(format as object) as string
suffix = ""
if format.isDrc = true
suffix = `${suffix}-drc`
end if
if format.isVoiceBoost = true
suffix = `${suffix}-vb`
end if
return suffix
end function
function GenerateImageAdaptationSets(xml as object, storyboards as object, id as integer) as integer
' https://developer.roku.com/en-ca/docs/developer-program/media-playback/trick-mode/hls-and-dash.md#dash-standard-thumbnail-tiles
for i = storyboards.Count() - 1 to 0 step -1
@@ -885,6 +897,7 @@ class DashManifest
lang: ""
acont: ""
isDrc: false
isVoiceBoost: false
isDubbed: false
isAutoDubbed: false
isDescriptive: false
@@ -921,6 +934,8 @@ class DashManifest
result.acont = tags[key]
else if key = "drc" and tags[key] = "1"
result.isDrc = true
else if key = "vb" and tags[key] = "1"
result.isVoiceBoost = true
end if
end for
@@ -1084,18 +1084,25 @@ namespace Innertube
function ParseLockupViewModel(nodeData as object, context as object) as object
contentType = ValidString(nodeData["contentType"])
if contentType = "LOCKUP_CONTENT_TYPE_VIDEO"
if contentType = "LOCKUP_CONTENT_TYPE_VIDEO" or contentType = "LOCKUP_CONTENT_TYPE_MOVIE"
return LockupViewModelTypeVideo(nodeData, context)
else if contentType = "LOCKUP_CONTENT_TYPE_SHORT"
return LockupViewModelTypeShort(nodeData, context)
else if contentType = "LOCKUP_CONTENT_TYPE_PLAYLIST"
else if contentType = "LOCKUP_CONTENT_TYPE_PLAYLIST" or contentType = "LOCKUP_CONTENT_TYPE_PODCAST" or contentType = "LOCKUP_CONTENT_TYPE_ALBUM"
return LockupViewModelTypePlaylist(nodeData, context)
else if contentType = "LOCKUP_CONTENT_TYPE_PODCAST"
return LockupViewModelTypePodcast(nodeData, context)
else if contentType = "LOCKUP_CONTENT_TYPE_ALBUM"
return LockupViewModelTypeAlbum(nodeData, context)
else if contentType = "LOCKUP_CONTENT_TYPE_MOVIE"
return LockupViewModelTypeVideo(nodeData, context)
else if contentType = "LOCKUP_CONTENT_TYPE_SHOW" or contentType = "LOCKUP_CONTENT_TYPE_SEASON" or contentType = "LOCKUP_CONTENT_TYPE_COURSE" or contentType = "LOCKUP_CONTENT_TYPE_STATION"
' For these content types the tap target, not the type, says what the item is: a show or season
' is a creator playlist or a paid Movies & TV title, a station is a live stream or a YouTube Music playlist.
contentId = ValidString(nodeData["contentId"])
command = ObjectUtils.Dig(nodeData, ["rendererContext", "commandContext", "onTap", "innertubeCommand"])
if contentId <> ""
if ValidString(ObjectUtils.Dig(command, ["watchEndpoint", "videoId"])) = contentId
return LockupViewModelTypeVideo(nodeData, context)
end if
if ValidString(ObjectUtils.Dig(command, ["watchEndpoint", "playlistId"])) = contentId or ValidString(ObjectUtils.Dig(command, ["watchPlaylistEndpoint", "playlistId"])) = contentId or ValidString(ObjectUtils.Dig(command, ["browseEndpoint", "browseId"])) = "VL" + contentId
return LockupViewModelTypePlaylist(nodeData, context)
end if
end if
end if
Warning(`Unknown content type: ${contentType}`, nodeData, context)
@@ -1109,7 +1116,7 @@ namespace Innertube
end function
' The badge overlay has two shapes: thumbnailOverlayBadgeViewModel.thumbnailBadges (older, still
' used on playlist/podcast/album lockups) and thumbnailBottomOverlayViewModel.badges (video lockups)
' used on playlist lockups) and thumbnailBottomOverlayViewModel.badges (video lockups)
function ParseThumbnailBadge(thumbnailViewModel as object) as object
overlays = ObjectUtils.Dig(thumbnailViewModel, ["overlays"])
if not IsArray(overlays)
@@ -1161,7 +1168,12 @@ namespace Innertube
metadata = ObjectUtils.Dig(nodeData, ["metadata", "lockupMetadataViewModel"])
title = ObjectUtils.Dig(metadata, ["title", "content"])
thumbnailViewModel = ObjectUtils.Dig(nodeData, ["contentImage", "thumbnailViewModel"])
contentImage = nodeData["contentImage"]
thumbnailViewModel = ObjectUtils.Dig(contentImage, ["thumbnailViewModel"])
if thumbnailViewModel = invalid
' Station lockups frame their live stream as a collection
thumbnailViewModel = ObjectUtils.Dig(contentImage, ["collectionThumbnailViewModel", "primaryThumbnail", "thumbnailViewModel"])
end if
if context.generateVideoThumbnails = true
videoThumbnails = GenerateVideoThumbnails(videoId)
@@ -1330,76 +1342,6 @@ namespace Innertube
return invalid
end function
function LockupViewModelTypePodcast(nodeData as object, context as object) as object
playlistId = nodeData["contentId"]
if not IsString(playlistId)
Warning("Invalid playlist ID in lockupViewModelTypePodcast", nodeData, context)
return invalid
end if
metadata = ObjectUtils.Dig(nodeData, ["metadata", "lockupMetadataViewModel"])
title = ObjectUtils.Dig(metadata, ["title", "content"])
thumbnailViewModel = ObjectUtils.Dig(nodeData, ["contentImage", "collectionThumbnailViewModel", "primaryThumbnail", "thumbnailViewModel"])
thumbnail = ObjectUtils.Dig(thumbnailViewModel, ["image", "sources", 0, "url"])
videoCountText = GetThumbnailBadgeText(thumbnailViewModel)
author = invalid
authorId = invalid
if IsString(context.currentAuthor) and IsString(context.currentAuthorId)
author = context.currentAuthor
authorId = context.currentAuthorId
end if
playlist = {
"type": "playlist"
"playlistId": playlistId
"title": title
"author": author
"authorId": authorId
"playlistThumbnail": thumbnail
"videoCountText": videoCountText
}
PushFeedItem(playlist, context)
return invalid
end function
function LockupViewModelTypeAlbum(nodeData as object, context as object) as object
playlistId = nodeData["contentId"]
if not IsString(playlistId)
Warning("Invalid playlist ID in lockupViewModelTypeAlbum", nodeData, context)
return invalid
end if
metadata = ObjectUtils.Dig(nodeData, ["metadata", "lockupMetadataViewModel"])
title = ObjectUtils.Dig(metadata, ["title", "content"])
thumbnailViewModel = ObjectUtils.Dig(nodeData, ["contentImage", "collectionThumbnailViewModel", "primaryThumbnail", "thumbnailViewModel"])
thumbnail = ObjectUtils.Dig(thumbnailViewModel, ["image", "sources", 0, "url"])
videoCountText = GetThumbnailBadgeText(thumbnailViewModel)
author = invalid
authorId = invalid
if IsString(context.currentAuthor) and IsString(context.currentAuthorId)
author = context.currentAuthor
authorId = context.currentAuthorId
end if
playlist = {
"type": "playlist"
"playlistId": playlistId
"title": title
"author": author
"authorId": authorId
"playlistThumbnail": thumbnail
"videoCountText": videoCountText
}
PushFeedItem(playlist, context)
return invalid
end function
function ParseShortsLockupViewModel(nodeData as object, context as object) as object
if context.disableShorts = true
LogInfo("Skipping Short based on user settings")
@@ -1496,6 +1438,12 @@ namespace Innertube
return invalid
end if
' "Explore more" tileRenderer, opens a search with a predefined query, like TILE_CONTENT_TYPE_EDU below
if TileRendererHasSearchEndpoint(nodeData["onSelectCommand"])
LogWarnNoTelemetry("Skipping tileRenderer without contentType for search endpoint")
return invalid
end if
Warning("TileRenderer without contentType", nodeData, context)
return invalid
end if
@@ -1526,6 +1474,29 @@ namespace Innertube
return invalid
end function
function TileRendererHasSearchEndpoint(onSelectCommand as object) as boolean
if not IsAssociativeArray(onSelectCommand)
return false
end if
if IsAssociativeArray(onSelectCommand["searchEndpoint"])
return true
end if
commands = ObjectUtils.Dig(onSelectCommand, ["commandExecutorCommand", "commands"])
if not IsArray(commands)
return false
end if
for each command in commands
if IsAssociativeArray(command) and IsAssociativeArray(command["searchEndpoint"])
return true
end if
end for
return false
end function
function TileRendererTypeVideo(nodeData as object, context as object) as object
videoId = nodeData["contentId"]
if not IsString(videoId)
@@ -17,6 +17,9 @@ namespace Innertube
if sessionData = invalid or not IsInt(sessionData.timestamp)
return false
end if
if StringUtils.IsNullOrEmpty(sessionData.visitorData)
return false
end if
nowSeconds = TimeUtils.Now().AsSeconds()
return nowSeconds - sessionData.timestamp <= INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS
end function
@@ -110,7 +110,7 @@ namespace Invidious
request.Headers(m.GetAuthenticationHeaders(auth.token))
request.Cancellation(cancellation)
response = request.Await()
m.MarkNeedsReauthOn403(response, auth.profile)
m.MarkNeedsReauthIfCredentialsRejected(response, auth.profile)
end function
function SearchSuggestions(q as string, cancellation = invalid as object) as object
@@ -214,7 +214,7 @@ namespace Invidious
response = request.Await()
if isAuthenticatedRequest
m.MarkNeedsReauthOn403(response, auth.profile)
m.MarkNeedsReauthIfCredentialsRejected(response, auth.profile)
end if
return response
end function
@@ -612,7 +612,7 @@ namespace Invidious
function AuthFeedHandler(context as object) as object
response = context.response
m.MarkNeedsReauthOn403(response, context.profile)
m.MarkNeedsReauthIfCredentialsRejected(response, context.profile)
if not response.IsSuccess()
return invalid
@@ -647,7 +647,7 @@ namespace Invidious
function WatchHistoryHandler(context as object) as object
response = context.response
m.MarkNeedsReauthOn403(response, context.profile)
m.MarkNeedsReauthIfCredentialsRejected(response, context.profile)
if not response.IsSuccess()
return invalid
@@ -699,14 +699,20 @@ namespace Invidious
return json
end function
' A 403 on an authenticated call is terminal — only a fresh sign-in recovers.
function MarkNeedsReauthOn403(response as object, profile as object) as void
function MarkNeedsReauthIfCredentialsRejected(response as object, profile as object) as void
if response.StatusCode() <> 403
return
end if
LogWarn(`Invidious instance responded with 403: ${response.Text()}`)
if profile <> invalid and profile.type = "invidious"
body = ValidString(response.Text())
LogWarn(`Invidious instance responded with 403: ${body}`)
if profile = invalid or profile.type <> "invidious"
return
end if
' Invidious answers 403 to any exception on /api/v1/auth/*, including a route failing after
' authentication succeeded. Only these errors, raised while validating the session, mean it's dead.
if body.InStr("Request must be authenticated") <> -1 or body.InStr("Invalid signature") <> -1 or body.InStr("Erroneous token") <> -1 or body.InStr("Token is expired") <> -1
profile@.MarkNeedsReauth()
end if
end function
@@ -773,7 +779,7 @@ namespace Invidious
request.Cancellation(cancellation)
response = request.Await()
m.MarkNeedsReauthOn403(response, auth.profile)
m.MarkNeedsReauthIfCredentialsRejected(response, auth.profile)
return response
end function
@@ -787,7 +793,7 @@ namespace Invidious
request.Cancellation(cancellation)
response = request.Await()
m.MarkNeedsReauthOn403(response, auth.profile)
m.MarkNeedsReauthIfCredentialsRejected(response, auth.profile)
return response
end function
@@ -801,7 +807,7 @@ namespace Invidious
request.Cancellation(cancellation)
response = request.Await()
m.MarkNeedsReauthOn403(response, auth.profile)
m.MarkNeedsReauthIfCredentialsRejected(response, auth.profile)
return response
end function
end class
+56 -24
View File
@@ -1,12 +1,61 @@
import "pkg:/source/services/HttpClient.bs"
const SENTRY_ENVELOPE_URL = "https://playlet-v8556.ondigitalocean.app/envelope"
const SUPPORTS_ATTACHMENTS = false
const SUPPORT_SERVER_ENVELOPE_URL = "https://playlet-v8556.ondigitalocean.app/envelope"
' A fallback is needed to investigate https://github.com/iBicha/playlet/issues/906
const SENTRY_FALLBACK_ENVELOPE_URL = "https://o4509923566288896.ingest.us.sentry.io/api/4512194184544256/envelope/"
const SENTRY_FALLBACK_KEY = "a16c510299b23ccc63bdc84f751c9950"
namespace Sentry
function SendEvents(events as object) as integer
payload = BuildEnvelope(events, false)
request = HttpClient.Post(SUPPORT_SERVER_ENVELOPE_URL, payload)
request.Header("Content-Type", "application/x-sentry-envelope")
response = request.Await()
' Only when the server never answered: its own failures hit every device at once and would exhaust the fallback's quota
if response.StatusCode() <= 0
LogWarnNoTelemetry("Support server unreachable, sending events to the Sentry fallback:", response.ErrorMessage())
request = HttpClient.Post(SENTRY_FALLBACK_ENVELOPE_URL, BuildEnvelope([CreateSupportServerUnreachableEvent(events[0], payload, response.ErrorMessage())], true))
request.Header("Content-Type", "application/x-sentry-envelope")
request.QueryParam("sentry_key", SENTRY_FALLBACK_KEY)
response = request.Await()
end if
if response.IsSuccess()
LogDebug("Sent events to", request.BuildUrl(), "Response:", response.Text())
return 0
end if
retryAfter = ValidString(response.Headers()["Retry-After"]).ToInt()
if retryAfter = 0
retryAfter = 60
end if
if response.StatusCode() = 429
LogErrorNoTelemetry("Rate limited by", request.BuildUrl(), "Retry after", retryAfter, "seconds")
else
LogErrorNoTelemetry("Failed to send events to", request.BuildUrl(), response.ErrorMessage(), `\nRetry after`, retryAfter, "seconds")
end if
return retryAfter
end function
function CreateSupportServerUnreachableEvent(originalEvent as object, payload as string, errorMessage as string) as object
return {
level: "warning"
message: `Support server unreachable: ${errorMessage}`
fingerprint: ["support server unreachable"]
release: originalEvent.release
tags: originalEvent.tags
userId: originalEvent.userId
attachments: [{
filename: "envelope.txt"
content_type: "text/plain"
data: payload
}]
}
end function
function BuildEnvelope(events as object, supportsAttachments as boolean) as string
timestamp = CreateObject("roDateTime").ToISOString()
payload = FormatJson({
@@ -66,7 +115,7 @@ namespace Sentry
hasAttachments = IsArray(event.attachments) and event.attachments.Count() > 0
if (not SUPPORTS_ATTACHMENTS) and hasAttachments
if (not supportsAttachments) and hasAttachments
extra = {}
for each attachment in event.attachments
extra[attachment.filename] = `content_type:${attachment.content_type}\n${Redact(attachment.data)}`
@@ -80,7 +129,7 @@ namespace Sentry
payload += FormatJson(eventPayload) + `\n`
if SUPPORTS_ATTACHMENTS and hasAttachments
if supportsAttachments and hasAttachments
tmpBuffer = CreateObject("roByteArray")
for each attachment in event.attachments
data = Redact(attachment.data)
@@ -95,24 +144,7 @@ namespace Sentry
end if
end for
request = HttpClient.Post(SENTRY_ENVELOPE_URL, payload)
request.Header("Content-Type", "application/x-sentry-envelope")
response = request.Await()
if not response.IsSuccess()
#if DEBUG
LogErrorNoTelemetry("Failed to send event to Sentry:", response.ErrorMessage(), `\nHeaders:`, response.Headers())
#end if
retryAfter = ValidString(response.Headers()["Retry-After"]).ToInt()
LogErrorNoTelemetry("Rate limited by Sentry. Retry after", retryAfter, "seconds")
if retryAfter = 0
retryAfter = 60
end if
return retryAfter
end if
LogDebug("Sent events to Sentry. Response:", response.Text())
return 0
return payload
end function
function GetFingerprint(message as dynamic) as dynamic
@@ -152,7 +184,7 @@ namespace Sentry
return text
end if
authHeader = /Authorization: [^\r\n]*/i
authHeader = /Authorization: (?!<REDACTED>)[^\r\n]*/i
for each match in authHeader.MatchAll(text)
text = text.Replace(match[0], "Authorization: <REDACTED>")
end for
@@ -1,4 +1,4 @@
#const SUPPORTS_BATCHING = false
#const SUPPORTS_BATCHING = true
import "pkg:/components/Telemetry/LastExitCrash.bs"
import "pkg:/components/Telemetry/Sentry.bs"
@@ -48,14 +48,14 @@ function TelemetryLoop() as void
m.dist = GetDist(m.tags)
m.userId = GetUserId()
ReportSessionStart()
ReportLastExitCrash()
m.top.observeField("LogInfo", msgPort)
m.top.observeField("LogWarn", msgPort)
m.top.observeField("LogError", msgPort)
m.top.observeField("LogEvent", msgPort)
ReportSessionStart()
ReportLastExitCrash()
#if SUPPORTS_BATCHING
debouceMs = 2000
debounceCountLimit = 20
@@ -72,7 +72,8 @@ function TelemetryLoop() as void
"LogError": "error"
}
messages = []
receivedAt = CreateObject("roDateTime")
inbox = []
events = []
while true
@@ -86,7 +87,8 @@ function TelemetryLoop() as void
end if
end if
messages.Push(msg)
receivedAt.Mark()
inbox.Push({ msg: msg, timestamp: receivedAt.ToISOString() })
#if SUPPORTS_BATCHING
debounceTimer.Mark()
@@ -97,8 +99,9 @@ function TelemetryLoop() as void
LogDebug("No more messages")
exit while
end if
messages.Push(msg)
if messages.Count() >= debounceCountLimit
receivedAt.Mark()
inbox.Push({ msg: msg, timestamp: receivedAt.ToISOString() })
if inbox.Count() >= debounceCountLimit
LogDebug("Reached debounce count limit")
exit while
end if
@@ -110,7 +113,8 @@ function TelemetryLoop() as void
#end if
events.Clear()
for each msg in messages
for each item in inbox
msg = item.msg
msgType = type(msg)
if msgType <> "roSGNodeEvent"
continue for
@@ -122,6 +126,7 @@ function TelemetryLoop() as void
events.Push({
level: levelMap[field]
message: msg.getData()
timestamp: item.timestamp
release: m.release
dist: m.dist
tags: m.tags
@@ -132,6 +137,7 @@ function TelemetryLoop() as void
events.Push({
level: data.level
message: data.message
timestamp: item.timestamp
release: m.release
dist: m.dist
tags: m.tags
@@ -141,7 +147,7 @@ function TelemetryLoop() as void
})
end if
end for
messages.Clear()
inbox.Clear()
if events.Count() = 0
continue while
@@ -5,6 +5,14 @@ import "pkg:/source/utils/CancellationUtils.bs"
import "pkg:/source/utils/Locale.bs"
import "pkg:/source/utils/MessagePortUtils.bs"
enum StreamSource
None = ""
DashUrl = "dashUrl"
AdaptiveFormats = "adaptiveFormats"
FormatStreams = "formatStreams"
HlsUrl = "hlsUrl"
end enum
@job("VideoContentJob")
function ExecuteJob() as void
input = JobGetInput()
@@ -116,7 +124,8 @@ function ExecuteJob() as void
return
end if
streamUrls = CreateStreamUrls(metadata, service, preferencesNode, backend, playletServerPort)
streamSource = SelectStreamSource(metadata)
streamUrls = CreateStreamUrls(streamSource, metadata, service, preferencesNode, backend, playletServerPort)
if streamUrls.Count() = 0
contentNode.addFields({ metadata: metadata })
error = "No playable streams found for this video."
@@ -159,6 +168,7 @@ function ExecuteJob() as void
' StreamUrls is taken
playletStreamUrls: streamUrls
playletStreamUrlIndex: 0
playletStreamSource: streamSource
})
firstUrl = streamUrls[0]
@@ -234,21 +244,34 @@ function ResolveBackendId(backend as string, service as Invidious.InvidiousServi
return "invidious"
end function
function CreateStreamUrls(metadata as object, service as Invidious.InvidiousService, preferences as object, backend as string, playletServerPort as integer) as object
function SelectStreamSource(metadata as object) as string
if SupportsDrmDashManifestUrl(metadata)
return StreamSource.DashUrl
else if SupportsDash(metadata)
return StreamSource.AdaptiveFormats
else if SupportsMuxedFormats(metadata)
return StreamSource.FormatStreams
else if SupportsHls(metadata)
return StreamSource.HlsUrl
end if
return StreamSource.None
end function
function CreateStreamUrls(source as string, metadata as object, service as Invidious.InvidiousService, preferences as object, backend as string, playletServerPort as integer) as object
instance = service.GetInstance()
proxyVideos = preferences["invidious.proxy_videos"]
preferredQuality = preferences["playback.preferred_quality"]
streamUrls = []
if SupportsDrmDashManifestUrl(metadata)
if source = StreamSource.DashUrl
dashUrl = UrlUtils.AppendQueryParams(`http://127.0.0.1:${playletServerPort}/api/dash`, {
url: metadata.dashUrl
})
streamUrls.push(dashUrl)
else if SupportsDash(metadata)
else if source = StreamSource.AdaptiveFormats
AddDashUrls(streamUrls, metadata, preferredQuality, backend, proxyVideos, playletServerPort)
else if SupportsMuxedFormats(metadata)
else if source = StreamSource.FormatStreams
for each stream in metadata.formatStreams
if StringUtils.IsNullOrEmpty(stream.url)
continue for
@@ -256,7 +279,7 @@ function CreateStreamUrls(metadata as object, service as Invidious.InvidiousServ
stream.url = AddInstanceToUrlIfNeeded(stream.url, instance)
streamUrls.push(stream.url)
end for
else if SupportsHls(metadata)
else if source = StreamSource.HlsUrl
metadata.hlsUrl = AddInstanceToUrlIfNeeded(metadata.hlsUrl, instance)
AddHlsUrls(streamUrls, metadata, preferredQuality, backend, proxyVideos, playletServerPort)
end if
@@ -0,0 +1,355 @@
import "pkg:/components/VideoPlayerDev/VideoNode.bs"
import "pkg:/source/utils/ErrorUtils.bs"
import "pkg:/source/utils/Locale.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
namespace PlaybackTelemetry
const PLAY_START_SAMPLE_CAP = 10
const UNDERRUN_SAMPLE_CAP = 10
const INV_D1_SAMPLE_CAP = 3
enum Outcome
Closed = "closed"
Finished = "finished"
Error = "error"
end enum
enum Span
None = 0
Playing = 1
BufferingWithoutStatus = 2
Underrun = 3
NotUnderrun = 4
end enum
function ContentBackend(content as object) as string
if content <> invalid and not StringUtils.IsNullOrEmpty(content.backend)
return content.backend
end if
return "unknown"
end function
' The summary's wire rule: false, 0, "", [] and invalid are omitted, at every depth; a reader takes an absent
' field as that default.
function OmitDefaults(value as dynamic) as dynamic
if IsAssociativeArray(value)
result = {}
for each key in value
item = PlaybackTelemetry.OmitDefaults(value[key])
if not PlaybackTelemetry.IsDefault(item)
result[key] = item
end if
end for
return result
end if
if IsArray(value)
result = []
for each item in value
result.Push(PlaybackTelemetry.OmitDefaults(item))
end for
return result
end if
return value
end function
function IsDefault(value as dynamic) as boolean
if value = invalid
return true
end if
if IsBool(value)
return not value
end if
if IsNumber(value)
return value = 0
end if
if IsString(value)
return value = ""
end if
if IsArray(value)
return value.Count() = 0
end if
return false
end function
class Recorder
private playerTimer as object = invalid ' started with the player: every *Ms is ms on it
private transport as object = invalid
private top as object = invalid
private outcome as string = PlaybackTelemetry.Outcome.Closed
private metadataDoneAtMs as integer = -1
private firstPlayingAtMs as integer = -1
private playStartInfos as object = invalid
private playStartCount as integer = 0
private span as integer = PlaybackTelemetry.Span.None
private spanStartMs as integer = 0
private lastIsUnderrun as boolean = false
private playingMs as integer = 0
private underrunCount as integer = 0
private underrunMs as integer = 0
private underrunSamples as object = invalid
private bufferingsWithoutStatusCount as integer = 0
private isUnderrunChangeCount as integer = 0
private errorCount as integer = 0
private healCount as integer = 0
private healSamples as object = invalid
private tailResolveCount as integer = 0
private tailResolveSamples as object = invalid
function new(deps as object)
m.playerTimer = deps.playerTimer
m.transport = deps.transport
m.top = deps.top
m.playStartInfos = []
m.underrunSamples = []
m.healSamples = []
m.tailResolveSamples = []
end function
function OnMetadataDone() as void
m.metadataDoneAtMs = m.playerTimer.TotalMilliseconds()
end function
function OnState(state as string) as void
nowMs = m.playerTimer.TotalMilliseconds()
m.CloseSpan(nowMs, state)
m.spanStartMs = nowMs
if state = VideoState.Playing
m.span = PlaybackTelemetry.Span.Playing
if m.firstPlayingAtMs < 0
m.firstPlayingAtMs = nowMs
end if
' playing under an error dialog: the playback recovered, so the error did not end it.
if m.outcome = PlaybackTelemetry.Outcome.Error
m.outcome = PlaybackTelemetry.Outcome.Closed
end if
else if state = VideoState.Buffering
m.span = PlaybackTelemetry.Span.BufferingWithoutStatus
else
m.span = PlaybackTelemetry.Span.None
end if
end function
' Measured: a seek, resume, startup or retry buffering reports isUnderrun false; only a playback that ran
' dry reports true.
function OnBufferingStatus(status as object) as void
if status = invalid or not IsBool(status.isUnderrun)
return
end if
isUnderrun = status.isUnderrun
if m.span = PlaybackTelemetry.Span.BufferingWithoutStatus
if isUnderrun
m.span = PlaybackTelemetry.Span.Underrun
else
m.span = PlaybackTelemetry.Span.NotUnderrun
end if
m.lastIsUnderrun = isUnderrun
else if (m.span = PlaybackTelemetry.Span.Underrun or m.span = PlaybackTelemetry.Span.NotUnderrun) and isUnderrun <> m.lastIsUnderrun
m.isUnderrunChangeCount += 1
m.lastIsUnderrun = isUnderrun
end if
end function
function OnPlayStartInfo(info as object) as void
if info = invalid
return
end if
m.playStartCount += 1
if m.playStartInfos.Count() < PlaybackTelemetry.PLAY_START_SAMPLE_CAP
m.playStartInfos.Push(info)
end if
end function
function OnErrorDialog() as void
m.outcome = PlaybackTelemetry.Outcome.Error
end function
function OnFinished() as void
m.outcome = PlaybackTelemetry.Outcome.Finished
end function
function RecordHeal(source as string) as void
m.healCount += 1
positionMs = Int(m.top.position * 1000)
floorMs = m.transport.SafetyFloorMs()
LogDebug(`INV-D1 heal: re-pause under active transport. src=${source} mode=${m.transport.transportMode} isLive=${m.transport.isLive} state=${m.top.state} posMs=${positionMs} cursorMs=${m.transport.cursorMs} edgeMs=${m.transport.edgeMs} floorMs=${floorMs} heal=${m.healCount}`)
if m.healSamples.Count() < PlaybackTelemetry.INV_D1_SAMPLE_CAP
m.healSamples.Push({
"at_ms": m.playerTimer.TotalMilliseconds()
"source": source
"mode": m.transport.transportMode
"position_ms": positionMs
"cursor_ms": m.transport.cursorMs
"edge_ms": m.transport.edgeMs
"floor_ms": floorMs ' -1 = no floor: VOD, or a live stream with an unknown window
})
end if
end function
function RecordTailResolve(source as string) as void
m.tailResolveCount += 1
positionMs = Int(m.top.position * 1000)
floorMs = m.transport.SafetyFloorMs()
LogDebug(`INV-D1 tail-resolve: resume forward. src=${source} posMs=${positionMs} cursorMs=${m.transport.cursorMs} floorMs=${floorMs} edgeMs=${m.transport.edgeMs} resolve=${m.tailResolveCount}`)
if m.tailResolveSamples.Count() < PlaybackTelemetry.INV_D1_SAMPLE_CAP
m.tailResolveSamples.Push({
"at_ms": m.playerTimer.TotalMilliseconds()
"source": source
"position_ms": positionMs
"cursor_ms": m.transport.cursorMs
"floor_ms": floorMs
"edge_ms": m.transport.edgeMs
})
end if
end function
function ReportVideoError(errorData as object, errorInfo as object, url as dynamic, urlIndex as dynamic, shownInDialog as boolean) as void
m.errorCount += 1
' malformed data: the last generated DASH/HLS manifest and player response diagnose it from the report.
attachments = invalid
if errorData.body.Instr("malformed data") <> -1 or errorData.body.Instr("invalid pathname") <> -1
attachments = [{
filename: "last_generated_dash.xml"
content_type: "plain/text"
data: ValidString(ReadAsciiFile("cachefs:/last_generated_dash.xml"))
}, {
filename: "last_generated_hls.m3u8"
content_type: "plain/text"
data: ValidString(ReadAsciiFile("cachefs:/last_generated_hls.m3u8"))
}, {
filename: "last_player_response.json"
content_type: "application/json"
data: ValidString(ReadAsciiFile("cachefs:/last_player_response.json"))
}]
end if
potAttached = false
potSource = "none"
loggedIn = false
urls = invalid
content = m.top.content
if content <> invalid
urls = content.playletStreamUrls
potAttached = ValidBool(content.potAttached)
loggedIn = ValidBool(content.loggedIn)
if not StringUtils.IsNullOrEmpty(content.potSource)
potSource = content.potSource
end if
end if
backend = PlaybackTelemetry.ContentBackend(content)
isLive = m.transport.isLive
message = [
errorData.title
errorData.body
`Dialog shown: ${shownInDialog}`
`Position: ${m.top.position}`
`Duration: ${m.top.duration}`
`Url: ${url}`
"Urls: " + FormatJson(urls)
`Url index: ${urlIndex}`
`pot_attached: ${potAttached}`
`pot_source: ${potSource}`
`logged_in: ${loggedIn}`
`backend: ${backend}`
`is_live: ${isLive}`
].Join(Chr(10))
fingerprint = [
Locale.VideoPlayer.ErrorPlayingVideo
m.top.errorMsg
m.top.errorCode
]
if errorInfo <> invalid
fingerprint.Append([
errorInfo.source
errorInfo.ignored
errorInfo.category
errorInfo.errcode
errorInfo.drmerrcode
])
end if
fingerprint.Append([shownInDialog, potAttached, potSource, loggedIn, backend, isLive])
if shownInDialog
level = "error"
else
level = "warning"
end if
LogTelemetryEvent({
level: level
message: message
fingerprint: fingerprint
attachments: attachments
})
end function
function ReportContentJobFailure(error as dynamic) as void
LogError(`VideoContentJob FAILED: ${error}\nbackend: ${PlaybackTelemetry.ContentBackend(m.top.content)}`)
end function
function ReportStopFailure(error as object) as void
LogError("error stopping video:", ErrorUtils.Format(error))
end function
function SendSummary() as void
lifetimeMs = m.playerTimer.TotalMilliseconds()
endedInUnderrun = m.span = PlaybackTelemetry.Span.Underrun
m.CloseSpan(lifetimeMs, "")
m.span = PlaybackTelemetry.Span.None
content = m.top.content
summary = {
"live": m.transport.isLive
"backend": PlaybackTelemetry.ContentBackend(content)
"outcome": m.outcome
"metadata_done_at_ms": m.metadataDoneAtMs
"first_playing_at_ms": m.firstPlayingAtMs
"play_start_infos": m.playStartInfos
"play_start_count": m.playStartCount
"lifetime_ms": lifetimeMs
"playing_ms": m.playingMs
"underrun_count": m.underrunCount
"underrun_ms": m.underrunMs
"underrun_samples": m.underrunSamples
"ended_in_underrun": endedInUnderrun
"bufferings_without_status_count": m.bufferingsWithoutStatusCount
"is_underrun_change_count": m.isUnderrunChangeCount
"error_count": m.errorCount
"heal_count": m.healCount
"heal_samples": m.healSamples
"tail_resolve_count": m.tailResolveCount
"tail_resolve_samples": m.tailResolveSamples
}
if content <> invalid
summary["stream_source"] = content.playletStreamSource
summary["drm"] = not StringUtils.IsNullOrEmpty(ValidAssociativeArray(content.drmParams).keySystem)
summary["stream_url_index"] = content.playletStreamUrlIndex
if m.firstPlayingAtMs < 0 or m.underrunCount > 0 or m.bufferingsWithoutStatusCount > 0 or m.isUnderrunChangeCount > 0 or m.errorCount > 0 or m.healCount > 0 or m.outcome = PlaybackTelemetry.Outcome.Error
summary["video_id"] = content.videoId
end if
end if
LogTelemetryEvent({
level: "info"
message: FormatJson(PlaybackTelemetry.OmitDefaults(summary))
fingerprint: ["playback summary"]
})
end function
' A buffering that got no status counts only when it reached playing: a close, pause or error can land before
' the first status, which follows the buffering edge by up to ~65 ms (measured).
function CloseSpan(nowMs as integer, nextState as string) as void
durationMs = nowMs - m.spanStartMs
if m.span = PlaybackTelemetry.Span.Playing
m.playingMs += durationMs
else if m.span = PlaybackTelemetry.Span.Underrun
m.underrunCount += 1
m.underrunMs += durationMs
if m.underrunCount <= PlaybackTelemetry.UNDERRUN_SAMPLE_CAP
m.underrunSamples.Push({ "at_ms": m.spanStartMs, "ms": durationMs })
end if
else if m.span = PlaybackTelemetry.Span.BufferingWithoutStatus and nextState = VideoState.Playing
m.bufferingsWithoutStatusCount += 1
end if
end function
end class
end namespace
@@ -1,8 +1,9 @@
# VideoPlayerDev
The custom video player intended to replace `components/VideoPlayer` — a stock-OS-trickplay replica plus a
control button row. It is selected at **compile time** by `#const USE_DEV_PLAYER` in `VideoQueue.bs` (default
`false`). Build with the flag `true` to run it (and the integration suite).
The custom video player that replaced `components/VideoPlayer` — a stock-OS-trickplay replica plus a control
button row. It is selected at **compile time** by `#const USE_DEV_PLAYER` in `VideoQueue.bs`, currently `true`:
this is the player that ships. Build with the flag `false` to fall back to the stock `VideoPlayer` (the
integration suite asserts the dev player, so it only passes with the flag on).
## Architecture
@@ -22,6 +23,9 @@ A thin coordinator over a pure-logic brain and projection-only renderers:
nav, storyboard normalize).
- **`SponsorBlockController.bs`** (class) / **`ErrorDialogController.bs`** (namespace functions) — SponsorBlock
and error logic; the coordinator owns the node-scoped pieces (job callbacks, the dialog node).
- **`PlaybackTelemetry.bs`** (class, `m.playbackTelemetry`) — every telemetry event the player sends: video error
reports, and the playback summary sent on close (startup, play starts, playing and underrun time, errors, INV-D1
heals and tail resolves, how it ended). The coordinator reports what happens; it holds no telemetry code.
- **Renderers** (`TrickPlayBar/`, `BifDisplay/`, `LargePause/`, `LoadBufferSpinner/`, `ButtonRow/`,
`VideoPlayerButton/`) — SceneGraph components that are pure projections of scalar input fields.
Each self-derives its own visibility from `transportMode` (a commit sets `transportMode=idle` and the bif
@@ -34,7 +38,7 @@ A thin coordinator over a pure-logic brain and projection-only renderers:
|-------|-------|----------|
| Unit — logic | `source/tests/VideoPlayerDev/*.spec.bs` | `npm run test:lib` |
| Unit — renderers | `components/VideoPlayerDev/**/*.spec.bs` | `npm run test:lib` |
| Seam (real coordinator, faked device) | `components/VideoPlayerDev/tests/VideoPlayerDevSeam.spec.bs` | `npm run test:lib` |
| Seam (real coordinator, faked device) | `components/VideoPlayerDev/tests/*.spec.bs` | `npm run test:lib` |
| Integration (on device) | `integration-tests/vpd-player-*.ts` | `npm run test:integration:player [-- filter]` |
The integration suite asserts `#VideoPlayer` is a `VideoPlayerDev`, so it only passes when the lib is built
@@ -5,12 +5,12 @@ import "pkg:/components/JobSystem/JobSystem.bs"
import "pkg:/components/Services/Innertube/Constants.bs"
import "pkg:/components/VideoPlayer/Lounge.bs"
import "pkg:/components/VideoPlayerDev/ErrorDialogController.bs"
import "pkg:/components/VideoPlayerDev/PlaybackTelemetry.bs"
import "pkg:/components/VideoPlayerDev/PlayerCoordinatorLogic.bs"
import "pkg:/components/VideoPlayerDev/SponsorBlockController.bs"
import "pkg:/components/VideoPlayerDev/TransportController.bs"
import "pkg:/components/VideoPlayerDev/VideoNode.bs"
import "pkg:/components/VideoQueue/VideoQueueUtils.bs"
import "pkg:/source/utils/ErrorUtils.bs"
import "pkg:/source/utils/Locale.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/MathUtils.bs"
@@ -18,11 +18,6 @@ import "pkg:/source/utils/RemoteKeys.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
' Per-content ceiling on INV-D1 heal / tail-resolve telemetry: a pathological loop otherwise emits one
' error per second for as long as it runs. Occurrences keep counting past the cap (each message carries
' its ordinal) and a capped heal loop's true total rides out in one summary event when the content ends.
const INV_D1_TELEMETRY_CAP = 3
' Coordinator for the custom video player. extends Video, enableUI=false.
'
' Owns the focused Video node + key router, the Chrome-group fade, PiP resize, and lifecycle plumbing. All
@@ -48,6 +43,11 @@ function Initialize()
m.top.notificationInterval = 1
m.transport = new TransportController.Controller()
m.playbackTelemetry = new PlaybackTelemetry.Recorder({
playerTimer: CreateObject("roTimespan")
transport: m.transport
top: m.top
})
m.videoContentJob = invalid
m.sponsorBlockSegmentsJob = invalid
@@ -60,8 +60,6 @@ function Initialize()
m.errorDialogNode = invalid
m.ignoreNextFinished = false ' a retry replay -> swallow the next "finished" edge
m.videoPlayedSuccessfully = false ' true once the stream has actually played (gates error-retry)
m.healCount = 0 ' INV-D1 heals this content (telemetry stops at INV_D1_TELEMETRY_CAP; total goes out in the close summary)
m.tailResolveCount = 0 ' live tail resolutions this content (telemetry capped the same way)
m.chromeMode = ChromeMode.Hidden
m.liveBadgeHoldActive = false ' the "● LIVE" reveal hold is running
@@ -168,6 +166,8 @@ function OnNodeReady()
m.top.ObserveField("thumbnailTiles", FuncName(OnThumbnailTiles))
' an external resume/play (the linked phone via Lounge) under an active transport must take over.
m.top.ObserveField("control", FuncName(OnControlChange))
m.top.ObserveField("bufferingStatus", FuncName(OnBufferingStatus))
m.top.ObserveField("playStartInfo", FuncName(OnPlayStartInfo))
' a player that starts minimized shows the PiP hint (1s after the shrink settles, auto-hides after 5s).
m.showFullScreenHint = not m.container.fullscreen
@@ -418,7 +418,7 @@ function TrySponsorBlockSkip() as boolean
end function
' OK/Select — the one shared key. Priority (after the SponsorBlock skip, handled in OnKeyEvent): commit (if a
' transport is active) -> chrome/pause toggle. OK is the VOD pause key (there is no separate ECP Pause). So
' transport is active) -> chrome/pause toggle. OK is the VOD pause key. So
' while idle: VOD = play/pause toggle (reveals chrome + LargePause); live = chrome toggle only (no pause).
function OnOkPress() as boolean
' commit an active transport.
@@ -736,6 +736,7 @@ function OnVideoState(event as object) as void
end if
state = event.getData()
LogInfo("videoState ->", state)
m.playbackTelemetry.OnState(state)
' push the new state to the cast/lounge side in real time.
Lounge.SendOnStateChange()
@@ -784,6 +785,20 @@ function OnVideoState(event as object) as void
end if
end function
function OnBufferingStatus(event as object) as void
if m.onCloseCalled = true
return
end if
m.playbackTelemetry.OnBufferingStatus(event.getData())
end function
function OnPlayStartInfo(event as object) as void
if m.onCloseCalled = true
return
end if
m.playbackTelemetry.OnPlayStartInfo(event.getData())
end function
' A transport freezes the video; if the device is playing under an active transport (Roku resumes a paused
' Video on a seek, or a freeze command was dropped), re-pause. The transport stays active so the bif stays
' visible over the now-paused video. Called from OnVideoState (the change edge) and OnPosition (the net —
@@ -797,33 +812,10 @@ function EnforceTransportFreeze(source as string) as void
' the play-through seek that opened this transport has landed, so clear autoplayAfterSeek; a later
' seek-complete must not silently un-freeze the video behind the transport.
m.top.autoplayAfterSeek = false
m.healCount += 1
' Position detail rides in the message; the fingerprint pins grouping (heal + mode + trigger) so it
' stays a handful of issues instead of fragmenting on the per-event posMs/cursorMs values.
' floorMs=-1 marks an unknown-window live stream — the one shape the tail resolution cannot cover.
healInfo = `INV-D1 heal: re-pause under active transport. src=${source} mode=${m.transport.transportMode} isLive=${m.transport.isLive} state=${m.top.state} posMs=${Int(m.top.position * 1000)} cursorMs=${m.transport.cursorMs} edgeMs=${m.transport.edgeMs} floorMs=${m.transport.SafetyFloorMs()} heal=${m.healCount}`
LogErrorNoTelemetry(healInfo)
if m.healCount <= INV_D1_TELEMETRY_CAP
LogTelemetryEvent({
level: "warning"
message: healInfo
fingerprint: ["INV-D1 heal", m.transport.transportMode, source]
})
end if
m.playbackTelemetry.RecordHeal(source)
else if action = PlayerCoordinatorLogic.SafetyAction.ResumeLiveTail
' the tail overtook the frozen playhead: resolve forward (ResolveLiveTail), don't heal. Telemetered
' at info level so the field shows the resolution working — resolve>1 on one content means the
' resumed playhead was overtaken AGAIN, i.e. LIVE_TAIL_RESUME_MARGIN_MS is too small.
m.tailResolveCount += 1
resolveInfo = `INV-D1 tail-resolve: resume forward. src=${source} posMs=${Int(m.top.position * 1000)} cursorMs=${m.transport.cursorMs} floorMs=${m.transport.SafetyFloorMs()} edgeMs=${m.transport.edgeMs} resolve=${m.tailResolveCount}`
LogInfo(resolveInfo)
if m.tailResolveCount <= INV_D1_TELEMETRY_CAP
LogTelemetryEvent({
level: "info"
message: resolveInfo
fingerprint: ["INV-D1 tail-resolve", source]
})
end if
' the tail overtook the frozen playhead: resolve forward (ResolveLiveTail), don't heal.
m.playbackTelemetry.RecordTailResolve(source)
m.transport.ResolveLiveTail()
ApplyTransport()
else if action = PlayerCoordinatorLogic.SafetyAction.FinishEof
@@ -836,19 +828,6 @@ function EnforceTransportFreeze(source as string) as void
end if
end function
' A heal loop that ran past the telemetry cap still reports its true size: one tally event when the
' content ends (close or content switch). Loop size is the discriminator between a singleton heal and a
' fight the player lost for minutes — the capped per-event stream can no longer show it.
function SendHealSummary() as void
if m.healCount > INV_D1_TELEMETRY_CAP
LogTelemetryEvent({
level: "warning"
message: `INV-D1 heal: ${m.healCount} heals over one content (${m.healCount - INV_D1_TELEMETRY_CAP} past the telemetry cap)`
fingerprint: ["INV-D1 heal suppressed"]
})
end if
end function
' The Video node reached state=error. ErrorDialogController decides retry-vs-dialog; the coordinator applies
' (replay the next URL, or show the scene-level TimedDialog).
function OnVideoError() as void
@@ -863,12 +842,15 @@ function OnVideoError() as void
errorData = GetPlayerErrorData(content.videoId, errorInfo)
' NoTelemetry: ReportVideoError below already telemeters this.
LogErrorNoTelemetry(errorData.title, errorData.body)
' read before deciding: a retry advances content.url and its index to the next stream url.
failedUrl = content.url
failedUrlIndex = content.playletStreamUrlIndex
decision = ErrorDialogController.DecideVideoError(content, errorInfo, m.videoPlayedSuccessfully)
if decision.action = ErrorDialogController.Action.Retry
LogInfo("error retry -> next stream url=", decision.nextUrl)
ReportVideoError(errorData, content.url, content.playletStreamUrls, content.playletStreamUrlIndex, false)
m.playbackTelemetry.ReportVideoError(errorData, errorInfo, failedUrl, failedUrlIndex, false)
' the controller already advanced content.url/index; replay it from the initial position (live edge /
' timestamp / percent watched). Swallow the next finished edge.
m.ignoreNextFinished = true
@@ -879,7 +861,7 @@ function OnVideoError() as void
end if
' a retry isn't possible: report it and show the error dialog (swallowing the trailing finished edge).
ReportVideoError(errorData, content.url, content.playletStreamUrls, content.playletStreamUrlIndex, true)
m.playbackTelemetry.ReportVideoError(errorData, errorInfo, failedUrl, failedUrlIndex, true)
m.ignoreNextFinished = true
ShowErrorDialog({ title: errorData.title, message: errorData.body })
end function
@@ -1149,10 +1131,11 @@ function OnVideoContentJobDone(event as object) as void
return
end if
m.playbackTelemetry.OnMetadataDone()
content = m.top.content
if not info.success
LogError(`VideoContentJob FAILED: ${info.error}\nbackend: ${ContentBackend(content)}`)
m.playbackTelemetry.ReportContentJobFailure(info.error)
decision = ErrorDialogController.DecideContentJobFailure(content, info.error)
ShowErrorDialog(decision)
Lounge.SendOnStateChange()
@@ -1168,9 +1151,6 @@ function OnVideoContentJobDone(event as object) as void
' fill them in for VOD.
isLive = content <> invalid and content.Live = true
m.transport.SetContent(isLive, 2000, false)
SendHealSummary() ' the previous content's capped heal tally, if any
m.healCount = 0
m.tailResolveCount = 0
' 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 same window decides rewindability: a buffer-sized window means no live trickplay at all.
@@ -1403,6 +1383,8 @@ end function
' EOF / close lifecycle.
'-------------------------------------------------------------------------------
function OnPlaybackFinished() as void
' before PlayNext/ClosePlayer: either can close this player, and send its summary, synchronously.
m.playbackTelemetry.OnFinished()
LogDebug("playback finished -> PlayNext or close")
if not VideoQueueUtils.PlayNext(m.videoQueue, m.invidious, m.preferences)
ClosePlayer()
@@ -1414,111 +1396,22 @@ end function
' the retry-vs-dialog decision is ErrorDialogController). 10s countdown on "Play next video"(default) /
' "Cancel"; any key cancels the countdown; response -> PlayNext or close.
'-------------------------------------------------------------------------------
' Build a structured error record from the Video node's error fields for telemetry. Always returns a record —
' callers dereference .title/.body unconditionally, so a state=error with no errorInfo must still produce one.
' Always returns a record — callers dereference .title/.body unconditionally, so a state=error with no errorInfo
' must still produce one.
function GetPlayerErrorData(videoId as string, errorInfo as object) as object
errorMsg = m.top.errorMsg
errorCode = m.top.errorCode
errorStr = m.top.errorStr
title = Tr(Locale.VideoPlayer.ErrorPlayingVideo).Replace("%1", videoId)
body = `errorMsg: ${errorMsg}\nerrorCode: ${errorCode}\nerrorStr: ${errorStr}`
fingerprint = [
Locale.VideoPlayer.ErrorPlayingVideo
errorMsg
errorCode
]
body = `errorMsg: ${m.top.errorMsg}\nerrorCode: ${m.top.errorCode}\nerrorStr: ${m.top.errorStr}`
if errorInfo <> invalid
for each key in errorInfo
body += `\n${key}: ${errorInfo[key]}`
end for
fingerprint.Append([
errorInfo.source
errorInfo.ignored
errorInfo.category
errorInfo.errcode
errorInfo.drmerrcode
])
end if
return { title: title, body: body, fingerprint: fingerprint }
end function
function ContentBackend(content as object) as string
if content <> invalid and not StringUtils.IsNullOrEmpty(content.backend)
return content.backend
end if
return "unknown"
end function
' Send a stream error to telemetry. For malformed-data errors, attach the last generated DASH/HLS manifest and
' player response so the failure can be diagnosed from the report.
function ReportVideoError(errorData as object, url as dynamic, urls as object, urlIndex as dynamic, shownInDialog as boolean) as void
if errorData = invalid
return
end if
attachments = invalid
if errorData.body.Instr("malformed data") <> -1 or errorData.body.Instr("invalid pathname") <> -1
attachments = [{
filename: "last_generated_dash.xml"
content_type: "plain/text"
data: ValidString(ReadAsciiFile("cachefs:/last_generated_dash.xml"))
}, {
filename: "last_generated_hls.m3u8"
content_type: "plain/text"
data: ValidString(ReadAsciiFile("cachefs:/last_generated_hls.m3u8"))
}, {
filename: "last_player_response.json"
content_type: "application/json"
data: ValidString(ReadAsciiFile("cachefs:/last_player_response.json"))
}]
end if
potAttached = false
potSource = "none"
loggedIn = false
content = m.top.content
if content <> invalid
potAttached = ValidBool(content.potAttached)
loggedIn = ValidBool(content.loggedIn)
if not StringUtils.IsNullOrEmpty(content.potSource)
potSource = content.potSource
end if
end if
backend = ContentBackend(content)
isLive = m.transport.isLive
message = [
errorData.title
errorData.body
`Dialog shown: ${shownInDialog}`
`Position: ${m.top.position}`
`Duration: ${m.top.duration}`
`Url: ${url}`
"Urls: " + FormatJson(urls)
`Url index: ${urlIndex}`
`pot_attached: ${potAttached}`
`pot_source: ${potSource}`
`logged_in: ${loggedIn}`
`backend: ${backend}`
`is_live: ${isLive}`
].Join(Chr(10))
errorData.fingerprint.Push(shownInDialog)
errorData.fingerprint.Push(potAttached)
errorData.fingerprint.Push(potSource)
errorData.fingerprint.Push(loggedIn)
errorData.fingerprint.Push(backend)
errorData.fingerprint.Push(isLive)
if shownInDialog
level = "error"
else
level = "warning"
end if
LogTelemetryEvent({
level: level
message: message
fingerprint: errorData.fingerprint
attachments: attachments
})
return { title: title, body: body }
end function
function ShowErrorDialog(decision as object) as void
' first: a blocked dialog closes this player, and sends its summary, synchronously (below).
m.playbackTelemetry.OnErrorDialog()
buttons = [Tr(Locale.Buttons.PlayNextVideo), Tr(Locale.Buttons.Cancel)]
dialog = DialogUtils.ShowTimedDialogButtons(decision.message, decision.title, buttons, 0, 10, true)
if dialog <> invalid
@@ -1571,7 +1464,7 @@ function OnClose() as void
end if
m.onCloseCalled = true
m.top.previousPlayer = invalid
SendHealSummary()
m.playbackTelemetry.SendSummary()
' A closed player must not react to anything anymore. The onCloseCalled guards already make the handlers
' no-ops; unobserving stops the traffic at the source — late device edges from the async stop, a stray
@@ -1584,6 +1477,8 @@ function OnClose() as void
m.top.unobserveField("duration")
m.top.unobserveField("thumbnailTiles")
m.top.unobserveField("control")
m.top.unobserveField("bufferingStatus")
m.top.unobserveField("playStartInfo")
m.top.unobserveField("close")
content = m.top.content
if content <> invalid
@@ -1634,7 +1529,7 @@ function OnClose() as void
try
m.top.control = VideoControl.Stop
catch error
LogError("error stopping video:", ErrorUtils.Format(error))
m.playbackTelemetry.ReportStopFailure(error)
end try
m.top.content = invalid
@@ -0,0 +1,196 @@
import "pkg:/components/VideoPlayerDev/VideoNode.bs"
import "pkg:/source/utils/RemoteKeys.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
namespace Tests
@SGNode("VideoPlayerDevMock")
@suite
class PlaybackTelemetryWiringTests extends Rooibos.BaseTestSuite
protected override function beforeEach()
m.top.callFunc("TestSetup")
end function
function State(state as string) as void
m.top.callFunc("TestSetState", state)
end function
function SetContent(urls as object) as void
content = CreateObject("roSGNode", "ContentNode")
content.addField("videoId", "string", false)
content.addField("backend", "string", false)
content.addField("playletStreamUrls", "array", false)
content.addField("playletStreamUrlIndex", "integer", false)
content.addField("playletStreamSource", "string", false)
content.setFields({
videoId: "vid1"
backend: "playlet"
url: urls[0]
playletStreamUrls: urls
playletStreamUrlIndex: 0
playletStreamSource: "adaptiveFormats"
})
m.top.content = content
end function
function BufferingStatus(isUnderrun as boolean) as void
m.top.bufferingStatus = { actualStart: 0, isUnderrun: isUnderrun, percentage: 0, prebufferDone: false }
end function
function SentSummary() as object
event = m.global.telemetry.LogEvent
m.assertEqual(event.fingerprint, ["playback summary"])
return StringUtils.ParseJsonSafe(event.message)
end function
function Close() as object
m.top.close = true
' an error dialog still up was closed by OnClose; drop it from the scene for the next test.
m.top.getScene().dialog = invalid
return m.SentSummary()
end function
function HttpError() as void
m.top.errorMsg = "There was an error in the HTTP response."
m.top.errorCode = -1
m.top.errorStr = "reader pick stream error:HTTP error"
m.top.errorInfo = { category: "http", source: "buffer:reader", ignored: false }
end function
@describe("playback telemetry wiring")
@it("state edges and bufferingStatus reach the summary: an underrun counts")
function _()
m.SetContent(["http://stream"])
m.State(VideoState.Playing)
m.State(VideoState.Buffering)
m.BufferingStatus(true)
m.State(VideoState.Playing)
summary = m.Close()
m.assertEqual(summary.underrun_count, 1)
m.assertTrue(ValidInt(summary.first_playing_at_ms) >= 0, "the first playing was recorded")
m.assertEqual(summary.backend, "playlet")
m.assertEqual(summary.stream_source, "adaptiveFormats")
m.assertFalse(summary.DoesExist("drm"), "an unset drmParams on a ContentNode reads as no DRM")
m.assertFalse(summary.DoesExist("stream_url_index"))
m.assertEqual(summary.outcome, "closed")
end function
@it("a buffering whose bufferingStatus is no underrun is not counted")
function _()
m.SetContent(["http://stream"])
m.State(VideoState.Playing)
m.State(VideoState.Buffering)
m.BufferingStatus(false)
m.State(VideoState.Playing)
m.assertFalse(m.Close().DoesExist("underrun_count"))
end function
@it("every playStartInfo reaches the summary")
function _()
m.SetContent(["http://stream"])
m.State(VideoState.Playing)
m.top.playStartInfo = { start_type: "init", total_dur: 0.5 }
m.top.playStartInfo = { start_type: "cseek", total_dur: 0.25 }
summary = m.Close()
m.assertEqual(summary.play_start_count, 2)
m.assertEqual(summary.play_start_infos[0].start_type, "init")
m.assertEqual(summary.play_start_infos[1].start_type, "cseek")
end function
@it("a retry: the report names the url that failed; the summary, the one that played")
function _()
m.SetContent(["http://a", "http://b"])
m.HttpError()
m.State(VideoState.Error)
report = m.global.telemetry.LogEvent
m.assertEqual(report.level, "warning", "retried: not shown to the viewer")
m.assertTrue(report.message.InStr("Url: http://a") > 0 and report.message.InStr("Url index: 0") > 0, "got: " + report.message)
m.State(VideoState.Playing)
summary = m.Close()
m.assertEqual(summary.error_count, 1)
m.assertEqual(summary.stream_url_index, 1)
m.assertEqual(summary.outcome, "closed")
end function
@it("an error with no retry left ends in error")
function _()
m.SetContent(["http://stream"])
m.State(VideoState.Playing)
m.HttpError()
m.State(VideoState.Error)
summary = m.Close()
m.assertEqual(summary.outcome, "error")
m.assertEqual(summary.error_count, 1)
end function
@it("content that never loaded ends in error, with no player error")
function _()
m.SetContent(["http://stream"])
m.top.callFunc("TestContentJobFailed", "content job failed")
summary = m.Close()
m.assertEqual(summary.outcome, "error")
m.assertFalse(summary.DoesExist("error_count"))
m.assertTrue(ValidInt(summary.metadata_done_at_ms) >= 0, "the content job's result is recorded")
end function
@it("after the close, a late playStartInfo or bufferingStatus reaches nothing")
function _()
m.SetContent(["http://stream"])
m.State(VideoState.Playing)
m.top.playStartInfo = { start_type: "init", total_dur: 0.5 }
m.State(VideoState.Buffering)
m.assertEqual(m.Close().play_start_count, 1)
m.top.playStartInfo = { start_type: "cseek", total_dur: 0.25 }
m.top.bufferingStatus = { isUnderrun: true, percentage: 0, prebufferDone: false, actualStart: 0 }
m.top.callFunc("TestResendSummary")
resent = m.SentSummary()
m.assertEqual(resent.play_start_count, 1)
m.assertFalse(resent.DoesExist("underrun_count"))
end function
@it("finishing ends in finished, sent from within the finish")
function _()
m.SetContent(["http://stream"])
m.top.callFunc("TestWireQueueClose") ' the stub queue closes the player on closePlayer, as the real one does
m.State(VideoState.Playing)
m.State(VideoState.Finished)
m.assertEqual(m.SentSummary().outcome, "finished")
end function
@it("a heal loop: every heal counted, the first 3 sampled, none sent on its own")
function _()
m.State(VideoState.Playing) ' the first playing opens the transport's ready gate
m.top.callFunc("TestKey", RemoteKeys.Left, true)
m.top.callFunc("TestKey", RemoteKeys.Left, false)
m.global.telemetry.LogEvent = {}
for i = 1 to 5
m.State(VideoState.Playing) ' playing under a scrub: healed
end for
m.assertInvalid(m.global.telemetry.LogEvent.message, "a heal sends nothing until the summary")
summary = m.Close()
m.assertEqual(summary.heal_count, 5)
m.assertEqual(summary.heal_samples.Count(), 3)
m.assertEqual(summary.heal_samples[0].source, "OnVideoState")
m.assertFalse(summary.DoesExist("tail_resolve_count"))
end function
@it("a live tail the sliding floor overtook is a tail resolve, not a heal")
function _()
m.State(VideoState.Playing) ' the first playing opens the transport's ready gate
m.top.callFunc("TestSetLive", 43200000)
m.top.position = 28805.0
m.top.callFunc("TestKey", RemoteKeys.Left, true)
m.top.callFunc("TestKey", RemoteKeys.Left, false)
m.State(VideoState.Playing) ' the device force-resumes the pause the tail overtook
summary = m.Close()
m.assertEqual(summary.tail_resolve_count, 1)
m.assertEqual(summary.tail_resolve_samples[0].source, "OnVideoState")
m.assertFalse(summary.DoesExist("heal_count"))
end function
end class
end namespace
@@ -26,7 +26,7 @@ function TestSetup() as void
m.global.logger = CreateObject("roSGNode", "Logger")
end if
' ReportVideoError -> LogTelemetryEvent writes m.global.telemetry.LogEvent; stub it so the error path runs.
' LogTelemetryEvent (error reports, the playback summary on close) writes m.global.telemetry.LogEvent; stub it.
if m.global.telemetry = invalid
m.global.addField("telemetry", "node", false)
telemetry = CreateObject("roSGNode", "Node")
@@ -80,10 +80,18 @@ function TestSetup() as void
' nudge counter above — stacked observers fire a handler once per prior TestSetup on every write,
' and OnPosition's latency learning reads two identical fires as a CONFIRMED min-gap, poisoning
' LiveEdgeMs for any live test that runs after another test in the suite.
for each deviceField in ["state", "position", "duration", "close", "thumbnailTiles", "control"]
for each deviceField in ["state", "position", "duration", "close", "thumbnailTiles", "control", "bufferingStatus", "playStartInfo"]
m.top.unobserveField(deviceField)
end for
' The mock node is shared across tests and `duration` is not alwaysNotify, so a leftover duration=100
' swallows the next test's identical write and OnDuration never fires. Reset with the observers off.
m.top.state = VideoState.None
m.top.control = VideoControl.None
m.top.position = 0
m.top.duration = 0
m.top.seek = 0
OnNodeReady()
end function
@@ -118,6 +126,13 @@ function TestSetLive(edgeMs as integer) as void
m.transport.OnPosition(edgeMs)
end function
' TestSeedSponsorBlock — the segments job's result, minus the job. Writing m.top.position afterwards runs the
' REAL OnPosition, which is what arms the manual notice.
function TestSeedSponsorBlock(segments as object) as void
m.sponsorblock.enabled = true
m.sponsorblock.segments = segments
end function
' TestFireLiveBadgeHold — fire the liveBadgeHold timer's handler now (the spec can't wait out the real timer).
function TestFireLiveBadgeHold() as void
OnLiveBadgeHoldFire()
@@ -181,6 +196,19 @@ function TestPlaybackErrorDialog(errorFields as object) as object
return result
end function
' TestContentJobFailed — the VideoContentJob's failure result, minus the job: runs the REAL OnVideoContentJobDone.
function TestContentJobFailed(errorMessage as string) as void
OnVideoContentJobDone({
info: { success: false, cancel: false, error: errorMessage }
getRoSGNode: function() as dynamic
return invalid
end function
getInfo: function() as object
return m.info
end function
})
end function
' TestCoordinatorFields — every non-function key on the coordinator's m, for the unmodeled-axis meta-test
' (the coordinator twin of the brain's reflection test). Call AFTER TestSetup so Initialize/OnNodeReady have
' populated m. The ONLY filtering here is the two DYNAMICALLY-named runtime families ("__delay_<uuid>" and
@@ -214,6 +242,7 @@ function TestSnapshot() as object
focusTarget: m.focusTarget
focusedButton: m.focusedButton
nudgeCount: m.top.nudgeCount
sponsorNoticeShown: SponsorBlock.GetCurrentNotification(m.notifications) <> invalid
forceLiveBadge: m.trickPlayBar.forceLiveBadge
liveBadgeShown: m.trickPlayBar.findNode("liveLabel").visible
barRemainingText: m.trickPlayBar.findNode("remainingLabel").text
@@ -227,6 +256,12 @@ function TestWireQueueClose() as void
m.videoQueue.observeFieldScoped("closePlayer", FuncName(OnTestQueueClose))
end function
' TestResendSummary — send the playback summary again after the close, so a spec can see whether anything reached
' the Recorder since.
function TestResendSummary() as void
m.playbackTelemetry.SendSummary()
end function
function OnTestQueueClose() as void
if m.videoQueue.closePlayer
m.top.close = true
@@ -26,6 +26,8 @@
<field id="errorMsg" type="string" />
<field id="errorStr" type="string" />
<field id="errorInfo" type="assocarray" />
<field id="bufferingStatus" type="assocarray" alwaysNotify="true" />
<field id="playStartInfo" type="assocarray" alwaysNotify="true" />
<!-- AutoBind deps + layout (set by TestSetup; NOT bound). -->
<field id="appController" type="node" />
<field id="jobQueue" type="node" />
@@ -50,13 +52,16 @@
<function name="TestSetState" />
<function name="TestSnapshot" />
<function name="TestWireQueueClose" />
<function name="TestResendSummary" />
<function name="TestSetControl" />
<function name="TestSetLive" />
<function name="TestSeedSponsorBlock" />
<function name="TestFireLiveBadgeHold" />
<function name="TestKillAutoHide" />
<function name="TestFinishChromeFadeOut" />
<function name="TestPlaybackErrorDialog" />
<function name="TestCoordinatorFields" />
<function name="TestContentJobFailed" />
</interface>
<children>
<Timer id="autoHide" duration="5" repeat="false" />
@@ -108,23 +108,6 @@ namespace Tests
m.assertEqual(snap.transportMode, TransportController.Mode.Idle, "the transport resolved instead of fighting")
m.assertEqual(snap.control, VideoControl.Resume, "resumed forward, not re-paused")
m.assertEqual(Int(m.top.seek * 1000), 28860000, "the resume parks a full margin above the trigger (28800s + 60s)")
' the resolution telemeters at info level (never as a heal) with its per-content ordinal.
sent = m.global.telemetry.LogEvent
m.assertEqual(sent.level, "info")
m.assertTrue(sent.message.InStr("INV-D1 tail-resolve") = 0, "got: " + sent.message)
m.assertTrue(sent.message.InStr("resolve=1") > 0)
end function
@it("heal telemetry stops at the cap while the occurrences keep counting")
function _()
' a frozen VOD scrub the device keeps flipping to playing: 5 heals, but only 3 events may leave.
m.top.callFunc("TestKey", RemoteKeys.Left, true)
m.top.callFunc("TestKey", RemoteKeys.Left, false)
for i = 1 to 5
m.top.callFunc("TestSetState", VideoState.Playing)
end for
sent = m.global.telemetry.LogEvent
m.assertTrue(sent.message.InStr("heal=3") > 0, "telemetry must stop at the 3rd heal; last sent: " + sent.message)
end function
@it("a sentinel-valued duration report cannot anchor the live-edge fallback clock")
@@ -216,11 +199,18 @@ namespace Tests
end function
' Up/Down reveal the chrome when it is hidden in idle (they otherwise do nothing).
@it("Up reveals the chrome when it is hidden in idle")
@it("Up and Down each reveal the chrome when it is hidden in idle")
function _()
m.assertFalse(m.Snap().chromeShown) ' starts hidden after setup
m.top.callFunc("TestKey", RemoteKeys.Up, true)
m.assertTrue(m.Snap().chromeShown, "Up revealed the chrome")
' back to fully hidden: the reveal only fires from Hidden, not mid fade-out.
m.top.callFunc("TestKey", RemoteKeys.Back, true)
m.top.callFunc("TestFinishChromeFadeOut")
m.assertFalse(m.Snap().chromeShown)
m.top.callFunc("TestKey", RemoteKeys.Down, true)
m.assertTrue(m.Snap().chromeShown, "Down revealed the chrome")
end function
' =========================================================================================
@@ -349,6 +339,121 @@ namespace Tests
m.assertTrue(m.top.videoQueue.closePlayer, "rung 4: Back closes")
end function
' =========================================================================================
' Key router — the branches that decide WHICH handler runs.
' =========================================================================================
' The segment shape SponsorBlockSegmentsJob returns.
function ManualSegment(startS as float, endS as float) as object
return [{ start: startS, end: endS, option: "manual_skip", title: "Sponsor", shortTitle: "Sponsor", actionText: "Press OK to skip", showNotification: true, UUID: "seg-manual", category: "sponsor" }]
end function
' Minimize is the discriminator: activating it would have hidden the chrome.
@it("an armed SponsorBlock notice outranks the buttons tier: OK skips instead of activating the button")
function _()
m.top.duration = 100
m.top.callFunc("TestSeedSponsorBlock", m.ManualSegment(10.0, 40.0))
m.top.position = 12.0 ' the REAL OnPosition arms the manual notice
m.assertTrue(m.Snap().sponsorNoticeShown, "the notice is up")
m.top.callFunc("TestKey", RemoteKeys.Up, true) ' reveal -> bar tier
m.top.callFunc("TestKey", RemoteKeys.Up, true) ' bar -> buttons tier
m.top.callFunc("TestKey", RemoteKeys.Right, true) ' highlight minimize
m.assertEqual(m.Snap().focusedButton, 1)
m.top.callFunc("TestKey", RemoteKeys.Ok, true)
after = m.Snap()
m.assertEqual(Int(m.top.seek * 1000), 40000, "OK skipped to the segment end, not into the focused button")
m.assertFalse(after.sponsorNoticeShown, "the skip took the notice down")
m.assertTrue(after.chromeShown, "minimize never ran -- it would have hidden the chrome")
end function
@it("an armed SponsorBlock notice outranks the Back ladder: Back dismisses the notice, not the player")
function _()
m.top.duration = 100
m.top.callFunc("TestSeedSponsorBlock", m.ManualSegment(10.0, 40.0))
m.top.position = 12.0
m.assertTrue(m.Snap().sponsorNoticeShown)
m.assertFalse(m.Snap().chromeShown, "chrome hidden: an unrouted Back here would CLOSE the player")
seekBefore = m.top.seek
m.top.callFunc("TestKey", RemoteKeys.Back, true)
after = m.Snap()
m.assertFalse(after.sponsorNoticeShown, "Back took the notice down")
m.assertFalse(m.top.videoQueue.closePlayer, "Back acted on the notice, NOT on the player")
m.assertEqual(m.top.seek, seekBefore, "dismissing is not skipping")
' one-shot: with the notice gone the next Back is the ordinary ladder again (rung 4 -> close).
m.top.callFunc("TestKey", RemoteKeys.Back, true)
m.assertTrue(m.top.videoQueue.closePlayer, "the notice consumed one Back, not every Back")
end function
@it("an armed notice on a segment at the video end finishes playback instead of seeking")
function _()
m.top.duration = 100
m.top.callFunc("TestSeedSponsorBlock", m.ManualSegment(90.0, 99.5)) ' ends within 2s of duration
m.top.position = 92.0
m.assertTrue(m.Snap().sponsorNoticeShown)
seekBefore = m.top.seek
m.top.callFunc("TestKey", RemoteKeys.Ok, true)
m.assertEqual(m.top.seek, seekBefore, "no seek was issued: the skip resolved to finish")
m.assertTrue(m.top.videoQueue.closePlayer, "no next video -> the finish closed the player")
end function
@it("the non-transport keys act on the key-DOWN edge only")
function _()
' Back goes first: only from the start state does its DOWN edge close the player.
m.assertFalse(m.top.callFunc("TestKey", RemoteKeys.Back, false), "the Back key-up is not consumed")
m.assertFalse(m.top.videoQueue.closePlayer, "the Back key-up must not close the player")
m.top.callFunc("TestKey", RemoteKeys.Ok, true) ' reveal
m.top.callFunc("TestKey", RemoteKeys.Ok, true) ' pause
m.top.callFunc("TestSetState", VideoState.Paused)
m.assertEqual(m.Snap().control, VideoControl.Pause)
m.assertFalse(m.top.callFunc("TestKey", RemoteKeys.Ok, false), "the OK key-up is not consumed")
m.assertFalse(m.top.callFunc("TestKey", RemoteKeys.Play, false), "the Play key-up is not consumed")
m.assertFalse(m.top.callFunc("TestKey", RemoteKeys.PlayOnly, false), "the PlayOnly key-up is not consumed")
m.assertFalse(m.top.callFunc("TestKey", RemoteKeys.Pause, false), "the Pause key-up is not consumed")
m.assertEqual(m.Snap().control, VideoControl.Pause, "no key-up toggled the pause back to playing")
end function
@it("Play commits an active transport, like OK")
function _()
m.top.callFunc("TestKey", RemoteKeys.Left, true)
m.top.callFunc("TestKey", RemoteKeys.Left, false)
m.assertEqual(m.Snap().transportMode, TransportController.Mode.Scrub)
m.top.callFunc("TestKey", RemoteKeys.Play, true)
after = m.Snap()
m.assertEqual(after.transportMode, TransportController.Mode.Idle, "Play committed the scrub")
m.assertTrue(after.seekSettling, "the commit emitted a play-through seek, not a play/pause toggle")
end function
@it("PlayOnly toggles play/pause, like Play")
function _()
m.top.callFunc("TestKey", RemoteKeys.PlayOnly, true)
m.assertEqual(m.Snap().control, VideoControl.Pause, "PlayOnly paused the playing video")
m.top.callFunc("TestSetState", VideoState.Paused)
m.top.callFunc("TestKey", RemoteKeys.PlayOnly, true)
m.assertEqual(m.Snap().control, VideoControl.Resume, "PlayOnly resumed the paused video")
end function
@it("the transport keys fall through the buttons tier to the transport")
function _()
m.top.callFunc("TestKey", RemoteKeys.Up, true) ' reveal -> bar tier
m.top.callFunc("TestKey", RemoteKeys.Up, true) ' bar -> buttons tier
m.assertEqual(m.Snap().focusTarget, PlayerCoordinatorLogic.FocusTarget.Buttons)
m.top.callFunc("TestKey", RemoteKeys.Rewind, true)
m.top.callFunc("TestKey", RemoteKeys.Rewind, false)
after = m.Snap()
m.assertEqual(after.transportMode, TransportController.Mode.Scan, "Rev started the scan from the buttons tier")
m.assertEqual(after.focusTarget, PlayerCoordinatorLogic.FocusTarget.Bar, "a transport key moves focus to the bar")
m.assertEqual(after.nudgeCount, 0, "the row did not treat it as one of its own keys")
end function
' The point of the bar-default: Left/Right seek and OK pauses with no navigation at all, straight off a
' fresh reveal. Pinned as its own test rather than left as a side effect of the tier round-trip tests.
@it("a fresh idle reveal defaults focus to the bar: Left/Right seek and OK pauses with no navigation")
@@ -555,6 +660,61 @@ namespace Tests
m.assertEqual(snap.focusedButton, 1, "the highlight is untouched")
end function
' Each arm is asserted: a state that silently failed to arm makes every row that follows vacuous.
function ArmRouterState(state as string) as void
m.top.callFunc("TestSetup")
m.top.callFunc("TestSetState", VideoState.Playing) ' opens the brain's ready-gate, as beforeEach does
if state = "idle hidden"
m.assertFalse(m.Snap().chromeShown, "armed: " + state)
else if state = "chrome/bar"
m.top.callFunc("TestKey", RemoteKeys.Up, true)
snap = m.Snap()
m.assertTrue(snap.chromeShown, "armed: " + state)
m.assertEqual(snap.focusTarget, PlayerCoordinatorLogic.FocusTarget.Bar, "armed: " + state)
else if state = "chrome/buttons"
m.top.callFunc("TestKey", RemoteKeys.Up, true)
m.top.callFunc("TestKey", RemoteKeys.Up, true)
snap = m.Snap()
m.assertTrue(snap.chromeShown, "armed: " + state)
m.assertEqual(snap.focusTarget, PlayerCoordinatorLogic.FocusTarget.Buttons, "armed: " + state)
else if state = "transport"
m.top.callFunc("TestKey", RemoteKeys.Left, true)
m.top.callFunc("TestKey", RemoteKeys.Left, false)
m.assertEqual(m.Snap().transportMode, TransportController.Mode.Scrub, "armed: " + state)
end if
end function
' BrighterScript enums are compile-time constants with no runtime form, so a new RemoteKeys member
' cannot fail this until someone lists it below — these lists are the decision record, not reflection.
@it("every remote key's disposition is pinned in every router state")
function _()
ownedEverywhere = [RemoteKeys.Left, RemoteKeys.Right, RemoteKeys.Rewind, RemoteKeys.FastForward, RemoteKeys.Replay, RemoteKeys.Ok, RemoteKeys.Back, RemoteKeys.Play, RemoteKeys.PlayOnly]
' AppController's, not the player's.
passedEverywhere = [RemoteKeys.Options, RemoteKeys.Pause, RemoteKeys.OkLongPress, RemoteKeys.OptionsLongPress]
' the tier keys are owned only while there is a tier to move through or a chrome to reveal.
tierKeys = [RemoteKeys.Up, RemoteKeys.Down]
for each state in ["idle hidden", "chrome/bar", "chrome/buttons", "transport"]
for each key in ownedEverywhere
m.ArmRouterState(state)
m.assertTrue(m.top.callFunc("TestKey", key, true), "'" + key + "' must be consumed in state " + state)
end for
for each key in passedEverywhere
m.ArmRouterState(state)
m.assertFalse(m.top.callFunc("TestKey", key, true), "'" + key + "' must pass to the parent in state " + state)
end for
for each key in tierKeys
m.ArmRouterState(state)
consumed = m.top.callFunc("TestKey", key, true)
if state = "transport"
m.assertFalse(consumed, "'" + key + "' has nothing to do under a transport -- it passes to the parent")
else
m.assertTrue(consumed, "'" + key + "' moves focus or reveals the chrome in state " + state)
end if
end for
end for
end function
' The coordinator twin of the brain's unmodeled-axis meta-test: every m.* field on the coordinator must
' be consciously classified here. A NEW coordinator field fails this until someone decides what it is —
' a state axis needs transition coverage, a flag needs its consuming path tested.
@@ -566,7 +726,7 @@ namespace Tests
classified[name] = "dep"
end for
' controllers (plain .bs class instances).
for each name in ["transport", "sponsorblock"]
for each name in ["transport", "sponsorblock", "playbackTelemetry"]
classified[name] = "controller"
end for
' cached child nodes / timers / animations / reusable helpers (structure, not state).
@@ -582,7 +742,7 @@ namespace Tests
classified[name] = "axis"
end for
' flags / scratch — one-shot latches and counters with a single consuming path.
for each name in ["onCloseCalled", "ignoreNextFinished", "videoPlayedSuccessfully", "firstFrameSeen", "showFullScreenHint", "repauseAfterSeek", "seekToPercent", "watchTimeMarker", "reportWatchTime", "errorDialogNode", "lastCommitSeq", "lastFinishSeq", "liveAstSeconds", "liveFallbackEdgeMs", "liveFallbackAtSeconds", "liveBadgeHoldActive", "healCount", "tailResolveCount"]
for each name in ["onCloseCalled", "ignoreNextFinished", "videoPlayedSuccessfully", "firstFrameSeen", "showFullScreenHint", "repauseAfterSeek", "seekToPercent", "watchTimeMarker", "reportWatchTime", "errorDialogNode", "lastCommitSeq", "lastFinishSeq", "liveAstSeconds", "liveFallbackEdgeMs", "liveFallbackAtSeconds", "liveBadgeHoldActive"]
classified[name] = "flag"
end for
' NOT coordinator state — node-scope + test-environment entries, pinned EXPLICITLY (no hidden
@@ -642,7 +802,7 @@ namespace Tests
container.fullscreen = true
' close the player (what the queue does when replacing the video), then throw every signal a dead
' player might still receive at it: fullscreen flips (the * key), device edges from the async stop,
' a stray control/seek write, late thumbnails, a second close. OnClose unobserves them all.
' a stray control/seek write, late thumbnails and buffering/start info, a second close. OnClose unobserves them all.
m.top.close = true
container.fullscreen = false
container.fullscreen = true
@@ -654,6 +814,8 @@ namespace Tests
m.top.duration = 99.0
m.top.seek = 5.0
m.top.thumbnailTiles = { x: [{ htiles: 1 }] }
m.top.bufferingStatus = { isUnderrun: true, percentage: 0, prebufferDone: false, actualStart: 0 }
m.top.playStartInfo = { start_type: "cseek", total_dur: 0.1 }
m.top.close = true
m.assertTrue(true, "no crash: the closed player ignored all post-close traffic")
end function
@@ -688,21 +850,6 @@ namespace Tests
m.assertTrue(m.Snap().onCloseCalled, "the finish closed the player from within the position tick")
end function
' Also at the end (closes the player): a heal loop that ran past the telemetry cap reports its
' true size in one tally event when the content ends.
@it("the close summary carries a capped heal loop's true size")
function _()
m.top.callFunc("TestKey", RemoteKeys.Left, true)
m.top.callFunc("TestKey", RemoteKeys.Left, false)
for i = 1 to 5
m.top.callFunc("TestSetState", VideoState.Playing)
end for
m.top.close = true
summary = m.global.telemetry.LogEvent
m.assertTrue(summary.message.InStr("5 heals") > 0, "got: " + summary.message)
m.assertTrue(summary.message.InStr("2 past the telemetry cap") > 0, "got: " + summary.message)
end function
end class
end namespace
-1
View File
@@ -1,4 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<!--! Font Awesome Pro 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc.-->
<path fill="#EBEBEB" d="M416 208c0 45.9-14.9 88.3-40 122.7l126.6 126.7c12.5 12.5 12.5 32.8 0 45.3s-32.8 12.5-45.3 0L330.7 376c-34.4 25.2-76.8 40-122.7 40C93.1 416 0 322.9 0 208S93.1 0 208 0s208 93.1 208 208M208 352c79.5 0 144-64.5 144-144S287.5 64 208 64 64 128.5 64 208s64.5 144 144 144"/>
</svg>

Before

Width:  |  Height:  |  Size: 533 B

After

Width:  |  Height:  |  Size: 365 B

@@ -1,5 +1,5 @@
{
inputHash: 'c4e2899f8a5e58f6ae711e91e518b4f3',
inputHash: '020c780cc50d3bc4ed9fc56f03bd1b21',
outputs: [
{
outputFilePath: 'images/icons/search.png',
+169 -1
View File
@@ -1182,7 +1182,7 @@
</message>
<message>
<source>Invidious instance to use. Example: https://example.com. Find more instances at %INVIDIOUS_PUBLIC_INSTANCES%</source>
<translation>Utilizar instancia de Invidious, Ejemplo: https://example.com. Encuentra más instancias en %INVIDIOUS_PUBLIC_INSTANCES%</translation>
<translation>Utilizar instancia de Invidious, Ejemplo: https://example.com. Encuentra más instancias en %INVIDIOUS_PUBLIC_INSTANCES%</translation>
</message>
<message>
<source>Tap &apos;Link with TV code&apos; and enter the code below.</source>
@@ -1252,5 +1252,173 @@
<source>Rewind live TV</source>
<translation>Retroceder TV en directo</translation>
</message>
<message>
<source>Do not show again</source>
<translation>No volver a mostrar de nuevo</translation>
</message>
<message>
<source>Recommended</source>
<translation>Recomendados</translation>
</message>
<message>
<source>Courses</source>
<translation>Cursos</translation>
</message>
<message>
<source>Session expired</source>
<translation>Sesion expirada</translation>
</message>
<message>
<source>The session has expired. Please sign in again with this profile, or switch to another profile.</source>
<translation>Esta sesión ha expirado. Por favor inicia sesion de nuevo con este perfil, o cambia a otro perfil.</translation>
</message>
<message>
<source>The session has expired.</source>
<translation>La sesión ha expirado.</translation>
</message>
<message>
<source>Please sign in again with this profile, or switch to another profile.</source>
<translation>Porfavor inicia sesion otra vez con este perfil, o cambia a otro perfil.</translation>
</message>
<message>
<source>Select a service to login</source>
<translation>Seleccione un servicio para iniciar sesion</translation>
</message>
<message>
<source>Login to YouTube</source>
<translation>Iniciar sesion en YouTube</translation>
</message>
<message>
<source>Open the link %1 and enter the following code:</source>
<translation>Abre el link %1 y escribe el siguiente código:</translation>
</message>
<message>
<source>Disclaimer</source>
<translation>Descargo de responsabilidad</translation>
</message>
<message>
<source>Playlet is a third-party app and is not affiliated with, endorsed by, or sponsored by YouTube or Google. All trademarks and registered trademarks mentioned are the property of their respective owners and are used only for identification purposes.</source>
<translation>Playlet es una aplicación de terceros y no está afiliada, respaldada ni patrocinada por YouTube ni Google. Todas las marcas comerciales y marcas registradas mencionadas son propiedad de sus respectivos dueños y se utilizan únicamente con fines de identificación.</translation>
</message>
<message>
<source>By using Playlet and signing in with your YouTube account, you acknowledge that you do so at your own risk. The developers of Playlet are not liable for any harm, including but not limited to data loss, account suspension or ban, hacking, or loss of content.</source>
<translation>Al usar Playlet e iniciar sesión con tu cuenta de YouTube, aceptas hacerlo bajo tu propia responsabilidad. Los desarrolladores de Playlet no se hacen responsables de ningún daño, incluyendo, entre otros, la pérdida de datos, la suspensión o el bloqueo de la cuenta, el pirateo informático o la pérdida de contenido.</translation>
</message>
<message>
<source>Use responsibly, especially if your YouTube account is tied to business or monetization.</source>
<translation>Usalo con responsabilidad, especialmente si tu cuenta de YouTube esta ligada a negocios o monetizacion.</translation>
</message>
<message>
<source>Who&apos;s watching?</source>
<translation>¿Quien esta viendo?</translation>
</message>
<message>
<source>No valid accounts found for YouTube login.</source>
<translation>No se encontraron cuentas válidas para iniciar sesión en YouTube.</translation>
</message>
<message>
<source>Error</source>
<translation>Error</translation>
</message>
<message>
<source>Backend</source>
<translation>Servidor</translation>
</message>
<message>
<source>Backend preferences</source>
<translation>Preferencias de el servidor</translation>
</message>
<message>
<source>Selected backend</source>
<translation>Servidor seleccionado</translation>
</message>
<message>
<source>The backend used for browsing and playing videos.</source>
<translation>El servidor es usado para navegar y reproducir videos.</translation>
</message>
<message>
<source>Content Feed</source>
<translation>Feed</translation>
</message>
<message>
<source>Feed preferences</source>
<translation>Preferencias de el feed</translation>
</message>
<message>
<source>Disable auto-dubbed audio</source>
<translation>Desactivar el doblaje automatico</translation>
</message>
<message>
<source>Remove AI-generated dubbed audio tracks.</source>
<translation>Elimina el doblaje generado por AI.</translation>
</message>
<message>
<source>Disable Shorts</source>
<translation>Desactivar Shorts</translation>
</message>
<message>
<source>Disable short videos.</source>
<translation>Desactivar videos shorts.</translation>
</message>
<message>
<source>Playlet built-in backend</source>
<translation>Servidor integrado de Playlet</translation>
</message>
<message>
<source>Categories</source>
<translation>Categorias</translation>
</message>
<message>
<source>Configure which segments to skip</source>
<translation>Configurar que segmentos para saltar</translation>
</message>
<message>
<source>Select option for %1</source>
<translation>Seleccione la opción para %1</translation>
</message>
<message>
<source>Press OK to skip</source>
<translation>Presiona OK para saltar</translation>
</message>
<message>
<source>Disable</source>
<translation>Desactivar</translation>
</message>
<message>
<source>Auto Skip</source>
<translation>Auto omitir</translation>
</message>
<message>
<source>Manual Skip</source>
<translation>Omisión manual</translation>
</message>
<message>
<source>Show in Seekbar</source>
<translation>Mostrar en la Seekbar</translation>
</message>
<message>
<source>Open in YouTube</source>
<translation>Abrir en YouTube</translation>
</message>
<message>
<source>Clear PoTokens</source>
<translation>Limpiar PoTokens</translation>
</message>
<message>
<source>Clear all stored PoTokens.</source>
<translation>Borra todos los PoTokens almacenados.</translation>
</message>
<message>
<source>PoTokens cleared.</source>
<translation>PoTokens eliminados.</translation>
</message>
<message>
<source>Enable Diagnostics</source>
<translation>Habilitar diagnósticos</translation>
</message>
<message>
<source>Help improve Playlet by enabling diagnostics. This will send anonymous diagnotics data to the developer.</source>
<translation>Ayuda a mejorar Playlet activando las herramientas de diagnóstico. Esto enviará datos de diagnóstico anónimos al desarrollador.</translation>
</message>
</context>
</TS>
+1 -1
View File
@@ -3,7 +3,7 @@ title=PlayletLib
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=48
build_version=00003
build_version=00007
ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p
+25 -2
View File
@@ -1,4 +1,27 @@
' Credits to https://github.com/kazuhikoarase/qrcode-generator/pull/110
' QR code generation ported from https://github.com/kazuhikoarase/qrcode-generator
' (PR #110).
'
' Original work: Copyright (c) 2009 Kazuhiko Arase - MIT License (full text below).
' Modifications: Copyright (c) Playlet contributors - AGPL-3.0, as part of this project.
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
'
' Main changes:
' - Removed Kanji, because it added a significant amount of size, while the use
' cases of this app does not include Kanji
@@ -7,4 +30,4 @@
' the generation more thread friendly (we can generate the qrcode in a task) without
' freezing the UI.
' - Added a simple cachefs cache file to avoid regenerating the same QRCode images
' TODO:P2 add original tests
' TODO:P2 add original tests
@@ -471,7 +471,15 @@ namespace HttpClient
backoffMs = 1000 + Rnd(2000)
tryNumber = m._tryCount - triesLeft + 1
LogWarnNoTelemetry("Request failed ID:", m.urlTransfer.GetIdentity(), "ErrorMessage:", response.ErrorMessage(), `\nRetrying: (`, tryNumber, "/", m._tryCount, ") in", backoffMs, "ms")
LogWarnTelemetry(response.ErrorMessage() + `\n` + m.ToCurlCommand())
LogTelemetryEvent({
level: "warning"
message: response.ErrorMessage()
attachments: [{
filename: "request.txt"
content_type: "text/plain"
data: m.ToCurlCommand()
}]
})
if IsFunction(m._retryCallback)
try
@@ -44,6 +44,15 @@ namespace Tests
m.assertEqual(Sentry.Redact(42), 42)
end function
@it("leaves an already-masked Authorization header alone inside a serialized envelope line")
function alreadyRedactedInEnvelopeLine()
line = FormatJson({
extra: { "request.txt": "curl -H 'Authorization: <REDACTED>'" + Chr(10) + " -H 'X-Other: 1'" }
level: "error"
})
m.assertEqual(Sentry.Redact(line), line)
end function
end class
end namespace
@@ -0,0 +1,452 @@
import "pkg:/components/VideoPlayerDev/PlaybackTelemetry.bs"
import "pkg:/components/VideoPlayerDev/TransportController.bs"
import "pkg:/components/VideoPlayerDev/VideoNode.bs"
import "pkg:/source/utils/Locale.bs"
import "pkg:/source/utils/StringUtils.bs"
namespace Tests
@suite
class PlaybackTelemetryTests extends Rooibos.BaseTestSuite
protected override function beforeEach()
' the logger plugin reads m.global.logger; LogTelemetryEvent writes m.global.telemetry.LogEvent.
if m.global.logger = invalid
m.global.addField("logger", "node", false)
m.global.logger = CreateObject("roSGNode", "Logger")
end if
if m.global.telemetry = invalid
m.global.addField("telemetry", "node", false)
telemetry = CreateObject("roSGNode", "Node")
telemetry.addField("LogEvent", "assocarray", false)
m.global.telemetry = telemetry
end if
m.playerClock = {
ms: 0
TotalMilliseconds: function() as integer
return m.ms
end function
}
m.fakeTransport = {
transportMode: TransportController.Mode.Idle
isLive: false
cursorMs: 0
edgeMs: 0
SafetyFloorMs: function() as integer
return -1
end function
}
m.fakeTop = {
content: { videoId: "vid1", backend: "playlet", playletStreamSource: "adaptiveFormats", playletStreamUrlIndex: 0 }
state: VideoState.Playing
position: 0.0
duration: 0.0
errorMsg: "There was an error in the HTTP response."
errorCode: -1
}
m.recorder = new PlaybackTelemetry.Recorder({ playerTimer: m.playerClock, transport: m.fakeTransport, top: m.fakeTop })
end function
function At(ms as integer) as void
m.playerClock.ms = ms
end function
function State(state as string) as void
m.recorder.OnState(state)
end function
function Status(isUnderrun as boolean) as void
m.recorder.OnBufferingStatus({ actualStart: 0, isUnderrun: isUnderrun, percentage: 0, prebufferDone: false })
end function
function StartInfo(startType as string) as void
m.recorder.OnPlayStartInfo({ start_type: startType, total_dur: 0.5, prebuf_dur: 0.25, drm_load_dur: 0 })
end function
function ReportError() as void
m.recorder.ReportVideoError({ title: "Error playing video vid1", body: "errorMsg: http" }, invalid, "http://stream", 0, false)
end function
function SendAt(ms as integer) as object
m.At(ms)
m.recorder.SendSummary()
event = m.global.telemetry.LogEvent
m.assertEqual(event.fingerprint, ["playback summary"])
return StringUtils.ParseJsonSafe(event.message)
end function
function SortedKeys(aa as object) as object
keys = aa.Keys()
keys.Sort()
return keys
end function
@describe("playback summary")
@it("a clean play sends only what is not a default")
function _()
m.At(1000)
m.recorder.OnMetadataDone()
m.At(1500)
m.State(VideoState.Buffering)
m.Status(false)
m.At(2000)
m.State(VideoState.Playing)
m.StartInfo("init")
summary = m.SendAt(62000)
m.assertEqual(m.SortedKeys(summary), ["backend", "first_playing_at_ms", "lifetime_ms", "metadata_done_at_ms", "outcome", "play_start_count", "play_start_infos", "playing_ms", "stream_source"])
m.assertEqual(summary.backend, "playlet")
m.assertEqual(summary.stream_source, "adaptiveFormats")
m.assertEqual(summary.outcome, "closed")
m.assertEqual(summary.metadata_done_at_ms, 1000)
m.assertEqual(summary.first_playing_at_ms, 2000)
m.assertEqual(summary.play_start_count, 1)
m.assertEqual(m.SortedKeys(summary.play_start_infos[0]), ["prebuf_dur", "start_type", "total_dur"])
m.assertEqual(summary.play_start_infos[0].start_type, "init")
m.assertEqual(summary.lifetime_ms, 62000)
m.assertEqual(summary.playing_ms, 60000)
end function
@it("count and total cover every underrun; samples stop at 10")
function _()
m.fakeTransport.isLive = true
m.At(1000)
m.State(VideoState.Playing)
t = 1000
for i = 1 to 12
t += 10000
m.At(t)
m.State(VideoState.Buffering)
m.Status(true)
t += i * 100
m.At(t)
m.State(VideoState.Playing)
end for
summary = m.SendAt(t + 1000)
m.assertEqual(summary.underrun_count, 12)
m.assertEqual(summary.underrun_ms, 7800)
m.assertEqual(summary.underrun_samples.Count(), 10)
m.assertEqual(summary.underrun_samples[0], { at_ms: 11000, ms: 100 })
m.assertEqual(summary.underrun_samples[9].ms, 1000)
m.assertTrue(summary.live)
m.assertFalse(summary.DoesExist("ended_in_underrun"))
m.assertEqual(summary.video_id, "vid1")
end function
@it("a buffering whose first bufferingStatus is no underrun is not counted")
function _()
m.At(1000)
m.State(VideoState.Playing)
m.At(5000)
m.State(VideoState.Buffering)
m.Status(false)
m.Status(false)
m.At(5500)
m.State(VideoState.Playing)
summary = m.SendAt(6000)
m.assertFalse(summary.DoesExist("underrun_count"))
m.assertFalse(summary.DoesExist("bufferings_without_status_count"))
m.assertEqual(summary.playing_ms, 4500)
end function
@it("an underrun before the first playing counts")
function _()
m.At(100)
m.State(VideoState.Buffering)
m.Status(true)
m.At(2100)
m.State(VideoState.Playing)
summary = m.SendAt(3000)
m.assertEqual(summary.underrun_count, 1)
m.assertEqual(summary.underrun_samples[0], { at_ms: 100, ms: 2000 })
end function
@it("a buffering with no valid bufferingStatus is counted as one, with the video id")
function _()
m.At(1000)
m.State(VideoState.Playing)
m.At(5000)
m.State(VideoState.Buffering)
m.recorder.OnBufferingStatus(invalid)
m.At(5150)
m.State(VideoState.Playing)
summary = m.SendAt(6000)
m.assertEqual(summary.bufferings_without_status_count, 1)
m.assertFalse(summary.DoesExist("underrun_count"))
m.assertEqual(summary.playing_ms, 4850)
m.assertEqual(summary.video_id, "vid1")
end function
@it("a buffering cut short before any status is not counted: a pause, an error, the close")
function _()
m.At(1000)
m.State(VideoState.Playing)
m.State(VideoState.Buffering)
m.State(VideoState.Paused)
m.State(VideoState.Buffering)
m.State(VideoState.Error)
m.State(VideoState.Buffering)
summary = m.SendAt(2000)
m.assertFalse(summary.DoesExist("bufferings_without_status_count"))
end function
@it("an update with no boolean isUnderrun is no status")
function _()
m.At(1000)
m.State(VideoState.Playing)
m.State(VideoState.Buffering)
m.recorder.OnBufferingStatus({ percentage: 33, prebufferDone: true })
m.recorder.OnBufferingStatus({ isUnderrun: "true", percentage: 99 })
m.At(2000)
m.State(VideoState.Playing)
summary = m.SendAt(3000)
m.assertEqual(summary.bufferings_without_status_count, 1)
m.assertFalse(summary.DoesExist("underrun_count"))
end function
@it("the first bufferingStatus classifies; each later isUnderrun change is counted")
function _()
m.At(1000)
m.State(VideoState.Playing)
m.At(5000)
m.State(VideoState.Buffering)
m.Status(false)
m.Status(true)
m.Status(true)
m.Status(false)
m.At(6000)
m.State(VideoState.Playing)
summary = m.SendAt(7000)
m.assertEqual(summary.is_underrun_change_count, 2)
m.assertFalse(summary.DoesExist("underrun_count"))
m.assertEqual(summary.video_id, "vid1")
end function
@it("a bufferingStatus outside a buffering is ignored")
function _()
m.At(1000)
m.State(VideoState.Playing)
m.Status(true)
m.At(2000)
m.State(VideoState.Paused)
m.Status(true)
summary = m.SendAt(3000)
m.assertFalse(summary.DoesExist("underrun_count"))
m.assertFalse(summary.DoesExist("is_underrun_change_count"))
end function
@it("an underrun ends at a pause")
function _()
m.At(1000)
m.State(VideoState.Playing)
m.At(5000)
m.State(VideoState.Buffering)
m.Status(true)
m.At(6000)
m.State(VideoState.Paused)
m.At(9000)
m.State(VideoState.Buffering)
m.Status(false)
m.At(9100)
m.State(VideoState.Playing)
summary = m.SendAt(10000)
m.assertEqual(summary.underrun_count, 1)
m.assertEqual(summary.underrun_samples[0], { at_ms: 5000, ms: 1000 })
end function
@it("an underrun still running at the send counts up to it, and ended the playback")
function _()
m.At(1000)
m.State(VideoState.Playing)
m.At(5000)
m.State(VideoState.Buffering)
m.Status(true)
summary = m.SendAt(8000)
m.assertEqual(summary.underrun_count, 1)
m.assertEqual(summary.underrun_samples[0], { at_ms: 5000, ms: 3000 })
m.assertTrue(summary.ended_in_underrun)
m.assertEqual(summary.playing_ms, 4000)
end function
@it("every playStartInfo is counted; the first 10 are kept as written")
function _()
m.recorder.OnPlayStartInfo(invalid)
m.StartInfo("init")
for i = 1 to 11
m.StartInfo("cseek")
end for
summary = m.SendAt(1000)
m.assertEqual(summary.play_start_count, 12)
m.assertEqual(summary.play_start_infos.Count(), 10)
m.assertEqual(summary.play_start_infos[0].start_type, "init")
m.assertEqual(summary.play_start_infos[1].start_type, "cseek")
end function
@it("a video that never played: -1 for what never happened, with its video id")
function _()
m.At(100)
m.State(VideoState.Buffering)
summary = m.SendAt(9000)
m.assertEqual(summary.metadata_done_at_ms, -1)
m.assertEqual(summary.first_playing_at_ms, -1)
m.assertFalse(summary.DoesExist("bufferings_without_status_count"), "a buffering open at the close never reached playing")
m.assertFalse(summary.DoesExist("play_start_infos"))
m.assertFalse(summary.DoesExist("playing_ms"))
m.assertEqual(summary.video_id, "vid1")
end function
@it("DRM content from the DASH manifest url, after a retry")
function _()
m.fakeTop.content = { videoId: "vid1", backend: "playlet", playletStreamSource: "dashUrl", playletStreamUrlIndex: 1, drmParams: { keySystem: "Widevine" } }
summary = m.SendAt(1000)
m.assertTrue(summary.drm)
m.assertEqual(summary.stream_source, "dashUrl")
m.assertEqual(summary.stream_url_index, 1)
end function
@it("content that never loaded sends no stream fields")
function _()
m.fakeTop.content = { videoId: "vid1", backend: "playlet" }
summary = m.SendAt(1000)
m.assertFalse(summary.DoesExist("stream_source"))
m.assertFalse(summary.DoesExist("drm"))
m.assertFalse(summary.DoesExist("stream_url_index"))
end function
@it("an error dialog ends the playback in error")
function _()
m.At(1000)
m.State(VideoState.Playing)
m.At(2000)
m.ReportError()
m.State(VideoState.Error)
m.recorder.OnErrorDialog()
summary = m.SendAt(3000)
m.assertEqual(summary.outcome, "error")
m.assertEqual(summary.error_count, 1)
m.assertEqual(summary.playing_ms, 1000)
m.assertEqual(summary.video_id, "vid1")
end function
@it("playing under the error dialog: recovered, so the error did not end it")
function _()
m.ReportError()
m.State(VideoState.Error)
m.recorder.OnErrorDialog()
m.At(2000)
m.State(VideoState.Playing)
summary = m.SendAt(4000)
m.assertEqual(summary.outcome, "closed")
m.assertEqual(summary.error_count, 1)
m.assertEqual(summary.video_id, "vid1")
end function
@it("a finished video ends in finished")
function _()
m.At(1000)
m.State(VideoState.Playing)
m.At(9000)
m.State(VideoState.Finished)
m.recorder.OnFinished()
summary = m.SendAt(9000)
m.assertEqual(summary.outcome, "finished")
m.assertEqual(summary.playing_ms, 8000)
m.assertFalse(summary.DoesExist("video_id"), "a clean finish carries no video id")
end function
@it("heals: all counted, the first 3 sampled, no event of their own")
function _()
m.fakeTransport.transportMode = TransportController.Mode.Scrub
m.fakeTransport.cursorMs = 48000
m.fakeTop.position = 51.2
m.State(VideoState.Playing)
m.global.telemetry.LogEvent = {}
for i = 1 to 5
m.At(i * 1000)
m.recorder.RecordHeal("OnPosition")
end for
m.assertInvalid(m.global.telemetry.LogEvent.message, "a heal sends nothing until the summary")
summary = m.SendAt(9000)
m.assertEqual(summary.heal_count, 5)
m.assertEqual(summary.heal_samples.Count(), 3)
m.assertEqual(summary.heal_samples[0], { at_ms: 1000, source: "OnPosition", mode: TransportController.Mode.Scrub, position_ms: 51200, cursor_ms: 48000, floor_ms: -1 })
m.assertEqual(summary.video_id, "vid1")
end function
@it("tail resolves: all counted, the first 3 sampled, no event of their own, no video id")
function _()
m.fakeTransport.isLive = true
m.fakeTransport.cursorMs = 6134000
m.fakeTransport.edgeMs = 6640000
m.fakeTransport.SafetyFloorMs = function() as integer
return 6134000
end function
m.fakeTop.position = 6137.0
m.State(VideoState.Playing)
m.global.telemetry.LogEvent = {}
for i = 1 to 4
m.At(i * 1000)
m.recorder.RecordTailResolve("OnVideoState")
end for
m.assertInvalid(m.global.telemetry.LogEvent.message, "a tail resolve sends nothing until the summary")
summary = m.SendAt(9000)
m.assertEqual(summary.tail_resolve_count, 4)
m.assertEqual(summary.tail_resolve_samples.Count(), 3)
m.assertEqual(summary.tail_resolve_samples[0], { at_ms: 1000, source: "OnVideoState", position_ms: 6137000, cursor_ms: 6134000, floor_ms: 6134000, edge_ms: 6640000 })
m.assertFalse(summary.DoesExist("video_id"))
end function
@it("no content: an unknown backend, no content fields")
function _()
m.fakeTop.content = invalid
summary = m.SendAt(1000)
m.assertEqual(summary.backend, "unknown")
m.assertFalse(summary.DoesExist("video_id"))
m.assertFalse(summary.DoesExist("stream_source"))
end function
@it("a video error report: its level, fingerprint and the summary's error count")
function _()
m.fakeTop.content = { videoId: "vid1", backend: "playlet", playletStreamUrls: ["http://a", "http://b"] }
errorInfo = { source: "buffer:reader", ignored: false, category: "http" }
m.recorder.ReportVideoError({ title: "Error playing video vid1", body: "errorMsg: http" }, errorInfo, "http://a", 0, false)
m.assertEqual(m.global.telemetry.LogEvent.level, "warning", "retried: not shown to the viewer")
m.recorder.ReportVideoError({ title: "Error playing video vid1", body: "errorMsg: http" }, errorInfo, "http://b", 1, true)
sent = m.global.telemetry.LogEvent
m.assertEqual(sent.level, "error")
m.assertTrue(sent.message.InStr("Url: http://b") > 0 and sent.message.InStr("Url index: 1") > 0, "got: " + sent.message)
m.assertTrue(sent.message.InStr(`Urls: ["http://a","http://b"]`) > 0, "got: " + sent.message)
m.assertEqual(sent.fingerprint, [Locale.VideoPlayer.ErrorPlayingVideo, "There was an error in the HTTP response.", -1, "buffer:reader", false, "http", invalid, invalid, true, false, "none", false, "playlet", false])
m.assertTrue(sent.message.InStr("backend: playlet") > 0, "got: " + sent.message)
m.assertEqual(m.SendAt(1000).error_count, 2)
end function
@describe("OmitDefaults")
@it("drops false, 0, 0.0, empty strings and arrays and invalid at every depth; keeps -1 and the rest")
function _()
value = {
f: false
zero: 0
zeroFloat: 0.0
empty: ""
none: []
missing: invalid
never: -1
yes: true
text: "x"
list: [{ zero: 0, one: 1 }]
nested: { zero: 0, inner: { f: false, two: 2.5 } }
}
m.assertEqual(PlaybackTelemetry.OmitDefaults(value), {
never: -1
yes: true
text: "x"
list: [{ one: 1 }]
nested: { inner: { two: 2.5 } }
})
end function
end class
end namespace
@@ -0,0 +1,412 @@
' Completeness suite for the playback summary: every short input sequence (exhaustive) and long random ones
' (seeded fuzz, shrunk to a minimal repro) go through the Recorder, and the summary it sends must equal the one
' an independent model rebuilds from the same event log, interval by interval.
import "pkg:/components/VideoPlayerDev/PlaybackTelemetry.bs"
import "pkg:/components/VideoPlayerDev/TransportController.bs"
import "pkg:/components/VideoPlayerDev/VideoNode.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
namespace Tests
@suite
class PlaybackTelemetryCompletenessTests extends Rooibos.BaseTestSuite
protected override function beforeEach()
if m.global.logger = invalid
m.global.addField("logger", "node", false)
m.global.logger = CreateObject("roSGNode", "Logger")
end if
if m.global.telemetry = invalid
m.global.addField("telemetry", "node", false)
telemetry = CreateObject("roSGNode", "Node")
telemetry.addField("LogEvent", "assocarray", false)
m.global.telemetry = telemetry
end if
end function
' ---------- inputs ----------
' One token = one input to the Recorder. The span tokens (0-8) drive the state machine; the rest are every
' other input the coordinator forwards.
function Tokens() as object
return [
{ kind: "wait", ms: 1000 } ' 0
{ kind: "state", state: VideoState.Playing } ' 1
{ kind: "state", state: VideoState.Buffering } ' 2
{ kind: "state", state: VideoState.Paused } ' 3
{ kind: "state", state: VideoState.Error } ' 4
{ kind: "status", status: { isUnderrun: true, percentage: 33 } } ' 5
{ kind: "status", status: { isUnderrun: false, percentage: 33 } } ' 6
{ kind: "status", status: invalid } ' 7
{ kind: "status", status: { percentage: 33 } } ' 8: no isUnderrun
{ kind: "wait", ms: 37 } ' 9
{ kind: "state", state: VideoState.Finished } ' 10
{ kind: "state", state: VideoState.Stopped } ' 11
{ kind: "start", info: { start_type: "init", total_dur: 1, prebuf_dur: 0 } } ' 12
{ kind: "start", info: { start_type: "cseek", total_dur: 2 } } ' 13
{ kind: "start", info: invalid } ' 14
{ kind: "heal" } ' 15
{ kind: "tail" } ' 16
{ kind: "videoError" } ' 17
{ kind: "dialog" } ' 18
{ kind: "finished" } ' 19
{ kind: "metadata" } ' 20
{ kind: "status", status: { isUnderrun: "true" } } ' 21: a non-boolean isUnderrun
]
end function
function NewTrial() as object
trial = {
clock: {
ms: 0
TotalMilliseconds: function() as integer
return m.ms
end function
}
transport: {
transportMode: TransportController.Mode.Scrub
isLive: false
cursorMs: 4000
edgeMs: 0
SafetyFloorMs: function() as integer
return -1
end function
}
top: {
content: { videoId: "vid1", backend: "playlet", playletStreamSource: "adaptiveFormats", playletStreamUrlIndex: 0 }
state: VideoState.Playing
position: 3.0
duration: 0.0
errorMsg: "boom"
errorCode: -1
}
log: []
}
trial.recorder = new PlaybackTelemetry.Recorder({ playerTimer: trial.clock, transport: trial.transport, top: trial.top })
return trial
end function
function Apply(trial as object, token as object) as void
trial.log.Push({ at: trial.clock.ms, token: token })
r = trial.recorder
kind = token.kind
if kind = "wait"
trial.clock.ms += token.ms
else if kind = "state"
r.OnState(token.state)
else if kind = "status"
r.OnBufferingStatus(token.status)
else if kind = "start"
r.OnPlayStartInfo(token.info)
else if kind = "heal"
r.RecordHeal("OnPosition")
else if kind = "tail"
r.RecordTailResolve("OnVideoState")
else if kind = "videoError"
r.ReportVideoError({ title: "t", body: "b" }, invalid, "http://a", 0, false)
else if kind = "dialog"
r.OnErrorDialog()
else if kind = "finished"
r.OnFinished()
else if kind = "metadata"
r.OnMetadataDone()
end if
end function
function Sent(trial as object) as object
trial.recorder.SendSummary()
return StringUtils.ParseJsonSafe(m.global.telemetry.LogEvent.message)
end function
' ---------- the model: the summary rebuilt from the event log, one state interval at a time ----------
function Expected(trial as object) as object
log = trial.log
lifetimeMs = trial.clock.ms
' intervals between state edges; the last one runs to the send (next state "").
edges = []
for i = 0 to log.Count() - 1
if log[i].token.kind = "state"
edges.Push(i)
end if
end for
playingMs = 0
underrunCount = 0
underrunMs = 0
samples = []
withoutStatus = 0
changes = 0
endedInUnderrun = false
for e = 0 to edges.Count() - 1
startIndex = edges[e]
state = log[startIndex].token.state
startMs = log[startIndex].at
if e + 1 < edges.Count()
endIndex = edges[e + 1]
endMs = log[endIndex].at
nextState = log[endIndex].token.state
else
endIndex = log.Count()
endMs = lifetimeMs
nextState = ""
end if
if state = VideoState.Playing
playingMs += endMs - startMs
else if state = VideoState.Buffering
values = []
for i = startIndex + 1 to endIndex - 1
token = log[i].token
if token.kind = "status" and token.status <> invalid and IsBool(token.status.isUnderrun)
values.Push(token.status.isUnderrun)
end if
end for
if values.Count() = 0
if nextState = VideoState.Playing
withoutStatus += 1
end if
else
for i = 1 to values.Count() - 1
if values[i] <> values[i - 1]
changes += 1
end if
end for
if values[0]
underrunCount += 1
underrunMs += endMs - startMs
if samples.Count() < 10
samples.Push({ "at_ms": startMs, "ms": endMs - startMs })
end if
endedInUnderrun = nextState = ""
end if
end if
end if
end for
outcome = "closed"
metadataDoneAtMs = -1
firstPlayingAtMs = -1
starts = []
startCount = 0
errorCount = 0
healCount = 0
heals = []
tailCount = 0
tails = []
for each entry in log
token = entry.token
kind = token.kind
if kind = "state" and token.state = VideoState.Playing
if firstPlayingAtMs < 0
firstPlayingAtMs = entry.at
end if
if outcome = "error"
outcome = "closed"
end if
else if kind = "dialog"
outcome = "error"
else if kind = "finished"
outcome = "finished"
else if kind = "metadata"
metadataDoneAtMs = entry.at
else if kind = "start" and token.info <> invalid
startCount += 1
if starts.Count() < 10
starts.Push(token.info)
end if
else if kind = "videoError"
errorCount += 1
else if kind = "heal"
healCount += 1
if heals.Count() < 3
heals.Push({ "at_ms": entry.at, "source": "OnPosition", "mode": trial.transport.transportMode, "position_ms": 3000, "cursor_ms": 4000, "edge_ms": 0, "floor_ms": -1 })
end if
else if kind = "tail"
tailCount += 1
if tails.Count() < 3
tails.Push({ "at_ms": entry.at, "source": "OnVideoState", "position_ms": 3000, "cursor_ms": 4000, "floor_ms": -1, "edge_ms": 0 })
end if
end if
end for
expected = {
"live": false
"backend": "playlet"
"stream_source": "adaptiveFormats"
"drm": false
"stream_url_index": 0
"outcome": outcome
"metadata_done_at_ms": metadataDoneAtMs
"first_playing_at_ms": firstPlayingAtMs
"play_start_infos": starts
"play_start_count": startCount
"lifetime_ms": lifetimeMs
"playing_ms": playingMs
"underrun_count": underrunCount
"underrun_ms": underrunMs
"underrun_samples": samples
"ended_in_underrun": endedInUnderrun
"bufferings_without_status_count": withoutStatus
"is_underrun_change_count": changes
"error_count": errorCount
"heal_count": healCount
"heal_samples": heals
"tail_resolve_count": tailCount
"tail_resolve_samples": tails
}
if firstPlayingAtMs < 0 or underrunCount > 0 or withoutStatus > 0 or changes > 0 or errorCount > 0 or healCount > 0 or outcome = "error"
expected["video_id"] = "vid1"
end if
return m.WithoutDefaults(expected)
end function
' the wire rule, written independently of PlaybackTelemetry.OmitDefaults.
function WithoutDefaults(value as dynamic) as dynamic
if IsArray(value)
out = []
for each item in value
out.Push(m.WithoutDefaults(item))
end for
return out
end if
if not IsAssociativeArray(value)
return value
end if
out = {}
for each key in value
item = value[key]
keep = true
if item = invalid
keep = false
else if IsBool(item)
keep = item
else if IsInt(item) or IsFloat(item)
keep = item <> 0
else if IsString(item)
keep = item <> ""
else if IsArray(item)
keep = item.Count() > 0
end if
if keep
out[key] = m.WithoutDefaults(item)
end if
end for
return out
end function
' replay a token sequence and compare; "" when the summary matches the model, else both summaries.
function Mismatch(sequence as object) as string
trial = m.NewTrial()
tokens = m.Tokens()
for each index in sequence
m.Apply(trial, tokens[index])
end for
actual = FormatJson(m.Sent(trial))
expected = FormatJson(m.Expected(trial))
if actual = expected
return ""
end if
return "sent " + actual + " | model " + expected
end function
@describe("playback summary completeness")
' "" when every sequence of `length` span tokens matches the model, else the first that does not.
function ExhaustiveFailure(length as integer) as string
spanTokens = 9
total = 1
for i = 1 to length
total *= spanTokens
end for
for n = 0 to total - 1
sequence = []
rest = n
for i = 1 to length
sequence.Push(rest mod spanTokens)
rest = rest \ spanTokens
end for
failure = m.Mismatch(sequence)
if failure <> ""
return "tokens " + FormatJson(sequence) + ": " + failure
end if
end for
return ""
end function
@it("every sequence of 4 span inputs sends the summary the model rebuilds")
function _()
m.assertEqual(m.ExhaustiveFailure(4), "")
end function
' ---------- seeded fuzz with shrink ----------
' a 16-bit LCG: deterministic and reproducible (Rnd is clock-seeded).
function Lcg(s as integer) as integer
return (s * 25173 + 13849) and 65535
end function
function GenSequence(seed as integer, n as integer, count as integer) as object
sequence = []
s = seed
for i = 0 to n - 1
s = m.Lcg(s)
sequence.Push(s mod count)
end for
return sequence
end function
function Shrink(sequence as object) as object
for k = 0 to sequence.Count() - 1
prefix = []
for j = 0 to k
prefix.Push(sequence[j])
end for
if m.Mismatch(prefix) <> ""
return prefix
end if
end for
return sequence
end function
function FuzzFailure(seeds as object, length as integer, tokenCount as integer) as string
for each seed in seeds
sequence = m.GenSequence(seed, length, tokenCount)
if m.Mismatch(sequence) <> ""
minimal = m.Shrink(sequence)
return "seed=" + seed.ToStr() + "; minimal repro (" + minimal.Count().ToStr() + " tokens) " + FormatJson(minimal) + ": " + m.Mismatch(minimal)
end if
end for
return ""
end function
@it("seeded random sequences of every input send the summary the model rebuilds (shrinkable)")
function _()
m.assertEqual(m.FuzzFailure([1, 2, 7, 42, 1337, 4242, 9001, 31337], 120, m.Tokens().Count()), "")
end function
@it("seeded random sequences of span inputs send the summary the model rebuilds (shrinkable)")
function _()
seeds = []
for seed = 100 to 160
seeds.Push(seed)
end for
m.assertEqual(m.FuzzFailure(seeds, 60, 9), "")
end function
@it("every summary the fuzz sends carries no default value at any depth")
function _()
for each seed in [3, 5, 11]
trial = m.NewTrial()
tokens = m.Tokens()
for each index in m.GenSequence(seed, 120, tokens.Count())
m.Apply(trial, tokens[index])
end for
sent = m.Sent(trial)
m.assertEqual(FormatJson(sent), FormatJson(m.WithoutDefaults(sent)), "seed=" + seed.ToStr())
end for
end function
end class
end namespace
@@ -35,6 +35,12 @@ namespace Tests
m.assertEqual(PlayerCoordinatorLogic.KeyToCommand(RemoteKeys.Ok), TransportController.Command.None)
m.assertEqual(PlayerCoordinatorLogic.KeyToCommand(RemoteKeys.Back), TransportController.Command.None)
m.assertEqual(PlayerCoordinatorLogic.KeyToCommand(RemoteKeys.Down), TransportController.Command.None)
m.assertEqual(PlayerCoordinatorLogic.KeyToCommand(RemoteKeys.Up), TransportController.Command.None)
m.assertEqual(PlayerCoordinatorLogic.KeyToCommand(RemoteKeys.Options), TransportController.Command.None)
' the play cluster: play-state keys, and a transport command here would make them seek instead.
m.assertEqual(PlayerCoordinatorLogic.KeyToCommand(RemoteKeys.Play), TransportController.Command.None)
m.assertEqual(PlayerCoordinatorLogic.KeyToCommand(RemoteKeys.PlayOnly), TransportController.Command.None)
m.assertEqual(PlayerCoordinatorLogic.KeyToCommand(RemoteKeys.Pause), TransportController.Command.None)
m.assertEqual(PlayerCoordinatorLogic.KeyToCommand("bogus"), TransportController.Command.None)
end function
-4
View File
@@ -33,10 +33,6 @@ function LogTelemetryEvent(event as object)
m.global.telemetry.LogEvent = event
end function
function LogWarnTelemetry(message as string)
m.global.telemetry.LogWarn = message
end function
function ToString(value as dynamic) as string
if getInterface(value, "ifString") <> invalid
return value
+566 -267
View File
File diff suppressed because it is too large. Load diff
+15 -15
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-web",
"version": "0.48.3",
"version": "0.48.7",
"type": "module",
"scripts": {
"dev": "vite",
@@ -9,27 +9,27 @@
"lint": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^7.2.0",
"@sveltejs/vite-plugin-svelte": "^7.3.1",
"@tailwindcss/postcss": "^4.3.3",
"@tailwindcss/typography": "^0.5.20",
"@tsconfig/svelte": "^5.0.8",
"@vitejs/plugin-legacy": "^8.2.2",
"autoprefixer": "^10.5.4",
"bgutils-js": "^4.0.2",
"daisyui": "^5.7.0",
"dotenv": "^17.4.2",
"@vitejs/plugin-legacy": "^8.2.3",
"autoprefixer": "^10.6.1",
"bgutils-js": "^4.0.3",
"daisyui": "^5.7.46",
"dotenv": "^18.0.4",
"ip": "^2.0.1",
"jszip": "^3.10.1",
"postcss": "^8.5.23",
"rollup-plugin-visualizer": "^7.0.1",
"svelte": "^5.56.8",
"svelte-check": "^4.7.3",
"svelte-preprocess": "6.0.3",
"jszip": "^3.10.2",
"postcss": "^8.5.28",
"rollup-plugin-visualizer": "^7.1.1",
"svelte": "^5.57.1",
"svelte-check": "^4.7.6",
"svelte-preprocess": "^6.0.5",
"tailwindcss": "^4.3.3",
"terser": "^5.49.0",
"terser": "^5.51.2",
"tslib": "^2.8.1",
"typescript": "^5.9.3",
"vite": "^8.1.5",
"vite": "^8.3.1",
"vite-plugin-compression": "^0.5.1"
}
}
@@ -12,6 +12,17 @@
let libUrlType;
let appId = "693751";
// Kept in step with PlayletLibUrls.MIN_VERSION in playlet-app, which drops anything older at boot.
const MIN_LIB_VERSION = "0.11.0";
function isSupported(tag) {
const version = /^v(\d+\.\d+\.\d+)$/.exec(tag ?? "")?.[1];
return (
!version ||
version.localeCompare(MIN_LIB_VERSION, undefined, { numeric: true }) >= 0
);
}
onMount(async () => {
releases = await fetchReleaseTags();
setCurrentlyUsedRelease();
@@ -62,17 +73,19 @@
break;
}
}
return releases.map((release) => {
return {
name: release.tag_name,
enabled:
release.assets.filter(
(asset) =>
asset.name === "playlet-lib.zip" ||
asset.name === "playlet-lib.squashfs.pkg"
).length > 0,
};
});
return releases
.filter((release) => isSupported(release.tag_name))
.map((release) => {
return {
name: release.tag_name,
enabled:
release.assets.filter(
(asset) =>
asset.name === "playlet-lib.zip" ||
asset.name === "playlet-lib.squashfs.pkg"
).length > 0,
};
});
}
async function apply() {
+3 -2
View File
@@ -1,8 +1,9 @@
{
"compilerOptions": {
"composite": true,
"module": "NodeNext",
"moduleResolution": "NodeNext"
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Bundler"
},
"include": [
"vite.config.ts"
+1 -1
View File
@@ -35,7 +35,7 @@ const config: UserConfig = {
// But the tools are not (because brighterscript is expecting CommonJs)
// so we can't import the function from the tools/get-env-vars.js.
function getEnvVars(requiredVars = undefined) {
const envFile = joinPath(__dirname, '../.env');
const envFile = joinPath(import.meta.dirname, '../.env');
let envVars = process.env;
if (existsSync(envFile)) {
+1 -2
View File
@@ -7,7 +7,6 @@ const { existsSync, writeFileSync, readFileSync } = require('fs');
const json5 = require('json5');
const md5 = require('crypto-js/md5');
const path = require('path');
const { executablePath } = require('puppeteer');
const META_EXT = '.meta.json5';
@@ -118,7 +117,7 @@ function checkFileHash(file, hash) {
async function generateImage(inputImage, options, rootDir) {
const opts = {
launch: { executablePath: await executablePath() },
launch: { channel: 'chrome' },
...options
};
opts.outputFilePath = path.join(rootDir, opts.outputFilePath);
+96 -58
View File
@@ -34,23 +34,27 @@ This page was automatically generated on ${formattedDate}.
fs.writeFileSync(markdownFile, markdownContent);
}
async function deleteExistingAttachments() {
try {
const files = fs.readdirSync(attachmentDestination);
function deleteExistingAttachments() {
const files = fs.readdirSync(attachmentDestination);
for (const file of files) {
if (path.extname(file) === '.png') {
fs.unlinkSync(path.join(attachmentDestination, file));
console.log(`Deleted ${file}`);
}
for (const file of files) {
if (path.extname(file) === '.png') {
fs.unlinkSync(path.join(attachmentDestination, file));
console.log(`Deleted ${file}`);
}
} catch (error) {
console.error(error);
}
}
const config = getEnvVars(['EMAIL', 'EMAIL_APP_PASSWORD']);
// Gmail can take 15s or more to answer LOGIN, well past node-imap's 5s default,
// and throttles an account that reconnects right after a failed attempt.
const AUTH_TIMEOUT_MS = 60 * 1000;
const CONNECT_TIMEOUT_MS = 30 * 1000;
const CONNECT_ATTEMPTS = 3;
const RETRY_DELAY_MS = 30 * 1000;
const RUN_TIMEOUT_MS = 10 * 60 * 1000;
const imap = new Imap({
user: config.EMAIL,
password: config.EMAIL_APP_PASSWORD,
@@ -59,7 +63,9 @@ const imap = new Imap({
tls: true,
tlsOptions: {
rejectUnauthorized: false
}
},
connTimeout: CONNECT_TIMEOUT_MS,
authTimeout: AUTH_TIMEOUT_MS
});
const searchAsync = promisify(imap.search).bind(imap);
@@ -129,59 +135,91 @@ async function moveToTrash(from, subject, since) {
console.log('Moved %d message(s) to Trash for subject "%s"', uids.length, subject);
}
const timeout = setTimeout(() => {
console.log('Timeout');
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function fail(error) {
console.error('Error:', error);
process.exit(1);
}, 10 * 60 * 1000);
}
imap.once('ready', async () => {
try {
await openBoxAsync('INBOX');
function connectAsync() {
return new Promise((resolve, reject) => {
const onReady = () => {
imap.removeListener('error', onError);
imap.on('error', fail);
resolve();
};
const onError = error => {
imap.removeListener('ready', onReady);
reject(error);
};
imap.once('ready', onReady);
imap.once('error', onError);
imap.connect();
});
}
const now = new Date();
const yesterday = new Date(now - 24 * 60 * 60 * 1000);
const yesterdayString = yesterday.toISOString().slice(0, 19).replace('T', ' ');
deleteExistingAttachments();
const images = []
images.push({
title: 'App Health',
filename: await getAttachementAsync('bdp_noreply@data.roku.com', 'App Health', yesterdayString)
})
images.push({
title: 'App Engagement',
filename: await getAttachementAsync('bdp_noreply@data.roku.com', 'App Engagement', yesterdayString)
})
images.push({
title: 'Viewership Summary',
filename: await getAttachementAsync('bdp_noreply@data.roku.com', 'Viewership Summary', yesterdayString)
})
images.push({
title: 'App Stability',
filename: await getAttachementAsync('bdp_noreply@data.roku.com', 'App Stability', yesterdayString)
})
writeMarkDownFile(images);
await moveToTrash('bdp_noreply@data.roku.com', 'App Health', yesterdayString);
await moveToTrash('bdp_noreply@data.roku.com', 'App Engagement', yesterdayString);
await moveToTrash('bdp_noreply@data.roku.com', 'Viewership Summary', yesterdayString);
await moveToTrash('bdp_noreply@data.roku.com', 'App Stability', yesterdayString);
imap.end();
} catch (error) {
console.error('Error:', error);
async function connectWithRetryAsync() {
for (let attempt = 1; ; attempt++) {
try {
await connectAsync();
return;
} catch (error) {
if (attempt === CONNECT_ATTEMPTS) {
throw error;
}
console.error('Connection attempt %d/%d failed: %s', attempt, CONNECT_ATTEMPTS, error.message);
await sleep(RETRY_DELAY_MS);
}
}
clearTimeout(timeout);
});
}
imap.once('error', err => {
console.error(err);
});
async function downloadStats() {
await connectWithRetryAsync();
await openBoxAsync('INBOX');
imap.once('end', () => {
const now = new Date();
const yesterday = new Date(now - 24 * 60 * 60 * 1000);
const yesterdayString = yesterday.toISOString().slice(0, 19).replace('T', ' ');
deleteExistingAttachments();
const images = []
images.push({
title: 'App Health',
filename: await getAttachementAsync('bdp_noreply@data.roku.com', 'App Health', yesterdayString)
})
images.push({
title: 'App Engagement',
filename: await getAttachementAsync('bdp_noreply@data.roku.com', 'App Engagement', yesterdayString)
})
images.push({
title: 'Viewership Summary',
filename: await getAttachementAsync('bdp_noreply@data.roku.com', 'Viewership Summary', yesterdayString)
})
images.push({
title: 'App Stability',
filename: await getAttachementAsync('bdp_noreply@data.roku.com', 'App Stability', yesterdayString)
})
writeMarkDownFile(images);
await moveToTrash('bdp_noreply@data.roku.com', 'App Health', yesterdayString);
await moveToTrash('bdp_noreply@data.roku.com', 'App Engagement', yesterdayString);
await moveToTrash('bdp_noreply@data.roku.com', 'Viewership Summary', yesterdayString);
await moveToTrash('bdp_noreply@data.roku.com', 'App Stability', yesterdayString);
imap.end();
}
imap.on('end', () => {
console.log('Connection ended');
});
imap.connect();
setTimeout(() => fail(new Error(`Gave up after ${RUN_TIMEOUT_MS / 1000}s`)), RUN_TIMEOUT_MS);
downloadStats().then(() => {
process.exit(0);
}).catch(fail);