Compare commits

..
5 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
25 changed files with 1790 additions and 249 deletions

No files matched your search

+10
View File
@@ -5,6 +5,16 @@ 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
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet",
"version": "0.48.6",
"version": "0.48.7",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "playlet",
"version": "0.48.6",
"version": "0.48.7",
"hasInstallScript": true,
"devDependencies": {
"@rokucommunity/bslint": "^0.8.46",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet",
"version": "0.48.6",
"version": "0.48.7",
"description": "Unofficial YouTube client for Roku",
"devDependencies": {
"@rokucommunity/bslint": "^0.8.46",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-app",
"version": "0.48.6",
"version": "0.48.7",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-app",
"version": "0.48.6"
"version": "0.48.7"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-app",
"version": "0.48.6",
"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=00006
build_version=00007
ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-lib",
"version": "0.48.6",
"version": "0.48.7",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-lib",
"version": "0.48.6"
"version": "0.48.7"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-lib",
"version": "0.48.6",
"version": "0.48.7",
"description": "Unofficial YouTube client for Roku",
"scripts": {
"prebuild": "node ../tools/rm.js ../build/playlet-lib",
+52 -33
View File
@@ -5,11 +5,57 @@ const SUPPORT_SERVER_ENVELOPE_URL = "https://playlet-v8556.ondigitalocean.app/en
const SENTRY_FALLBACK_ENVELOPE_URL = "https://o4509923566288896.ingest.us.sentry.io/api/4512194184544256/envelope/"
const SENTRY_FALLBACK_KEY = "a16c510299b23ccc63bdc84f751c9950"
const SUPPORTS_ATTACHMENTS = false
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({
@@ -69,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)}`
@@ -83,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)
@@ -98,34 +144,7 @@ namespace Sentry
end if
end for
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, payload)
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
return payload
end function
function GetFingerprint(message as dynamic) as dynamic
@@ -165,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"
@@ -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
@@ -23,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
@@ -35,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
@@ -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,7 +80,7 @@ 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
@@ -196,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
@@ -243,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,6 +52,7 @@
<function name="TestSetState" />
<function name="TestSnapshot" />
<function name="TestWireQueueClose" />
<function name="TestResendSummary" />
<function name="TestSetControl" />
<function name="TestSetLive" />
<function name="TestSeedSponsorBlock" />
@@ -58,6 +61,7 @@
<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")
@@ -743,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).
@@ -759,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
@@ -819,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
@@ -831,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
@@ -865,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
+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=00006
build_version=00007
ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p
@@ -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
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-web",
"version": "0.48.6",
"version": "0.48.7",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "playlet-web",
"version": "0.48.6",
"version": "0.48.7",
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^7.3.1",
"@tailwindcss/postcss": "^4.3.3",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-web",
"version": "0.48.6",
"version": "0.48.7",
"type": "module",
"scripts": {
"dev": "vite",