Live stream fixes

This commit is contained in:
Brahim Hadriche committed 2026-10-16 14:05:19 -04:00
1 parent ae1d2b8acf
commit 555665488d
17 files changed
+280 -148

No files matched your search

+1
View File
@@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed ### Fixed
- Error message when account requires age verification - Error message when account requires age verification
- Live stream fixes
## [0.48.9] - 2026-10-14 ## [0.48.9] - 2026-10-14
@@ -54,7 +54,6 @@ class DashManifest
adaptiveFormats = m.ProxyFormatsThroughInvidious(adaptiveFormats) adaptiveFormats = m.ProxyFormatsThroughInvidious(adaptiveFormats)
end if end if
duration = m.GetDuration(metadata)
isLive = ValidBool(metadata.liveNow) isLive = ValidBool(metadata.liveNow)
groupings = m.CreateFormatGroupings(adaptiveFormats, metadata.isPostLiveDvr, isLive) groupings = m.CreateFormatGroupings(adaptiveFormats, metadata.isPostLiveDvr, isLive)
@@ -119,7 +118,7 @@ class DashManifest
else else
mpdAttributes["profiles"] = "urn:mpeg:dash:profile:full:2011" mpdAttributes["profiles"] = "urn:mpeg:dash:profile:full:2011"
mpdAttributes["type"] = "static" mpdAttributes["type"] = "static"
mpdAttributes["mediaPresentationDuration"] = `PT${duration}S` mpdAttributes["mediaPresentationDuration"] = m.FormatDuration(m.GetDurationMs(metadata))
end if end if
' Live needs an explicit Period start to anchor the timeline against availabilityStartTime. ' Live needs an explicit Period start to anchor the timeline against availabilityStartTime.
@@ -169,17 +168,17 @@ class DashManifest
return proxied return proxied
end function end function
function GetDuration(metadata as object) as dynamic function GetDurationMs(metadata as object) as longinteger
if metadata["isPostLiveDvr"] = true and IsInt(metadata["postLiveDvrDurationMs"]) if metadata["isPostLiveDvr"] = true and metadata["postLiveDvrDurationMs"] <> invalid
return metadata["postLiveDvrDurationMs"] / 1000.0 return metadata["postLiveDvrDurationMs"]
end if end if
approxDurationMs = ValidString(ObjectUtils.Dig(metadata, ["adaptiveFormats", 0, "approxDurationMs"])).ToInt() approxDurationMs = StringUtils.ParseJsonSafe(ObjectUtils.Dig(metadata, ["adaptiveFormats", 0, "approxDurationMs"]))
if approxDurationMs > 0 if IsNumber(approxDurationMs) and approxDurationMs > 0
return approxDurationMs / 1000.0 return approxDurationMs
end if end if
return ValidInt(metadata["lengthSeconds"]) return ValidInt(metadata["lengthSeconds"]) * 1000&
end function end function
' `durationRuns` ascending. ' `durationRuns` ascending.
@@ -246,7 +245,7 @@ class DashManifest
return seqnum return seqnum
end function end function
function FormatDuration(ms as integer) as string function FormatDuration(ms as longinteger) as string
return `PT${ms \ 1000}.${Right("00" + (ms mod 1000).ToStr(), 3)}S` return `PT${ms \ 1000}.${Right("00" + (ms mod 1000).ToStr(), 3)}S`
end function end function
@@ -638,8 +637,7 @@ class DashManifest
if not IsInt(postLiveDvrSegmentCount) if not IsInt(postLiveDvrSegmentCount)
xml.Comment(`[ERROR] Post-Live DVR metadata missing postLiveDvrSegmentCount for itag: ${stream.itag}`) xml.Comment(`[ERROR] Post-Live DVR metadata missing postLiveDvrSegmentCount for itag: ${stream.itag}`)
' We're going to guess segment count from targetDurationSec and total duration ' We're going to guess segment count from targetDurationSec and total duration
totalDurationMs = m.GetDuration(metadata) * 1000.0 postLiveDvrSegmentCount = MathUtils.Max(Fix(m.GetDurationMs(metadata) / (stream.targetDurationSec * 1000)), 1)
postLiveDvrSegmentCount = MathUtils.Max(Fix(totalDurationMs / (stream.targetDurationSec * 1000)), 1)
xml.Comment(`[INFO] Guessing postLiveDvrSegmentCount as ${postLiveDvrSegmentCount} for itag: ${stream.itag}`) xml.Comment(`[INFO] Guessing postLiveDvrSegmentCount as ${postLiveDvrSegmentCount} for itag: ${stream.itag}`)
end if end if
@@ -1,3 +0,0 @@
' The head check counts of the latest live video load, as { video_load_id, counts }. One file,
' overwritten by each live load: tmp:/ lasts as long as the app.
const LIVE_HEAD_COUNTS_PATH = "tmp:/live_head_counts.json"
@@ -0,0 +1,3 @@
' The head check and timeline counts of the latest live video load, as { video_load_id, live_head,
' live_timeline }. One file, overwritten by each live load: tmp:/ lasts as long as the app.
const LIVE_LOAD_COUNTS_PATH = "tmp:/live_load_counts.json"
@@ -33,33 +33,17 @@ namespace Innertube
end if end if
headUrl = GetLiveHeadUrl(adaptiveFormats[0]["url"], cpn) headUrl = GetLiveHeadUrl(adaptiveFormats[0]["url"], cpn)
request = CreateLiveHeadRequest(headUrl) response = FetchLiveHead(headUrl, cancellation)
request.RetryCount(1) if not HasLiveHead(response)
request.RetryIf(function(response as HttpClient.Response) as string
if Innertube.ReadLiveHeadSeqnum(response) < 0 or (Innertube.ReadLiveHeadTimeMs(response) = invalid and Innertube.ReadLiveHeadTimeSecAsMs(response) = invalid)
return `no X-Head-* in the response (HTTP ${response.StatusCode()})`
end if
return ""
end function)
request.Cancellation(cancellation)
response = request.Await()
headSeqnum = ReadLiveHeadSeqnum(response)
headTimeMs = ReadLiveHeadTimeMs(response)
averagedTimeMs = headTimeMs
if averagedTimeMs = invalid
averagedTimeMs = ReadLiveHeadTimeSecAsMs(response)
end if
if headSeqnum < 0 or averagedTimeMs = invalid
parsedResponse["error"] = `Live stream head check returned no X-Head-Seqnum / X-Head-Time (HTTP ${response.StatusCode()})\n${response.ErrorMessage()}` parsedResponse["error"] = `Live stream head check returned no X-Head-Seqnum / X-Head-Time (HTTP ${response.StatusCode()})\n${response.ErrorMessage()}`
return return
end if end if
now = CreateObject("roDateTime") now = CreateObject("roDateTime")
timeline = GetLiveTimeline(headSeqnum, averagedTimeMs, ValidInt(adaptiveFormats[0]["targetDurationSec"]), ValidInt(adaptiveFormats[0]["maxDvrDurationSec"]), chunkReadahead, now.AsSeconds(), now.GetMilliseconds()) timeline = GetLiveTimeline(ReadLiveHeadSeqnum(response), ReadLiveHeadAnyTimeMs(response), ValidInt(adaptiveFormats[0]["targetDurationSec"]), ValidInt(adaptiveFormats[0]["maxDvrDurationSec"]), chunkReadahead, now.AsSeconds(), now.GetMilliseconds())
parsedResponse.Append(timeline) parsedResponse.Append(timeline)
parsedResponse["liveHeadUrl"] = headUrl parsedResponse["liveHeadUrl"] = headUrl
parsedResponse["liveHeadTimeMs"] = headTimeMs parsedResponse["liveHeadTimeMs"] = ReadLiveHeadTimeMs(response)
end function end function
' The live timeline fields for a stream whose head (newest segment) is ' The live timeline fields for a stream whose head (newest segment) is
@@ -148,6 +132,25 @@ namespace Innertube
return request return request
end function end function
' The head check's answer, sent once more when it lacks the head (HasLiveHead), whatever its HTTP status.
function FetchLiveHead(headUrl as string, cancellation as object) as HttpClient.Response
request = CreateLiveHeadRequest(headUrl)
request.RetryCount(1)
request.RetryIf(function(response as HttpClient.Response) as string
if not Innertube.HasLiveHead(response)
return `no X-Head-* in the response (HTTP ${response.StatusCode()})`
end if
return ""
end function)
request.Cancellation(cancellation)
return request.Await()
end function
' Whether a head check's answer carries the head's seqnum and time.
function HasLiveHead(response as HttpClient.Response) as boolean
return ReadLiveHeadSeqnum(response) >= 0 and ReadLiveHeadAnyTimeMs(response) <> invalid
end function
' X-Head-Seqnum of a live head response, -1 if absent. Not gated on HTTP status: a ' X-Head-Seqnum of a live head response, -1 if absent. Not gated on HTTP status: a
' head check can come back non-2xx yet still carry the X-Head-* headers ' head check can come back non-2xx yet still carry the X-Head-* headers
' (observed: one stream returns 500, another 200; both include them). ' (observed: one stream returns 500, another 200; both include them).
@@ -167,6 +170,15 @@ namespace Innertube
return StringUtils.ParseJsonSafe(ValidString(response.Headers()["X-Head-Time-Millis"])) return StringUtils.ParseJsonSafe(ValidString(response.Headers()["X-Head-Time-Millis"]))
end function end function
' X-Head-Time-Millis, else X-Head-Time-Sec in ms, invalid if neither.
function ReadLiveHeadAnyTimeMs(response as HttpClient.Response) as dynamic
timeMs = ReadLiveHeadTimeMs(response)
if timeMs = invalid
timeMs = ReadLiveHeadTimeSecAsMs(response)
end if
return timeMs
end function
' X-Head-Time-Sec in ms, invalid if absent: whole seconds, too coarse to average a ' X-Head-Time-Sec in ms, invalid if absent: whole seconds, too coarse to average a
' young stream's few segments or to time the head between checks. ' young stream's few segments or to time the head between checks.
function ReadLiveHeadTimeSecAsMs(response as HttpClient.Response) as dynamic function ReadLiveHeadTimeSecAsMs(response as HttpClient.Response) as dynamic
@@ -190,7 +190,7 @@ namespace Innertube
if isPostLiveDvr if isPostLiveDvr
LogDebug("Fetching Post-Live DVR info") LogDebug("Fetching Post-Live DVR info")
GetPostLiveDvrInfo(parsedResponse, adaptiveFormats, playerRequest.cpn, client, cancellation) GetPostLiveDvrInfo(parsedResponse, adaptiveFormats, playerRequest.cpn, cancellation)
end if end if
if isOTF if isOTF
@@ -1,11 +1,11 @@
import "pkg:/components/Services/Innertube/Context.bs" import "pkg:/components/Services/Innertube/LiveStreamInfo.bs"
import "pkg:/source/services/HttpClient.bs" import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/UrlUtils.bs" import "pkg:/source/utils/UrlUtils.bs"
namespace Innertube namespace Innertube
function GetPostLiveDvrInfo(parsedResponse as object, adaptiveFormats as object, cpn as dynamic, client as Innertube.ClientType, cancellation as object) as void function GetPostLiveDvrInfo(parsedResponse as object, adaptiveFormats as object, cpn as dynamic, cancellation as object) as void
if adaptiveFormats.Count() = 0 if adaptiveFormats.Count() = 0
LogWarn("GetPostLiveDvrInfo: No adaptive formats available") LogWarn("GetPostLiveDvrInfo: No adaptive formats available")
return return
@@ -19,25 +19,16 @@ namespace Innertube
' Query the live edge (no sq): that response is Cache-Control: no-cache, always ' Query the live edge (no sq): that response is Cache-Control: no-cache, always
' served fresh, so it carries X-Head-*. A finished stream's head is its final ' served fresh, so it carries X-Head-*. A finished stream's head is its final
' segment, so X-Head-Seqnum is the total count and X-Head-Time-Millis the duration. ' segment, so X-Head-Seqnum is the total count and X-Head-Time-* the duration.
primary = FetchPostLiveDvrHead(formatUrl, invalid, cpn, client, cancellation) headUrl = GetLiveHeadUrl(formatUrl, cpn)
headers = invalid response = FetchLiveHead(headUrl, cancellation)
if HasPostLiveDvrHead(primary) if not HasLiveHead(response)
headers = primary.headers ' sq=0 is cacheable, so an edge can return it missing X-Head-*; fall back to it
else ' only when the live-edge query misses.
' sq=0 is cacheable, so an edge can return it missing X-Head-* (#359); fall fallback = FetchLiveHead(UrlUtils.AppendQueryParams(headUrl, { "sq": "0" }), cancellation)
' back to it only when the live-edge query misses. diagnostics = PostLiveDvrDiagnostics(parsedResponse["videoId"], headUrl, response, fallback)
fallback = FetchPostLiveDvrHead(formatUrl, "0", cpn, client, cancellation) if not HasLiveHead(fallback)
diagnostics = PostLiveDvrDiagnostics(parsedResponse["videoId"], primary, fallback)
if HasPostLiveDvrHead(fallback)
headers = fallback.headers
LogTelemetryEvent({
level: "warning"
message: `GetPostLiveDvrInfo: no-sq missing head, sq=0 fallback recovered\n${diagnostics}`
fingerprint: ["GetPostLiveDvrInfo: sq=0 fallback recovered"]
})
else
' Warning, not error: a known transport-failure tail where playback fails regardless. ' Warning, not error: a known transport-failure tail where playback fails regardless.
LogTelemetryEvent({ LogTelemetryEvent({
level: "warning" level: "warning"
@@ -46,10 +37,16 @@ namespace Innertube
}) })
return return
end if end if
LogTelemetryEvent({
level: "warning"
message: `GetPostLiveDvrInfo: no-sq missing head, sq=0 fallback recovered\n${diagnostics}`
fingerprint: ["GetPostLiveDvrInfo: sq=0 fallback recovered"]
})
response = fallback
end if end if
durationMs = ValidString(headers["X-Head-Time-Millis"]).ToInt() durationMs = ReadLiveHeadAnyTimeMs(response)
segmentCount = ValidString(headers["X-Head-Seqnum"]).ToInt() segmentCount = ReadLiveHeadSeqnum(response)
if durationMs > 0 if durationMs > 0
parsedResponse["postLiveDvrDurationMs"] = durationMs parsedResponse["postLiveDvrDurationMs"] = durationMs
@@ -59,40 +56,8 @@ namespace Innertube
end if end if
end function end function
function FetchPostLiveDvrHead(formatUrl as string, sq as dynamic, cpn as dynamic, client as Innertube.ClientType, cancellation as object) as object function PostLiveDvrDiagnostics(videoId as dynamic, headUrl as string, primary as HttpClient.Response, fallback as HttpClient.Response) as string
queryComponents = UrlUtils.ParseQueryComponents(formatUrl) return `VideoID: ${ValidString(videoId)}` + Chr(10) + `URL (no-sq; sq=0 appends &sq=0): ${headUrl}` + Chr(10) + `no-sq HEAD status: ${primary.StatusCode().ToStr()} headers: ${FormatJson(primary.Headers())}` + Chr(10) + `sq=0 HEAD status: ${fallback.StatusCode().ToStr()} headers: ${FormatJson(fallback.Headers())}`
queryComponents["rn"] = "0"
if sq <> invalid
queryComponents["sq"] = sq
end if
if not StringUtils.IsNullOrEmpty(cpn)
queryComponents["cpn"] = cpn
end if
url = UrlUtils.SetQueryParams(formatUrl, queryComponents)
request = HttpClient.Head(url)
requestHeaders = Innertube.CreateHeaders(client)
requestHeaders["origin"] = "https://www.youtube.com"
requestHeaders["referer"] = "https://www.youtube.com"
requestHeaders["DNT"] = "?1"
request.Headers(requestHeaders)
request.RetryCount(1)
request.Cancellation(cancellation)
response = request.Await()
return {
url: url
statusCode: response.StatusCode()
headers: response.Headers()
}
end function
function HasPostLiveDvrHead(result as object) as boolean
return IsAssociativeArray(result) and IsAssociativeArray(result.headers) and result.headers.DoesExist("X-Head-Time-Millis") and result.headers.DoesExist("X-Head-Seqnum")
end function
function PostLiveDvrDiagnostics(videoId as dynamic, primary as object, fallback as object) as string
return `VideoID: ${ValidString(videoId)}` + Chr(10) + `URL (no-sq; sq=0 appends &sq=0): ${primary.url}` + Chr(10) + `no-sq HEAD status: ${primary.statusCode.ToStr()} headers: ${FormatJson(primary.headers)}` + Chr(10) + `sq=0 HEAD status: ${fallback.statusCode.ToStr()} headers: ${FormatJson(fallback.headers)}`
end function end function
end namespace end namespace
@@ -1,4 +1,4 @@
import "pkg:/components/Services/Dash/LiveHeadCounts.bs" import "pkg:/components/Services/Dash/LiveLoadCounts.bs"
import "pkg:/components/VideoPlayerDev/VideoNode.bs" import "pkg:/components/VideoPlayerDev/VideoNode.bs"
import "pkg:/source/utils/ErrorUtils.bs" import "pkg:/source/utils/ErrorUtils.bs"
import "pkg:/source/utils/Locale.bs" import "pkg:/source/utils/Locale.bs"
@@ -345,10 +345,11 @@ namespace PlaybackTelemetry
"tail_resolve_samples": m.tailResolveSamples "tail_resolve_samples": m.tailResolveSamples
} }
if m.transport.isLive if m.transport.isLive
liveHead = StringUtils.ParseJsonSafe(ReadAsciiFile(LIVE_HEAD_COUNTS_PATH)) liveLoadCounts = StringUtils.ParseJsonSafe(ReadAsciiFile(LIVE_LOAD_COUNTS_PATH))
if liveHead <> invalid and liveHead["video_load_id"] = summary["video_load_id"] if liveLoadCounts <> invalid and liveLoadCounts["video_load_id"] = summary["video_load_id"]
summary["live_head"] = liveHead["counts"] summary["live_head"] = liveLoadCounts["live_head"]
DeleteFile(LIVE_HEAD_COUNTS_PATH) summary["live_timeline"] = liveLoadCounts["live_timeline"]
DeleteFile(LIVE_LOAD_COUNTS_PATH)
end if end if
summary["start_segment_bitrate_bps"] = m.startSegmentBitrateBps summary["start_segment_bitrate_bps"] = m.startSegmentBitrateBps
summary["start_measured_bitrate_bps"] = m.startMeasuredBitrateBps summary["start_measured_bitrate_bps"] = m.startMeasuredBitrateBps
@@ -1,6 +1,6 @@
import "pkg:/components/Services/Dash/DashManifest.bs" import "pkg:/components/Services/Dash/DashManifest.bs"
import "pkg:/components/Services/Dash/LiveHeadChecks.bs" import "pkg:/components/Services/Dash/LiveHeadChecks.bs"
import "pkg:/components/Services/Dash/LiveHeadCounts.bs" import "pkg:/components/Services/Dash/LiveLoadCounts.bs"
import "pkg:/components/Services/Dash/LiveTimeline.types.bs" import "pkg:/components/Services/Dash/LiveTimeline.types.bs"
import "pkg:/components/Services/Innertube/LiveStreamInfo.bs" import "pkg:/components/Services/Innertube/LiveStreamInfo.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs" import "pkg:/components/Services/Invidious/InvidiousService.bs"
@@ -52,6 +52,7 @@ namespace Http
m.liveLeadMs = 0 m.liveLeadMs = 0
m.liveDriftMs = 0 m.liveDriftMs = 0
m.liveLastCheckJumped = false m.liveLastCheckJumped = false
m.liveTimelineCounts = invalid
m.reportedLiveCorrection = false m.reportedLiveCorrection = false
m.liveManifestTemplate = "" m.liveManifestTemplate = ""
m.liveManifestTemplateKey = invalid m.liveManifestTemplateKey = invalid
@@ -250,13 +251,13 @@ namespace Http
newest = head newest = head
end if end if
end for end for
WriteAsciiFile(LIVE_HEAD_COUNTS_PATH, FormatJson({ "video_load_id": m.cachedVideoLoadId, "counts": m.liveHeadChecks.counts }))
' Listed segments can't be withdrawn: the head only moves forward. ' Listed segments can't be withdrawn: the head only moves forward.
if newest <> invalid and newest.seqnum > m.liveHeadSeqnum if newest <> invalid and newest.seqnum > m.liveHeadSeqnum
m.AlignLiveTimeline(newest) m.AlignLiveTimeline(newest)
m.liveHeadSeqnum = newest.seqnum m.liveHeadSeqnum = newest.seqnum
end if end if
WriteAsciiFile(LIVE_LOAD_COUNTS_PATH, FormatJson({ "video_load_id": m.cachedVideoLoadId, "live_head": m.liveHeadChecks.counts, "live_timeline": m.liveTimelineCounts }))
end function end function
' Segments are listed at the duration at load, the stream's lifetime average: off ' Segments are listed at the duration at load, the stream's lifetime average: off
@@ -272,11 +273,23 @@ namespace Http
if head.timeMs = invalid or m.liveBaseTimeMs = invalid if head.timeMs = invalid or m.liveBaseTimeMs = invalid
return return
end if end if
' The cadence since the base.
sinceBaseDurationMs = Cint((head.timeMs - m.liveBaseTimeMs) / (head.seqnum - m.liveBaseSeqnum))
if sinceBaseDurationMs <= 0
LogWarnNoTelemetry("Live head time went back:", head.timeMs, "ms at", head.seqnum, "after", m.liveBaseTimeMs, "ms at", m.liveBaseSeqnum)
return
end if
durationRuns = m.liveDurationRuns durationRuns = m.liveDurationRuns
headEndMs = m.liveBaseEndMs + Cint(head.timeMs - m.liveBaseTimeMs) headEndMs = m.liveBaseEndMs + Cint(head.timeMs - m.liveBaseTimeMs)
driftMs = m.dashManifest.LiveSegmentStartMs(durationRuns, head.seqnum + 1) - headEndMs - m.liveLeadMs driftMs = m.dashManifest.LiveSegmentStartMs(durationRuns, head.seqnum + 1) - headEndMs - m.liveLeadMs
stepMs = driftMs - m.liveDriftMs stepMs = driftMs - m.liveDriftMs
m.liveDriftMs = driftMs m.liveDriftMs = driftMs
counts = m.liveTimelineCounts
counts["timed_checks"] += 1
counts["drift_ms_min"] = MathUtils.Min(counts["drift_ms_min"], driftMs)
counts["drift_ms_max"] = MathUtils.Max(counts["drift_ms_max"], driftMs)
counts["step_ms_min"] = MathUtils.Min(counts["step_ms_min"], stepMs)
counts["step_ms_max"] = MathUtils.Max(counts["step_ms_max"], stepMs)
lastCheckJumped = m.liveLastCheckJumped lastCheckJumped = m.liveLastCheckJumped
m.liveLastCheckJumped = false m.liveLastCheckJumped = false
listedDurationMs = durationRuns[durationRuns.Count() - 1].durationMs listedDurationMs = durationRuns[durationRuns.Count() - 1].durationMs
@@ -288,14 +301,9 @@ namespace Http
' large cadence error can leap too (a young stream between sparse checks): the ' large cadence error can leap too (a young stream between sparse checks): the
' next check measures it. ' next check measures it.
isStall = stepMs < -LIVE_STALL_JUMP_MS and not lastCheckJumped isStall = stepMs < -LIVE_STALL_JUMP_MS and not lastCheckJumped
durationMs = sinceBaseDurationMs
if isStall if isStall
durationMs = listedDurationMs durationMs = listedDurationMs
else
durationMs = Cint((head.timeMs - m.liveBaseTimeMs) / (head.seqnum - m.liveBaseSeqnum))
if durationMs <= 0
LogWarnNoTelemetry("Live head time went back:", head.timeMs, "ms at", head.seqnum, "after", m.liveBaseTimeMs, "ms at", m.liveBaseSeqnum)
return
end if
end if end if
fromSeqnum = m.dashManifest.LiveLastListedSeqnum(durationRuns, m.liveHeadSeqnum) + 1 fromSeqnum = m.dashManifest.LiveLastListedSeqnum(durationRuns, m.liveHeadSeqnum) + 1
@@ -316,6 +324,11 @@ namespace Http
durationRuns.Shift() durationRuns.Shift()
end while end while
durationRuns.Push({ fromSeqnum: fromSeqnum, startMs: startMs, durationMs: durationMs }) durationRuns.Push({ fromSeqnum: fromSeqnum, startMs: startMs, durationMs: durationMs })
counts["corrections"] += 1
if isStall
counts["stall_corrections"] += 1
end if
counts["duration_runs_max"] = MathUtils.Max(counts["duration_runs_max"], durationRuns.Count())
m.ReportLiveCorrection(head, durationMs, driftMs, stepMs, isStall) m.ReportLiveCorrection(head, durationMs, driftMs, stepMs, isStall)
end function end function
@@ -393,6 +406,16 @@ namespace Http
m.liveLeadMs = 0 m.liveLeadMs = 0
m.liveDriftMs = 0 m.liveDriftMs = 0
m.liveLastCheckJumped = false m.liveLastCheckJumped = false
m.liveTimelineCounts = {
"timed_checks": 0
"corrections": 0
"stall_corrections": 0
"drift_ms_min": 0
"drift_ms_max": 0
"step_ms_min": 0
"step_ms_max": 0
"duration_runs_max": m.liveDurationRuns.Count()
}
m.reportedLiveCorrection = false m.reportedLiveCorrection = false
m.liveManifestTemplate = "" m.liveManifestTemplate = ""
m.liveManifestTemplateKey = invalid m.liveManifestTemplateKey = invalid
@@ -7,7 +7,8 @@ import "pkg:/source/utils/Types.bs"
' /delay/<ms> 200 after <ms> ' /delay/<ms> 200 after <ms>
' /echo 200 with the request's { method, path, headers, body } as JSON ' /echo 200 with the request's { method, path, headers, body } as JSON
' /maxage/<seconds>/<id> 200 with Cache-Control: max-age=<seconds> ' /maxage/<seconds>/<id> 200 with Cache-Control: max-age=<seconds>
' A path in routes (its query aside) responds as its route says instead: { status, headers, body, delayMs }. ' A path in routes responds as its route says instead: { status, headers, body, delayMs }. A route keyed
' with a query answers that query only, ahead of the route keyed with the bare path.
' A route { drop: true } closes the connection without a response. ' A route { drop: true } closes the connection without a response.
' Every response carries X-Hit, the request's count for its path. Connections are read and responded to ' Every response carries X-Hit, the request's count for its path. Connections are read and responded to
' without blocking each other, so a slow or abandoned one holds up nothing. ' without blocking each other, so a slow or abandoned one holds up nothing.
@@ -162,7 +163,11 @@ function BuildResponse(item as object) as object
m.top.lastRequest = request m.top.lastRequest = request
delayMs = MIN_RESPONSE_DELAY_MS delayMs = MIN_RESPONSE_DELAY_MS
route = ValidAssociativeArray(m.top.routes)[path.Split("?")[0]] routes = ValidAssociativeArray(m.top.routes)
route = routes[path]
if route = invalid
route = routes[path.Split("?")[0]]
end if
if route <> invalid if route <> invalid
if ValidInt(route.delayMs) > delayMs if ValidInt(route.delayMs) > delayMs
delayMs = route.delayMs delayMs = route.delayMs
@@ -140,6 +140,24 @@ namespace Tests
m.assertEqual(manifest.FormatDuration(999), "PT0.999S") m.assertEqual(manifest.FormatDuration(999), "PT0.999S")
m.assertEqual(manifest.FormatDuration(1500), "PT1.500S") m.assertEqual(manifest.FormatDuration(1500), "PT1.500S")
m.assertEqual(manifest.FormatDuration(10000), "PT10.000S") m.assertEqual(manifest.FormatDuration(10000), "PT10.000S")
m.assertEqual(manifest.FormatDuration(17900000123&), "PT17900000.123S")
end function
@describe("DashManifest.GetDurationMs")
@it("returns a post-live DVR duration past 32 bits")
function _()
manifest = new DashManifest("")
m.assertEqual(manifest.GetDurationMs({ isPostLiveDvr: true, postLiveDvrDurationMs: 17900000123& }), 17900000123&)
end function
@it("falls back to the first format's approxDurationMs, then to lengthSeconds")
function _()
manifest = new DashManifest("")
m.assertEqual(manifest.GetDurationMs({ adaptiveFormats: [{ approxDurationMs: "17900000123" }], lengthSeconds: 60 }), 17900000123&)
m.assertEqual(manifest.GetDurationMs({ adaptiveFormats: [{ approxDurationMs: "0" }], lengthSeconds: 60 }), 60000&)
m.assertEqual(manifest.GetDurationMs({ adaptiveFormats: [{}], lengthSeconds: 60 }), 60000&)
m.assertEqual(manifest.GetDurationMs({ isPostLiveDvr: true, adaptiveFormats: [], lengthSeconds: 60 }), 60000&)
end function end function
end class end class
@@ -160,6 +160,22 @@ namespace Tests
m.assertEqual(parsedResponse.error, `Live stream head check returned no X-Head-Seqnum / X-Head-Time (HTTP 200)\n`) m.assertEqual(parsedResponse.error, `Live stream head check returned no X-Head-Seqnum / X-Head-Time (HTTP 200)\n`)
end function end function
@describe("Innertube.FetchLiveHead")
@it("sends the check once more when the answer lacks the head, whatever its status")
function _()
m.server.routes = {
"/live/failing": { status: 503 }
"/live/failingwithhead": { status: 503, headers: { "X-Head-Seqnum": "40", "X-Head-Time-Millis": "80000" } }
}
failing = Tests.HttpTestServerUrl("/live/failing?itag=1")
m.assertFalse(Innertube.HasLiveHead(Innertube.FetchLiveHead(failing, invalid)))
m.assertEqual(Tests.HttpTestServerHits(m.server, failing), 2)
failingWithHead = Tests.HttpTestServerUrl("/live/failingwithhead?itag=1")
m.assertTrue(Innertube.HasLiveHead(Innertube.FetchLiveHead(failingWithHead, invalid)))
m.assertEqual(Tests.HttpTestServerHits(m.server, failingWithHead), 1)
end function
@describe("Innertube.ReadLiveHeadSeqnum") @describe("Innertube.ReadLiveHeadSeqnum")
@it("reads X-Head-Seqnum") @it("reads X-Head-Seqnum")
@@ -187,6 +203,15 @@ namespace Tests
m.assertInvalid(Innertube.ReadLiveHeadTimeSecAsMs(m.ResponseWithHeaders({ "X-Head-Time-Millis": "17900000123" }))) m.assertInvalid(Innertube.ReadLiveHeadTimeSecAsMs(m.ResponseWithHeaders({ "X-Head-Time-Millis": "17900000123" })))
end function end function
@describe("Innertube.ReadLiveHeadAnyTimeMs")
@it("reads X-Head-Time-Millis, else X-Head-Time-Sec")
function _()
m.assertEqual(Innertube.ReadLiveHeadAnyTimeMs(m.ResponseWithHeaders({ "X-Head-Time-Millis": "17900000123", "X-Head-Time-Sec": "17900000" })), 17900000123&)
m.assertEqual(Innertube.ReadLiveHeadAnyTimeMs(m.ResponseWithHeaders({ "X-Head-Time-Sec": "17900000" })), 17900000000&)
m.assertInvalid(Innertube.ReadLiveHeadAnyTimeMs(m.ResponseWithHeaders({ "X-Head-Seqnum": "40" })))
end function
function ResponseWithHeaders(headers as object) as HttpClient.Response function ResponseWithHeaders(headers as object) as HttpClient.Response
return new HttpClient.Response({ headers: headers }) return new HttpClient.Response({ headers: headers })
end function end function
@@ -1,6 +1,7 @@
import "pkg:/components/Services/Innertube/PostLiveDvrInfo.bs" import "pkg:/components/Services/Innertube/PostLiveDvrInfo.bs"
import "pkg:/source/tests/HttpTestServer.bs" import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs" import "pkg:/source/tests/LoggingGlobals.bs"
import "pkg:/source/utils/UrlUtils.bs"
namespace Tests namespace Tests
@@ -21,37 +22,52 @@ namespace Tests
m.global.telemetry.LogEvent = {} m.global.telemetry.LogEvent = {}
end function end function
@describe("Innertube.FetchPostLiveDvrHead")
@it("reads a HEAD's status and headers")
function _()
m.server.routes = { "/dvr/head": { status: 200, headers: { "X-Head-Seqnum": "40", "X-Head-Time-Millis": "80000" } } }
result = Innertube.FetchPostLiveDvrHead(Tests.HttpTestServerUrl("/dvr/head?itag=1"), invalid, "cpn1", Innertube.ClientType.Tv, invalid)
m.assertEqual(result.statusCode, 200)
m.assertTrue(Innertube.HasPostLiveDvrHead(result))
m.assertEqual(Tests.HttpTestServerHits(m.server, result.url), 1)
end function
@it("sends a failed HEAD once more")
function _()
m.server.routes = { "/dvr/failing": { status: 503 } }
result = Innertube.FetchPostLiveDvrHead(Tests.HttpTestServerUrl("/dvr/failing?itag=1"), "0", invalid, Innertube.ClientType.Tv, invalid)
m.assertEqual(result.statusCode, 503)
m.assertFalse(Innertube.HasPostLiveDvrHead(result))
m.assertEqual(Tests.HttpTestServerHits(m.server, result.url), 2)
end function
@describe("Innertube.GetPostLiveDvrInfo") @describe("Innertube.GetPostLiveDvrInfo")
@it("reads the duration and segment count from the live edge's head") @it("reads the duration and segment count from the live edge's head")
function _() function _()
m.server.routes = { "/dvr/ended": { status: 200, headers: { "X-Head-Seqnum": "40", "X-Head-Time-Millis": "80000" } } } m.server.routes = { "/dvr/ended": { status: 200, headers: { "X-Head-Seqnum": "40", "X-Head-Time-Millis": "80000" } } }
parsedResponse = {} parsedResponse = {}
Innertube.GetPostLiveDvrInfo(parsedResponse, [{ url: Tests.HttpTestServerUrl("/dvr/ended?itag=1") }], invalid, Innertube.ClientType.Tv, invalid) Innertube.GetPostLiveDvrInfo(parsedResponse, [{ url: Tests.HttpTestServerUrl("/dvr/ended?itag=1") }], invalid, invalid)
m.assertEqual(parsedResponse.postLiveDvrDurationMs, 80000) m.assertEqual(parsedResponse.postLiveDvrDurationMs, 80000)
m.assertEqual(parsedResponse.postLiveDvrSegmentCount, 40) m.assertEqual(parsedResponse.postLiveDvrSegmentCount, 40)
end function end function
@it("reads a duration past 32 bits")
function _()
m.server.routes = { "/dvr/long": { status: 200, headers: { "X-Head-Seqnum": "3580000", "X-Head-Time-Millis": "17900000123" } } }
parsedResponse = {}
Innertube.GetPostLiveDvrInfo(parsedResponse, [{ url: Tests.HttpTestServerUrl("/dvr/long?itag=1") }], invalid, invalid)
m.assertEqual(parsedResponse.postLiveDvrDurationMs, 17900000123&)
m.assertEqual(parsedResponse.postLiveDvrSegmentCount, 3580000)
end function
@it("reads the head from sq=0 when the live edge has none")
function _()
formatUrl = Tests.HttpTestServerUrl("/dvr/cached?itag=1")
fallbackUrl = UrlUtils.AppendQueryParams(Innertube.GetLiveHeadUrl(formatUrl, "cpn1"), { "sq": "0" })
routes = { "/dvr/cached": { status: 200 } }
routes[fallbackUrl.Replace(Tests.HttpTestServerUrl(""), "")] = { status: 200, headers: { "X-Head-Seqnum": "40", "X-Head-Time-Millis": "80000" } }
m.server.routes = routes
parsedResponse = {}
Innertube.GetPostLiveDvrInfo(parsedResponse, [{ url: formatUrl }], "cpn1", invalid)
m.assertEqual(Tests.HttpTestServerHits(m.server, Innertube.GetLiveHeadUrl(formatUrl, "cpn1")), 2)
m.assertEqual(Tests.HttpTestServerHits(m.server, fallbackUrl), 1)
m.assertEqual(parsedResponse.postLiveDvrDurationMs, 80000)
m.assertEqual(parsedResponse.postLiveDvrSegmentCount, 40)
end function
@it("sets nothing when neither the live edge nor sq=0 has a head")
function _()
m.server.routes = { "/dvr/nohead": { status: 200 } }
formatUrl = Tests.HttpTestServerUrl("/dvr/nohead?itag=1")
parsedResponse = {}
Innertube.GetPostLiveDvrInfo(parsedResponse, [{ url: formatUrl }], "cpn1", invalid)
m.assertEqual(Tests.HttpTestServerHits(m.server, UrlUtils.AppendQueryParams(Innertube.GetLiveHeadUrl(formatUrl, "cpn1"), { "sq": "0" })), 2)
m.assertFalse(parsedResponse.DoesExist("postLiveDvrDurationMs"))
m.assertFalse(parsedResponse.DoesExist("postLiveDvrSegmentCount"))
end function
end class end class
end namespace end namespace
@@ -388,34 +388,45 @@ namespace Tests
m.assertFalse(summary.DoesExist("stream_source")) m.assertFalse(summary.DoesExist("stream_source"))
end function end function
@it("the live head check counts of the video load, without defaults, read once") @it("the live head check and timeline counts of the video load, without defaults, read once")
function _() function _()
m.fakeTransport.isLive = true m.fakeTransport.isLive = true
m.fakeTop.content.videoLoadId = "live1" m.fakeTop.content.videoLoadId = "live1"
WriteAsciiFile(LIVE_HEAD_COUNTS_PATH, FormatJson({ "video_load_id": "live1", "counts": { "checks_sent": 6, "answered_after_wait": 1, "timed_out": 0 } })) WriteAsciiFile(LIVE_LOAD_COUNTS_PATH, FormatJson({
"video_load_id": "live1"
"live_head": { "checks_sent": 6, "answered_after_wait": 1, "timed_out": 0 }
"live_timeline": { "timed_checks": 3, "corrections": 1, "stall_corrections": 0, "drift_ms_min": -3425, "drift_ms_max": 0, "duration_runs_max": 2 }
}))
summary = m.SendAt(1000) summary = m.SendAt(1000)
m.assertEqual(summary.live_head, { "checks_sent": 6, "answered_after_wait": 1 }) m.assertEqual(summary.live_head, { "checks_sent": 6, "answered_after_wait": 1 })
m.assertFalse(CreateObject("roFileSystem").Exists(LIVE_HEAD_COUNTS_PATH), "read once") m.assertEqual(summary.live_timeline, { "timed_checks": 3, "corrections": 1, "drift_ms_min": -3425, "duration_runs_max": 2 })
m.assertFalse(m.SendAt(2000).DoesExist("live_head")) m.assertFalse(CreateObject("roFileSystem").Exists(LIVE_LOAD_COUNTS_PATH), "read once")
summary = m.SendAt(2000)
m.assertFalse(summary.DoesExist("live_head"))
m.assertFalse(summary.DoesExist("live_timeline"))
end function end function
@it("a live play without live head check counts has none") @it("a live play without live load counts has none")
function _() function _()
m.fakeTransport.isLive = true m.fakeTransport.isLive = true
m.fakeTop.content.videoLoadId = "live1" m.fakeTop.content.videoLoadId = "live1"
DeleteFile(LIVE_HEAD_COUNTS_PATH) DeleteFile(LIVE_LOAD_COUNTS_PATH)
m.assertFalse(m.SendAt(1000).DoesExist("live_head")) summary = m.SendAt(1000)
m.assertFalse(summary.DoesExist("live_head"))
m.assertFalse(summary.DoesExist("live_timeline"))
end function end function
@it("leaves the live head check counts of another video load") @it("leaves the live load counts of another video load")
function _() function _()
m.fakeTransport.isLive = true m.fakeTransport.isLive = true
m.fakeTop.content.videoLoadId = "live1" m.fakeTop.content.videoLoadId = "live1"
handoff = FormatJson({ "video_load_id": "live2", "counts": { "checks_sent": 6 } }) handoff = FormatJson({ "video_load_id": "live2", "live_head": { "checks_sent": 6 }, "live_timeline": { "corrections": 1 } })
WriteAsciiFile(LIVE_HEAD_COUNTS_PATH, handoff) WriteAsciiFile(LIVE_LOAD_COUNTS_PATH, handoff)
m.assertFalse(m.SendAt(1000).DoesExist("live_head")) summary = m.SendAt(1000)
m.assertEqual(ReadAsciiFile(LIVE_HEAD_COUNTS_PATH), handoff) m.assertFalse(summary.DoesExist("live_head"))
DeleteFile(LIVE_HEAD_COUNTS_PATH) m.assertFalse(summary.DoesExist("live_timeline"))
m.assertEqual(ReadAsciiFile(LIVE_LOAD_COUNTS_PATH), handoff)
DeleteFile(LIVE_LOAD_COUNTS_PATH)
end function end function
@it("a live play: the first video segment's bitrate and the network's at the first playing") @it("a live play: the first video segment's bitrate and the network's at the first playing")
@@ -32,7 +32,7 @@ namespace Tests
end function end function
protected override function afterEach() protected override function afterEach()
DeleteFile(LIVE_HEAD_COUNTS_PATH) DeleteFile(LIVE_LOAD_COUNTS_PATH)
end function end function
' What VideoContentJob sets on the player's content for a video load. ' What VideoContentJob sets on the player's content for a video load.
@@ -172,15 +172,18 @@ namespace Tests
m.assertInvalid(pending["_fetch"]["_urlTransfer"]) m.assertInvalid(pending["_fetch"]["_urlTransfer"])
end function end function
@it("writes the load's head check counts at every refresh") @it("writes the load's head check and timeline counts at every refresh, after its correction")
function _() function _()
m.LoadLive([{ seqnum: 10, timeMs: 18630 }, { seqnum: -1, timeMs: invalid }]) m.LoadLive([{ seqnum: 10, timeMs: 18630 }, { seqnum: -1, timeMs: invalid }])
m.RefreshDue() m.RefreshDue()
handoff = StringUtils.ParseJsonSafe(ReadAsciiFile(LIVE_LOAD_COUNTS_PATH))
m.assertEqual(handoff["live_timeline"]["corrections"], 1)
m.RefreshDue() m.RefreshDue()
handoff = StringUtils.ParseJsonSafe(ReadAsciiFile(LIVE_HEAD_COUNTS_PATH)) handoff = StringUtils.ParseJsonSafe(ReadAsciiFile(LIVE_LOAD_COUNTS_PATH))
m.assertEqual(handoff["video_load_id"], "live1") m.assertEqual(handoff["video_load_id"], "live1")
m.assertEqual(handoff["counts"]["checks_sent"], 2) m.assertEqual(handoff["live_head"]["checks_sent"], 2)
m.assertEqual(handoff["counts"]["answered_without_head"], 1) m.assertEqual(handoff["live_head"]["answered_without_head"], 1)
m.assertEqual(handoff["live_timeline"], m.router.liveTimelineCounts)
end function end function
@it("gives a list behind the head the cadence since load; the load head ended where the list stays ahead") @it("gives a list behind the head the cadence since load; the load head ended where the list stays ahead")
@@ -220,6 +223,16 @@ namespace Tests
' head 5: 600 ms behind, within half a segment ' head 5: 600 ms behind, within half a segment
m.RefreshDue() m.RefreshDue()
m.assertEqual(m.router.liveDurationRuns.Count(), 1) m.assertEqual(m.router.liveDurationRuns.Count(), 1)
m.assertEqual(m.router.liveTimelineCounts, {
"timed_checks": 1
"corrections": 0
"stall_corrections": 0
"drift_ms_min": -600
"drift_ms_max": 0
"step_ms_min": -600
"step_ms_max": 0
"duration_runs_max": 1
})
' head 15 ends at 6000 + 28600 = 34600, listed at 32000: 5 onwards (4 is the last ' head 15 ends at 6000 + 28600 = 34600, listed at 32000: 5 onwards (4 is the last
' listed) take 2200 ms, placed to end 15 there: from 10400, past 4's end (10000) ' listed) take 2200 ms, placed to end 15 there: from 10400, past 4's end (10000)
m.global.telemetry.LogEvent = {} m.global.telemetry.LogEvent = {}
@@ -233,6 +246,17 @@ namespace Tests
m.RefreshDue() m.RefreshDue()
m.assertEqual(m.router.liveDurationRuns, [{ fromSeqnum: 5, startMs: 10400, durationMs: 2200 }, { fromSeqnum: 15, startMs: 91600 - 26 * 2253, durationMs: 2253 }]) m.assertEqual(m.router.liveDurationRuns, [{ fromSeqnum: 5, startMs: 10400, durationMs: 2200 }, { fromSeqnum: 15, startMs: 91600 - 26 * 2253, durationMs: 2253 }])
m.assertEmpty(m.global.telemetry.LogEvent) m.assertEmpty(m.global.telemetry.LogEvent)
' drift -600, -2600, then -2000 off the realigned list
m.assertEqual(m.router.liveTimelineCounts, {
"timed_checks": 3
"corrections": 2
"stall_corrections": 0
"drift_ms_min": -2600
"drift_ms_max": 0
"step_ms_min": -2000
"step_ms_max": 0
"duration_runs_max": 2
})
end function end function
@it("takes a stall as a gap: the cadence stays, and the list stays on the head after it") @it("takes a stall as a gap: the cadence stays, and the list stays on the head after it")
@@ -256,6 +280,9 @@ namespace Tests
end for end for
m.assertEqual(m.router.liveDurationRuns.Count(), 2) m.assertEqual(m.router.liveDurationRuns.Count(), 2)
m.assertEqual(m.router.liveLeadMs, 0) m.assertEqual(m.router.liveLeadMs, 0)
m.assertEqual(m.router.liveTimelineCounts["corrections"], 1)
m.assertEqual(m.router.liveTimelineCounts["stall_corrections"], 1)
m.assertEqual(m.router.liveTimelineCounts["step_ms_min"], -90000)
end function end function
@it("takes a list ahead by more than the stall bound as cadence: a stall before load heals at once") @it("takes a list ahead by more than the stall bound as cadence: a stall before load heals at once")
@@ -264,6 +291,9 @@ namespace Tests
m.LoadLive([{ seqnum: 10, timeMs: 40000 }, { seqnum: 15, timeMs: 50000 }], { liveHeadSeqnum: 5, liveHeadTimeMs: 30000, liveSegmentDurationMs: 6000 }) m.LoadLive([{ seqnum: 10, timeMs: 40000 }, { seqnum: 15, timeMs: 50000 }], { liveHeadSeqnum: 5, liveHeadTimeMs: 30000, liveSegmentDurationMs: 6000 })
m.RefreshDue() m.RefreshDue()
m.assertEqual(m.router.liveDurationRuns[1].durationMs, 2000) m.assertEqual(m.router.liveDurationRuns[1].durationMs, 2000)
' head 10 ends at 36000 + 10000, listed to end at 11 x 6000
m.assertEqual(m.router.liveTimelineCounts["drift_ms_max"], 20000)
m.assertEqual(m.router.liveTimelineCounts["step_ms_max"], 20000)
m.RefreshDue() m.RefreshDue()
m.assertEqual(m.router.liveDurationRuns.Count(), 2) m.assertEqual(m.router.liveDurationRuns.Count(), 2)
end function end function
@@ -318,8 +348,25 @@ namespace Tests
m.RefreshDue() m.RefreshDue()
m.assertEqual(m.router.liveHeadSeqnum, 7) m.assertEqual(m.router.liveHeadSeqnum, 7)
m.assertEqual(m.router.liveDurationRuns.Count(), 1) m.assertEqual(m.router.liveDurationRuns.Count(), 1)
m.assertEqual(m.router.liveTimelineCounts["timed_checks"], 0)
m.RefreshDue() m.RefreshDue()
m.assertEqual(m.router.liveDurationRuns.Count(), 2) m.assertEqual(m.router.liveDurationRuns.Count(), 2)
m.assertEqual(m.router.liveTimelineCounts["timed_checks"], 1)
end function
@it("skips a head check whose time went back, unmeasured, and corrects at a later one")
function _()
' the load head (2) is at 2630 ms; head 7 claims 2000
m.LoadLive([{ seqnum: 7, timeMs: 2000 }, { seqnum: 12, timeMs: 22630 }])
m.RefreshDue()
m.assertEqual(m.router.liveHeadSeqnum, 7)
m.assertEqual(m.router.liveDurationRuns.Count(), 1)
m.assertEqual(m.router.liveDriftMs, 0)
m.assertEqual(m.router.liveTimelineCounts["timed_checks"], 0)
m.assertEqual(m.router.liveTimelineCounts["drift_ms_max"], 0)
m.RefreshDue()
m.assertEqual(m.router.liveDurationRuns.Count(), 2)
m.assertEqual(m.router.liveTimelineCounts["timed_checks"], 1)
end function end function
@it("times the head of a stream live for 111 days (head time past 32 bits)") @it("times the head of a stream live for 111 days (head time past 32 bits)")
+2 -2
View File
@@ -58,9 +58,9 @@ function ValidDouble(obj as dynamic) as double
end if end if
end function end function
' Returns true if the given object is numeric (Integer, Float, or Double) ' Returns true if the given object is numeric (Integer, LongInteger, Float, or Double)
function IsNumber(obj as dynamic) as boolean function IsNumber(obj as dynamic) as boolean
return obj <> invalid and (GetInterface(obj, "ifInt") <> invalid or GetInterface(obj, "ifFloat") <> invalid or GetInterface(obj, "ifDouble") <> invalid) return obj <> invalid and (GetInterface(obj, "ifInt") <> invalid or GetInterface(obj, "ifLongInt") <> invalid or GetInterface(obj, "ifFloat") <> invalid or GetInterface(obj, "ifDouble") <> invalid)
end function end function
' Returns true if the given object is of type String, false otherwise ' Returns true if the given object is of type String, false otherwise
@@ -23,6 +23,16 @@ namespace Tests
m.assertEqual(ValidString(obj), expected) m.assertEqual(ValidString(obj), expected)
end function end function
@it("Checks if an object is a number")
function _()
m.assertTrue(IsNumber(-5))
m.assertTrue(IsNumber(17900000123&))
m.assertTrue(IsNumber(1.5!))
m.assertTrue(IsNumber(1.5#))
m.assertFalse(IsNumber("5"))
m.assertFalse(IsNumber(invalid))
end function
end class end class
end namespace end namespace