Files
playlet-piped/playlet-lib/src/components/Web/PlayletWebServer/Middleware/DashRouter.bs
T

661 lines
31 KiB
Plaintext

import "pkg:/components/Services/Dash/DashManifest.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/components/Web/WebServer/Http/HttpRouter.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
' How many DASH segments ahead to warm per representation. On a request for segment
' N we Send (without Await) the next few so their downloads overlap N's await +
' playback; when the player asks for them the Await is short/instant. Small on
' purpose to bound concurrent roUrlTransfers (x2 representations).
const LIVE_PREFETCH_SEGMENTS = 2
namespace Http
class DashRouter extends HttpRouter
' Starting probe size for the live-segment box walk (see LocateBoxes):
' ftyp+moov+emsg sit well within this (observed ~920 bytes), so we never read
' the (large) mdat just to find where moof starts.
private INITIAL_PROBE_BYTE_COUNT = 2048
' Hard ceiling on the probe so a fragment that genuinely has no moof (corrupt)
' can't make us slurp a whole multi-hundred-KB mdat into memory while growing.
private MAX_PROBE_BYTE_COUNT = 65536
function new(server as object)
super()
m.videoQueueNode = server.sceneNodes.videoQueue
m.invidiousNode = server.sceneNodes.invidious
m.preferencesNode = server.sceneNodes.preferences
m.serverPort = server.settings.Port
m.invidiousService = new Invidious.InvidiousService(m.invidiousNode)
' No need to pass the invidious instance here, we will refresh it for
' each request to make sure we are using the latest one
m.dashManifest = new DashManifest("")
m.fs = CreateObject("roFileSystem")
' Live manifests are re-fetched every `minimumUpdatePeriod` (~20s), and
' reading metadata off the videoQueue node is a cross-thread rendezvous
' that deep-copies the whole (~39 KB) metadata AA. The metadata is
' immutable for a given videoId, so cache it and only dig the node when
' the video changes. The same dig also feeds the live-segment lookups
' below, so /api/dash and /api/dash/live-seg share one dig + one copy.
m.cachedVideoId = invalid
m.cachedBackend = invalid
m.cachedMetadata = invalid
' Live-segment caches, (re)built from the same metadata dig:
m.cachedUrls = {} ' itag -> signed base url
m.cachedTypes = {} ' itag -> "audio/mp4" | "video/mp4"
m.cachedInitSeqnum = 0 ' live-edge fragment to source the init from
m.probeByteCount = m.INITIAL_PROBE_BYTE_COUNT ' current box-walk probe; only grows
m.reportedFailures = {} ' per-video telemetry dedupe (see ReportSegmentFailure)
' Prefetch cache: "itag|nativeSq" -> in-flight StartSegmentFetch entry,
' warmed ahead of the player so awaits hit already-downloading fragments.
m.prefetch = {}
' Last itag served per media kind. When the player switches representation
' (ABR video / audio track), the previous itag's warmed entries are evicted
' so they don't leak until the next video change.
m.lastVideoItag = invalid
m.lastAudioItag = invalid
end function
' Returns the cached metadata AA for video id `v`, digging the videoQueue
' node (a render-thread rendezvous) only on a cache miss / video change. On a
' miss, also (re)builds the live-segment caches from the same copy.
function GetMetadata(v as string, backend as string) as dynamic
' Key on backend too, not just videoId: switching backends replays the
' same videoId but pushes fresh metadata onto the content node (different
' parser, different live fields). Keyed on videoId alone we'd keep serving
' the previous backend's stale copy. The backend is carried on the request
' query (set when the stream urls are built) so we never read the prefs
' node on this hot path.
if m.cachedVideoId = v and m.cachedBackend = backend and IsAssociativeArray(m.cachedMetadata)
return m.cachedMetadata
end if
metadata = ObjectUtils.DigUnsafe(m.videoQueueNode, ["player", "content", "metadata"])
if IsAssociativeArray(metadata) and metadata.videoId = v
m.cachedMetadata = metadata
m.cachedVideoId = v
m.cachedBackend = backend
m.RebuildLiveCache(metadata)
end if
return metadata
end function
@get("/api/dash")
function GenerateDashManifest(context as object) as boolean
request = context.request
response = context.response
url = request.query.url
if not StringUtils.IsNullOrEmpty(url)
return m.GenerateDashManifestAppendStoryboards(context)
end if
v = request.query.v
local = request.query.local
quality = request.query.quality
if StringUtils.IsNullOrEmpty(v)
response.Default(400, "Missing video id")
WriteAsciiFile("cachefs:/last_generated_dash.xml", "400 Missing video id")
return true
end if
metadata = m.GetMetadata(v, ValidString(request.query.backend))
if not IsAssociativeArray(metadata)
response.Default(500, "videoQueue.player.content.metadata is invalid")
WriteAsciiFile("cachefs:/last_generated_dash.xml", "500 videoQueue.player.content.metadata is invalid")
return true
end if
if metadata.videoId <> v
response.Default(400, "videoQueue.player.content.metadata.videoId does not match the requested video id")
WriteAsciiFile("cachefs:/last_generated_dash.xml", "400 videoQueue.player.content.metadata.videoId does not match the requested video id")
return true
end if
m.dashManifest.invidiousInstance = m.invidiousService.GetInstance()
m.dashManifest.disableAutoDubbed = ValidBool(m.preferencesNode["playback.disable_auto_dubbed"])
' For live streams, segments are addressed to the /api/dash/live-seg proxy
' on this same web server (the video player reaches it over 127.0.0.1).
m.dashManifest.liveSegmentBaseUrl = `http://127.0.0.1:${m.serverPort}`
m.dashManifest.liveBackend = ValidString(request.query.backend)
qualityFilter = m.CreateQualityFilter(quality)
xmlContent = m.dashManifest.FromVideoMetadata(metadata, qualityFilter, ValidString(local) = "true")
if xmlContent.InStr("[ERROR]") <> -1
LogErrorNoTelemetry("Dash manifest generated with errors")
lastPlayerResponse = ValidString(ReadAsciiFile("cachefs:/last_player_response.json"))
LogTelemetryEvent({
level: "error"
message: "Dash manifest generated with errors"
attachments: [{
filename: "dash.xml"
content_type: "text/plain"
data: xmlContent
}, {
filename: "last_player_response.json"
content_type: "application/json"
data: lastPlayerResponse
}]
})
end if
response.http_code = 200
response.SetBodyDataString(xmlContent)
response.ContentType("application/dash+xml")
WriteAsciiFile("cachefs:/last_generated_dash.xml", xmlContent)
return true
end function
function CreateQualityFilter(quality as dynamic) as object
qualityFilter = {}
if not IsString(quality)
return qualityFilter
end if
includeList = quality.split(",")
for each quality in includeList
if quality = "auto"
continue for
end if
pIndex = quality.InStr("p")
if pIndex <> -1
quality = quality.Mid(0, pIndex)
end if
qualityFilter[quality] = true
end for
return qualityFilter
end function
function GenerateDashManifestAppendStoryboards(context as object) as boolean
request = context.request
response = context.response
url = request.query.url
storyboards = ObjectUtils.DigUnsafe(m.videoQueueNode, ["player", "content", "metadata", "storyboards"])
if not IsArray(storyboards) or storyboards.count() = 0
response.Redirect(url)
return true
end if
dashRequest = HttpClient.Get(url)
dashResponse = dashRequest.Await()
if not dashResponse.IsSuccess()
LogError("Failed to fetch DASH manifest from URL", dashResponse.ErrorMessage())
response.Redirect(url)
return true
end if
dashContent = ValidString(dashResponse.Text())
storyboardIndex = dashContent.InStr("</Period>")
if storyboardIndex = -1
response.Redirect(url)
return true
end if
xml = new XmlObject()
manifestObj = new DashManifest("")
manifestObj.GenerateImageAdaptationSets(xml, storyboards, 100)
storyboardXml = xml.ToXmlString(false)
newDashContent = dashContent.Left(storyboardIndex) + storyboardXml + dashContent.Mid(storyboardIndex)
response.http_code = 200
response.SetBodyDataString(newDashContent)
response.ContentType("application/dash+xml")
return true
end function
' ------------------------------------------------------------------------
' Live segment proxy
'
' Proxies YouTube live segments so Roku can demux them as DASH. YouTube live
' fragments (`&sq=N`) are self-initializing: every fragment is
' `ftyp+moov+emsg+moof+mdat`. Standard DASH (and Roku) want the init segment to
' be `ftyp+moov` only and media segments to be `moof+mdat` only; a per-fragment
' moov makes Roku fail with `Cannot seek to video: error -36`. YouTube serves
' no clean init or moof-only media directly (`&range=` -> 400, the HTTP Range
' header is ignored), so this transform is unavoidable.
'
' Endpoint (see DashManifest live SegmentTemplate); segments map 1:1 to native
' fragments, so the DASH segment number is the native sq:
' /api/dash/live-seg?v=<id>&itag=<itag>&sq=init -> ftyp+moov of the live-edge fragment
' /api/dash/live-seg?v=<id>&itag=<itag>&sq=<N> -> moof+mdat of fragment N
'
' This is a hot path (called for every audio + video segment, continuously),
' so it is written to minimize per-request work: the itag -> url/type lookups
' and live-edge seqnum are resolved once per video id (shared with /api/dash via
' GetMetadata), the segment URL is a plain string concat (no URL parse/encode),
' and the moof/moov split reads only the needed byte ranges from the temp file.
' ------------------------------------------------------------------------
@get("/api/dash/live-seg")
function GetLiveSegment(context as object) as boolean
request = context.request
response = context.response
v = request.query.v
itag = request.query.itag
sq = request.query.sq
if StringUtils.IsNullOrEmpty(itag) or StringUtils.IsNullOrEmpty(sq) or StringUtils.IsNullOrEmpty(v)
response.Default(400, "Missing v, itag or sq")
return true
end if
' Warm the shared cache for this video (one node dig on a video change;
' the manifest request usually warmed it already).
m.GetMetadata(v, ValidString(request.query.backend))
baseUrl = m.cachedUrls[itag]
if StringUtils.IsNullOrEmpty(baseUrl)
LogErrorNoTelemetry("[LIVE-SEG] no live format url for v:", v, "itag:", itag, "-> 404")
m.ReportSegmentFailure("no live format url", { v: v, itag: itag, sq: sq })
response.Default(404, "No live format url for itag " + itag)
return true
end if
if sq = "init"
' Init segment: ftyp+moov. We must NOT use fragment 0 - for a
' long-running live stream (e.g. a 24/7 channel up for weeks) sq=0 is
' far outside the DVR window and googlevideo 404s it. Every live
' fragment is self-initializing with an identical moov (constant
' codec config), so we source the init from the live-edge fragment
' (cachedInitSeqnum), which is always within the DVR window.
output = m.AwaitTransformedSegment(m.StartSegmentFetch(baseUrl, m.cachedInitSeqnum, v, itag), true)
if output = invalid
' Root-cause telemetry already emitted by AwaitTransformedSegment.
LogErrorNoTelemetry("[LIVE-SEG] INIT fetch failed v:", v, "itag:", itag, "-> 502")
response.Default(502, "Failed to fetch live init segment")
return true
end if
else
' Media DASH segment = one native YouTube fragment, reduced to moof+mdat
' so Roku reads the init segment only once. The manifest addresses the
' proxy 1:1, so the DASH segment number is the native sq.
nativeSq = sq.ToInt()
' Representation switch (ABR video / audio track): the previous itag of
' this kind stops being requested, so evict its warmed fragments now -
' EvictPrefetchOutside is itag-scoped and would never reach them, so
' they'd otherwise leak (temp files + idle transfers) until video change.
if m.cachedTypes[itag] = "audio/mp4"
if IsString(m.lastAudioItag) and m.lastAudioItag <> itag
m.EvictPrefetchItag(m.lastAudioItag)
end if
m.lastAudioItag = itag
else
if IsString(m.lastVideoItag) and m.lastVideoItag <> itag
m.EvictPrefetchItag(m.lastVideoItag)
end if
m.lastVideoItag = itag
end if
' Reuse a warmed fetch if present, else start one. Warm the next few
' (Send, no Await) BEFORE blocking here so their downloads overlap this
' fragment's await + playback; then drop entries now outside the window
' (played past, or stranded by a seek) so the cache + temp files stay bounded.
entry = m.GetOrStartFetch(baseUrl, nativeSq, v, itag)
m.PrefetchAhead(baseUrl, v, itag, nativeSq, LIVE_PREFETCH_SEGMENTS)
m.EvictPrefetchOutside(itag, nativeSq + 1, nativeSq + LIVE_PREFETCH_SEGMENTS)
output = m.AwaitTransformedSegment(entry, false)
if output = invalid
' Root-cause telemetry already emitted by AwaitTransformedSegment.
LogErrorNoTelemetry("[LIVE-SEG] media fragment failed v:", v, "itag:", itag, "sq:", nativeSq, "-> 502")
response.Default(502, "Failed to fetch live media segment")
return true
end if
end if
response.http_code = 200
response.headers["Content-Type"] = m.cachedTypes[itag]
response.headers["Cache-Control"] = "no-cache, must-revalidate"
response.headers["Cross-Origin-Resource-Policy"] = "cross-origin"
response.SetBodyDataBuffer(output)
return true
end function
' (Re)build the live-segment lookups (itag -> url/type, live-edge seqnum) from
' an already-dug metadata AA - NO second node dig. Called from GetMetadata on a
' video change. Also sweeps orphaned temp files and re-arms the telemetry guard.
function RebuildLiveCache(metadata as object) as void
' Prefetched fetches from the previous video may still be in flight (they
' outlive the request that started them), so cancel them first - otherwise
' they'd race the sweep below (and keep writing temp files).
m.ClearPrefetch()
' Video changed: sweep any orphaned segment temp files. Each request
' deletes its own temp files on every path, so this is only a safety net
' for an unexpected error that skipped a delete - without it, tmp:/
' (RAM-backed, never reaped by the OS) could grow across a long session.
m.CleanupTempSegments()
' Re-arm the per-video telemetry dedupe (see ReportSegmentFailure).
m.reportedFailures = {}
urls = {}
types = {}
adaptiveFormats = ObjectUtils.DigUnsafe(metadata, ["adaptiveFormats"])
if IsArray(adaptiveFormats)
for each format in adaptiveFormats
if IsString(format.itag) and not StringUtils.IsNullOrEmpty(format.url)
urls[format.itag] = format.url
if IsString(format.type) and format.type.StartsWith("audio")
types[format.itag] = "audio/mp4"
else
types[format.itag] = "video/mp4"
end if
end if
end for
else
LogErrorNoTelemetry("[LIVE-SEG] RebuildLiveCache: adaptiveFormats not an array for v:", metadata.videoId)
m.ReportSegmentFailure("adaptiveFormats not an array", { v: ValidString(metadata.videoId) })
end if
m.cachedUrls = urls
m.cachedTypes = types
' Live-edge fragment to source the init segment from. Falls back to 0 if
' absent - fine for young streams where sq=0 is still inside the DVR window.
m.cachedInitSeqnum = ValidInt(ObjectUtils.DigUnsafe(metadata, ["liveHeadSeqnum"]))
end function
' Delete any leftover `tmp:/live-seg-*.m4s` files. Only our segment temp
' files match the prefix, so this never touches other tmp: data.
function CleanupTempSegments() as void
listing = m.fs.GetDirectoryListing("tmp:/")
if not IsArray(listing)
return
end if
for each name in listing
if IsString(name) and name.StartsWith("live-seg-")
DeleteFile(`tmp:/${name}`)
end if
end for
end function
' Start an async fetch of one YouTube live fragment (`&sq=N`) to a unique
' temp file. Returns the in-flight request plus the context the failure
' telemetry needs (v, itag, segUrl). The request is already sent (Send), so
' callers can start a whole group before awaiting any of them.
function StartSegmentFetch(baseUrl as string, sq as integer, v as string, itag as string) as object
' Plain concat: the base url is already a fully signed googlevideo url
' (it has a query string), so appending &sq/&rn is safe. Must NOT route
' through UrlUtils here - re-parsing/re-encoding the query breaks the
' signature (sig/n) and googlevideo returns 403; it is also far slower.
segUrl = `${baseUrl}&sq=${sq}&rn=0`
tmpPath = `tmp:/live-seg-${StringUtils.RandomId()}.m4s`
req = HttpClient.Get(segUrl).ToFile(tmpPath).NoCache().Send()
return { req: req, tmpPath: tmpPath, sq: sq, v: v, itag: itag, segUrl: segUrl }
end function
' Return a warmed (prefetched) fetch for this native fragment if present,
' consuming it from the cache; otherwise start a fresh one.
function GetOrStartFetch(baseUrl as string, sq as integer, v as string, itag as string) as object
key = `${itag}|${sq}`
if m.prefetch.DoesExist(key)
entry = m.prefetch[key]
m.prefetch.Delete(key)
return entry
end if
return m.StartSegmentFetch(baseUrl, sq, v, itag)
end function
' Send (without awaiting) the next `count` native fragments after `fromSq` so
' their downloads overlap the current segment. Already-warmed ones are left be.
function PrefetchAhead(baseUrl as string, v as string, itag as string, fromSq as integer, count as integer) as void
for i = 1 to count
key = `${itag}|${fromSq + i}`
if not m.prefetch.DoesExist(key)
m.prefetch[key] = m.StartSegmentFetch(baseUrl, fromSq + i, v, itag)
end if
end for
end function
' Drop warmed fragments for `itag` whose sq is outside [lowSq, highSq] - played
' past or stranded by a seek - cancelling the in-flight transfer and deleting
' its temp file so the cache and tmp:/ stay bounded.
function EvictPrefetchOutside(itag as string, lowSq as integer, highSq as integer) as void
prefix = `${itag}|`
stale = []
for each key in m.prefetch
if key.StartsWith(prefix)
sq = key.Mid(prefix.Len()).ToInt()
if sq < lowSq or sq > highSq
stale.Push(key)
end if
end if
end for
for each key in stale
m.DiscardFetch(m.prefetch[key])
m.prefetch.Delete(key)
end for
end function
' Cancel and drop every warmed fragment belonging to `itag` (used when the
' player switches away from a representation).
function EvictPrefetchItag(itag as string) as void
prefix = `${itag}|`
stale = []
for each key in m.prefetch
if key.StartsWith(prefix)
stale.Push(key)
end if
end for
for each key in stale
m.DiscardFetch(m.prefetch[key])
m.prefetch.Delete(key)
end for
end function
' Cancel every warmed fetch and clear the cache. Called on a video change
' before the temp-file sweep so in-flight prefetch transfers don't race it.
function ClearPrefetch() as void
for each key in m.prefetch
m.DiscardFetch(m.prefetch[key])
end for
m.prefetch = {}
m.lastVideoItag = invalid
m.lastAudioItag = invalid
end function
' Abort an in-flight fetch and delete its temp file (non-blocking).
function DiscardFetch(entry as object) as void
if not IsAssociativeArray(entry)
return
end if
if entry.req <> invalid and entry.req.urlTransfer <> invalid
entry.req.urlTransfer.AsyncCancel()
end if
DeleteFile(entry.tmpPath)
end function
' Await a fetch started by StartSegmentFetch and return just the bytes Roku
' needs:
' wantInit = true -> ftyp+moov (init segment)
' wantInit = false -> moof+mdat (media segment)
' Reads only the required byte range from the temp file and always deletes
' it. Returns invalid on failure.
function AwaitTransformedSegment(entry as object, wantInit as boolean) as dynamic
tmpPath = entry.tmpPath
sq = entry.sq
response = entry.req.Await()
if not response.IsSuccess()
LogErrorNoTelemetry("[LIVE-SEG] fetch sq", sq, "failed:", response.StatusCode())
m.ReportSegmentFailure("fragment fetch failed", { v: entry.v, itag: entry.itag, sq: sq, segUrl: entry.segUrl, response: response })
DeleteFile(tmpPath)
return invalid
end if
stat = m.fs.Stat(tmpPath)
fileLen = 0
if IsAssociativeArray(stat)
fileLen = ValidInt(stat.size)
end if
if fileLen <= 0
LogErrorNoTelemetry("[LIVE-SEG] fetch sq", sq, "empty file")
m.ReportSegmentFailure("empty fragment file", { v: entry.v, itag: entry.itag, sq: sq, segUrl: entry.segUrl, response: response })
DeleteFile(tmpPath)
return invalid
end if
boxes = m.LocateBoxes(tmpPath, fileLen)
out = CreateObject("roByteArray")
if wantInit
if boxes.moovEnd <= 0 or boxes.moovEnd > fileLen
LogErrorNoTelemetry("[LIVE-SEG] no moov in fragment sq", sq, "(moovEnd:", boxes.moovEnd, ")")
m.ReportSegmentFailure("no moov in fragment", { v: entry.v, itag: entry.itag, sq: sq, segUrl: entry.segUrl, response: response })
DeleteFile(tmpPath)
return invalid
end if
out.ReadFile(tmpPath, 0, boxes.moovEnd)
else
if boxes.moofStart <= 0 or boxes.moofStart >= fileLen
LogErrorNoTelemetry("[LIVE-SEG] no moof in fragment sq", sq, "(moofStart:", boxes.moofStart, ")")
m.ReportSegmentFailure("no moof in fragment", { v: entry.v, itag: entry.itag, sq: sq, segUrl: entry.segUrl, response: response })
DeleteFile(tmpPath)
return invalid
end if
out.ReadFile(tmpPath, boxes.moofStart, fileLen - boxes.moofStart)
end if
DeleteFile(tmpPath)
return out
end function
' Read the leading boxes of a fragment temp file and return moov/moof offsets.
' Starts with m.probeByteCount; if moof falls past the probe (a moov larger
' than expected), grow the probe (doubling, capped by file size and
' MAX_PROBE_BYTE_COUNT) and re-walk. A successful grow persists to
' m.probeByteCount so the rest of the session reads the larger window in one
' shot - the common (small-moov) case still does a single 2 KB read.
function LocateBoxes(tmpPath as string, fileLen as integer) as object
probeByteCount = m.probeByteCount
if probeByteCount > fileLen
probeByteCount = fileLen
end if
boxes = {}
while true
head = CreateObject("roByteArray")
head.ReadFile(tmpPath, 0, probeByteCount)
boxes = m.WalkBoxes(head)
' Self-initializing fragment = ftyp+moov+emsg+moof+mdat, so both
' offsets are present once the probe reaches moof. If the probe already
' covers the whole file (or we've hit the ceiling), stop regardless -
' a still-missing box is a genuine "no moof/moov", reported by caller.
foundBoth = boxes.moovEnd > 0 and boxes.moofStart > 0
if foundBoth or probeByteCount >= fileLen or probeByteCount >= m.MAX_PROBE_BYTE_COUNT
exit while
end if
nextByteCount = probeByteCount * 2
if nextByteCount > fileLen
nextByteCount = fileLen
end if
if nextByteCount > m.MAX_PROBE_BYTE_COUNT
nextByteCount = m.MAX_PROBE_BYTE_COUNT
end if
' Persist the grown probe for subsequent fragments this session.
probeByteCount = nextByteCount
m.probeByteCount = probeByteCount
LogWarnNoTelemetry("[LIVE-SEG] moof past probe; grew probe to", probeByteCount, "bytes")
end while
return boxes
end function
' Emit a rich, actionable telemetry event for a live-segment failure. The
' per-failure console logs above stay terse; this carries the detail needed to
' diagnose a YouTube-side break: video id, itag, sq, status code, error message,
' and the (signed) segment url.
'
' `info` keys (all optional): v, itag, sq, segUrl, response.
'
' Deduped to one event per (reason, status) per video session: enough to
' capture a transient blip and a later persistent failure separately, without
' flooding identical failures every few seconds (Sentry quota). Re-armed per
' video in RebuildLiveCache.
function ReportSegmentFailure(reason as string, info as object) as void
statusText = "n/a"
errorMessage = ""
response = info.response
if response <> invalid
statusText = Str(response.StatusCode()).Trim()
errorMessage = ValidString(response.ErrorMessage(false))
end if
dedupeKey = `${reason}:${statusText}`
if m.reportedFailures.DoesExist(dedupeKey)
return
end if
m.reportedFailures[dedupeKey] = true
details = [
"reason: " + reason
"videoId: " + ValidString(info.v)
"itag: " + ValidString(info.itag)
"sq: " + ToString(info.sq)
"status: " + statusText
"error: " + errorMessage
"url: " + ValidString(info.segUrl)
]
LogTelemetryEvent({
level: "error"
message: `[LIVE-SEG] ${reason} (status ${statusText})`
fingerprint: ["live-seg fetch failure", reason]
attachments: [{
filename: "live-seg-failure.txt"
content_type: "text/plain"
data: details.Join(Chr(10))
}]
})
end function
' Walk top-level ISO-BMFF boxes from the front, returning the byte offset
' where moov ends and where moof starts. Stops at moof, so it only ever
' reads the small leading boxes - never the large mdat.
function WalkBoxes(bytes as object) as object
moovEnd = 0
moofStart = 0
count = bytes.Count()
i = 0
while i + 8 <= count
' 32-bit big-endian box size. Leading boxes are small, so this
' arithmetic is overflow-safe.
size = (bytes[i] * 16777216) + (bytes[i + 1] * 65536) + (bytes[i + 2] * 256) + bytes[i + 3]
if size <= 0
exit while
end if
' Box type chars: 'm'=109 'o'=111 'v'=118 'f'=102. Compare the raw
' bytes (cheaper than building a string per box).
b4 = bytes[i + 4]
b5 = bytes[i + 5]
b6 = bytes[i + 6]
b7 = bytes[i + 7]
if b4 = 109 and b5 = 111 and b6 = 111 ' "moo*"
if b7 = 118 ' "moov"
moovEnd = i + size
else if b7 = 102 ' "moof"
moofStart = i
exit while
end if
end if
i += size
end while
return { moovEnd: moovEnd, moofStart: moofStart }
end function
end class
end namespace