Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
Generate videos longer than one clip and join them losslessly
Claude84c980bed629
diff --git a/docs/providers-and-models.md b/docs/providers-and-models.mdindex d17bd83db..61747ed9d 100644--- a/docs/providers-and-models.md+++ b/docs/providers-and-models.md@@ -302,6 +302,23 @@ can charge for a partner generation already in flight. Inline media is limited tas media assets, so their previews and save links survive panel reopening withoutputting base64 bytes in the run journal or model context.+With an OpenRouter video model, a video can be longer than one clip. The model+estimates how long the requested video should run (`estimated_duration`). A+single clip can set `duration`, `aspect_ratio` and `resolution`, which are+checked against the model's catalog entry (`supported_durations`,+`supported_aspect_ratios`, `supported_resolutions`) before anything is+submitted. A longer video is passed as `scenes`: WebBrain fits each scene to the+clip lengths the model offers, splitting a scene that is longer than its longest+clip, generates up to three clips at a time with one retry each, and joins them+into one MP4 without re-encoding (`src/*/src/agent/video-join.js`, which parses+the clips with the vendored mp4box.js). Videos are capped at 120 seconds and 24+clips. When the estimate is longer than 120 seconds, WebBrain asks on its own+card whether to generate the shorter version before any clip is submitted; the+card never times out, and an unattended run generates nothing. Clips whose+encodings differ, or that would join into more than 160 MB, are kept as separate+clips and shown in order. The model never sees the video, so the tool result+gives it the video's real length (`durationSeconds`) and `clipCount` to report.+The Act system prompt and planner direct the model to call `generate_image` whenthe user asks to generate media. Provider results are treated as untrusted content.Inline bytes are shown in chat and excluded from model context.diff --git a/package.json b/package.jsonindex 35c0ae609..f46485044 100644--- a/package.json+++ b/package.json@@ -84,7 +84,7 @@"test:cms:browser": "node --test test/cms-browser-smoke.mjs","test:compass-quota": "node --test test/compass-quota.mjs","test:compass-quota:ui": "node test/compass-quota-ui.mjs",- "test:generative-media": "node --test test/generative-media.mjs test/generative-media-availability.mjs",+ "test:generative-media": "node --test test/generative-media.mjs test/generative-media-availability.mjs test/generative-media-video.mjs","test:generative-media:ui": "node test/generative-media-ui.mjs","test:generative-media:extension": "node test/generative-media-extension.mjs","test:feedback": "node --test test/feedback-traces.mjs",diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex dc685546a..62185a534 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -7753,6 +7753,9 @@ export class Agent extends LoopDetector {if (data.unverifiedStepConfirmation) {display.unverifiedStepConfirmation = normalizeUnverifiedStepConfirmation(data.unverifiedStepConfirmation);}+ if (data.videoLengthConfirmation) {+ display.videoLengthConfirmation = record(data.videoLengthConfirmation, ['estimatedSeconds', 'totalSeconds', 'clipCount', 'maxSeconds']);+ }if (data.researchEscalation) display.researchEscalation = record(data.researchEscalation, ['engine', 'request'], 6000);if (data.workflowHealing) {const target = value => record(value, ['role', 'name', 'label', 'ariaLabel', 'placeholder',@@ -32738,6 +32741,50 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dclick: `Click this control on ${host}?` }[step?.action] || `Submit this on ${host}?`;}+ /**+ * video-length-cap: the requested video needs longer than WebBrain makes+ * (generative-media.js MAX_VIDEO_SECONDS), so before any clip is submitted+ * the user decides on WebBrain's card whether the shorter version the model+ * planned is worth generating. Each clip is billed, so the card never times+ * out and never goes ahead on its own; an unattended scheduled run cannot+ * ask and generates nothing. Returns 'once', 'deny', 'unavailable', or null+ * when Stop or a correction cancelled the card.+ */+ async _promptVideoLengthConfirmation(tabId, details = {}, onUpdate = null) {+ const seconds = value => Math.max(0, Math.round(Number(value) || 0));+ const confirmation = {+ estimatedSeconds: seconds(details.estimatedSeconds),+ totalSeconds: seconds(details.totalSeconds),+ clipCount: seconds(details.clipCount),+ maxSeconds: seconds(details.maxSeconds),+ };+ if (this.scheduledRunPolicies.get(tabId)?.requireConsequentialConfirmation === false) return 'unavailable';+ if (typeof onUpdate !== 'function') return 'unavailable';+ const clarifyId = `video_length_${secureRandomBase36Token(12)}`;+ const tabPending = this._pendingClarifications.get(tabId) || new Map();+ this._pendingClarifications.set(tabId, tabPending);+ const responsePromise = new Promise((resolve) => {+ tabPending.set(clarifyId, { resolve, ts: Date.now(), timer: null, settled: false, timeoutSec: 0, deadlineTs: 0, onUpdate });+ });+ const clock = value => (value < 60 ? `${value} s` : `${Math.floor(value / 60)}:${String(value % 60).padStart(2, '0')}`);+ try {+ onUpdate('clarify', {+ promptKind: 'video_length',+ clarifyId,+ // English for traces and surfaces without the side panel's localized copy.+ question: `This video needs about ${clock(confirmation.estimatedSeconds)}, but WebBrain makes videos up to `+ + `${clock(confirmation.maxSeconds)}. Generate a ${clock(confirmation.totalSeconds)} version from ${confirmation.clipCount} clips instead?`,+ videoLengthConfirmation: confirmation,+ options: ['once', 'deny'],+ });+ } catch { /* UI emit must never break the run */ }+ const response = await responsePromise;+ tabPending.delete(clarifyId);+ if (tabPending.size === 0 && this._pendingClarifications.get(tabId) === tabPending) this._pendingClarifications.delete(tabId);+ if (response?.cancelled) return null;+ return String(response?.answer || '').trim().toLowerCase() === 'once' ? 'once' : 'deny';+ }+// What an unverified-step card shows: text the guard already holds (a// composer snapshot) or the field read now. The digest binds the user's// answer to exactly this content; the text is bounded page content that@@ -43276,8 +43323,15 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d_limitToolResult(result, maxResultChars = STANDARD_TOOL_RESULT_CHARS) {maxResultChars = Number(maxResultChars) === 16000 ? 16000 : STANDARD_TOOL_RESULT_CHARS;// Inline media is rendered for the user; base64 bytes have no value in model context.+ // The model never sees the media, so it may report only what WebBrain knows.if (result?.success && result?.provider && (result.inlineMedia || /^data:(image|video|audio)\//.test(result.url || ''))) {- result = { ...result, url: undefined, mediaId: undefined, inlineMedia: true, note: 'Generated media is displayed in the chat with a save link. Tell the user it is ready; do not invent a hosted URL.' };+ const clips = Array.isArray(result.clips)+ ? result.clips.map(({ mediaId: _mediaId, ...clip }) => clip) : undefined;+ const note = 'Generated media is displayed in the chat with a save link. Tell the user it is ready. You have not seen it: '+ + 'describe it only by what you asked for and by its durationSeconds and clipCount when present, never by its contents; '+ + 'do not invent a hosted URL.'+ + (result.joined === false ? ' Its clips could not be joined into one file, so the chat shows them one after another.' : '');+ result = { ...result, url: undefined, mediaId: undefined, clips, inlineMedia: true, note };}const windowSafeResult = isReadPageWindowResult(result)? fitReadPageWindowResult(result, maxResultChars)@@ -48283,7 +48337,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn await fetchUrl(args.url, args, { tabId, signal: executionContext?._contentActionAbortSignal });}if (name === 'generate_image') {- return await generateImage(args, { signal: executionContext?._contentActionAbortSignal, ...(executionContext?.imageGenConfig ? { config: executionContext.imageGenConfig } : {}) });+ return await generateImage(args, {+ signal: executionContext?._contentActionAbortSignal,+ ...(executionContext?.imageGenConfig ? { config: executionContext.imageGenConfig } : {}),+ onProgress: message => onUpdate?.('tool_progress', { name, message }),+ confirmVideoLength: details => this._promptVideoLengthConfirmation(tabId, details, onUpdate),+ });}if (name === 'read_page_source') {return await readPageSource(args.url, args, { tabId, signal: executionContext?._contentActionAbortSignal });diff --git a/src/chrome/src/agent/generative-media.js b/src/chrome/src/agent/generative-media.jsindex ffbf00b49..5beabe33a 100644--- a/src/chrome/src/agent/generative-media.js+++ b/src/chrome/src/agent/generative-media.js@@ -1,9 +1,16 @@import { runFalGeneration, FAL_AUTH_PROBE_URL } from './fal-media.js';-import { storeGeneratedMedia } from '../generated-media-store.js';+import { MAX_JOINED_VIDEO_BYTES, storeGeneratedMedia, storeGeneratedMediaBlob } from '../generated-media-store.js';import { IMAGE_GEN_MODEL_KEY, MEDIA_PROVIDERS, mediaProvider, normalizeMediaModel, comfyBaseUrl, parseMediaJson, validateMediaConfig, bindMediaPrompt } from './media-config.js';+import { VideoJoinError, joinMp4Clips, mp4DurationSeconds } from './video-join.js';const GENERATION_TIMEOUT_MS = 600000;const MAX_INLINE_BYTES = 20 * 1024 * 1024;+// A video made of scenes: at most two minutes, one clip per scene or several+// when a scene is longer than the model's longest clip.+export const MAX_VIDEO_SECONDS = 120;+export const MAX_VIDEO_CLIPS = 24;+const VIDEO_CLIP_CONCURRENCY = 3;+const VIDEO_ARGUMENTS = ['duration', 'aspect_ratio', 'resolution', 'scenes', 'estimated_duration'];const INLINE_MEDIA = /^data:(image\/(?:png|jpeg|webp|gif)|audio\/(?:mpeg|wav|ogg)|video\/mp4);base64,[A-Za-z0-9+/=\s]+$/;export function safeMediaUrl(value) {@@ -100,22 +107,271 @@ async function mediaResponse(response, label) {return url;}-async function openRouterMediaType(model, headers, request) {+// The catalog entry lists what a video model accepts (supported_durations,+// supported_resolutions, supported_aspect_ratios).+async function openRouterMediaModel(model, headers, request) {for (const kind of ['images', 'videos']) {const catalog = await jsonResponse(await request(`https://openrouter.ai/api/v1/${kind}/models`, { headers }), `OpenRouter ${kind} models`);- if (catalog.data?.some(item => item.id === model)) return kind;+ const entry = Array.isArray(catalog.data) ? catalog.data.find(item => item?.id === model) : null;+ if (entry) return { kind, entry };}throw new Error('The selected OpenRouter model is not in the image or video generation catalog.');}-export async function runMediaGeneration({ prompt, config, fetchImpl = fetch, signal, timeoutMs = GENERATION_TIMEOUT_MS, pollIntervalMs }) {+async function openRouterMediaType(model, headers, request) {+ return (await openRouterMediaModel(model, headers, request)).kind;+}++function formatSeconds(seconds) {+ const whole = Math.round(seconds);+ return whole < 60 ? `${whole} s` : `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, '0')}`;+}++function videoArguments(args) {+ const video = {};+ for (const key of VIDEO_ARGUMENTS) if (args?.[key] !== undefined) video[key] = args[key];+ return Object.keys(video).length ? video : null;+}++function supportedValues(entry, key) {+ const values = entry?.[key];+ return Array.isArray(values) && values.length ? values : null;+}++function clipDurations(entry) {+ const values = supportedValues(entry, 'supported_durations');+ if (!values) return null;+ const durations = [...new Set(values.map(Number).filter(value => Number.isInteger(value) && value > 0))].sort((a, b) => a - b);+ return durations.length ? durations : null;+}++// aspect_ratio and resolution, checked against the model's catalog entry so an+// unsupported value fails before a paid submission.+function videoShape(entry, video) {+ const shape = {};+ for (const [name, key] of [['aspect_ratio', 'supported_aspect_ratios'], ['resolution', 'supported_resolutions']]) {+ if (video?.[name] === undefined) continue;+ const supported = supportedValues(entry, key);+ if (supported && !supported.some(value => String(value) === String(video[name]))) {+ throw new Error(`This video model does not support ${name} "${video[name]}". Supported: ${supported.join(', ')}.`);+ }+ shape[name] = String(video[name]);+ }+ return shape;+}++/**+ * The clips for a video described as scenes. A scene longer than the model's+ * longest clip becomes several clips, and every clip length rounds up to one+ * the model offers. Refuses more than `maxSeconds` in total or `maxClips`.+ */+export function planVideoClips(scenes, durations, { maxSeconds = MAX_VIDEO_SECONDS, maxClips = MAX_VIDEO_CLIPS } = {}) {+ if (!durations?.length) {+ throw new Error('This video model does not list the clip lengths it supports, so WebBrain cannot make a video from scenes with it. Generate one clip instead.');+ }+ const longest = durations[durations.length - 1];+ const clips = [];+ scenes.forEach((scene, index) => {+ const prompt = String(scene?.prompt || '').trim();+ if (!prompt) throw new Error(`Scene ${index + 1} needs a prompt.`);+ const parts = Math.ceil(scene.duration / longest);+ const each = Math.ceil(scene.duration / parts);+ for (let part = 1; part <= parts; part++) {+ clips.push({+ prompt: parts > 1 ? `${prompt} (part ${part} of ${parts})` : prompt,+ duration: durations.find(value => value >= each) ?? longest,+ });+ }+ });+ const total = clips.reduce((sum, clip) => sum + clip.duration, 0);+ if (clips.length > maxClips) {+ throw new Error(`These scenes need ${clips.length} clips and WebBrain makes at most ${maxClips}. Use fewer, longer scenes.`);+ }+ if (total > maxSeconds) {+ throw new Error(`These scenes come to ${total} s with this model's clip lengths (${durations.join(', ')} s), and WebBrain makes videos up to ${maxSeconds} s. Shorten or merge scenes.`);+ }+ return { clips, total };+}++// What one generate_image call asks a video model for: one clip, or the+// clips of its scenes.+function planVideo(prompt, video, entry) {+ const durations = clipDurations(entry);+ const shape = videoShape(entry, video);+ const scenes = Array.isArray(video?.scenes) ? video.scenes : null;+ if (scenes?.length) {+ if (video.duration !== undefined) throw new Error('With scenes, give each scene its duration instead of duration.');+ if (video.estimated_duration === undefined) {+ throw new Error('With scenes, give estimated_duration: how many seconds the requested video needs before fitting it to the 120 s maximum.');+ }+ const { clips, total } = planVideoClips(scenes, durations);+ return {+ scenes: true,+ total,+ estimated: video.estimated_duration,+ shape,+ // Every clip carries the shared look so the scenes match.+ clips: clips.map((clip, index) => ({ ...clip, prompt: `${prompt}\n\nScene ${index + 1} of ${clips.length}: ${clip.prompt}` })),+ };+ }+ const longest = durations?.[durations.length - 1];+ const wanted = video?.duration ?? video?.estimated_duration;+ if (wanted !== undefined && longest && wanted > longest) {+ throw new Error(`A ${formatSeconds(wanted)} video needs more than one clip: this model makes clips of up to ${longest} s. Describe it as scenes of up to ${longest} s each, ${MAX_VIDEO_SECONDS} s in total, with estimated_duration.`);+ }+ let duration;+ if (video?.duration !== undefined) {+ if (durations && !durations.includes(video.duration)) {+ throw new Error(`This video model does not make ${video.duration} s clips. Supported: ${durations.join(', ')} s.`);+ }+ duration = video.duration;+ } else if (wanted !== undefined && durations) {+ duration = durations.find(value => value >= wanted) ?? longest;+ }+ return { scenes: false, shape, clips: [{ prompt, ...(duration !== undefined ? { duration } : {}) }] };+}++function videoRequestBody(model, clip, shape) {+ return { model, prompt: clip.prompt, ...(clip.duration !== undefined ? { duration: clip.duration } : {}), ...shape };+}++// Submits one OpenRouter video job, polls it and returns the content response.+async function openRouterVideoJob({ base, headers, request, signal, pollMs, body }) {+ const res = await request(base, { method: 'POST', headers, body: JSON.stringify(body) });+ const queued = await jsonResponse(res, 'OpenRouter video submit');+ if (!/^[A-Za-z0-9_-]+$/.test(queued.id || '')) throw new Error('OpenRouter returned an invalid video job ID.');+ // Construct authenticated paths ourselves; returned URLs cannot select a key recipient.+ const jobUrl = `${base}/${queued.id}`;+ let waitMs = pollDelay(res, pollMs);+ while (true) {+ await delay(waitMs, signal);+ const statusRes = await request(jobUrl, { headers });+ const status = await jsonResponse(statusRes, 'OpenRouter video status');+ waitMs = pollDelay(statusRes, pollMs);+ if (status.status === 'completed') return request(`${jobUrl}/content?index=0`, { headers });+ if (!['pending', 'in_progress'].includes(status.status)) throw new Error(`OpenRouter video generation ${status.status || 'returned an unknown status'}.`);+ }+}++function dataUrlBytes(url) {+ const match = /^data:([^;]+);base64,([A-Za-z0-9+/=\s]+)$/.exec(url || '');+ if (!match) return null;+ const binary = atob(match[2].replace(/\s+/g, ''));+ return { bytes: Uint8Array.from(binary, char => char.charCodeAt(0)), mime: match[1] };+}++// A clip that will be joined is kept as bytes, not as a data URL.+async function videoBytes(response, label) {+ const mime = (response.headers?.get?.('Content-Type') || '').split(';')[0].trim();+ if (response.ok && mime === 'video/mp4') {+ const bytes = new Uint8Array(await response.arrayBuffer());+ if (bytes.length > MAX_INLINE_BYTES) throw new Error('A generated clip exceeds the 20 MB inline limit.');+ return bytes;+ }+ const decoded = dataUrlBytes(await mediaResponse(response, label));+ if (decoded?.mime !== 'video/mp4') throw new Error(`${label} did not return an MP4 video.`);+ return decoded.bytes;+}++// Runs `task` for each item, `limit` at a time. The first failure stops the+// others; Stop aborts them all with its own reason.+async function mapWithConcurrency(items, limit, signal, task) {+ const controller = new AbortController();+ const onAbort = () => controller.abort(signal.reason);+ if (signal?.aborted) onAbort(); else signal?.addEventListener('abort', onAbort, { once: true });+ const results = new Array(items.length);+ let next = 0;+ const worker = async () => {+ while (next < items.length && !controller.signal.aborted) {+ const index = next++;+ try { results[index] = await task(items[index], index, controller.signal); }+ catch (error) {+ if (!controller.signal.aborted) controller.abort(error);+ throw signal?.aborted ? signal.reason : error;+ }+ }+ };+ try {+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));+ controller.signal.throwIfAborted();+ return results;+ } finally { signal?.removeEventListener('abort', onAbort); }+}++async function runOpenRouter({ text, model, config, video, fetchImpl, signal, timeoutMs, pollMs, onProgress, confirmVideoLength }) {+ const headers = { Authorization: `Bearer ${config.apiKey}`, 'Content-Type': 'application/json' };+ // One bounded operation: its own deadline, aborted by Stop as well.+ const bounded = async (parent, task) => {+ const operation = operationSignal(parent, timeoutMs);+ const request = (url, init = {}) => {+ operation.signal.throwIfAborted();+ return fetchImpl(url, { ...init, signal: operation.signal, redirect: 'error', credentials: 'omit' });+ };+ try { return await task(request, operation.signal); }+ catch (error) { throw operation.signal.aborted ? operation.signal.reason : error; }+ finally { operation.dispose(); }+ };+ const base = 'https://openrouter.ai/api/v1/videos';+ let plan = null;+ const single = await bounded(signal, async (request, jobSignal) => {+ const { kind, entry } = await openRouterMediaModel(model, headers, request);+ if (kind === 'images') {+ if (video) throw new Error('Video length, aspect ratio, resolution and scenes need a video model; the selected OpenRouter model makes images.');+ const res = await request('https://openrouter.ai/api/v1/images', { method: 'POST', headers, body: JSON.stringify({ model, prompt: text }) });+ return { url: await mediaResponse(res, 'OpenRouter generation'), model };+ }+ plan = planVideo(text, video, entry);+ if (plan.scenes) return null;+ const res = await openRouterVideoJob({ base, headers, request, signal: jobSignal, pollMs, body: videoRequestBody(model, plan.clips[0], plan.shape) });+ return { url: await mediaResponse(res, 'OpenRouter video download'), model };+ });+ if (single) return single;++ // A video longer than WebBrain makes: the user decides on its card whether a+ // shorter version is worth generating, before anything is submitted. The+ // card is outside the generation deadline.+ const lengthDetails = { estimatedSeconds: plan.estimated, totalSeconds: plan.total, clipCount: plan.clips.length, maxSeconds: MAX_VIDEO_SECONDS };+ if (plan.estimated > MAX_VIDEO_SECONDS) {+ const answer = typeof confirmVideoLength === 'function' ? await confirmVideoLength(lengthDetails) : 'unavailable';+ signal?.throwIfAborted?.();+ if (answer !== 'once') return { declined: true, answer: answer || 'cancelled', model, ...lengthDetails };+ }+ onProgress?.(`Generating ${plan.clips.length} video clips…`);+ let ready = 0;+ const clips = await mapWithConcurrency(plan.clips, VIDEO_CLIP_CONCURRENCY, signal, async (clip, index, groupSignal) => {+ for (let attempt = 1; ; attempt++) {+ try {+ const bytes = await bounded(groupSignal, async (request, jobSignal) => videoBytes(+ await openRouterVideoJob({ base, headers, request, signal: jobSignal, pollMs, body: videoRequestBody(model, clip, plan.shape) }),+ 'OpenRouter video download'));+ ready += 1;+ onProgress?.(`Video clips: ${ready} of ${plan.clips.length} ready`);+ return bytes;+ } catch (error) {+ // One retry per clip; a second failure, Stop or another clip's failure ends the video.+ if (groupSignal.aborted || attempt >= 2) {+ throw groupSignal.aborted ? (groupSignal.reason ?? error) : new Error(`Clip ${index + 1} of ${plan.clips.length} failed: ${error.message}`);+ }+ }+ }+ });+ return { clips, model, ...lengthDetails };+}++export async function runMediaGeneration({ prompt, config, video = null, fetchImpl = fetch, signal, timeoutMs = GENERATION_TIMEOUT_MS, pollIntervalMs, onProgress, confirmVideoLength }) {const provider = validateMediaConfig(config);const text = String(prompt || '').trim();if (!text) throw new Error('prompt is required.');+ if (video && provider !== 'openrouter') {+ throw new Error(`Video length, aspect ratio, resolution and scenes work with OpenRouter video models. Omit them to use the ${MEDIA_PROVIDERS[provider].label} default.`);+ }if (provider === 'fal') return runFalGeneration({ prompt: text, config, fetchImpl, signal, timeoutMs });- const operation = operationSignal(signal, timeoutMs);const pollMs = pollIntervalMs ?? (provider === 'openrouter' ? 30000 : 2000);const model = provider === 'comfyui' ? 'ComfyUI workflow' : normalizeMediaModel(config.model);+ if (provider === 'openrouter') {+ return runOpenRouter({ text, model, config, video, fetchImpl, signal, timeoutMs, pollMs, onProgress, confirmVideoLength });+ }+ const operation = operationSignal(signal, timeoutMs);const request = (url, init = {}) => {operation.signal.throwIfAborted();return fetchImpl(url, { ...init, signal: operation.signal, redirect: 'error', credentials: 'omit' });@@ -123,32 +379,6 @@ export async function runMediaGeneration({ prompt, config, fetchImpl = fetch, silet cancelUrl = '', cancelInit;let completed = false;try {- if (provider === 'openrouter') {- const headers = { Authorization: `Bearer ${config.apiKey}`, 'Content-Type': 'application/json' };- const kind = await openRouterMediaType(model, headers, request);- const base = `https://openrouter.ai/api/v1/${kind}`;- const res = await request(base, {- method: 'POST', headers,- body: JSON.stringify({ model, prompt: text }),- });- if (kind === 'images') return { url: await mediaResponse(res, 'OpenRouter generation'), model };- const queued = await jsonResponse(res, 'OpenRouter video submit');- if (!/^[A-Za-z0-9_-]+$/.test(queued.id || '')) throw new Error('OpenRouter returned an invalid video job ID.');- // Construct authenticated paths ourselves; returned URLs cannot select a key recipient.- const jobUrl = `${base}/${queued.id}`;- let waitMs = pollDelay(res, pollMs);- while (true) {- await delay(waitMs, operation.signal);- const statusRes = await request(jobUrl, { headers });- const status = await jsonResponse(statusRes, 'OpenRouter video status');- waitMs = pollDelay(statusRes, pollMs);- if (status.status === 'completed') {- const result = await request(`${jobUrl}/content?index=0`, { headers });- return { url: await mediaResponse(result, 'OpenRouter video download'), model };- }- if (!['pending', 'in_progress'].includes(status.status)) throw new Error(`OpenRouter video generation ${status.status || 'returned an unknown status'}.`);- }- }if (provider === 'comfyrouter') {const base = `https://api.comfy.org/v2/models/${model}/requests`;const headers = { 'X-API-Key': config.apiKey, 'Content-Type': 'application/json' };@@ -215,17 +445,68 @@ export async function readMediaConfig() {return stored?.[IMAGE_GEN_MODEL_KEY];}+const roundSeconds = seconds => (Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds * 10) / 10 : undefined);++function declinedVideoMessage({ answer, estimatedSeconds, totalSeconds }) {+ const length = `The video needs about ${formatSeconds(estimatedSeconds)}, and WebBrain makes videos up to ${formatSeconds(MAX_VIDEO_SECONDS)}`;+ if (answer === 'deny') return `${length}. The user chose not to generate the ${formatSeconds(totalSeconds)} version, so nothing was generated. Ask what they would like instead.`;+ if (answer === 'unavailable') return `${length}. This run could not ask the user whether a ${formatSeconds(totalSeconds)} version is wanted, so nothing was generated. Tell the user.`;+ return `${length}. The question about a ${formatSeconds(totalSeconds)} version was withdrawn before an answer, so nothing was generated.`;+}++// Joins a video's clips into one stored asset. Clips that cannot be joined+// losslessly are stored one by one and shown in order.+async function storeVideoClips(clips, onProgress) {+ if (clips.length > 1) {+ try {+ onProgress?.(`Joining ${clips.length} clips…`);+ const joined = joinMp4Clips(clips, { maxBytes: MAX_JOINED_VIDEO_BYTES });+ const asset = await storeGeneratedMediaBlob(new Blob([joined.bytes], { type: 'video/mp4' }), { maxBytes: MAX_JOINED_VIDEO_BYTES });+ return { ...asset, durationSeconds: roundSeconds(joined.durationSeconds), clipCount: clips.length };+ } catch (error) {+ if (!(error instanceof VideoJoinError)) throw error;+ }+ }+ const stored = [];+ for (const bytes of clips) {+ const asset = await storeGeneratedMediaBlob(new Blob([bytes], { type: 'video/mp4' }));+ stored.push({ mediaId: asset.mediaId, mimeType: asset.mimeType, durationSeconds: roundSeconds(mp4DurationSeconds(bytes)) });+ }+ const durationSeconds = roundSeconds(stored.reduce((sum, clip) => sum + (clip.durationSeconds || 0), 0));+ if (stored.length === 1) return { ...stored[0], inlineMedia: true, durationSeconds, clipCount: 1 };+ return { inlineMedia: true, mimeType: 'video/mp4', clips: stored, clipCount: stored.length, durationSeconds, joined: false };+}++/**+ * The generate_image tool. `options.onProgress(message)` reports progress of+ * a video made of scenes, and `options.confirmVideoLength(details)` asks the+ * user when the requested video is longer than WebBrain makes ('once' to go+ * ahead; 'deny', 'unavailable' or null otherwise).+ */export async function generateImage(args, options = {}) {const fetchImpl = typeof options === 'function' ? options : options.fetchImpl || fetch;try {const config = Object.hasOwn(options, 'config') ? options.config : await readMediaConfig();if (!config) throw new Error('Configure Generative Media in Providers → Generative.');- const result = await runMediaGeneration({ prompt: args?.prompt, config, fetchImpl, signal: options.signal });+ const provider = mediaProvider(config);+ const result = await runMediaGeneration({+ prompt: args?.prompt, video: videoArguments(args), config, fetchImpl, signal: options.signal,+ onProgress: options.onProgress, confirmVideoLength: options.confirmVideoLength,+ });+ if (result.declined) {+ return { success: false, declined: true, provider, model: result.model, error: declinedVideoMessage(result) };+ }+ if (Array.isArray(result.clips)) {+ return { success: true, model: result.model, provider, ...(await storeVideoClips(result.clips, options.onProgress)) };+ }if (result.url.startsWith('data:')) {const asset = await storeGeneratedMedia(result.url);- return { success: true, model: result.model, provider: mediaProvider(config), ...asset };+ // A clip's real length, so the agent can say how long the video is.+ const video = asset.mimeType === 'video/mp4' ? dataUrlBytes(result.url) : null;+ const durationSeconds = video ? roundSeconds(mp4DurationSeconds(video.bytes)) : undefined;+ return { success: true, model: result.model, provider, ...asset, ...(durationSeconds ? { durationSeconds } : {}) };}- return { success: true, ...result, provider: mediaProvider(config) };+ return { success: true, ...result, provider };} catch (error) { return { success: false, error: error.message }; }}diff --git a/src/chrome/src/agent/guard-policy.js b/src/chrome/src/agent/guard-policy.jsindex c6e939d09..31b4f230e 100644--- a/src/chrome/src/agent/guard-policy.js+++ b/src/chrome/src/agent/guard-policy.js@@ -354,6 +354,9 @@ export const GUARDS = Object.freeze({summary: "The upload selector matched several file inputs (now or on the previous attempt, until an inspection runs)." },"upload-source-validation": { class: "infra", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",summary: "The local upload path is missing/unreadable (inconclusive probes pass as unverified), or the file bytes do not match, or cannot be verified against, the input accept types." },+ "video-length-cap": { class: "permission_gate", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "generate_image scenes over 120 s or 24 clips are refused before submission, and an estimate over 120 s asks the user on WebBrain's card before the shorter version is generated (an unattended run generates nothing).",+ mustNotBlock: "test/generative-media-video.mjs#a video of two minutes or less generates without asking" },"viewport-inspection-budget": { class: "permission_gate", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",summary: "inspect_viewport is skipped once the user-configured maxScreenshotsPerTurn budget is used up." },"webmcp-frame-binding": { class: "host_check", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",diff --git a/src/chrome/src/agent/scheduler.js b/src/chrome/src/agent/scheduler.jsindex 5e7df9a45..20fd87bfd 100644--- a/src/chrome/src/agent/scheduler.js+++ b/src/chrome/src/agent/scheduler.js@@ -188,6 +188,17 @@ function normalizePendingClarify(data, now = Date.now()) {if (unverifiedStep.guardId || unverifiedStep.action) {pending.unverifiedStepConfirmation = normalizeUnverifiedStepConfirmation(unverifiedStep);}+ // WebBrain's card about a video longer than it makes: the lengths it shows.+ const videoLength = asObject(obj.videoLengthConfirmation);+ if (Number(videoLength.estimatedSeconds) > 0) {+ const whole = value => Math.max(0, Math.min(86400, Math.round(Number(value) || 0)));+ pending.videoLengthConfirmation = {+ estimatedSeconds: whole(videoLength.estimatedSeconds),+ totalSeconds: whole(videoLength.totalSeconds),+ clipCount: whole(videoLength.clipCount),+ maxSeconds: whole(videoLength.maxSeconds),+ };+ }return pending;}diff --git a/src/chrome/src/agent/tools.js b/src/chrome/src/agent/tools.jsindex bc97cba95..1bce230f4 100644--- a/src/chrome/src/agent/tools.js+++ b/src/chrome/src/agent/tools.js@@ -35,7 +35,8 @@ const DONE_REQUIRED = ['summary'];const DONE_REQUIRED_WITH_OUTCOME = ['summary', 'outcome'];export const SYSTEM_PROMPT_GENERATIVE_MEDIA = `GENERATIVE MEDIA:-- generate_image: Create media (usually an image, sometimes video/audio) directly from a text prompt through the user's configured generative-media provider. When the user asks to GENERATE media ("generate an image of a red apple", "make a logo", "create a video clip"), call this tool — do NOT navigate to third-party image sites (Midjourney, DALL·E, Bing Images, etc.). Not available in Ask mode.`;+- generate_image: Create media (usually an image, sometimes video/audio) directly from a text prompt through the user's configured generative-media provider. When the user asks to GENERATE media ("generate an image of a red apple", "make a logo", "create a video clip"), call this tool — do NOT navigate to third-party image sites (Midjourney, DALL·E, Bing Images, etc.). Not available in Ask mode.+- Videos: estimate how long the requested video should run. One that needs more than one clip (an explainer, a story) is one call with scenes, at most 120 s in total, and estimated_duration set to the full length it needs; WebBrain joins the clips into one video and asks the user first when that estimate is longer than 120 s. You never see the result: report its length and clip count from the tool result, not its contents.`;export const SYSTEM_PROMPT_BATCHING = `BATCHING:- Use browser_batch for predictable steps on the current page with targets you already observed, such as filling known fields or opening a menu and choosing a known item. A navigation followed by a page read can also share one batch.@@ -1487,11 +1488,27 @@ export const AGENT_TOOLS = [type: 'function',function: {name: 'generate_image',- description: 'Generate media (usually an image) from a text prompt using the user\'s configured generative media provider (Providers → Generative). Supports fal.ai, OpenRouter, Comfy Router and local ComfyUI workflows; generation may take several minutes. Returns a media URL or inline media displayed in the chat. Not available in Ask mode.',+ description: 'Generate media (usually an image) from a text prompt using the user\'s configured generative media provider (Providers → Generative). Supports fal.ai, OpenRouter, Comfy Router and local ComfyUI workflows; generation may take several minutes. Returns a media URL or inline media displayed in the chat. With an OpenRouter video model, estimate how long the requested video should run (estimated_duration): one clip can set duration, aspect_ratio and resolution; a longer video passes scenes, which WebBrain fits to the model\'s clip lengths and joins into one video of up to 120 s, asking the user first when the estimate is longer. Not available in Ask mode.',parameters: {type: 'object',properties: {- prompt: { type: 'string', description: 'Text prompt describing the media to generate.' },+ prompt: { type: 'string', description: 'Text prompt describing the media to generate. With scenes: the look, subject and style every clip shares.' },+ estimated_duration: { type: 'integer', minimum: 1, description: 'Video only: seconds the requested video needs, estimated before fitting it to the 120 s maximum. Required with scenes.' },+ duration: { type: 'integer', minimum: 1, description: 'Video only: seconds for a single clip.' },+ aspect_ratio: { type: 'string', description: 'Video only, for example "16:9" or "9:16".' },+ resolution: { type: 'string', description: 'Video only, for example "720p".' },+ scenes: {+ type: 'array',+ description: 'Video only: the scenes of a video longer than one clip, in order, at most 120 seconds in total.',+ items: {+ type: 'object',+ properties: {+ prompt: { type: 'string', description: 'What this scene shows.' },+ duration: { type: 'integer', minimum: 1, description: 'Seconds.' },+ },+ required: ['prompt', 'duration'],+ },+ },},required: ['prompt'],},diff --git a/src/chrome/src/agent/video-join.js b/src/chrome/src/agent/video-join.jsnew file mode 100644index 000000000..5e430fb98--- /dev/null+++ b/src/chrome/src/agent/video-join.js@@ -0,0 +1,405 @@+// Joins generated MP4 clips into one MP4 without re-encoding.+//+// Clips from one video model share their codec setup, so their samples can be+// laid end to end: the joiner keeps the first clip's sample descriptions+// (stsd) and writes new sample tables for the combined timeline. Clips whose+// tracks or codec setup differ cannot be joined this way (`clips_incompatible`);+// the caller then shows them one after another instead. mp4box.js parses the+// input. The output is a plain (not fragmented) MP4 with moov before mdat.+//+// Shared byte for byte by the Chrome and Firefox builds.++import { createFile, MP4BoxBuffer } from '../../vendor/mp4box/mp4box.all.mjs';++export class VideoJoinError extends Error {+ constructor(message, code) {+ super(message);+ this.name = 'VideoJoinError';+ this.code = code;+ }+}++const incompatible = reason => new VideoJoinError(`The clips cannot be joined into one file: ${reason}.`, 'clips_incompatible');+const MEDIA_HEADER_TYPES = new Set(['vmhd', 'smhd', 'nmhd', 'sthd', 'hmhd']);+const MAX_UINT32 = 2 ** 32 - 1;++function toArrayBuffer(input) {+ if (input instanceof ArrayBuffer) return input;+ if (ArrayBuffer.isView(input)) return input.buffer.slice(input.byteOffset, input.byteOffset + input.byteLength);+ throw new VideoJoinError('Expected MP4 bytes.', 'not_mp4');+}++function sameBytes(a, b) {+ if (!a || !b || a.length !== b.length) return false;+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;+ return true;+}++function rawBox(bytes, box) {+ return box && Number.isInteger(box.start) && Number.isInteger(box.size) && box.size > 0+ ? bytes.subarray(box.start, box.start + box.size) : null;+}++// esds: ES_Descriptor (tag 3), then DecoderConfigDescriptor (tag 4) whose+// bufferSizeDB, maxBitrate and avgBitrate follow objectTypeIndication and+// streamType.+function blankEsdsBitrates(bytes, box, blank) {+ const end = box.start + box.size;+ let p = box.start + 12;+ const skipLength = () => {+ for (let i = 0; i < 4 && p < end; i++) if (!(bytes[p++] & 0x80)) break;+ };+ if (bytes[p++] !== 0x03) return;+ skipLength();+ p += 2;+ const flags = bytes[p++];+ if (flags & 0x80) p += 2;+ if (flags & 0x40) p += 1 + bytes[p];+ if (flags & 0x20) p += 2;+ if (bytes[p++] !== 0x04) return;+ skipLength();+ if (p + 13 <= end) blank(p + 2, p + 13);+}++// The sample description with this encode's bitrate figures blanked: every+// clip reports its own, and they do not change how the samples decode.+function sampleDescriptionKey(bytes, stsd) {+ const key = bytes.slice(stsd.start, stsd.start + stsd.size);+ const blank = (from, to) => key.fill(0, from - stsd.start, to - stsd.start);+ for (const entry of stsd.entries || []) {+ for (const child of entry.boxes || []) {+ if (!Number.isInteger(child.start) || !(child.size > 8)+ || child.start < stsd.start || child.start + child.size > stsd.start + stsd.size) continue;+ if (child.type === 'btrt') blank(child.start + 8, child.start + child.size);+ if (child.type === 'esds') blankEsdsBitrates(bytes, child, blank);+ }+ }+ return key;+}++function readTrack(trak, movieTimescale, bytes) {+ const mdia = trak?.mdia, minf = mdia?.minf, stbl = minf?.stbl;+ const handler = mdia?.hdlr?.handler;+ const timescale = mdia?.mdhd?.timescale;+ const samples = Array.isArray(trak?.samples) ? trak.samples : [];+ if (!stbl?.stsd || !(timescale > 0) || !samples.length) throw incompatible('a track has no samples');+ if ((stbl.stsd.entries?.length || 0) !== 1 || samples.some(sample => sample.description_index !== 0)) {+ throw incompatible('a track switches codec settings');+ }+ // Reordered frames (B-frames) are shown after they are decoded, so the+ // track's picture ends at its last composition time, not its last decode time.+ const compositionEnd = samples.reduce((end, sample) => Math.max(end, sample.cts + sample.duration), 0);+ // One edit that skips the codec's start-up delay is normal. Empty edits or+ // several edits describe a timeline these tables cannot carry over.+ const edits = trak.edts?.elst?.entries || [];+ if (edits.length > 1 || edits.some(edit => edit.media_time < 0 || edit.media_rate_integer !== 1)) {+ throw incompatible('a track has a complex edit list');+ }+ // Without an edit the track is shown from its first composition time+ // (fragmented files from some encoders start video after a B-frame delay).+ const mediaTime = edits.length ? edits[0].media_time : samples.reduce((min, sample) => Math.min(min, sample.cts), Infinity);+ const editDuration = edits.length && edits[0].segment_duration > 0+ ? Math.round(edits[0].segment_duration * timescale / movieTimescale) : compositionEnd - mediaTime;+ return {+ handler,+ timescale,+ samples,+ mediaTime,+ presented: Math.max(0, Math.min(editDuration, compositionEnd - mediaTime)),+ hasEdit: edits.length > 0,+ tkhd: trak.tkhd,+ language: mdia.mdhd.language,+ stsd: rawBox(bytes, stbl.stsd),+ stsdKey: sampleDescriptionKey(bytes, stbl.stsd),+ hdlr: rawBox(bytes, mdia.hdlr),+ mediaHeader: rawBox(bytes, (minf.boxes || []).find(box => MEDIA_HEADER_TYPES.has(box.type))),+ dinf: rawBox(bytes, (minf.boxes || []).find(box => box.type === 'dinf')),+ };+}++function parseClip(input) {+ const arrayBuffer = toArrayBuffer(input);+ const bytes = new Uint8Array(arrayBuffer);+ const file = createFile();+ let failed = false;+ file.onError = () => { failed = true; };+ try {+ file.appendBuffer(MP4BoxBuffer.fromArrayBuffer(arrayBuffer, 0));+ file.flush();+ } catch { failed = true; }+ const moov = file.moov;+ const movieTimescale = moov?.mvhd?.timescale;+ if (failed || !(movieTimescale > 0) || !Array.isArray(moov.traks) || !moov.traks.length) {+ throw new VideoJoinError('The clip is not a readable MP4 file.', 'not_mp4');+ }+ // Video first, then audio; other tracks (timed metadata) are not carried over.+ const order = { vide: 0, soun: 1 };+ const tracks = moov.traks+ .filter(trak => Object.hasOwn(order, trak.mdia?.hdlr?.handler))+ .map(trak => readTrack(trak, movieTimescale, bytes))+ .sort((a, b) => order[a.handler] - order[b.handler]);+ if (!tracks.length) throw incompatible('a clip has no video or audio track');+ const timing = tracks[0];+ return {+ bytes,+ movieTimescale,+ matrix: moov.mvhd.matrix,+ ftyp: rawBox(bytes, (file.boxes || []).find(box => box.type === 'ftyp')),+ tracks,+ duration: timing.presented / timing.timescale,+ };+}++/** Presented length of an MP4 in seconds, or null when it is not one. */+export function mp4DurationSeconds(input) {+ try { return parseClip(input).duration; } catch { return null; }+}++// Lays out one output track: each clip's samples in order, with the previous+// clip's last sample lengthened or shortened so that this clip starts where+// the timeline says. At each join the audio follows the picture: a later+// clip's codec start-up frames are dropped, and so are the previous clip's+// frames that would mostly play after this clip's audio begins (padding, or+// audio longer than the picture). Video frames are never dropped.+function joinTrack(clips, index, starts) {+ const first = clips[0].tracks[index];+ const samples = [];+ const chunks = [];+ clips.forEach((clip, clipIndex) => {+ const track = clip.tracks[index];+ const audio = track.handler === 'soun';+ const kept = audio && clipIndex > 0+ ? track.samples.filter(sample => sample.cts + sample.duration / 2 >= track.mediaTime)+ : track.samples;+ if (!kept.length) throw incompatible('a clip has an empty track');+ if (samples.length) {+ const target = Math.round(starts[clipIndex] * track.timescale) + (kept[0].dts - track.mediaTime) + first.mediaTime;+ const previous = chunks[chunks.length - 1];+ while (audio && previous.count > 1+ && samples[samples.length - 1].dts + samples[samples.length - 1].duration / 2 >= target) {+ previous.count -= 1;+ previous.size -= samples.pop().size;+ }+ const last = samples[samples.length - 1];+ last.duration = Math.max(1, target - last.dts);+ }+ let dts = samples.length ? samples[samples.length - 1].dts + samples[samples.length - 1].duration : 0;+ chunks.push({ clipIndex, first: samples.length, count: kept.length, size: 0, offset: 0 });+ const chunk = chunks[chunks.length - 1];+ for (const sample of kept) {+ samples.push({+ dts,+ duration: sample.duration,+ offset: sample.cts - sample.dts,+ size: sample.size,+ source: sample.offset,+ sync: sample.is_sync !== false,+ clipIndex,+ });+ chunk.size += sample.size;+ dts += sample.duration;+ }+ });+ const mediaDuration = samples.reduce((sum, sample) => sum + sample.duration, 0);+ return { first, samples, chunks, mediaDuration };+}++class Writer {+ constructor() {+ this.buffer = new Uint8Array(1 << 16);+ this.view = new DataView(this.buffer.buffer);+ this.position = 0;+ }+ ensure(length) {+ if (this.position + length <= this.buffer.length) return;+ let size = this.buffer.length * 2;+ while (size < this.position + length) size *= 2;+ const next = new Uint8Array(size);+ next.set(this.buffer.subarray(0, this.position));+ this.buffer = next;+ this.view = new DataView(next.buffer);+ }+ u8(value) { this.ensure(1); this.view.setUint8(this.position, value); this.position += 1; }+ u16(value) { this.ensure(2); this.view.setUint16(this.position, value); this.position += 2; }+ i16(value) { this.ensure(2); this.view.setInt16(this.position, value); this.position += 2; }+ u32(value) { this.ensure(4); this.view.setUint32(this.position, value); this.position += 4; }+ i32(value) { this.ensure(4); this.view.setInt32(this.position, value); this.position += 4; }+ bytes(value) { this.ensure(value.length); this.buffer.set(value, this.position); this.position += value.length; }+ type(value) { for (let i = 0; i < 4; i++) this.u8(value.charCodeAt(i)); }+ box(type, body) {+ const start = this.position;+ this.u32(0);+ this.type(type);+ body();+ this.view.setUint32(start, this.position - start);+ }+ full(type, version, flags, body) {+ this.box(type, () => { this.u32(((version & 255) << 24 | (flags & 0xffffff)) >>> 0); body(); });+ }+ result() { return this.buffer.slice(0, this.position); }+}++function runs(values) {+ const out = [];+ for (const value of values) {+ const last = out[out.length - 1];+ if (last && last.value === value) last.count += 1;+ else out.push({ value, count: 1 });+ }+ return out;+}++function writeMatrix(writer, matrix) {+ const values = matrix && matrix.length === 9 ? matrix : [0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x40000000];+ for (const value of values) writer.i32(value);+}++function writeSampleTable(writer, track) {+ const { first, samples, chunks } = track;+ writer.box('stbl', () => {+ writer.bytes(first.stsd);+ const durations = runs(samples.map(sample => sample.duration));+ writer.full('stts', 0, 0, () => {+ writer.u32(durations.length);+ for (const run of durations) { writer.u32(run.count); writer.u32(run.value); }+ });+ if (samples.some(sample => sample.offset !== 0)) {+ const negative = samples.some(sample => sample.offset < 0);+ const offsets = runs(samples.map(sample => sample.offset));+ writer.full('ctts', negative ? 1 : 0, 0, () => {+ writer.u32(offsets.length);+ for (const run of offsets) { writer.u32(run.count); if (negative) writer.i32(run.value); else writer.u32(run.value); }+ });+ }+ if (samples.some(sample => !sample.sync)) {+ const sync = samples.flatMap((sample, i) => (sample.sync ? [i + 1] : []));+ writer.full('stss', 0, 0, () => { writer.u32(sync.length); for (const number of sync) writer.u32(number); });+ }+ const perChunk = runs(chunks.map(chunk => chunk.count));+ writer.full('stsc', 0, 0, () => {+ writer.u32(perChunk.length);+ let chunkNumber = 1;+ for (const run of perChunk) { writer.u32(chunkNumber); writer.u32(run.value); writer.u32(1); chunkNumber += run.count; }+ });+ writer.full('stsz', 0, 0, () => {+ writer.u32(0);+ writer.u32(samples.length);+ for (const sample of samples) writer.u32(sample.size);+ });+ writer.full('stco', 0, 0, () => { writer.u32(chunks.length); for (const chunk of chunks) writer.u32(chunk.offset); });+ });+}++function writeMovie(clips, tracks, totalSeconds) {+ const movieTimescale = clips[0].movieTimescale;+ const movieDuration = Math.round(totalSeconds * movieTimescale);+ const writer = new Writer();+ writer.box('moov', () => {+ writer.full('mvhd', 0, 0, () => {+ writer.u32(0); writer.u32(0);+ writer.u32(movieTimescale); writer.u32(movieDuration);+ writer.u32(0x00010000); writer.u16(0x0100); writer.u16(0); writer.u32(0); writer.u32(0);+ writeMatrix(writer, clips[0].matrix);+ for (let i = 0; i < 6; i++) writer.u32(0);+ writer.u32(tracks.length + 1);+ });+ tracks.forEach((track, index) => {+ const { first } = track;+ writer.box('trak', () => {+ writer.full('tkhd', 0, first.tkhd?.flags ?? 3, () => {+ writer.u32(0); writer.u32(0);+ writer.u32(index + 1); writer.u32(0);+ writer.u32(movieDuration);+ writer.u32(0); writer.u32(0);+ writer.i16(first.tkhd?.layer || 0); writer.i16(first.tkhd?.alternate_group || 0);+ writer.u16(((first.tkhd?.volume || 0) & 255) << 8); writer.u16(0);+ writeMatrix(writer, first.tkhd?.matrix);+ writer.u32(first.tkhd?.width >>> 0 || 0); writer.u32(first.tkhd?.height >>> 0 || 0);+ });+ if (first.hasEdit) {+ writer.box('edts', () => writer.full('elst', 0, 0, () => {+ writer.u32(1); writer.u32(movieDuration); writer.i32(first.mediaTime); writer.i16(1); writer.i16(0);+ }));+ }+ writer.box('mdia', () => {+ writer.full('mdhd', 0, 0, () => {+ writer.u32(0); writer.u32(0);+ writer.u32(first.timescale); writer.u32(track.mediaDuration);+ writer.u16(first.language & 0x7fff); writer.u16(0);+ });+ writer.bytes(first.hdlr);+ writer.box('minf', () => {+ if (first.mediaHeader) writer.bytes(first.mediaHeader);+ if (first.dinf) writer.bytes(first.dinf);+ writeSampleTable(writer, track);+ });+ });+ });+ });+ });+ return writer.result();+}++/**+ * Joins MP4 clips (ArrayBuffer or typed array each) in order. Returns+ * `{ bytes, durationSeconds }`; throws VideoJoinError with `clips_incompatible`+ * when their tracks or codec setup differ, `not_mp4` for unreadable input and+ * `too_large` above `maxBytes`.+ */+export function joinMp4Clips(inputs, { maxBytes = Infinity } = {}) {+ if (!Array.isArray(inputs) || !inputs.length) throw new VideoJoinError('No clips to join.', 'not_mp4');+ const clips = inputs.map(parseClip);+ const reference = clips[0];+ for (const clip of clips.slice(1)) {+ if (clip.tracks.length !== reference.tracks.length) throw incompatible('the clips have different tracks');+ clip.tracks.forEach((track, index) => {+ const expected = reference.tracks[index];+ if (track.handler !== expected.handler || track.timescale !== expected.timescale || !sameBytes(track.stsdKey, expected.stsdKey)) {+ throw incompatible('the clips use different codec settings');+ }+ });+ }+ const starts = [];+ let totalSeconds = 0;+ for (const clip of clips) { starts.push(totalSeconds); totalSeconds += clip.duration; }+ const tracks = reference.tracks.map((_track, index) => joinTrack(clips, index, starts));+ const payload = tracks.reduce((sum, track) => sum + track.chunks.reduce((size, chunk) => size + chunk.size, 0), 0);+ const ftyp = reference.ftyp || (() => {+ const writer = new Writer();+ writer.box('ftyp', () => { writer.type('isom'); writer.u32(0x200); for (const brand of ['isom', 'iso2', 'mp41']) writer.type(brand); });+ return writer.result();+ })();+ // Chunk offsets do not change the size of the movie box, so lay out with a+ // provisional box, then write it again with the real offsets.+ let moov = writeMovie(clips, tracks, totalSeconds);+ const total = ftyp.length + moov.length + 8 + payload;+ if (total > maxBytes) throw new VideoJoinError('The joined video is larger than WebBrain can keep in the chat.', 'too_large');+ if (total > MAX_UINT32) throw new VideoJoinError('The joined video is too large.', 'too_large');+ let offset = ftyp.length + moov.length + 8;+ const ordered = [];+ clips.forEach((_clip, clipIndex) => tracks.forEach(track => {+ const chunk = track.chunks.find(candidate => candidate.clipIndex === clipIndex);+ if (!chunk) return;+ chunk.offset = offset;+ offset += chunk.size;+ ordered.push({ track, chunk });+ }));+ moov = writeMovie(clips, tracks, totalSeconds);+ const out = new Uint8Array(total);+ out.set(ftyp, 0);+ out.set(moov, ftyp.length);+ const view = new DataView(out.buffer);+ let position = ftyp.length + moov.length;+ view.setUint32(position, 8 + payload);+ out.set([0x6d, 0x64, 0x61, 0x74], position + 4);+ position += 8;+ for (const { track, chunk } of ordered) {+ const source = clips[chunk.clipIndex].bytes;+ for (let i = chunk.first; i < chunk.first + chunk.count; i++) {+ const sample = track.samples[i];+ out.set(source.subarray(sample.source, sample.source + sample.size), position);+ position += sample.size;+ }+ }+ return { bytes: out, durationSeconds: totalSeconds };+}diff --git a/src/chrome/src/generated-media-store.js b/src/chrome/src/generated-media-store.jsindex 5d8b27c5b..3ef3b11cb 100644--- a/src/chrome/src/generated-media-store.js+++ b/src/chrome/src/generated-media-store.js@@ -2,6 +2,8 @@const DB_NAME = 'webbrain_generated_media';const STORE_NAME = 'assets';const MAX_BYTES = 20 * 1024 * 1024;+// A video joined from its scenes' clips: up to two minutes of generated video.+export const MAX_JOINED_VIDEO_BYTES = 160 * 1024 * 1024;const MEDIA_MIME = /^(image\/(?:png|jpeg|webp|gif)|audio\/(?:mpeg|wav|ogg)|video\/mp4)$/;async function openDB() {@@ -19,7 +21,14 @@ export async function storeGeneratedMedia(dataUrl) {const binary = atob(match[2]);if (binary.length > MAX_BYTES) throw new Error('Generated media exceeds the 20 MB inline limit.');const bytes = Uint8Array.from(binary, char => char.charCodeAt(0));- const blob = new Blob([bytes], { type: match[1] });+ return storeGeneratedMediaBlob(new Blob([bytes], { type: match[1] }));+}++// `maxBytes` above 20 MB is for a joined video only.+export async function storeGeneratedMediaBlob(blob, { maxBytes = MAX_BYTES } = {}) {+ if (!(blob instanceof Blob) || !MEDIA_MIME.test(blob.type)) throw new Error('Unsupported generated media.');+ const limit = Math.min(maxBytes, blob.type === 'video/mp4' ? MAX_JOINED_VIDEO_BYTES : MAX_BYTES);+ if (blob.size > limit) throw new Error(`Generated media exceeds the ${Math.round(limit / 1024 / 1024)} MB inline limit.`);const id = crypto.randomUUID();const db = await openDB();try {@@ -42,7 +51,8 @@ export async function loadGeneratedMedia(id) {const request = db.transaction(STORE_NAME, 'readonly').objectStore(STORE_NAME).get(id);request.onsuccess = () => {const blob = request.result?.blob;- resolve(blob instanceof Blob && MEDIA_MIME.test(blob.type) && blob.size <= MAX_BYTES ? blob : null);+ const limit = blob?.type === 'video/mp4' ? MAX_JOINED_VIDEO_BYTES : MAX_BYTES;+ resolve(blob instanceof Blob && MEDIA_MIME.test(blob.type) && blob.size <= limit ? blob : null);};request.onerror = () => reject(request.error);});diff --git a/src/chrome/src/run-ui-journal.js b/src/chrome/src/run-ui-journal.jsindex cf21371a4..f01795778 100644--- a/src/chrome/src/run-ui-journal.js+++ b/src/chrome/src/run-ui-journal.js@@ -101,6 +101,16 @@ function compactRunUiToolResult(result, name) {if (typeof source[key] === 'string') compacted[key] = source[key];}if (source.inlineMedia === true) compacted.inlineMedia = true;+ for (const key of ['durationSeconds', 'clipCount']) {+ if (Number.isFinite(source[key])) compacted[key] = source[key];+ }+ // Clips of a video that could not be joined into one file, shown in order.+ if (source.joined === false && Array.isArray(source.clips)) {+ compacted.joined = false;+ compacted.clips = source.clips.slice(0, 24).flatMap(clip => (typeof clip?.mediaId === 'string'+ ? [{ mediaId: clip.mediaId, mimeType: String(clip.mimeType || ''), ...(Number.isFinite(clip.durationSeconds) ? { durationSeconds: clip.durationSeconds } : {}) }]+ : []));+ }}if (Object.keys(compacted).length === 0) {try {diff --git a/src/chrome/src/ui/generated-media-view.js b/src/chrome/src/ui/generated-media-view.jsindex 55f2ff4aa..9cf21095e 100644--- a/src/chrome/src/ui/generated-media-view.js+++ b/src/chrome/src/ui/generated-media-view.js@@ -46,6 +46,11 @@ async function hydrateStoredMedia(wrapper, t) {// A synchronous placeholder keeps the asset handle in chat snapshots even if// the panel closes before the IndexedDB read finishes.export function appendGeneratedMedia(container, result, t) {+ // A video whose clips could not be joined into one file: its clips in order.+ if (container && result?.success && Array.isArray(result.clips) && !result.mediaId && typeof result.url !== 'string') {+ return Promise.all(result.clips.slice(0, 24)+ .map(clip => appendGeneratedMedia(container, { success: true, mediaId: clip?.mediaId }, t)));+ }if (!container || !result?.success || (!result.mediaId && typeof result.url !== 'string')) return;const wrapper = document.createElement('div');wrapper.className = 'generated-media';diff --git a/src/chrome/src/ui/locales/ar.js b/src/chrome/src/ui/locales/ar.jsindex d6bd2ad18..53b79844d 100644--- a/src/chrome/src/ui/locales/ar.js+++ b/src/chrome/src/ui/locales/ar.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "يسأل الموقع: “{dialog}”","sp.delete.delete": "حذف","sp.delete.dont_delete": "عدم الحذف",+ "sp.video_length.question": "يحتاج هذا الفيديو إلى نحو {estimate}، لكن WebBrain ينشئ مقاطع فيديو حتى {max}.",+ "sp.video_length.offer": "هل تريد إنشاء نسخة مدتها {total} من {clips} مقاطع بدلاً من ذلك؟",+ "sp.video_length.generate": "إنشاء نسخة {total}",+ "sp.video_length.dont": "عدم الإنشاء",+ "sp.video_length.seconds": "{seconds} ث","sp.unverified.question.commit": "هل تريد إيداع هذا على {host}؟","sp.unverified.question.submit": "هل تريد إرسال هذا على {host}؟","sp.unverified.question.publish": "هل تريد نشر هذا على {host}؟",diff --git a/src/chrome/src/ui/locales/bn.js b/src/chrome/src/ui/locales/bn.jsindex 1b12e5576..7c97c5299 100644--- a/src/chrome/src/ui/locales/bn.js+++ b/src/chrome/src/ui/locales/bn.js@@ -460,6 +460,11 @@ export default {"sp.delete.site_asks": "সাইটটি জিজ্ঞেস করছে: “{dialog}”","sp.delete.delete": "মুছুন","sp.delete.dont_delete": "মুছবেন না",+ "sp.video_length.question": "এই ভিডিওর জন্য প্রায় {estimate} দরকার, কিন্তু WebBrain সর্বোচ্চ {max} দৈর্ঘ্যের ভিডিও তৈরি করে।",+ "sp.video_length.offer": "এর বদলে {clips}টি ক্লিপ থেকে {total} দৈর্ঘ্যের একটি সংস্করণ তৈরি করবেন?",+ "sp.video_length.generate": "{total} সংস্করণ তৈরি করুন",+ "sp.video_length.dont": "তৈরি করবেন না",+ "sp.video_length.seconds": "{seconds} সে.","sp.unverified.question.commit": "{host}-এ এটি কমিট করবেন?","sp.unverified.question.submit": "{host}-এ এটি জমা দেবেন?","sp.unverified.question.publish": "{host}-এ এটি প্রকাশ করবেন?",diff --git a/src/chrome/src/ui/locales/de.js b/src/chrome/src/ui/locales/de.jsindex acfb4b5ec..b62b819d7 100644--- a/src/chrome/src/ui/locales/de.js+++ b/src/chrome/src/ui/locales/de.js@@ -478,6 +478,11 @@ export default {"sp.delete.site_asks": "Die Website fragt: „{dialog}“","sp.delete.delete": "Löschen","sp.delete.dont_delete": "Nicht löschen",+ "sp.video_length.question": "Dieses Video bräuchte etwa {estimate}, WebBrain erstellt aber Videos bis {max}.",+ "sp.video_length.offer": "Stattdessen eine {total}-Version aus {clips} Clips erstellen?",+ "sp.video_length.generate": "{total}-Version erstellen",+ "sp.video_length.dont": "Nicht erstellen",+ "sp.video_length.seconds": "{seconds} s","sp.unverified.question.commit": "Das auf {host} committen?","sp.unverified.question.submit": "Das auf {host} absenden?","sp.unverified.question.publish": "Das auf {host} veröffentlichen?",diff --git a/src/chrome/src/ui/locales/en.js b/src/chrome/src/ui/locales/en.jsindex d73bcb0ce..65c503656 100644--- a/src/chrome/src/ui/locales/en.js+++ b/src/chrome/src/ui/locales/en.js@@ -465,6 +465,11 @@ export default {"sp.delete.site_asks": "The site asks: “{dialog}”","sp.delete.delete": "Delete","sp.delete.dont_delete": "Don’t delete",+ "sp.video_length.question": "This video needs about {estimate}, but WebBrain makes videos up to {max}.",+ "sp.video_length.offer": "Generate a {total} version from {clips} clips instead?",+ "sp.video_length.generate": "Generate {total} version",+ "sp.video_length.dont": "Don’t generate",+ "sp.video_length.seconds": "{seconds} s","sp.unverified.question.commit": "Commit this on {host}?","sp.unverified.question.submit": "Submit this on {host}?","sp.unverified.question.publish": "Publish this on {host}?",diff --git a/src/chrome/src/ui/locales/es.js b/src/chrome/src/ui/locales/es.jsindex 54dd394b1..865ac4235 100644--- a/src/chrome/src/ui/locales/es.js+++ b/src/chrome/src/ui/locales/es.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "El sitio pregunta: «{dialog}»","sp.delete.delete": "Eliminar","sp.delete.dont_delete": "No eliminar",+ "sp.video_length.question": "Este vídeo necesita unos {estimate}, pero WebBrain crea vídeos de hasta {max}.",+ "sp.video_length.offer": "¿Generar en su lugar una versión de {total} a partir de {clips} clips?",+ "sp.video_length.generate": "Generar versión de {total}",+ "sp.video_length.dont": "No generar",+ "sp.video_length.seconds": "{seconds} s","sp.unverified.question.commit": "¿Hacer commit de esto en {host}?","sp.unverified.question.submit": "¿Enviar esto en {host}?","sp.unverified.question.publish": "¿Publicar esto en {host}?",diff --git a/src/chrome/src/ui/locales/fa.js b/src/chrome/src/ui/locales/fa.jsindex 884123591..76e77653a 100644--- a/src/chrome/src/ui/locales/fa.js+++ b/src/chrome/src/ui/locales/fa.js@@ -460,6 +460,11 @@ export default {"sp.delete.site_asks": "سایت میپرسد: «{dialog}»","sp.delete.delete": "حذف","sp.delete.dont_delete": "حذف نکن",+ "sp.video_length.question": "این ویدیو حدود {estimate} زمان نیاز دارد، اما WebBrain ویدیوهایی تا {max} میسازد.",+ "sp.video_length.offer": "بهجای آن نسخهای {total} از {clips} کلیپ ساخته شود؟",+ "sp.video_length.generate": "ساخت نسخهٔ {total}",+ "sp.video_length.dont": "نساز",+ "sp.video_length.seconds": "{seconds} ثانیه","sp.unverified.question.commit": "این در {host} کامیت شود؟","sp.unverified.question.submit": "این در {host} ارسال شود؟","sp.unverified.question.publish": "این در {host} منتشر شود؟",diff --git a/src/chrome/src/ui/locales/fr.js b/src/chrome/src/ui/locales/fr.jsindex 5fed41fef..085c484fd 100644--- a/src/chrome/src/ui/locales/fr.js+++ b/src/chrome/src/ui/locales/fr.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "Le site demande : « {dialog} »","sp.delete.delete": "Supprimer","sp.delete.dont_delete": "Ne pas supprimer",+ "sp.video_length.question": "Cette vidéo nécessite environ {estimate}, mais WebBrain crée des vidéos de {max} maximum.",+ "sp.video_length.offer": "Générer plutôt une version de {total} à partir de {clips} clips ?",+ "sp.video_length.generate": "Générer la version de {total}",+ "sp.video_length.dont": "Ne pas générer",+ "sp.video_length.seconds": "{seconds} s","sp.unverified.question.commit": "Valider (commit) ceci sur {host} ?","sp.unverified.question.submit": "Envoyer ceci sur {host} ?","sp.unverified.question.publish": "Publier ceci sur {host} ?",diff --git a/src/chrome/src/ui/locales/he.js b/src/chrome/src/ui/locales/he.jsindex 9e9b21736..783f14d43 100644--- a/src/chrome/src/ui/locales/he.js+++ b/src/chrome/src/ui/locales/he.js@@ -451,6 +451,11 @@ export default {"sp.delete.site_asks": "האתר שואל: \"{dialog}\"","sp.delete.delete": "למחוק","sp.delete.dont_delete": "לא למחוק",+ "sp.video_length.question": "הסרטון הזה דורש כ-{estimate}, אבל WebBrain יוצר סרטונים של עד {max}.",+ "sp.video_length.offer": "ליצור במקום זאת גרסה של {total} מ-{clips} קטעים?",+ "sp.video_length.generate": "יצירת גרסה של {total}",+ "sp.video_length.dont": "לא ליצור",+ "sp.video_length.seconds": "{seconds} שנ׳","sp.unverified.question.commit": "לבצע commit לזה ב-{host}?","sp.unverified.question.submit": "לשלוח את זה ב-{host}?","sp.unverified.question.publish": "לפרסם את זה ב-{host}?",diff --git a/src/chrome/src/ui/locales/hi.js b/src/chrome/src/ui/locales/hi.jsindex 9fce50d4c..4f76647cc 100644--- a/src/chrome/src/ui/locales/hi.js+++ b/src/chrome/src/ui/locales/hi.js@@ -460,6 +460,11 @@ export default {"sp.delete.site_asks": "साइट पूछ रही है: “{dialog}”","sp.delete.delete": "हटाएँ","sp.delete.dont_delete": "न हटाएँ",+ "sp.video_length.question": "इस वीडियो के लिए लगभग {estimate} चाहिए, लेकिन WebBrain अधिकतम {max} तक के वीडियो बनाता है।",+ "sp.video_length.offer": "इसके बजाय {clips} क्लिप से {total} का संस्करण बनाएँ?",+ "sp.video_length.generate": "{total} संस्करण बनाएँ",+ "sp.video_length.dont": "न बनाएँ",+ "sp.video_length.seconds": "{seconds} से.","sp.unverified.question.commit": "{host} पर इसे कमिट करें?","sp.unverified.question.submit": "{host} पर इसे सबमिट करें?","sp.unverified.question.publish": "{host} पर इसे प्रकाशित करें?",diff --git a/src/chrome/src/ui/locales/id.js b/src/chrome/src/ui/locales/id.jsindex d11b6daaf..af7f3137f 100644--- a/src/chrome/src/ui/locales/id.js+++ b/src/chrome/src/ui/locales/id.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "Situs bertanya: “{dialog}”","sp.delete.delete": "Hapus","sp.delete.dont_delete": "Jangan hapus",+ "sp.video_length.question": "Video ini membutuhkan sekitar {estimate}, tetapi WebBrain membuat video hingga {max}.",+ "sp.video_length.offer": "Buat versi {total} dari {clips} klip sebagai gantinya?",+ "sp.video_length.generate": "Buat versi {total}",+ "sp.video_length.dont": "Jangan buat",+ "sp.video_length.seconds": "{seconds} dtk","sp.unverified.question.commit": "Commit ini di {host}?","sp.unverified.question.submit": "Kirim ini di {host}?","sp.unverified.question.publish": "Publikasikan ini di {host}?",diff --git a/src/chrome/src/ui/locales/ja.js b/src/chrome/src/ui/locales/ja.jsindex f48b6d3c5..977e06856 100644--- a/src/chrome/src/ui/locales/ja.js+++ b/src/chrome/src/ui/locales/ja.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "サイトの確認:「{dialog}」","sp.delete.delete": "削除する","sp.delete.dont_delete": "削除しない",+ "sp.video_length.question": "この動画には約{estimate}必要ですが、WebBrainが作成できる動画は最長{max}です。",+ "sp.video_length.offer": "代わりに{clips}本のクリップから{total}の動画を作成しますか?",+ "sp.video_length.generate": "{total}版を作成",+ "sp.video_length.dont": "作成しない",+ "sp.video_length.seconds": "{seconds}秒","sp.unverified.question.commit": "{host} でこれをコミットしますか?","sp.unverified.question.submit": "{host} でこれを送信しますか?","sp.unverified.question.publish": "{host} でこれを公開しますか?",diff --git a/src/chrome/src/ui/locales/ko.js b/src/chrome/src/ui/locales/ko.jsindex 23ad9fe7e..f66a46a81 100644--- a/src/chrome/src/ui/locales/ko.js+++ b/src/chrome/src/ui/locales/ko.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "사이트 확인 메시지: “{dialog}”","sp.delete.delete": "삭제","sp.delete.dont_delete": "삭제하지 않기",+ "sp.video_length.question": "이 동영상에는 약 {estimate} 분량이 필요하지만 WebBrain은 최대 {max} 길이까지 동영상을 만듭니다.",+ "sp.video_length.offer": "대신 클립 {clips}개로 {total} 버전을 만들까요?",+ "sp.video_length.generate": "{total} 버전 만들기",+ "sp.video_length.dont": "만들지 않기",+ "sp.video_length.seconds": "{seconds}초","sp.unverified.question.commit": "{host}에서 이 내용을 커밋할까요?","sp.unverified.question.submit": "{host}에서 이 내용을 제출할까요?","sp.unverified.question.publish": "{host}에서 이 내용을 게시할까요?",diff --git a/src/chrome/src/ui/locales/ms.js b/src/chrome/src/ui/locales/ms.jsindex 4f94d394b..f27405ddc 100644--- a/src/chrome/src/ui/locales/ms.js+++ b/src/chrome/src/ui/locales/ms.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "Laman bertanya: “{dialog}”","sp.delete.delete": "Padam","sp.delete.dont_delete": "Jangan padam",+ "sp.video_length.question": "Video ini memerlukan kira-kira {estimate}, tetapi WebBrain menghasilkan video sehingga {max}.",+ "sp.video_length.offer": "Jana versi {total} daripada {clips} klip sebagai ganti?",+ "sp.video_length.generate": "Jana versi {total}",+ "sp.video_length.dont": "Jangan jana",+ "sp.video_length.seconds": "{seconds} saat","sp.unverified.question.commit": "Commit ini di {host}?","sp.unverified.question.submit": "Serahkan ini di {host}?","sp.unverified.question.publish": "Terbitkan ini di {host}?",diff --git a/src/chrome/src/ui/locales/nl.js b/src/chrome/src/ui/locales/nl.jsindex 92add1259..9031bdcaf 100644--- a/src/chrome/src/ui/locales/nl.js+++ b/src/chrome/src/ui/locales/nl.js@@ -448,6 +448,11 @@ export default {"sp.delete.site_asks": "De site vraagt: ‘{dialog}’","sp.delete.delete": "Verwijderen","sp.delete.dont_delete": "Niet verwijderen",+ "sp.video_length.question": "Deze video heeft ongeveer {estimate} nodig, maar WebBrain maakt video's van maximaal {max}.",+ "sp.video_length.offer": "In plaats daarvan een versie van {total} uit {clips} clips maken?",+ "sp.video_length.generate": "Versie van {total} maken",+ "sp.video_length.dont": "Niet maken",+ "sp.video_length.seconds": "{seconds} s","sp.unverified.question.commit": "Dit committen op {host}?","sp.unverified.question.submit": "Dit versturen op {host}?","sp.unverified.question.publish": "Dit publiceren op {host}?",diff --git a/src/chrome/src/ui/locales/pl.js b/src/chrome/src/ui/locales/pl.jsindex ce22d8a93..3c3241af9 100644--- a/src/chrome/src/ui/locales/pl.js+++ b/src/chrome/src/ui/locales/pl.js@@ -349,6 +349,11 @@ export default {"sp.delete.site_asks": "Strona pyta: „{dialog}”","sp.delete.delete": "Usuń","sp.delete.dont_delete": "Nie usuwaj",+ "sp.video_length.question": "Ten film wymaga około {estimate}, ale WebBrain tworzy filmy o długości do {max}.",+ "sp.video_length.offer": "Zamiast tego utworzyć wersję {total} (liczba klipów: {clips})?",+ "sp.video_length.generate": "Utwórz wersję {total}",+ "sp.video_length.dont": "Nie twórz",+ "sp.video_length.seconds": "{seconds} s","sp.unverified.question.commit": "Zatwierdzić (commit) to w {host}?","sp.unverified.question.submit": "Wysłać to w {host}?","sp.unverified.question.publish": "Opublikować to w {host}?",diff --git a/src/chrome/src/ui/locales/pt.js b/src/chrome/src/ui/locales/pt.jsindex 3c1929a49..9943d2937 100644--- a/src/chrome/src/ui/locales/pt.js+++ b/src/chrome/src/ui/locales/pt.js@@ -460,6 +460,11 @@ export default {"sp.delete.site_asks": "O site pergunta: “{dialog}”","sp.delete.delete": "Excluir","sp.delete.dont_delete": "Não excluir",+ "sp.video_length.question": "Este vídeo precisa de cerca de {estimate}, mas o WebBrain cria vídeos de até {max}.",+ "sp.video_length.offer": "Gerar uma versão de {total} com {clips} clipes em vez disso?",+ "sp.video_length.generate": "Gerar versão de {total}",+ "sp.video_length.dont": "Não gerar",+ "sp.video_length.seconds": "{seconds} s","sp.unverified.question.commit": "Fazer commit disto em {host}?","sp.unverified.question.submit": "Enviar isto em {host}?","sp.unverified.question.publish": "Publicar isto em {host}?",diff --git a/src/chrome/src/ui/locales/ru.js b/src/chrome/src/ui/locales/ru.jsindex a6971efd2..75a12d471 100644--- a/src/chrome/src/ui/locales/ru.js+++ b/src/chrome/src/ui/locales/ru.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "Сайт спрашивает: «{dialog}»","sp.delete.delete": "Удалить","sp.delete.dont_delete": "Не удалять",+ "sp.video_length.question": "Этому видео нужно около {estimate}, но WebBrain создаёт видео длиной не более {max}.",+ "sp.video_length.offer": "Создать вместо этого версию на {total} из {clips} клипов?",+ "sp.video_length.generate": "Создать версию на {total}",+ "sp.video_length.dont": "Не создавать",+ "sp.video_length.seconds": "{seconds} с","sp.unverified.question.commit": "Закоммитить это на {host}?","sp.unverified.question.submit": "Отправить это на {host}?","sp.unverified.question.publish": "Опубликовать это на {host}?",diff --git a/src/chrome/src/ui/locales/th.js b/src/chrome/src/ui/locales/th.jsindex 54b35b0bf..3a0c1fdac 100644--- a/src/chrome/src/ui/locales/th.js+++ b/src/chrome/src/ui/locales/th.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "เว็บไซต์ถามว่า: “{dialog}”","sp.delete.delete": "ลบ","sp.delete.dont_delete": "ไม่ลบ",+ "sp.video_length.question": "วิดีโอนี้ต้องใช้เวลาประมาณ {estimate} แต่ WebBrain สร้างวิดีโอได้ยาวสูงสุด {max}",+ "sp.video_length.offer": "สร้างเวอร์ชัน {total} จาก {clips} คลิปแทนหรือไม่",+ "sp.video_length.generate": "สร้างเวอร์ชัน {total}",+ "sp.video_length.dont": "ไม่สร้าง",+ "sp.video_length.seconds": "{seconds} วินาที","sp.unverified.question.commit": "คอมมิตสิ่งนี้บน {host} ไหม?","sp.unverified.question.submit": "ส่งสิ่งนี้บน {host} ไหม?","sp.unverified.question.publish": "เผยแพร่สิ่งนี้บน {host} ไหม?",diff --git a/src/chrome/src/ui/locales/tl.js b/src/chrome/src/ui/locales/tl.jsindex d05eaca6b..119446c8d 100644--- a/src/chrome/src/ui/locales/tl.js+++ b/src/chrome/src/ui/locales/tl.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "Tanong ng site: “{dialog}”","sp.delete.delete": "Burahin","sp.delete.dont_delete": "Huwag burahin",+ "sp.video_length.question": "Kailangan ng video na ito ng mga {estimate}, pero hanggang {max} lang ang ginagawang video ng WebBrain.",+ "sp.video_length.offer": "Gumawa na lang ng {total} na bersyon mula sa {clips} clip?",+ "sp.video_length.generate": "Gumawa ng {total} na bersyon",+ "sp.video_length.dont": "Huwag gumawa",+ "sp.video_length.seconds": "{seconds} seg","sp.unverified.question.commit": "I-commit ito sa {host}?","sp.unverified.question.submit": "Isumite ito sa {host}?","sp.unverified.question.publish": "I-publish ito sa {host}?",diff --git a/src/chrome/src/ui/locales/tr.js b/src/chrome/src/ui/locales/tr.jsindex 16784e3f8..57a517719 100644--- a/src/chrome/src/ui/locales/tr.js+++ b/src/chrome/src/ui/locales/tr.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "Site soruyor: “{dialog}”","sp.delete.delete": "Sil","sp.delete.dont_delete": "Silme",+ "sp.video_length.question": "Bu video yaklaşık {estimate} gerektiriyor, ancak WebBrain en fazla {max} uzunluğunda video üretiyor.",+ "sp.video_length.offer": "Bunun yerine {clips} klipten {total} uzunluğunda bir sürüm üretilsin mi?",+ "sp.video_length.generate": "{total} sürümünü üret",+ "sp.video_length.dont": "Üretme",+ "sp.video_length.seconds": "{seconds} sn","sp.unverified.question.commit": "{host} üzerinde bu commit edilsin mi?","sp.unverified.question.submit": "{host} üzerinde bu gönderilsin mi?","sp.unverified.question.publish": "{host} üzerinde bu yayınlansın mı?",diff --git a/src/chrome/src/ui/locales/uk.js b/src/chrome/src/ui/locales/uk.jsindex b0d3ea9e7..450339ca6 100644--- a/src/chrome/src/ui/locales/uk.js+++ b/src/chrome/src/ui/locales/uk.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "Сайт питає: «{dialog}»","sp.delete.delete": "Видалити","sp.delete.dont_delete": "Не видаляти",+ "sp.video_length.question": "Цьому відео потрібно приблизно {estimate}, але WebBrain створює відео тривалістю до {max}.",+ "sp.video_length.offer": "Створити натомість версію на {total} з {clips} кліпів?",+ "sp.video_length.generate": "Створити версію на {total}",+ "sp.video_length.dont": "Не створювати",+ "sp.video_length.seconds": "{seconds} с","sp.unverified.question.commit": "Закомітити це на {host}?","sp.unverified.question.submit": "Надіслати це на {host}?","sp.unverified.question.publish": "Опублікувати це на {host}?",diff --git a/src/chrome/src/ui/locales/vi.js b/src/chrome/src/ui/locales/vi.jsindex cfceaf827..e7d5726d9 100644--- a/src/chrome/src/ui/locales/vi.js+++ b/src/chrome/src/ui/locales/vi.js@@ -460,6 +460,11 @@ export default {"sp.delete.site_asks": "Trang web hỏi: “{dialog}”","sp.delete.delete": "Xóa","sp.delete.dont_delete": "Không xóa",+ "sp.video_length.question": "Video này cần khoảng {estimate}, nhưng WebBrain chỉ tạo video dài tối đa {max}.",+ "sp.video_length.offer": "Thay vào đó, tạo bản {total} từ {clips} đoạn clip?",+ "sp.video_length.generate": "Tạo bản {total}",+ "sp.video_length.dont": "Không tạo",+ "sp.video_length.seconds": "{seconds} giây","sp.unverified.question.commit": "Commit nội dung này trên {host}?","sp.unverified.question.submit": "Gửi nội dung này trên {host}?","sp.unverified.question.publish": "Đăng nội dung này trên {host}?",diff --git a/src/chrome/src/ui/locales/zh.js b/src/chrome/src/ui/locales/zh.jsindex ece2a1044..f7600b2b4 100644--- a/src/chrome/src/ui/locales/zh.js+++ b/src/chrome/src/ui/locales/zh.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "网站询问:“{dialog}”","sp.delete.delete": "删除","sp.delete.dont_delete": "不删除",+ "sp.video_length.question": "这个视频大约需要 {estimate},但 WebBrain 最多只能生成 {max} 的视频。",+ "sp.video_length.offer": "改为用 {clips} 个片段生成 {total} 的版本?",+ "sp.video_length.generate": "生成 {total} 版本",+ "sp.video_length.dont": "不生成",+ "sp.video_length.seconds": "{seconds} 秒","sp.unverified.question.commit": "要在 {host} 上提交(commit)这些内容吗?","sp.unverified.question.submit": "要在 {host} 上提交这些内容吗?","sp.unverified.question.publish": "要在 {host} 上发布这些内容吗?",diff --git a/src/chrome/src/ui/sidepanel.js b/src/chrome/src/ui/sidepanel.jsindex 445027d47..d44228db1 100644--- a/src/chrome/src/ui/sidepanel.js+++ b/src/chrome/src/ui/sidepanel.js@@ -6718,7 +6718,8 @@ function rebindClarifyCards() {// Restart countdown after HTML restore when timeout metadata survived on// the card. Skip permission/form-submit cards (they never auto-timeout).if (card.dataset.permission === '1' || card.dataset.submitConfirmation === '1'- || card.dataset.recipientConfirmation === '1' || card.dataset.mutationConfirmation === '1') return;+ || card.dataset.recipientConfirmation === '1' || card.dataset.mutationConfirmation === '1'+ || card.dataset.videoLengthConfirmation === '1') return;const deadlineTs = Number(card.dataset.deadlineTs);if (!Number.isFinite(deadlineTs) || deadlineTs <= 0) return;const firstOption = card.dataset.firstOption@@ -11674,7 +11675,7 @@ function renderClarifyCard(data) {card.dataset.memorySource = scheduledJobId? 'scheduled_clarification': data.workflowHealing || data.pendingReconciliation === true || data.recipientConfirmation- || data.mutationConfirmation || data.unverifiedStepConfirmation+ || data.mutationConfirmation || data.unverifiedStepConfirmation || data.videoLengthConfirmation? '': data.submitConfirmation? 'form_confirmation'@@ -11901,6 +11902,44 @@ function renderClarifyCard(data) {return;}+ // Video length: the requested video needs longer than WebBrain makes, so+ // the user decides whether the shorter version is worth its clips. Fixed+ // choices return stable values ('once'/'deny'); the card never times out.+ if (data.videoLengthConfirmation) {+ card.dataset.videoLengthConfirmation = '1';+ const video = data.videoLengthConfirmation || {};+ const clock = value => {+ const seconds = Math.max(0, Math.round(Number(value) || 0));+ return seconds < 60 ? t('sp.video_length.seconds', { seconds }) : `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;+ };+ qEl.textContent = t('sp.video_length.question', { estimate: clock(video.estimatedSeconds), max: clock(video.maxSeconds) });+ const offerEl = document.createElement('div');+ offerEl.className = 'clarify-reason';+ offerEl.textContent = t('sp.video_length.offer', {+ total: clock(video.totalSeconds),+ clips: Math.max(1, Math.round(Number(video.clipCount) || 1)),+ });+ card.appendChild(offerEl);+ const optionsEl = document.createElement('div');+ optionsEl.className = 'clarify-options';+ for (const [value, label] of [['once', t('sp.video_length.generate', { total: clock(video.totalSeconds) })], ['deny', t('sp.video_length.dont')]]) {+ const b = document.createElement('button');+ b.type = 'button';+ b.className = 'clarify-option';+ b.textContent = String(label).slice(0, 200);+ b.dataset.value = value;+ b.addEventListener('click', () => {+ card.dataset.answerLabel = b.textContent;+ submitClarify(card, tabId, clarifyId, value, 'option');+ });+ optionsEl.appendChild(b);+ }+ card.appendChild(optionsEl);+ content.appendChild(card);+ scrollToBottom({ force: true });+ return;+ }+// Unverifiable step: one of WebBrain's checks could not verify a commit,// publish or submit, so it asks instead of refusing. The text is what the// page showed when WebBrain asked: page content, shown as text only@@ -12245,7 +12284,8 @@ function lockClarifyCardFromAuto(data) {// of a quality check: it locks on the timeout's answer like a question.const unverifiedStep = card.dataset.unverifiedStepConfirmation === '1';if (card.dataset.permission === '1' || card.dataset.submitConfirmation === '1'- || card.dataset.recipientConfirmation === '1' || card.dataset.mutationConfirmation === '1') return;+ || card.dataset.recipientConfirmation === '1' || card.dataset.mutationConfirmation === '1'+ || card.dataset.videoLengthConfirmation === '1') return;clearClarifyCountdown(card);card.classList.add('clarify-answered');for (const el of card.querySelectorAll('button, input')) {diff --git a/src/chrome/vendor/mp4box/LICENSE b/src/chrome/vendor/mp4box/LICENSEnew file mode 100644index 000000000..dccb790ea--- /dev/null+++ b/src/chrome/vendor/mp4box/LICENSE@@ -0,0 +1,24 @@+Copyright (c) 2012. Telecom ParisTech/TSI/MM/GPAC Cyril Concolato+All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:+ * Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.+ * Redistributions in binary form must reproduce the above copyright+ notice, this list of conditions and the following disclaimer in the+ documentation and/or other materials provided with the distribution.+ * Neither the name of the copyright holder nor the+ names of its contributors may be used to endorse or promote products+ derived from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/src/chrome/vendor/mp4box/README.webbrain.md b/src/chrome/vendor/mp4box/README.webbrain.mdnew file mode 100644index 000000000..cb5788f5c--- /dev/null+++ b/src/chrome/vendor/mp4box/README.webbrain.md@@ -0,0 +1,18 @@+# Vendored mp4box.js++- Package: `mp4box`+- Version: `2.4.1`+- Upstream: <https://github.com/gpac/mp4box.js>+- Files: `dist/mp4box.all.mjs`, `dist/styp-9TIZZDLN.mjs` and+ `dist/rolldown-runtime-w6R9maHv.mjs` from the published npm package,+ unmodified (the entry file imports the other two by these names)+- SHA-256:+ - `mp4box.all.mjs`: `34fa8fd681e8b63998ca9e4c3b477830dd11310c8aaedc37ecb8f49c5452d259`+ - `styp-9TIZZDLN.mjs`: `ae15acb79233251b72af7f7cc9f47e7f47cadb209206753b7000b502a2391049`+ - `rolldown-runtime-w6R9maHv.mjs`: `183552fe973134bce551888434b581d5a2cb695a82d8907e2cd9d2b61e12ce24`+- License: BSD-3-Clause (see `LICENSE`)++WebBrain uses `createFile` and `MP4BoxBuffer` only to parse generated MP4+clips: their sample tables, edit lists and codec configuration. The joined file+is written by `src/agent/video-join.js`. The dependency is bundled with the+extension; no executable code is fetched at runtime.diff --git a/src/chrome/vendor/mp4box/mp4box.all.mjs b/src/chrome/vendor/mp4box/mp4box.all.mjsnew file mode 100644index 000000000..1de72dcfd--- /dev/null+++ b/src/chrome/vendor/mp4box/mp4box.all.mjs@@ -0,0 +1,3427 @@+import { t as __exportAll } from "./rolldown-runtime-w6R9maHv.mjs";+import { $ as hvc2SampleEntry, $n as SingleItemTypeReferenceBoxLarge, $t as hinfBox, A as OpusSampleEntry, An as xmlBox, At as metxSampleEntry, B as dvh1SampleEntry, Bn as ContainerBox, Bt as mehdBox, C as sdtpBox, Cn as strdBox, Ct as colrBox, D as stxtSampleEntry, Dn as trgrBox, Dt as waveBox, E as tx3gSampleEntry, En as trakBox, Et as lvcCBox, F as avc2SampleEntry, Fn as SampleEntry, Ft as pitmBox, G as encsSampleEntry, Gn as DIFF_BOXES_PROP_NAMES, Gt as elngBox, H as ec_3SampleEntry, Hn as parseOneBox, Ht as hvcCBox, I as avc3SampleEntry, In as SubtitleSampleEntry, It as irefBox, J as encvSampleEntry, Jn as boxEqualFields, Jt as dinfBox, K as enctSampleEntry, Kn as DIFF_PRIMITIVE_ARRAY_PROP_NAMES, Kt as drefBox, L as avc4SampleEntry, Ln as SystemSampleEntry, Lt as ilocBox, M as ac_4SampleEntry, Mn as AudioSampleEntry, Mt as mvhdBox, N as av01SampleEntry, Nn as HintSampleEntry, Nt as mfhdBox, O as stppSampleEntry, On as udtaBox, Ot as esdsBox, P as avc1SampleEntry, Pn as MetadataSampleEntry, Pt as metaBox, Q as hvc1SampleEntry, Qn as SingleItemTypeReferenceBox, Qt as grplBox, R as avs3SampleEntry, Rn as TextSampleEntry, Rt as iinfBox, S as sgpdBox, Sn as stblBox, St as vvs1SampleEntry, T as wvttSampleEntry, Tn as trafBox, Tt as vpcCBox, U as encaSampleEntry, Un as registerBoxes, Ut as hdlrBox, V as dvheSampleEntry, Vn as parseHex16, Vt as mdhdBox, W as encmSampleEntry, Wn as registerDescriptors, Wt as ftypBox, X as hev1SampleEntry, Xn as FullBox, Xt as etypBox, Y as fLaCSampleEntry, Yn as Box, Yt as edtsBox, Z as hev2SampleEntry, Zn as SampleGroupEntry, Zt as freeBox, _ as stscBox, _n as povdBox, _t as vp08SampleEntry, a as ISOFile, an as iproBox, ar as Endianness, at as m4aeSampleEntry, b as smhdBox, bn as sinfBox, bt as vvcNSampleEntry, c as urlBox, cn as mdatBox, ct as mhm1SampleEntry, d as tkhdBox, dn as mfraBox, dt as mjpgSampleEntry, en as hmhdBox, er as TrackGroupTypeBox, et as hvt1SampleEntry, f as tfhdBox, fn as minfBox, ft as mp4aSampleEntry, g as stsdBox, gn as nmhdBox, gt as uncvSampleEntry, h as stszBox, hn as mvexBox, ht as resvSampleEntry, i as createFile, in as ipcoBox, ir as DataStream, it as lvc1SampleEntry, j as ac_3SampleEntry, jn as avcCBox, jt as mettSampleEntry, k as sbttSampleEntry, kn as vttcBox, kt as av1CBox, l as trunBox, ln as mdiaBox, lt as mhm2SampleEntry, m as sttsBox, mn as moovBox, mt as mp4vSampleEntry, n as ssixBox, nn as idatBox, nr as MultiBufferStream, nt as lhe1SampleEntry, o as SampleGroupInfo, on as iprpBox, or as MP4BoxBuffer, ot as mha1SampleEntry, p as tfdtBox, pn as moofBox, pt as mp4sSampleEntry, q as encuSampleEntry, qn as boxEqual, qt as bxmlBox, r as emsgBox, rn as iodsBox, rr as Log, rt as lhv1SampleEntry, s as vmhdBox, sn as j2kHBox, sr as MAX_UINT32, st as mha2SampleEntry, t as stypBox, tn as hntiBox, tr as TrackReferenceTypeBox, tt as j2kiSampleEntry, u as trexBox, un as mecoBox, ut as mjp2SampleEntry, v as sthdBox, vn as rinfBox, vt as vp09SampleEntry, w as sbgpBox, wn as strkBox, wt as vvcCBox, x as sidxBox, xn as skipBox, xt as vvi1SampleEntry, y as stcoBox, yn as schiBox, yt as vvc1SampleEntry, z as dav1SampleEntry, zn as VisualSampleEntry, zt as infeBox } from "./styp-9TIZZDLN.mjs";++//#region src/descriptor.ts+var descriptor_exports = /* @__PURE__ */ __exportAll({+ Descriptor: () => Descriptor,+ ES_Descriptor: () => ES_Descriptor,+ MPEG4DescriptorParser: () => MPEG4DescriptorParser+});+const ES_DescrTag = 3;+const DecoderConfigDescrTag = 4;+const DecSpecificInfoTag = 5;+const SLConfigDescrTag = 6;+var Descriptor = class Descriptor {+ constructor(tag, size) {+ this.tag = tag;+ this.size = size;+ this.descs = [];+ }+ parse(stream) {+ this.data = stream.readUint8Array(this.size);+ }+ findDescriptor(tag) {+ for (let i = 0; i < this.descs.length; i++) if (this.descs[i].tag === tag) return this.descs[i];+ }+ parseOneDescriptor(stream) {+ let size = 0;+ const tag = stream.readUint8();+ let byteRead = stream.readUint8();+ while (byteRead & 128) {+ size = (size << 7) + (byteRead & 127);+ byteRead = stream.readUint8();+ }+ size = (size << 7) + (byteRead & 127);+ Log.debug("Descriptor", "Found " + (descTagToName[tag] || "Descriptor " + tag) + ", size " + size + " at position " + stream.getPosition());+ const desc = descTagToName[tag] ? new DESCRIPTOR_CLASSES[descTagToName[tag]](size) : new Descriptor(size);+ desc.parse(stream);+ return desc;+ }+ parseRemainingDescriptors(stream) {+ const start = stream.getPosition();+ while (stream.getPosition() < start + this.size) {+ const desc = this.parseOneDescriptor?.(stream);+ this.descs.push(desc);+ }+ }+};+var ES_Descriptor = class extends Descriptor {+ constructor(size) {+ super(ES_DescrTag, size);+ }+ parse(stream) {+ this.ES_ID = stream.readUint16();+ this.flags = stream.readUint8();+ this.size -= 3;+ if (this.flags & 128) {+ this.dependsOn_ES_ID = stream.readUint16();+ this.size -= 2;+ } else this.dependsOn_ES_ID = 0;+ if (this.flags & 64) {+ const l = stream.readUint8();+ this.URL = stream.readString(l);+ this.size -= l + 1;+ } else this.URL = "";+ if (this.flags & 32) {+ this.OCR_ES_ID = stream.readUint16();+ this.size -= 2;+ } else this.OCR_ES_ID = 0;+ this.parseRemainingDescriptors(stream);+ }+ getOTI() {+ const dcd = this.findDescriptor(DecoderConfigDescrTag);+ if (dcd) return dcd.oti;+ else return 0;+ }+ getAudioConfig() {+ const dcd = this.findDescriptor(DecoderConfigDescrTag);+ if (!dcd) return;+ const dsi = dcd.findDescriptor(DecSpecificInfoTag);+ if (dsi && dsi.data) {+ let audioObjectType = (dsi.data[0] & 248) >> 3;+ if (audioObjectType === 31 && dsi.data.length >= 2) audioObjectType = 32 + ((dsi.data[0] & 7) << 3) + ((dsi.data[1] & 224) >> 5);+ return audioObjectType;+ }+ }+};+var DecoderConfigDescriptor = class extends Descriptor {+ constructor(size) {+ super(DecoderConfigDescrTag, size);+ }+ parse(stream) {+ this.oti = stream.readUint8();+ this.streamType = stream.readUint8();+ this.upStream = (this.streamType >> 1 & 1) !== 0;+ this.streamType = this.streamType >>> 2;+ this.bufferSize = stream.readUint24();+ this.maxBitrate = stream.readUint32();+ this.avgBitrate = stream.readUint32();+ this.size -= 13;+ this.parseRemainingDescriptors(stream);+ }+};+var DecoderSpecificInfo = class extends Descriptor {+ constructor(size) {+ super(DecSpecificInfoTag, size);+ }+};+var SLConfigDescriptor = class extends Descriptor {+ constructor(size) {+ super(SLConfigDescrTag, size);+ }+};+const DESCRIPTOR_CLASSES = {+ Descriptor,+ ES_Descriptor,+ DecoderConfigDescriptor,+ DecoderSpecificInfo,+ SLConfigDescriptor+};+const descTagToName = {+ [ES_DescrTag]: "ES_Descriptor",+ [DecoderConfigDescrTag]: "DecoderConfigDescriptor",+ [DecSpecificInfoTag]: "DecoderSpecificInfo",+ [SLConfigDescrTag]: "SLConfigDescriptor"+};+var MPEG4DescriptorParser = class {+ constructor() {+ this.parseOneDescriptor = Descriptor.prototype.parseOneDescriptor;+ }+ getDescriptorName(tag) {+ return descTagToName[tag];+ }+};++//#endregion+//#region src/text-mp4.ts+var VTTin4Parser = class {+ parseSample(data) {+ const cues = [];+ const stream = new MultiBufferStream(MP4BoxBuffer.fromArrayBuffer(data.buffer, 0));+ while (!stream.isEof()) {+ const cue = parseOneBox(stream, false);+ if (cue.code === 1 && cue.box?.type === "vttc") cues.push(cue.box);+ }+ return cues;+ }+ getText(startTime, endTime, data) {+ function pad(value, width) {+ const string = value.toString();+ if (string.length >= width) return string;+ return new Array(width - string.length + 1).join("0") + string;+ }+ function secToTimestamp(insec) {+ const h = Math.floor(insec / 3600);+ const m = Math.floor((insec - h * 3600) / 60);+ const s = Math.floor(insec - h * 3600 - m * 60);+ const ms = Math.floor((insec - h * 3600 - m * 60 - s) * 1e3);+ return "" + pad(h, 2) + ":" + pad(m, 2) + ":" + pad(s, 2) + "." + pad(ms, 3);+ }+ const cues = this.parseSample(data);+ let string = "";+ for (let i = 0; i < cues.length; i++) {+ const cueIn4 = cues[i];+ string += secToTimestamp(startTime) + " --> " + secToTimestamp(endTime) + "\r\n";+ string += cueIn4.payl.text;+ }+ return string;+ }+};+var XMLSubtitlein4Parser = class {+ parseSample(sample) {+ const res = {+ resources: [],+ documentString: "",+ document: void 0+ };+ const stream = new DataStream(sample.data.buffer);+ if (!sample.subsamples || sample.subsamples.length === 0) res.documentString = stream.readString(sample.data.length);+ else {+ res.documentString = stream.readString(sample.subsamples[0].size);+ if (sample.subsamples.length > 1) for (let i = 1; i < sample.subsamples.length; i++) res.resources[i] = stream.readUint8Array(sample.subsamples[i].size);+ }+ if (typeof DOMParser !== "undefined") res.document = new DOMParser().parseFromString(res.documentString, "application/xml");+ return res;+ }+};+var Textin4Parser = class {+ parseSample(sample) {+ return new DataStream(sample.data.buffer).readString(sample.data.length);+ }+ parseConfig(data) {+ const stream = new DataStream(data.buffer);+ stream.readUint32();+ return stream.readCString();+ }+};+var TX3GParser = class {+ parseSample(sample) {+ const stream = new DataStream(sample.data.buffer);+ const size = stream.readUint16();+ if (size === 0) return;+ return stream.readString(size);+ }+};++//#endregion+//#region src/boxes/a1lx.ts+var a1lxBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "AV1LayeredImageIndexingProperty";+ }+ static {+ this.fourcc = "a1lx";+ }+ parse(stream) {+ const FieldLength = ((stream.readUint8() & 1) + 1) * 16;+ this.layer_size = [];+ for (let i = 0; i < 3; i++) if (FieldLength === 16) this.layer_size[i] = stream.readUint16();+ else this.layer_size[i] = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/a1op.ts+var a1opBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "OperatingPointSelectorProperty";+ }+ static {+ this.fourcc = "a1op";+ }+ parse(stream) {+ this.op_index = stream.readUint8();+ }+};++//#endregion+//#region src/boxes/auxC.ts+var auxCBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "AuxiliaryTypeProperty";+ }+ static {+ this.fourcc = "auxC";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.aux_type = stream.readCString();+ const aux_subtype_length = this.size - this.hdr_size - (this.aux_type.length + 1);+ this.aux_subtype = stream.readUint8Array(aux_subtype_length);+ }+};++//#endregion+//#region src/boxes/btrt.ts+var btrtBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "BitRateBox";+ }+ static {+ this.fourcc = "btrt";+ }+ parse(stream) {+ this.bufferSizeDB = stream.readUint32();+ this.maxBitrate = stream.readUint32();+ this.avgBitrate = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/ccst.ts+var ccstBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CodingConstraintsBox";+ }+ static {+ this.fourcc = "ccst";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const flags = stream.readUint8();+ this.all_ref_pics_intra = (flags & 128) === 128;+ this.intra_pred_used = (flags & 64) === 64;+ this.max_ref_per_pic = (flags & 63) >> 2;+ stream.readUint24();+ }+};++//#endregion+//#region src/boxes/cdef.ts+var cdefBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ComponentDefinitionBox";+ }+ static {+ this.fourcc = "cdef";+ }+ parse(stream) {+ this.channel_count = stream.readUint16();+ this.channel_indexes = [];+ this.channel_types = [];+ this.channel_associations = [];+ for (let i = 0; i < this.channel_count; i++) {+ this.channel_indexes.push(stream.readUint16());+ this.channel_types.push(stream.readUint16());+ this.channel_associations.push(stream.readUint16());+ }+ }+};++//#endregion+//#region src/boxes/clap.ts+var clapBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CleanApertureBox";+ }+ static {+ this.fourcc = "clap";+ }+ parse(stream) {+ this.cleanApertureWidthN = stream.readUint32();+ this.cleanApertureWidthD = stream.readUint32();+ this.cleanApertureHeightN = stream.readUint32();+ this.cleanApertureHeightD = stream.readUint32();+ this.horizOffN = stream.readUint32();+ this.horizOffD = stream.readUint32();+ this.vertOffN = stream.readUint32();+ this.vertOffD = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/clli.ts+var clliBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ContentLightLevelBox";+ }+ static {+ this.fourcc = "clli";+ }+ parse(stream) {+ this.max_content_light_level = stream.readUint16();+ this.max_pic_average_light_level = stream.readUint16();+ }+};++//#endregion+//#region src/boxes/cmex.ts+var cmexBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CameraExtrinsicMatrixProperty";+ }+ static {+ this.fourcc = "cmex";+ }+ parse(stream) {+ if (this.flags & 1) this.pos_x = stream.readInt32();+ if (this.flags & 2) this.pos_y = stream.readInt32();+ if (this.flags & 4) this.pos_z = stream.readInt32();+ if (this.flags & 8) {+ if (this.version === 0) if (this.flags & 16) {+ this.quat_x = stream.readInt32();+ this.quat_y = stream.readInt32();+ this.quat_z = stream.readInt32();+ } else {+ this.quat_x = stream.readInt16();+ this.quat_y = stream.readInt16();+ this.quat_z = stream.readInt16();+ }+ else if (this.version === 1) {}+ }+ if (this.flags & 32) this.id = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/cmin.ts+var cminBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CameraIntrinsicMatrixProperty";+ }+ static {+ this.fourcc = "cmin";+ }+ parse(stream) {+ this.focal_length_x = stream.readInt32();+ this.principal_point_x = stream.readInt32();+ this.principal_point_y = stream.readInt32();+ if (this.flags & 1) {+ this.focal_length_y = stream.readInt32();+ this.skew_factor = stream.readInt32();+ }+ }+};++//#endregion+//#region src/boxes/cmpC.ts+var cmpCBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CompressionConfigurationBox";+ }+ static {+ this.fourcc = "cmpC";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.compression_type = stream.readString(4);+ this.compressed_unit_type = stream.readUint8();+ }+};++//#endregion+//#region src/boxes/cmpd.ts+var cmpdBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ComponentDefinitionBox";+ }+ static {+ this.fourcc = "cmpd";+ }+ parse(stream) {+ this.component_count = stream.readUint32();+ this.component_types = [];+ this.component_type_urls = [];+ for (let i = 0; i < this.component_count; i++) {+ const component_type = stream.readUint16();+ this.component_types.push(component_type);+ if (component_type >= 32768) this.component_type_urls.push(stream.readCString());+ }+ }+};++//#endregion+//#region src/boxes/co64.ts+var co64Box = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ChunkLargeOffsetBox";+ }+ static {+ this.fourcc = "co64";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const entry_count = stream.readUint32();+ this.chunk_offsets = [];+ if (this.version === 0) for (let i = 0; i < entry_count; i++) this.chunk_offsets.push(stream.readUint64());+ }+ /** @bundle writing/co64.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 4 + 8 * this.chunk_offsets.length;+ this.writeHeader(stream);+ stream.writeUint32(this.chunk_offsets.length);+ for (let i = 0; i < this.chunk_offsets.length; i++) stream.writeUint64(this.chunk_offsets[i]);+ }+};++//#endregion+//#region src/boxes/CoLL.ts+var CoLLBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ContentLightLevelBox";+ }+ static {+ this.fourcc = "CoLL";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.maxCLL = stream.readUint16();+ this.maxFALL = stream.readUint16();+ }+};++//#endregion+//#region src/boxes/covi.ts+var SphereRegion = class {+ toString() {+ let s = "centre_azimuth: ";+ s += this.centre_azimuth;+ s += " (";+ s += this.centre_azimuth * 2 ** -16;+ s += "°), centre_elevation: ";+ s += this.centre_elevation;+ s += " (";+ s += this.centre_elevation * 2 ** -16;+ s += "°), centre_tilt: ";+ s += this.centre_tilt;+ s += " (";+ s += this.centre_tilt * 2 ** -16;+ s += "°)";+ if (this.range_included_flag) {+ s += ", azimuth_range: ";+ s += this.azimuth_range;+ s += " (";+ s += this.azimuth_range * 2 ** -16;+ s += "°), elevation_range: ";+ s += this.elevation_range;+ s += " (";+ s += this.elevation_range * 2 ** -16;+ s += "°)";+ }+ if (this.interpolate_included_flag) {+ s += ", interpolate: ";+ s += this.interpolate;+ }+ return s;+ }+};+var CoverageSphereRegion = class {+ toString() {+ let s = "";+ if (this.view_idc) {+ s += "view_idc: ";+ s += this.view_idc;+ s += ", ";+ }+ s += "sphere_region: {";+ s += this.sphere_region;+ s += "}";+ return s;+ }+};+var coviBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CoverageInformationBox";+ }+ static {+ this.fourcc = "covi";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.coverage_shape_type = stream.readUint8();+ const num_regions = stream.readUint8();+ const f = stream.readInt8();+ const view_idc_presence_flag = f & 128;+ if (view_idc_presence_flag) this.default_view_idc = (f & 96) >> 5;+ this.coverage_regions = new Array();+ for (let i = 0; i < num_regions; i++) {+ const region = new CoverageSphereRegion();+ if (view_idc_presence_flag) region.view_idc = stream.readUint8() >> 6;+ region.sphere_region = this.parseSphereRegion(stream, true, true);+ this.coverage_regions.push(region);+ }+ }+ parseSphereRegion(stream, range_included_flag, interpolate_included_flag) {+ const sphere_region = new SphereRegion();+ sphere_region.centre_azimuth = stream.readInt32();+ sphere_region.centre_elevation = stream.readInt32();+ sphere_region.centre_tilt = stream.readInt32();+ sphere_region.range_included_flag = range_included_flag;+ if (range_included_flag) {+ sphere_region.azimuth_range = stream.readUint32();+ sphere_region.elevation_range = stream.readUint32();+ }+ sphere_region.interpolate_included_flag = interpolate_included_flag;+ if (interpolate_included_flag) sphere_region.interpolate = (stream.readUint8() & 128) === 128;+ return sphere_region;+ }+};++//#endregion+//#region src/boxes/cprt.ts+var cprtBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CopyrightBox";+ }+ static {+ this.fourcc = "cprt";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.parseLanguage(stream);+ this.notice = stream.readCString();+ }+};++//#endregion+//#region src/boxes/csch.ts+var cschBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CompatibleSchemeTypeBox";+ }+ static {+ this.fourcc = "csch";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.scheme_type = stream.readString(4);+ this.scheme_version = stream.readUint32();+ if (this.flags & 1) this.scheme_uri = stream.readCString();+ }+};++//#endregion+//#region src/boxes/cslg.ts+const INT32_MAX = 2147483647;+var cslgBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CompositionToDecodeBox";+ }+ static {+ this.fourcc = "cslg";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 0) {+ this.compositionToDTSShift = stream.readInt32();+ this.leastDecodeToDisplayDelta = stream.readInt32();+ this.greatestDecodeToDisplayDelta = stream.readInt32();+ this.compositionStartTime = stream.readInt32();+ this.compositionEndTime = stream.readInt32();+ } else if (this.version === 1) {+ this.compositionToDTSShift = stream.readInt64();+ this.leastDecodeToDisplayDelta = stream.readInt64();+ this.greatestDecodeToDisplayDelta = stream.readInt64();+ this.compositionStartTime = stream.readInt64();+ this.compositionEndTime = stream.readInt64();+ }+ }+ /** @bundle writing/cslg.js */+ write(stream) {+ this.version = 0;+ if (this.compositionToDTSShift > INT32_MAX || this.leastDecodeToDisplayDelta > INT32_MAX || this.greatestDecodeToDisplayDelta > INT32_MAX || this.compositionStartTime > INT32_MAX || this.compositionEndTime > INT32_MAX) this.version = 1;+ this.flags = 0;+ if (this.version === 0) {+ this.size = 20;+ this.writeHeader(stream);+ stream.writeInt32(this.compositionToDTSShift);+ stream.writeInt32(this.leastDecodeToDisplayDelta);+ stream.writeInt32(this.greatestDecodeToDisplayDelta);+ stream.writeInt32(this.compositionStartTime);+ stream.writeInt32(this.compositionEndTime);+ } else if (this.version === 1) {+ this.size = 40;+ this.writeHeader(stream);+ stream.writeInt64(this.compositionToDTSShift);+ stream.writeInt64(this.leastDecodeToDisplayDelta);+ stream.writeInt64(this.greatestDecodeToDisplayDelta);+ stream.writeInt64(this.compositionStartTime);+ stream.writeInt64(this.compositionEndTime);+ }+ }+};++//#endregion+//#region src/boxes/ctts.ts+var cttsBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CompositionOffsetBox";+ }+ static {+ this.fourcc = "ctts";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const entry_count = stream.readUint32();+ this.sample_counts = [];+ this.sample_offsets = [];+ if (this.version === 0) for (let i = 0; i < entry_count; i++) {+ this.sample_counts.push(stream.readUint32());+ const value = stream.readInt32();+ if (value < 0) Log.warn("BoxParser", "ctts box uses negative values without using version 1");+ this.sample_offsets.push(value);+ }+ else if (this.version === 1) for (let i = 0; i < entry_count; i++) {+ this.sample_counts.push(stream.readUint32());+ this.sample_offsets.push(stream.readInt32());+ }+ }+ /** @bundle writing/ctts.js */+ write(stream) {+ this.version = this.sample_offsets.some((offset) => offset < 0) ? 1 : 0;+ this.flags = 0;+ this.size = 4 + 8 * this.sample_counts.length;+ this.writeHeader(stream);+ stream.writeUint32(this.sample_counts.length);+ for (let i = 0; i < this.sample_counts.length; i++) {+ stream.writeUint32(this.sample_counts[i]);+ if (this.version === 1) stream.writeInt32(this.sample_offsets[i]);+ else stream.writeUint32(this.sample_offsets[i]);+ }+ }+ /** @bundle box-unpack.js */+ unpack(samples) {+ let k = 0;+ for (let i = 0; i < this.sample_counts.length; i++) for (let j = 0; j < this.sample_counts[i]; j++) {+ samples[k].pts = samples[k].dts + this.sample_offsets[i];+ k++;+ }+ }+};++//#endregion+//#region src/boxes/dac3.ts+var dac3Box = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "AC3SpecificBox";+ }+ static {+ this.fourcc = "dac3";+ }+ parse(stream) {+ const tmp_byte1 = stream.readUint8();+ const tmp_byte2 = stream.readUint8();+ const tmp_byte3 = stream.readUint8();+ this.fscod = tmp_byte1 >> 6;+ this.bsid = tmp_byte1 >> 1 & 31;+ this.bsmod = (tmp_byte1 & 1) << 2 | tmp_byte2 >> 6 & 3;+ this.acmod = tmp_byte2 >> 3 & 7;+ this.lfeon = tmp_byte2 >> 2 & 1;+ this.bit_rate_code = tmp_byte2 & 3 | tmp_byte3 >> 5 & 7;+ }+};++//#endregion+//#region src/boxes/dec3.ts+var dec3Box = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "EC3SpecificBox";+ }+ static {+ this.fourcc = "dec3";+ }+ parse(stream) {+ const tmp_16 = stream.readUint16();+ this.data_rate = tmp_16 >> 3;+ this.num_ind_sub = tmp_16 & 7;+ this.ind_subs = [];+ for (let i = 0; i < this.num_ind_sub + 1; i++) {+ const tmp_byte1 = stream.readUint8();+ const tmp_byte2 = stream.readUint8();+ const tmp_byte3 = stream.readUint8();+ const ind_sub = {+ fscod: tmp_byte1 >> 6,+ bsid: tmp_byte1 >> 1 & 31,+ bsmod: (tmp_byte1 & 1) << 4 | tmp_byte2 >> 4 & 15,+ acmod: tmp_byte2 >> 1 & 7,+ lfeon: tmp_byte2 & 1,+ num_dep_sub: tmp_byte3 >> 1 & 15+ };+ this.ind_subs.push(ind_sub);+ if (ind_sub.num_dep_sub > 0) ind_sub.chan_loc = (tmp_byte3 & 1) << 8 | stream.readUint8();+ }+ }+};++//#endregion+//#region src/boxes/dfLa.ts+var dfLaBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "FLACSpecificBox";+ }+ static {+ this.fourcc = "dfLa";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const BLOCKTYPE_MASK = 127;+ const LASTMETADATABLOCKFLAG_MASK = 128;+ const boxesFound = [];+ const knownBlockTypes = [+ "STREAMINFO",+ "PADDING",+ "APPLICATION",+ "SEEKTABLE",+ "VORBIS_COMMENT",+ "CUESHEET",+ "PICTURE",+ "RESERVED"+ ];+ let flagAndType;+ do {+ flagAndType = stream.readUint8();+ const type = Math.min(flagAndType & BLOCKTYPE_MASK, knownBlockTypes.length - 1);+ if (!type) {+ stream.readUint8Array(13);+ this.samplerate = stream.readUint32() >> 12;+ stream.readUint8Array(20);+ } else stream.readUint8Array(stream.readUint24());+ boxesFound.push(knownBlockTypes[type]);+ } while (flagAndType & LASTMETADATABLOCKFLAG_MASK);+ this.numMetadataBlocks = boxesFound.length + " (" + boxesFound.join(", ") + ")";+ }+};++//#endregion+//#region src/boxes/dimm.ts+var dimmBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintimmediateBytesSent";+ }+ static {+ this.fourcc = "dimm";+ }+ parse(stream) {+ this.bytessent = stream.readUint64();+ }+};++//#endregion+//#region src/boxes/dmax.ts+var dmax = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintlongestpacket";+ }+ static {+ this.fourcc = "dmax";+ }+ parse(stream) {+ this.time = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/dmed.ts+var dmedBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintmediaBytesSent";+ }+ static {+ this.fourcc = "dmed";+ }+ parse(stream) {+ this.bytessent = stream.readUint64();+ }+};++//#endregion+//#region src/boxes/dOps.ts+var dOpsBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "OpusSpecificBox";+ }+ static {+ this.fourcc = "dOps";+ }+ parse(stream) {+ this.Version = stream.readUint8();+ this.OutputChannelCount = stream.readUint8();+ this.PreSkip = stream.readUint16();+ this.InputSampleRate = stream.readUint32();+ this.OutputGain = stream.readInt16();+ this.ChannelMappingFamily = stream.readUint8();+ if (this.ChannelMappingFamily !== 0) {+ this.StreamCount = stream.readUint8();+ this.CoupledCount = stream.readUint8();+ this.ChannelMapping = [];+ for (let i = 0; i < this.OutputChannelCount; i++) this.ChannelMapping[i] = stream.readUint8();+ }+ }+ write(stream) {+ this.size = 11;+ if (this.ChannelMappingFamily !== 0) this.size += 2 + this.OutputChannelCount;+ this.writeHeader(stream);+ stream.writeUint8(this.Version);+ stream.writeUint8(this.OutputChannelCount);+ stream.writeUint16(this.PreSkip);+ stream.writeUint32(this.InputSampleRate);+ stream.writeInt16(this.OutputGain);+ stream.writeUint8(this.ChannelMappingFamily);+ if (this.ChannelMappingFamily !== 0) {+ stream.writeUint8(this.StreamCount);+ stream.writeUint8(this.CoupledCount);+ for (let i = 0; i < this.OutputChannelCount; i++) stream.writeUint8(this.ChannelMapping[i]);+ }+ }+};++//#endregion+//#region src/boxes/drep.ts+var drepBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintrepeatedBytesSent";+ }+ static {+ this.fourcc = "drep";+ }+ parse(stream) {+ this.bytessent = stream.readUint64();+ }+};++//#endregion+//#region src/boxes/elst.ts+var elstBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "EditListBox";+ }+ static {+ this.fourcc = "elst";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.entries = [];+ const entry_count = stream.readUint32();+ for (let i = 0; i < entry_count; i++) {+ const entry = {+ segment_duration: this.version === 1 ? stream.readUint64() : stream.readUint32(),+ media_time: this.version === 1 ? stream.readInt64() : stream.readInt32(),+ media_rate_integer: stream.readInt16(),+ media_rate_fraction: stream.readInt16()+ };+ this.entries.push(entry);+ }+ }+ /** @bundle writing/elst.js */+ write(stream) {+ const useVersion1 = this.entries.some((entry) => entry.segment_duration > MAX_UINT32 || entry.media_time > MAX_UINT32) || this.version === 1;+ this.version = useVersion1 ? 1 : 0;+ this.size = 4 + 12 * this.entries.length;+ this.size += useVersion1 ? 8 * this.entries.length : 0;+ this.writeHeader(stream);+ stream.writeUint32(this.entries.length);+ for (let i = 0; i < this.entries.length; i++) {+ const entry = this.entries[i];+ if (useVersion1) {+ stream.writeUint64(entry.segment_duration);+ stream.writeInt64(entry.media_time);+ } else {+ stream.writeUint32(entry.segment_duration);+ stream.writeInt32(entry.media_time);+ }+ stream.writeInt16(entry.media_rate_integer);+ stream.writeInt16(entry.media_rate_fraction);+ }+ }+};++//#endregion+//#region src/boxes/EntityToGroup/base.ts+var EntityToGroup = class extends FullBox {+ parse(stream) {+ this.parseFullHeader(stream);+ this.group_id = stream.readUint32();+ this.num_entities_in_group = stream.readUint32();+ this.entity_ids = [];+ for (let i = 0; i < this.num_entities_in_group; i++) {+ const entity_id = stream.readUint32();+ this.entity_ids.push(entity_id);+ }+ }+};++//#endregion+//#region src/boxes/EntityToGroup/index.ts+var aebrBox = class extends EntityToGroup {+ constructor(..._args) {+ super(..._args);+ this.box_name = "Auto exposure bracketing";+ }+ static {+ this.fourcc = "aebr";+ }+};+var afbrBox = class extends EntityToGroup {+ constructor(..._args2) {+ super(..._args2);+ this.box_name = "Flash exposure information";+ }+ static {+ this.fourcc = "afbr";+ }+};+var albcBox = class extends EntityToGroup {+ constructor(..._args3) {+ super(..._args3);+ this.box_name = "Album collection";+ }+ static {+ this.fourcc = "albc";+ }+};+var altrBox = class extends EntityToGroup {+ constructor(..._args4) {+ super(..._args4);+ this.box_name = "Alternative entity";+ }+ static {+ this.fourcc = "altr";+ }+};+var brstBox = class extends EntityToGroup {+ constructor(..._args5) {+ super(..._args5);+ this.box_name = "Burst image";+ }+ static {+ this.fourcc = "brst";+ }+};+var dobrBox = class extends EntityToGroup {+ constructor(..._args6) {+ super(..._args6);+ this.box_name = "Depth of field bracketing";+ }+ static {+ this.fourcc = "dobr";+ }+};+var eqivBox = class extends EntityToGroup {+ constructor(..._args7) {+ super(..._args7);+ this.box_name = "Equivalent entity";+ }+ static {+ this.fourcc = "eqiv";+ }+};+var favcBox = class extends EntityToGroup {+ constructor(..._args8) {+ super(..._args8);+ this.box_name = "Favorites collection";+ }+ static {+ this.fourcc = "favc";+ }+};+var fobrBox = class extends EntityToGroup {+ constructor(..._args9) {+ super(..._args9);+ this.box_name = "Focus bracketing";+ }+ static {+ this.fourcc = "fobr";+ }+};+var iaugBox = class extends EntityToGroup {+ constructor(..._args10) {+ super(..._args10);+ this.box_name = "Image item with an audio track";+ }+ static {+ this.fourcc = "iaug";+ }+};+var panoBox = class extends EntityToGroup {+ constructor(..._args11) {+ super(..._args11);+ this.box_name = "Panorama";+ }+ static {+ this.fourcc = "pano";+ }+};+var slidBox = class extends EntityToGroup {+ constructor(..._args12) {+ super(..._args12);+ this.box_name = "Slideshow";+ }+ static {+ this.fourcc = "slid";+ }+};+var sterBox = class extends EntityToGroup {+ constructor(..._args13) {+ super(..._args13);+ this.box_name = "Stereo";+ }+ static {+ this.fourcc = "ster";+ }+};+var tsynBox = class extends EntityToGroup {+ constructor(..._args14) {+ super(..._args14);+ this.box_name = "Time-synchronized capture";+ }+ static {+ this.fourcc = "tsyn";+ }+};+var wbbrBox = class extends EntityToGroup {+ constructor(..._args15) {+ super(..._args15);+ this.box_name = "White balance bracketing";+ }+ static {+ this.fourcc = "wbbr";+ }+};+var prgrBox = class extends EntityToGroup {+ constructor(..._args16) {+ super(..._args16);+ this.box_name = "Progressive rendering";+ }+ static {+ this.fourcc = "prgr";+ }+};+var pymdBox = class extends EntityToGroup {+ constructor(..._args17) {+ super(..._args17);+ this.box_name = "Image pyramid";+ }+ static {+ this.fourcc = "pymd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.group_id = stream.readUint32();+ this.num_entities_in_group = stream.readUint32();+ this.entity_ids = [];+ for (let i = 0; i < this.num_entities_in_group; i++) {+ const entity_id = stream.readUint32();+ this.entity_ids.push(entity_id);+ }+ this.tile_size_x = stream.readUint16();+ this.tile_size_y = stream.readUint16();+ this.layer_binning = [];+ this.tiles_in_layer_column_minus1 = [];+ this.tiles_in_layer_row_minus1 = [];+ for (let i = 0; i < this.num_entities_in_group; i++) {+ this.layer_binning[i] = stream.readUint16();+ this.tiles_in_layer_row_minus1[i] = stream.readUint16();+ this.tiles_in_layer_column_minus1[i] = stream.readUint16();+ }+ }+};++//#endregion+//#region src/boxes/fiel.ts+var fielBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "FieldHandlingBox";+ }+ static {+ this.fourcc = "fiel";+ }+ parse(stream) {+ this.fieldCount = stream.readUint8();+ this.fieldOrdering = stream.readUint8();+ }+};++//#endregion+//#region src/boxes/frma.ts+var frmaBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "OriginalFormatBox";+ }+ static {+ this.fourcc = "frma";+ }+ parse(stream) {+ this.data_format = stream.readString(4);+ }+};++//#endregion+//#region src/boxes/imir.ts+var imirBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ImageMirror";+ }+ static {+ this.fourcc = "imir";+ }+ parse(stream) {+ const tmp = stream.readUint8();+ this.reserved = tmp >> 7;+ this.axis = tmp & 1;+ }+};++//#endregion+//#region src/boxes/ipma.ts+var ipmaBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ItemPropertyAssociationBox";+ }+ static {+ this.fourcc = "ipma";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const entry_count = stream.readUint32();+ this.associations = [];+ for (let i = 0; i < entry_count; i++) {+ const id = this.version < 1 ? stream.readUint16() : stream.readUint32();+ const props = [];+ const association_count = stream.readUint8();+ for (let j = 0; j < association_count; j++) {+ const tmp = stream.readUint8();+ props.push({+ essential: (tmp & 128) >> 7 === 1,+ property_index: this.flags & 1 ? (tmp & 127) << 8 | stream.readUint8() : tmp & 127+ });+ }+ this.associations.push({+ id,+ props+ });+ }+ }+};++//#endregion+//#region src/boxes/irot.ts+var irotBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ImageRotation";+ }+ static {+ this.fourcc = "irot";+ }+ parse(stream) {+ this.angle = stream.readUint8() & 3;+ }+};++//#endregion+//#region src/boxes/ispe.ts+var ispeBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ImageSpatialExtentsProperty";+ }+ static {+ this.fourcc = "ispe";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.image_width = stream.readUint32();+ this.image_height = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/itai.ts+var itaiBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TAITimestampBox";+ }+ static {+ this.fourcc = "itai";+ }+ parse(stream) {+ this.TAI_timestamp = stream.readUint64();+ const status_bits = stream.readUint8();+ this.sychronization_state = status_bits >> 7 & 1;+ this.timestamp_generation_failure = status_bits >> 6 & 1;+ this.timestamp_is_modified = status_bits >> 5 & 1;+ }+};++//#endregion+//#region src/boxes/kind.ts+var kindBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "KindBox";+ }+ static {+ this.fourcc = "kind";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.schemeURI = stream.readCString();+ if (!this.isEndOfBox(stream)) this.value = stream.readCString();+ }+ /** @bundle writing/kind.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = this.schemeURI.length + 1 + (this.value ? this.value.length + 1 : 0);+ this.writeHeader(stream);+ stream.writeCString(this.schemeURI);+ if (this.value) stream.writeCString(this.value);+ }+};++//#endregion+//#region src/boxes/leva.ts+var levaBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "LevelAssignmentBox";+ }+ static {+ this.fourcc = "leva";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const count = stream.readUint8();+ this.levels = [];+ for (let i = 0; i < count; i++) {+ const level = {};+ this.levels[i] = level;+ level.track_ID = stream.readUint32();+ const tmp_byte = stream.readUint8();+ level.padding_flag = tmp_byte >> 7;+ level.assignment_type = tmp_byte & 127;+ switch (level.assignment_type) {+ case 0:+ level.grouping_type = stream.readString(4);+ break;+ case 1:+ level.grouping_type = stream.readString(4);+ level.grouping_type_parameter = stream.readUint32();+ break;+ case 2: break;+ case 3: break;+ case 4:+ level.sub_track_id = stream.readUint32();+ break;+ default: Log.warn("BoxParser", `Unknown level assignment type: ${level.assignment_type}`);+ }+ }+ }+};++//#endregion+//#region src/boxes/lhvC.ts+var lhvCBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "LHEVCConfigurationBox";+ }+ static {+ this.fourcc = "lhvC";+ }+ parse(stream) {+ this.configurationVersion = stream.readUint8();+ this.min_spatial_segmentation_idc = stream.readUint16() & 4095;+ this.parallelismType = stream.readUint8() & 3;+ let tmp_byte = stream.readUint8();+ this.numTemporalLayers = (tmp_byte & 13) >> 3;+ this.temporalIdNested = (tmp_byte & 4) >> 2;+ this.lengthSizeMinusOne = tmp_byte & 3;+ this.nalu_arrays = [];+ const numOfArrays = stream.readUint8();+ for (let i = 0; i < numOfArrays; i++) {+ const nalu_array = [];+ this.nalu_arrays.push(nalu_array);+ tmp_byte = stream.readUint8();+ nalu_array.completeness = (tmp_byte & 128) >> 7;+ nalu_array.nalu_type = tmp_byte & 63;+ const numNalus = stream.readUint16();+ for (let j = 0; j < numNalus; j++) {+ const length = stream.readUint16();+ nalu_array.push({ data: stream.readUint8Array(length) });+ }+ }+ }+};++//#endregion+//#region src/boxes/lsel.ts+var lselBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "LayerSelectorProperty";+ }+ static {+ this.fourcc = "lsel";+ }+ parse(stream) {+ this.layer_id = stream.readUint16();+ }+};++//#endregion+//#region src/boxes/maxr.ts+var maxrBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintmaxrate";+ }+ static {+ this.fourcc = "maxr";+ }+ parse(stream) {+ this.period = stream.readUint32();+ this.bytes = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/displays/colorPoint.ts+var ColorPoint = class {+ constructor(x, y) {+ this.x = x;+ this.y = y;+ }+ toString() {+ return "(" + this.x + "," + this.y + ")";+ }+};++//#endregion+//#region src/boxes/mdcv.ts+var mdcvBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "MasteringDisplayColourVolumeBox";+ }+ static {+ this.fourcc = "mdcv";+ }+ parse(stream) {+ this.display_primaries = [];+ this.display_primaries[0] = new ColorPoint(stream.readUint16(), stream.readUint16());+ this.display_primaries[1] = new ColorPoint(stream.readUint16(), stream.readUint16());+ this.display_primaries[2] = new ColorPoint(stream.readUint16(), stream.readUint16());+ this.white_point = new ColorPoint(stream.readUint16(), stream.readUint16());+ this.max_display_mastering_luminance = stream.readUint32();+ this.min_display_mastering_luminance = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/mfro.ts+var mfroBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "MovieFragmentRandomAccessOffsetBox";+ }+ static {+ this.fourcc = "mfro";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this._size = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/mskC.ts+var mskCBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "MaskConfigurationProperty";+ }+ static {+ this.fourcc = "mskC";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.bits_per_pixel = stream.readUint8();+ }+};++//#endregion+//#region src/boxes/npck.ts+var npckBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintPacketsSent";+ }+ static {+ this.fourcc = "npck";+ }+ parse(stream) {+ this.packetssent = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/nump.ts+var numpBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintPacketsSent";+ }+ static {+ this.fourcc = "nump";+ }+ parse(stream) {+ this.packetssent = stream.readUint64();+ }+};++//#endregion+//#region src/boxes/padb.ts+var PaddingBit = class {+ constructor(pad1, pad2) {+ this.pad1 = pad1;+ this.pad2 = pad2;+ }+};+var padbBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "PaddingBitsBox";+ }+ static {+ this.fourcc = "padb";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const sample_count = stream.readUint32();+ this.padbits = [];+ for (let i = 0; i < Math.floor((sample_count + 1) / 2); i++) {+ const bits = stream.readUint8();+ const pad1 = (bits & 112) >> 4;+ const pad2 = bits & 7;+ this.padbits.push(new PaddingBit(pad1, pad2));+ }+ }+};++//#endregion+//#region src/boxes/pasp.ts+var paspBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "PixelAspectRatioBox";+ }+ static {+ this.fourcc = "pasp";+ }+ parse(stream) {+ this.hSpacing = stream.readUint32();+ this.vSpacing = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/payl.ts+var paylBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CuePayloadBox";+ }+ static {+ this.fourcc = "payl";+ }+ parse(stream) {+ this.text = stream.readString(this.size - this.hdr_size);+ }+};++//#endregion+//#region src/boxes/payt.ts+var paytBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintpayloadID";+ }+ static {+ this.fourcc = "payt";+ }+ parse(stream) {+ this.payloadID = stream.readUint32();+ const count = stream.readUint8();+ this.rtpmap_string = stream.readString(count);+ }+};++//#endregion+//#region src/boxes/pdin.ts+var pdinBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ProgressiveDownloadInfoBox";+ this.rate = [];+ this.initial_delay = [];+ }+ static {+ this.fourcc = "pdin";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const count = (this.size - this.hdr_size) / 8;+ for (let i = 0; i < count; i++) {+ this.rate[i] = stream.readUint32();+ this.initial_delay[i] = stream.readUint32();+ }+ }+};++//#endregion+//#region src/boxes/pixi.ts+var pixiBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "PixelInformationProperty";+ }+ static {+ this.fourcc = "pixi";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.num_channels = stream.readUint8();+ this.bits_per_channels = [];+ for (let i = 0; i < this.num_channels; i++) this.bits_per_channels[i] = stream.readUint8();+ }+};++//#endregion+//#region src/boxes/pmax.ts+var pmaxBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintlargestpacket";+ }+ static {+ this.fourcc = "pmax";+ }+ parse(stream) {+ this.bytes = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/prdi.ts+var prdiBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ProgressiveDerivedImageItemInformationProperty";+ }+ static {+ this.fourcc = "prdi";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.step_count = stream.readUint16();+ this.item_count = [];+ if (this.flags & 2) for (let i = 0; i < this.step_count; i++) this.item_count[i] = stream.readUint16();+ }+};++//#endregion+//#region src/boxes/prfr.ts+var prfrBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ProjectionFormatBox";+ }+ static {+ this.fourcc = "prfr";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.projection_type = stream.readUint8() & 31;+ }+};++//#endregion+//#region src/boxes/prft.ts+var prftBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ProducerReferenceTimeBox";+ }+ static {+ this.fourcc = "prft";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.ref_track_id = stream.readUint32();+ this.ntp_timestamp = stream.readUint64();+ if (this.version === 0) this.media_time = stream.readUint32();+ else this.media_time = stream.readUint64();+ }+};++//#endregion+//#region src/boxes/pssh.ts+var psshBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ProtectionSystemSpecificHeaderBox";+ }+ static {+ this.fourcc = "pssh";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.system_id = parseHex16(stream);+ this.kid = [];+ if (this.version > 0) {+ const count = stream.readUint32();+ for (let i = 0; i < count; i++) this.kid[i] = parseHex16(stream);+ }+ const datasize = stream.readUint32();+ if (datasize > 0) this.protection_data = stream.readUint8Array(datasize);+ }+};++//#endregion+//#region src/boxes/qt/clef.ts+var clefBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackCleanApertureDimensionsBox";+ }+ static {+ this.fourcc = "clef";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.width = stream.readUint32();+ this.height = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/qt/data.ts+function parseItifData(type, data) {+ if (type === dataBox.Types.UTF8) return new TextDecoder("utf-8").decode(data);+ const view = new DataView(data.buffer);+ if (type === dataBox.Types.BE_UNSIGNED_INT) if (data.length === 1) return view.getUint8(0);+ else if (data.length === 2) return view.getUint16(0, false);+ else if (data.length === 4) return view.getUint32(0, false);+ else if (data.length === 8) return view.getBigUint64(0, false);+ else throw new Error("Unsupported ITIF_TYPE_BE_UNSIGNED_INT length " + data.length);+ else if (type === dataBox.Types.BE_SIGNED_INT) if (data.length === 1) return view.getInt8(0);+ else if (data.length === 2) return view.getInt16(0, false);+ else if (data.length === 4) return view.getInt32(0, false);+ else if (data.length === 8) return view.getBigInt64(0, false);+ else throw new Error("Unsupported ITIF_TYPE_BE_SIGNED_INT length " + data.length);+ else if (type === dataBox.Types.BE_FLOAT32) return view.getFloat32(0, false);+ Log.warn("DataBox", "Unsupported or unimplemented itif data type: " + type);+}+var dataBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "DataBox";+ }+ static {+ this.fourcc = "data";+ }+ static {+ this.Types = {+ RESERVED: 0,+ UTF8: 1,+ UTF16: 2,+ SJIS: 3,+ UTF8_SORT: 4,+ UTF16_SORT: 5,+ JPEG: 13,+ PNG: 14,+ BE_SIGNED_INT: 21,+ BE_UNSIGNED_INT: 22,+ BE_FLOAT32: 23,+ BE_FLOAT64: 24,+ BMP: 27,+ QT_ATOM: 28,+ BE_SIGNED_INT8: 65,+ BE_SIGNED_INT16: 66,+ BE_SIGNED_INT32: 67,+ BE_FLOAT32_POINT: 70,+ BE_FLOAT32_DIMENSIONS: 71,+ BE_FLOAT32_RECT: 72,+ BE_SIGNED_INT64: 74,+ BE_UNSIGNED_INT8: 75,+ BE_UNSIGNED_INT16: 76,+ BE_UNSIGNED_INT32: 77,+ BE_UNSIGNED_INT64: 78,+ BE_FLOAT64_AFFINE_TRANSFORM: 79+ };+ }+ parse(stream) {+ this.valueType = stream.readUint32();+ this.country = stream.readUint16();+ if (this.country > 255) {+ stream.seek(stream.getPosition() - 2);+ this.countryString = stream.readString(2);+ }+ this.language = stream.readUint16();+ if (this.language > 255) {+ stream.seek(stream.getPosition() - 2);+ this.parseLanguage(stream);+ }+ this.raw = stream.readUint8Array(this.size - this.hdr_size - 8);+ this.value = parseItifData(this.valueType, this.raw);+ }+};++//#endregion+//#region src/boxes/qt/enof.ts+var enofBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackEncodedPixelsDimensionsBox";+ }+ static {+ this.fourcc = "enof";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.width = stream.readUint32();+ this.height = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/qt/ilst.ts+var ilstBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "IlstBox";+ }+ static {+ this.fourcc = "ilst";+ }+ parse(stream) {+ this.list = {};+ let total = this.size - this.hdr_size;+ while (total > 0) {+ const size = stream.readUint32();+ const index = stream.readUint32();+ const res = parseOneBox(stream, false, size - 8);+ if (res.code === 1) this.list[index] = res.box;+ total -= size;+ }+ }+};++//#endregion+//#region src/boxes/qt/keys.ts+var keysBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "KeysBox";+ }+ static {+ this.fourcc = "keys";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.count = stream.readUint32();+ this.keys = {};+ for (let i = 0; i < this.count; i++) {+ const len = stream.readUint32();+ this.keys[i + 1] = stream.readString(len - 4);+ }+ }+};++//#endregion+//#region src/boxes/qt/prof.ts+var profBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackProductionApertureDimensionsBox";+ }+ static {+ this.fourcc = "prof";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.width = stream.readUint32();+ this.height = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/qt/tapt.ts+var taptBox = class extends ContainerBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackApertureModeDimensionsBox";+ this.clefs = [];+ this.profs = [];+ this.enofs = [];+ this.subBoxNames = [+ "clef",+ "prof",+ "enof"+ ];+ }+ static {+ this.fourcc = "tapt";+ }+};++//#endregion+//#region src/boxes/rtp.ts+var rtp_Box = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "rtpmoviehintinformation";+ }+ static {+ this.fourcc = "rtp ";+ }+ parse(stream) {+ this.descriptionformat = stream.readString(4);+ this.sdptext = stream.readString(this.size - this.hdr_size - 4);+ }+};++//#endregion+//#region src/boxes/saio.ts+var saioBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SampleAuxiliaryInformationOffsetsBox";+ }+ static {+ this.fourcc = "saio";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.flags & 1) {+ this.aux_info_type = stream.readString(4);+ this.aux_info_type_parameter = stream.readUint32();+ }+ this.entry_count = stream.readUint32();+ this.offset = [];+ for (let i = 0; i < this.entry_count; i++) if (this.version === 0) this.offset[i] = stream.readUint32();+ else this.offset[i] = stream.readUint64();+ }+};++//#endregion+//#region src/boxes/saiz.ts+var saizBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SampleAuxiliaryInformationSizesBox";+ }+ static {+ this.fourcc = "saiz";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.flags & 1) {+ this.aux_info_type = stream.readString(4);+ this.aux_info_type_parameter = stream.readUint32();+ }+ this.default_sample_info_size = stream.readUint8();+ this.sample_count = stream.readUint32();+ this.sample_info_size = [];+ if (this.default_sample_info_size === 0) for (let i = 0; i < this.sample_count; i++) this.sample_info_size[i] = stream.readUint8();+ }+};++//#endregion+//#region src/boxes/displays/pixel.ts+var Pixel = class {+ constructor(bad_pixel_row, bad_pixel_column) {+ this.bad_pixel_row = bad_pixel_row;+ this.bad_pixel_column = bad_pixel_column;+ }+ toString() {+ return "[row: " + this.bad_pixel_row + ", column: " + this.bad_pixel_column + "]";+ }+};++//#endregion+//#region src/boxes/sbpm.ts+var sbpmBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SensorBadPixelsMapBox";+ }+ static {+ this.fourcc = "sbpm";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.component_count = stream.readUint16();+ this.component_index = [];+ for (let i = 0; i < this.component_count; i++) this.component_index.push(stream.readUint16());+ const flags = stream.readUint8();+ this.correction_applied = 128 === (flags & 128);+ this.num_bad_rows = stream.readUint32();+ this.num_bad_cols = stream.readUint32();+ this.num_bad_pixels = stream.readUint32();+ this.bad_rows = [];+ this.bad_columns = [];+ this.bad_pixels = [];+ for (let i = 0; i < this.num_bad_rows; i++) this.bad_rows.push(stream.readUint32());+ for (let i = 0; i < this.num_bad_cols; i++) this.bad_columns.push(stream.readUint32());+ for (let i = 0; i < this.num_bad_pixels; i++) {+ const row = stream.readUint32();+ const col = stream.readUint32();+ this.bad_pixels.push(new Pixel(row, col));+ }+ }+};++//#endregion+//#region src/boxes/schm.ts+var schmBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SchemeTypeBox";+ }+ static {+ this.fourcc = "schm";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.scheme_type = stream.readString(4);+ this.scheme_version = stream.readUint32();+ if (this.flags & 1) this.scheme_uri = stream.readString(this.size - this.hdr_size - 8);+ }+};++//#endregion+//#region src/boxes/sdp.ts+var sdp_Box = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "rtptracksdphintinformation";+ }+ static {+ this.fourcc = "sdp ";+ }+ parse(stream) {+ this.sdptext = stream.readString(this.size - this.hdr_size);+ }+};++//#endregion+//#region src/boxes/senc.ts+var sencBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SampleEncryptionBox";+ }+ static {+ this.fourcc = "senc";+ }+};++//#endregion+//#region src/boxes/SmDm.ts+var SmDmBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SMPTE2086MasteringDisplayMetadataBox";+ }+ static {+ this.fourcc = "SmDm";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.primaryRChromaticity_x = stream.readUint16();+ this.primaryRChromaticity_y = stream.readUint16();+ this.primaryGChromaticity_x = stream.readUint16();+ this.primaryGChromaticity_y = stream.readUint16();+ this.primaryBChromaticity_x = stream.readUint16();+ this.primaryBChromaticity_y = stream.readUint16();+ this.whitePointChromaticity_x = stream.readUint16();+ this.whitePointChromaticity_y = stream.readUint16();+ this.luminanceMax = stream.readUint32();+ this.luminanceMin = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/srat.ts+var sratBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SamplingRateBox";+ }+ static {+ this.fourcc = "srat";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.sampling_rate = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/stdp.ts+var stdpBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "DegradationPriorityBox";+ }+ static {+ this.fourcc = "stdp";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const count = (this.size - this.hdr_size) / 2;+ this.priority = [];+ for (let i = 0; i < count; i++) this.priority[i] = stream.readUint16();+ }+};++//#endregion+//#region src/boxes/stri.ts+var striBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SubTrackInformationBox";+ }+ static {+ this.fourcc = "stri";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.switch_group = stream.readUint16();+ this.alternate_group = stream.readUint16();+ this.sub_track_id = stream.readUint32();+ const count = (this.size - this.hdr_size - 8) / 4;+ this.attribute_list = [];+ for (let i = 0; i < count; i++) this.attribute_list[i] = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/stsg.ts+var stsgBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SubTrackSampleGroupBox";+ }+ static {+ this.fourcc = "stsg";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.grouping_type = stream.readUint32();+ const count = stream.readUint16();+ this.group_description_index = [];+ for (let i = 0; i < count; i++) this.group_description_index[i] = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/stsh.ts+var stshBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ShadowSyncSampleBox";+ }+ static {+ this.fourcc = "stsh";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const entry_count = stream.readUint32();+ this.shadowed_sample_numbers = [];+ this.sync_sample_numbers = [];+ if (this.version === 0) for (let i = 0; i < entry_count; i++) {+ this.shadowed_sample_numbers.push(stream.readUint32());+ this.sync_sample_numbers.push(stream.readUint32());+ }+ }+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 4 + 8 * this.shadowed_sample_numbers.length;+ this.writeHeader(stream);+ stream.writeUint32(this.shadowed_sample_numbers.length);+ for (let i = 0; i < this.shadowed_sample_numbers.length; i++) {+ stream.writeUint32(this.shadowed_sample_numbers[i]);+ stream.writeUint32(this.sync_sample_numbers[i]);+ }+ }+};++//#endregion+//#region src/boxes/stss.ts+var stssBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SyncSampleBox";+ }+ static {+ this.fourcc = "stss";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const entry_count = stream.readUint32();+ if (this.version === 0) {+ this.sample_numbers = [];+ for (let i = 0; i < entry_count; i++) this.sample_numbers.push(stream.readUint32());+ }+ }+ /** @bundle writing/stss.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 4 + 4 * this.sample_numbers.length;+ this.writeHeader(stream);+ stream.writeUint32(this.sample_numbers.length);+ stream.writeUint32Array(this.sample_numbers);+ }+};++//#endregion+//#region src/boxes/stvi.ts+var stviBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "StereoVideoBox";+ }+ static {+ this.fourcc = "stvi";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const tmp32 = stream.readUint32();+ this.single_view_allowed = tmp32 & 3;+ this.stereo_scheme = stream.readUint32();+ const length = stream.readUint32();+ this.stereo_indication_type = stream.readString(length);+ this.boxes = [];+ while (stream.getPosition() < this.start + this.size) {+ const ret = parseOneBox(stream, false, this.size - (stream.getPosition() - this.start));+ if (ret.code === 1) {+ const box = ret.box;+ this.boxes.push(box);+ this[box.type] = box;+ } else return;+ }+ }+};++//#endregion+//#region src/boxes/stz2.ts+var stz2Box = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CompactSampleSizeBox";+ }+ static {+ this.fourcc = "stz2";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.sample_sizes = [];+ if (this.version === 0) {+ this.reserved = stream.readUint24();+ this.field_size = stream.readUint8();+ const sample_count = stream.readUint32();+ if (this.field_size === 4) for (let i = 0; i < sample_count; i += 2) {+ const tmp = stream.readUint8();+ this.sample_sizes[i] = tmp >> 4 & 15;+ this.sample_sizes[i + 1] = tmp & 15;+ }+ else if (this.field_size === 8) for (let i = 0; i < sample_count; i++) this.sample_sizes[i] = stream.readUint8();+ else if (this.field_size === 16) for (let i = 0; i < sample_count; i++) this.sample_sizes[i] = stream.readUint16();+ else Log.error("BoxParser", "Error in length field in stz2 box", stream.isofile);+ }+ }+};++//#endregion+//#region src/boxes/subs.ts+var subsBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SubSampleInformationBox";+ }+ static {+ this.fourcc = "subs";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const entry_count = stream.readUint32();+ this.entries = [];+ let subsample_count;+ for (let i = 0; i < entry_count; i++) {+ const sampleInfo = {};+ this.entries[i] = sampleInfo;+ sampleInfo.sample_delta = stream.readUint32();+ sampleInfo.subsamples = [];+ subsample_count = stream.readUint16();+ if (subsample_count > 0) for (let j = 0; j < subsample_count; j++) {+ const subsample = {};+ sampleInfo.subsamples.push(subsample);+ if (this.version === 1) subsample.size = stream.readUint32();+ else subsample.size = stream.readUint16();+ subsample.priority = stream.readUint8();+ subsample.discardable = stream.readUint8();+ subsample.codec_specific_parameters = stream.readUint32();+ }+ }+ }+};++//#endregion+//#region src/boxes/taic.ts+var taicBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TAIClockInfoBox";+ }+ static {+ this.fourcc = "taic";+ }+ parse(stream) {+ this.time_uncertainty = stream.readUint64();+ this.clock_resolution = stream.readUint32();+ this.clock_drift_rate = stream.readInt32();+ const reserved_byte = stream.readUint8();+ this.clock_type = (reserved_byte & 192) >> 6;+ }+};++//#endregion+//#region src/boxes/tenc.ts+var tencBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackEncryptionBox";+ }+ static {+ this.fourcc = "tenc";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ stream.readUint8();+ if (this.version === 0) stream.readUint8();+ else {+ const tmp = stream.readUint8();+ this.default_crypt_byte_block = tmp >> 4 & 15;+ this.default_skip_byte_block = tmp & 15;+ }+ this.default_isProtected = stream.readUint8();+ this.default_Per_Sample_IV_Size = stream.readUint8();+ this.default_KID = parseHex16(stream);+ if (this.default_isProtected === 1 && this.default_Per_Sample_IV_Size === 0) {+ this.default_constant_IV_size = stream.readUint8();+ this.default_constant_IV = stream.readUint8Array(this.default_constant_IV_size);+ }+ }+};++//#endregion+//#region src/boxes/tfra.ts+var TfraEntry = class {};+var tfraBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackFragmentRandomAccessBox";+ }+ static {+ this.fourcc = "tfra";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.track_ID = stream.readUint32();+ stream.readUint24();+ const tmp_byte = stream.readUint8();+ this.length_size_of_traf_num = tmp_byte >> 4 & 3;+ this.length_size_of_trun_num = tmp_byte >> 2 & 3;+ this.length_size_of_sample_num = tmp_byte & 3;+ this.entries = [];+ const number_of_entries = stream.readUint32();+ for (let i = 0; i < number_of_entries; i++) {+ const entry = new TfraEntry();+ if (this.version === 1) {+ entry.time = stream.readUint64();+ entry.moof_offset = stream.readUint64();+ } else {+ entry.time = stream.readUint32();+ entry.moof_offset = stream.readUint32();+ }+ entry.traf_number = stream["readUint" + 8 * (this.length_size_of_traf_num + 1)]();+ entry.trun_number = stream["readUint" + 8 * (this.length_size_of_trun_num + 1)]();+ entry.sample_delta = stream["readUint" + 8 * (this.length_size_of_sample_num + 1)]();+ this.entries.push(entry);+ }+ }+};++//#endregion+//#region src/boxes/tmax.ts+var tmaxBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintmaxrelativetime";+ }+ static {+ this.fourcc = "tmax";+ }+ parse(stream) {+ this.time = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/tmin.ts+var tminBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintminrelativetime";+ }+ static {+ this.fourcc = "tmin";+ }+ parse(stream) {+ this.time = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/totl.ts+var totlBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintBytesSent";+ }+ static {+ this.fourcc = "totl";+ }+ parse(stream) {+ this.bytessent = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/tpay.ts+var tpayBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintBytesSent";+ }+ static {+ this.fourcc = "tpay";+ }+ parse(stream) {+ this.bytessent = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/tpyl.ts+var tpylBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintBytesSent";+ }+ static {+ this.fourcc = "tpyl";+ }+ parse(stream) {+ this.bytessent = stream.readUint64();+ }+};++//#endregion+//#region src/boxes/trackgroups/msrc.ts+var msrcTrackGroupTypeBox = class extends TrackGroupTypeBox {+ static {+ this.fourcc = "msrc";+ }+};++//#endregion+//#region src/boxes/tref.ts+var trefBox = class trefBox extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackReferenceBox";+ this.references = [];+ }+ static {+ this.fourcc = "tref";+ }+ static {+ this.allowed_types = [+ "hint",+ "cdsc",+ "font",+ "hind",+ "vdep",+ "vplx",+ "subt",+ "thmb",+ "auxl",+ "cdtg",+ "shsc",+ "aest"+ ];+ }+ parse(stream) {+ while (stream.getPosition() < this.start + this.size) {+ const ret = parseOneBox(stream, true, this.size - (stream.getPosition() - this.start));+ if (ret.code === 1) {+ if (!trefBox.allowed_types.includes(ret.type)) Log.warn("BoxParser", `Unknown track reference type: '${ret.type}'`);+ const box = new TrackReferenceTypeBox(ret.type, ret.size, ret.hdr_size, ret.start);+ if (box.write === Box.prototype.write && box.type !== "mdat") {+ Log.info("BoxParser", "TrackReference " + box.type + " box writing not yet implemented, keeping unparsed data in memory for later write");+ box.parseDataAndRewind(stream);+ }+ box.parse(stream);+ this.references.push(box);+ } else return;+ }+ }+};++//#endregion+//#region src/boxes/trep.ts+var trepBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackExtensionPropertiesBox";+ }+ static {+ this.fourcc = "trep";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.track_ID = stream.readUint32();+ this.boxes = [];+ while (stream.getPosition() < this.start + this.size) {+ const ret = parseOneBox(stream, false, this.size - (stream.getPosition() - this.start));+ if (ret.code === 1) {+ const box = ret.box;+ this.boxes.push(box);+ } else return;+ }+ }+};++//#endregion+//#region src/boxes/trpy.ts+var trpyBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintBytesSent";+ }+ static {+ this.fourcc = "trpy";+ }+ parse(stream) {+ this.bytessent = stream.readUint64();+ }+};++//#endregion+//#region src/boxes/tsel.ts+var tselBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackSelectionBox";+ }+ static {+ this.fourcc = "tsel";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.switch_group = stream.readUint32();+ const count = (this.size - this.hdr_size - 4) / 4;+ this.attribute_list = [];+ for (let i = 0; i < count; i++) this.attribute_list[i] = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/txtC.ts+var txtcBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TextConfigBox";+ }+ static {+ this.fourcc = "txtc";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.config = stream.readCString();+ }+};++//#endregion+//#region src/boxes/tyco.ts+var tycoBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TypeCombinationBox";+ }+ static {+ this.fourcc = "tyco";+ }+ parse(stream) {+ const count = (this.size - this.hdr_size) / 4;+ this.compatible_brands = [];+ for (let i = 0; i < count; i++) this.compatible_brands[i] = stream.readString(4);+ }+};++//#endregion+//#region src/boxes/udes.ts+var udesBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "UserDescriptionProperty";+ }+ static {+ this.fourcc = "udes";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.lang = stream.readCString();+ this.name = stream.readCString();+ this.description = stream.readCString();+ this.tags = stream.readCString();+ }+};++//#endregion+//#region src/boxes/uncC.ts+var uncCBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "UncompressedFrameConfigBox";+ }+ static {+ this.fourcc = "uncC";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.profile = stream.readString(4);+ if (this.version === 1) {} else if (this.version === 0) {+ this.component_count = stream.readUint32();+ this.component_index = [];+ this.component_bit_depth_minus_one = [];+ this.component_format = [];+ this.component_align_size = [];+ for (let i = 0; i < this.component_count; i++) {+ this.component_index.push(stream.readUint16());+ this.component_bit_depth_minus_one.push(stream.readUint8());+ this.component_format.push(stream.readUint8());+ this.component_align_size.push(stream.readUint8());+ }+ this.sampling_type = stream.readUint8();+ this.interleave_type = stream.readUint8();+ this.block_size = stream.readUint8();+ const flags = stream.readUint8();+ this.component_little_endian = flags >> 7 & 1;+ this.block_pad_lsb = flags >> 6 & 1;+ this.block_little_endian = flags >> 5 & 1;+ this.block_reversed = flags >> 4 & 1;+ this.pad_unknown = flags >> 3 & 1;+ this.pixel_size = stream.readUint32();+ this.row_align_size = stream.readUint32();+ this.tile_align_size = stream.readUint32();+ this.num_tile_cols_minus_one = stream.readUint32();+ this.num_tile_rows_minus_one = stream.readUint32();+ }+ }+};++//#endregion+//#region src/boxes/urn.ts+var urnBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "DataEntryUrnBox";+ }+ static {+ this.fourcc = "urn ";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.name = stream.readCString();+ if (this.size - this.hdr_size - this.name.length - 1 > 0) this.location = stream.readCString();+ }+ /** @bundle writing/urn.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = this.name.length + 1 + (this.location ? this.location.length + 1 : 0);+ this.writeHeader(stream);+ stream.writeCString(this.name);+ if (this.location) stream.writeCString(this.location);+ }+};++//#endregion+//#region src/boxes/vttC.ts+var vttCBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "WebVTTConfigurationBox";+ }+ static {+ this.fourcc = "vttC";+ }+ parse(stream) {+ this.text = stream.readString(this.size - this.hdr_size);+ }+};++//#endregion+//#region src/boxes/vvnC.ts+var vvnCBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "VvcNALUConfigBox";+ }+ static {+ this.fourcc = "vvnC";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const tmp = stream.readUint8();+ this.lengthSizeMinusOne = tmp & 3;+ }+};++//#endregion+//#region src/boxes/samplegroups/alst.ts+var alstSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "alst";+ }+ parse(stream) {+ const roll_count = stream.readUint16();+ this.first_output_sample = stream.readUint16();+ this.sample_offset = [];+ for (let i = 0; i < roll_count; i++) this.sample_offset[i] = stream.readUint32();+ const remaining = this.description_length - 4 - 4 * roll_count;+ this.num_output_samples = [];+ this.num_total_samples = [];+ for (let i = 0; i < remaining / 4; i++) {+ this.num_output_samples[i] = stream.readUint16();+ this.num_total_samples[i] = stream.readUint16();+ }+ }+};++//#endregion+//#region src/boxes/samplegroups/avll.ts+var avllSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "avll";+ }+ parse(stream) {+ this.layerNumber = stream.readUint8();+ this.accurateStatisticsFlag = stream.readUint8();+ this.avgBitRate = stream.readUint16();+ this.avgFrameRate = stream.readUint16();+ }+};++//#endregion+//#region src/boxes/samplegroups/avss.ts+var avssSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "avss";+ }+ parse(stream) {+ this.subSequenceIdentifier = stream.readUint16();+ this.layerNumber = stream.readUint8();+ const tmp_byte = stream.readUint8();+ this.durationFlag = tmp_byte >> 7;+ this.avgRateFlag = tmp_byte >> 6 & 1;+ if (this.durationFlag) this.duration = stream.readUint32();+ if (this.avgRateFlag) {+ this.accurateStatisticsFlag = stream.readUint8();+ this.avgBitRate = stream.readUint16();+ this.avgFrameRate = stream.readUint16();+ }+ this.dependency = [];+ const numReferences = stream.readUint8();+ for (let i = 0; i < numReferences; i++) this.dependency.push({+ subSeqDirectionFlag: stream.readUint8(),+ layerNumber: stream.readUint8(),+ subSequenceIdentifier: stream.readUint16()+ });+ }+};++//#endregion+//#region src/boxes/samplegroups/dtrt.ts+var dtrtSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "dtrt";+ }+ parse(_stream) {+ Log.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed");+ }+};++//#endregion+//#region src/boxes/samplegroups/mvif.ts+var mvifSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "mvif";+ }+ parse(_stream) {+ Log.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed");+ }+};++//#endregion+//#region src/boxes/samplegroups/prol.ts+var prolSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "prol";+ }+ parse(stream) {+ this.roll_distance = stream.readInt16();+ }+};++//#endregion+//#region src/boxes/samplegroups/rap.ts+var rapSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "rap ";+ }+ parse(stream) {+ const tmp_byte = stream.readUint8();+ this.num_leading_samples_known = tmp_byte >> 7;+ this.num_leading_samples = tmp_byte & 127;+ }+};++//#endregion+//#region src/boxes/samplegroups/rash.ts+var rashSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "rash";+ }+ parse(stream) {+ this.operation_point_count = stream.readUint16();+ if (this.description_length !== 2 + (this.operation_point_count === 1 ? 2 : this.operation_point_count * 6) + 9) {+ Log.warn("BoxParser", "Mismatch in " + this.grouping_type + " sample group length");+ this.data = stream.readUint8Array(this.description_length - 2);+ } else {+ if (this.operation_point_count === 1) this.target_rate_share = stream.readUint16();+ else {+ this.target_rate_share = [];+ this.available_bitrate = [];+ for (let i = 0; i < this.operation_point_count; i++) {+ this.available_bitrate[i] = stream.readUint32();+ this.target_rate_share[i] = stream.readUint16();+ }+ }+ this.maximum_bitrate = stream.readUint32();+ this.minimum_bitrate = stream.readUint32();+ this.discard_priority = stream.readUint8();+ }+ }+};++//#endregion+//#region src/boxes/samplegroups/roll.ts+var rollSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "roll";+ }+ parse(stream) {+ this.roll_distance = stream.readInt16();+ }+};++//#endregion+//#region src/boxes/samplegroups/scif.ts+var scifSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "scif";+ }+ parse(_stream) {+ Log.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed");+ }+};++//#endregion+//#region src/boxes/samplegroups/scnm.ts+var scnmSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "scnm";+ }+ parse(_stream) {+ Log.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed");+ }+};++//#endregion+//#region src/boxes/samplegroups/seig.ts+var seigSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "seig";+ }+ parse(stream) {+ this.reserved = stream.readUint8();+ const tmp = stream.readUint8();+ this.crypt_byte_block = tmp >> 4;+ this.skip_byte_block = tmp & 15;+ this.isProtected = stream.readUint8();+ this.Per_Sample_IV_Size = stream.readUint8();+ this.KID = parseHex16(stream);+ this.constant_IV_size = 0;+ this.constant_IV = 0;+ if (this.isProtected === 1 && this.Per_Sample_IV_Size === 0) {+ this.constant_IV_size = stream.readUint8();+ this.constant_IV = stream.readUint8Array(this.constant_IV_size);+ }+ }+};++//#endregion+//#region src/boxes/samplegroups/stsa.ts+var stsaSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "stsa";+ }+ parse(_stream) {+ Log.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed");+ }+};++//#endregion+//#region src/boxes/samplegroups/sync.ts+var syncSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "sync";+ }+ parse(stream) {+ const tmp_byte = stream.readUint8();+ this.NAL_unit_type = tmp_byte & 63;+ }+};++//#endregion+//#region src/boxes/samplegroups/tele.ts+var teleSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "tele";+ }+ parse(stream) {+ const tmp_byte = stream.readUint8();+ this.level_independently_decodable = tmp_byte >> 7;+ }+};++//#endregion+//#region src/boxes/samplegroups/tsas.ts+var tsasSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "tsas";+ }+ parse(_stream) {+ Log.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed");+ }+};++//#endregion+//#region src/boxes/samplegroups/tscl.ts+var tsclSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "tscl";+ }+ parse(_stream) {+ Log.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed");+ }+};++//#endregion+//#region src/boxes/samplegroups/vipr.ts+var viprSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "vipr";+ }+ parse(_stream) {+ Log.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed");+ }+};++//#endregion+//#region src/boxes/uuid/index.ts+var UUIDBox = class extends Box {+ static {+ this.fourcc = "uuid";+ }+};+var UUIDFullBox = class extends FullBox {+ static {+ this.fourcc = "uuid";+ }+};+var piffLsmBox = class extends UUIDFullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "LiveServerManifestBox";+ }+ static {+ this.uuid = "a5d40b30e81411ddba2f0800200c9a66";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.LiveServerManifest = stream.readString(this.size - this.hdr_size).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");+ }+};+var piffPsshBox = class extends UUIDFullBox {+ constructor(..._args2) {+ super(..._args2);+ this.box_name = "PiffProtectionSystemSpecificHeaderBox";+ }+ static {+ this.uuid = "d08a4f1810f34a82b6c832d8aba183d3";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.system_id = parseHex16(stream);+ const datasize = stream.readUint32();+ if (datasize > 0) this.data = stream.readUint8Array(datasize);+ }+};+var piffSencBox = class extends UUIDFullBox {+ constructor(..._args3) {+ super(..._args3);+ this.box_name = "PiffSampleEncryptionBox";+ }+ static {+ this.uuid = "a2394f525a9b4f14a2446c427c648df4";+ }+};+var piffTencBox = class extends UUIDFullBox {+ constructor(..._args4) {+ super(..._args4);+ this.box_name = "PiffTrackEncryptionBox";+ }+ static {+ this.uuid = "8974dbce7be74c5184f97148f9882554";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.default_AlgorithmID = stream.readUint24();+ this.default_IV_size = stream.readUint8();+ this.default_KID = parseHex16(stream);+ }+};+var piffTfrfBox = class extends UUIDFullBox {+ constructor(..._args5) {+ super(..._args5);+ this.box_name = "TfrfBox";+ }+ static {+ this.uuid = "d4807ef2ca3946958e5426cb9e46a79f";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.fragment_count = stream.readUint8();+ this.entries = [];+ for (let i = 0; i < this.fragment_count; i++) {+ let absolute_time = 0;+ let absolute_duration = 0;+ if (this.version === 1) {+ absolute_time = stream.readUint64();+ absolute_duration = stream.readUint64();+ } else {+ absolute_time = stream.readUint32();+ absolute_duration = stream.readUint32();+ }+ this.entries.push({+ absolute_time,+ absolute_duration+ });+ }+ }+};+var piffTfxdBox = class extends UUIDFullBox {+ constructor(..._args6) {+ super(..._args6);+ this.box_name = "TfxdBox";+ }+ static {+ this.uuid = "6d1d9b0542d544e680e2141daff757b2";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 1) {+ this.absolute_time = stream.readUint64();+ this.duration = stream.readUint64();+ } else {+ this.absolute_time = stream.readUint32();+ this.duration = stream.readUint32();+ }+ }+};+var ItemContentIDPropertyBox = class extends UUIDBox {+ constructor(..._args7) {+ super(..._args7);+ this.box_name = "ItemContentIDProperty";+ }+ static {+ this.uuid = "261ef3741d975bbaacbd9d2c8ea73522";+ }+ parse(stream) {+ this.content_id = stream.readCString();+ }+};+var ItemComponentContentIDPropertyBox = class extends UUIDBox {+ constructor(..._args8) {+ super(..._args8);+ this.box_name = "ItemComponentContentIDProperty";+ }+ static {+ this.uuid = "9db9dd6e373c5a4e811021fc83a911fd";+ }+ parse(stream) {+ this.number_of_components = stream.readUint32();+ this.content_ids = [];+ for (let i = 0; i < this.number_of_components; i++) {+ const content_id = stream.readCString();+ this.content_ids.push(content_id);+ }+ }+};++//#endregion+//#region entries/all-boxes.ts+var all_boxes_exports = /* @__PURE__ */ __exportAll({+ CoLLBox: () => CoLLBox,+ ItemComponentContentIDPropertyBox: () => ItemComponentContentIDPropertyBox,+ ItemContentIDPropertyBox: () => ItemContentIDPropertyBox,+ OpusSampleEntry: () => OpusSampleEntry,+ SmDmBox: () => SmDmBox,+ a1lxBox: () => a1lxBox,+ a1opBox: () => a1opBox,+ ac_3SampleEntry: () => ac_3SampleEntry,+ ac_4SampleEntry: () => ac_4SampleEntry,+ aebrBox: () => aebrBox,+ afbrBox: () => afbrBox,+ albcBox: () => albcBox,+ alstSampleGroupEntry: () => alstSampleGroupEntry,+ altrBox: () => altrBox,+ auxCBox: () => auxCBox,+ av01SampleEntry: () => av01SampleEntry,+ av1CBox: () => av1CBox,+ avc1SampleEntry: () => avc1SampleEntry,+ avc2SampleEntry: () => avc2SampleEntry,+ avc3SampleEntry: () => avc3SampleEntry,+ avc4SampleEntry: () => avc4SampleEntry,+ avcCBox: () => avcCBox,+ avllSampleGroupEntry: () => avllSampleGroupEntry,+ avs3SampleEntry: () => avs3SampleEntry,+ avssSampleGroupEntry: () => avssSampleGroupEntry,+ brstBox: () => brstBox,+ btrtBox: () => btrtBox,+ bxmlBox: () => bxmlBox,+ ccstBox: () => ccstBox,+ cdefBox: () => cdefBox,+ clapBox: () => clapBox,+ clefBox: () => clefBox,+ clliBox: () => clliBox,+ cmexBox: () => cmexBox,+ cminBox: () => cminBox,+ cmpCBox: () => cmpCBox,+ cmpdBox: () => cmpdBox,+ co64Box: () => co64Box,+ colrBox: () => colrBox,+ coviBox: () => coviBox,+ cprtBox: () => cprtBox,+ cschBox: () => cschBox,+ cslgBox: () => cslgBox,+ cttsBox: () => cttsBox,+ dOpsBox: () => dOpsBox,+ dac3Box: () => dac3Box,+ dataBox: () => dataBox,+ dav1SampleEntry: () => dav1SampleEntry,+ dec3Box: () => dec3Box,+ dfLaBox: () => dfLaBox,+ dimmBox: () => dimmBox,+ dinfBox: () => dinfBox,+ dmax: () => dmax,+ dmedBox: () => dmedBox,+ dobrBox: () => dobrBox,+ drefBox: () => drefBox,+ drepBox: () => drepBox,+ dtrtSampleGroupEntry: () => dtrtSampleGroupEntry,+ dvh1SampleEntry: () => dvh1SampleEntry,+ dvheSampleEntry: () => dvheSampleEntry,+ ec_3SampleEntry: () => ec_3SampleEntry,+ edtsBox: () => edtsBox,+ elngBox: () => elngBox,+ elstBox: () => elstBox,+ emsgBox: () => emsgBox,+ encaSampleEntry: () => encaSampleEntry,+ encmSampleEntry: () => encmSampleEntry,+ encsSampleEntry: () => encsSampleEntry,+ enctSampleEntry: () => enctSampleEntry,+ encuSampleEntry: () => encuSampleEntry,+ encvSampleEntry: () => encvSampleEntry,+ enofBox: () => enofBox,+ eqivBox: () => eqivBox,+ esdsBox: () => esdsBox,+ etypBox: () => etypBox,+ fLaCSampleEntry: () => fLaCSampleEntry,+ favcBox: () => favcBox,+ fielBox: () => fielBox,+ fobrBox: () => fobrBox,+ freeBox: () => freeBox,+ frmaBox: () => frmaBox,+ ftypBox: () => ftypBox,+ grplBox: () => grplBox,+ hdlrBox: () => hdlrBox,+ hev1SampleEntry: () => hev1SampleEntry,+ hev2SampleEntry: () => hev2SampleEntry,+ hinfBox: () => hinfBox,+ hmhdBox: () => hmhdBox,+ hntiBox: () => hntiBox,+ hvc1SampleEntry: () => hvc1SampleEntry,+ hvc2SampleEntry: () => hvc2SampleEntry,+ hvcCBox: () => hvcCBox,+ hvt1SampleEntry: () => hvt1SampleEntry,+ iaugBox: () => iaugBox,+ idatBox: () => idatBox,+ iinfBox: () => iinfBox,+ ilocBox: () => ilocBox,+ ilstBox: () => ilstBox,+ imirBox: () => imirBox,+ infeBox: () => infeBox,+ iodsBox: () => iodsBox,+ ipcoBox: () => ipcoBox,+ ipmaBox: () => ipmaBox,+ iproBox: () => iproBox,+ iprpBox: () => iprpBox,+ irefBox: () => irefBox,+ irotBox: () => irotBox,+ ispeBox: () => ispeBox,+ itaiBox: () => itaiBox,+ j2kHBox: () => j2kHBox,+ j2kiSampleEntry: () => j2kiSampleEntry,+ keysBox: () => keysBox,+ kindBox: () => kindBox,+ levaBox: () => levaBox,+ lhe1SampleEntry: () => lhe1SampleEntry,+ lhv1SampleEntry: () => lhv1SampleEntry,+ lhvCBox: () => lhvCBox,+ lselBox: () => lselBox,+ lvc1SampleEntry: () => lvc1SampleEntry,+ lvcCBox: () => lvcCBox,+ m4aeSampleEntry: () => m4aeSampleEntry,+ maxrBox: () => maxrBox,+ mdatBox: () => mdatBox,+ mdcvBox: () => mdcvBox,+ mdhdBox: () => mdhdBox,+ mdiaBox: () => mdiaBox,+ mecoBox: () => mecoBox,+ mehdBox: () => mehdBox,+ metaBox: () => metaBox,+ mettSampleEntry: () => mettSampleEntry,+ metxSampleEntry: () => metxSampleEntry,+ mfhdBox: () => mfhdBox,+ mfraBox: () => mfraBox,+ mfroBox: () => mfroBox,+ mha1SampleEntry: () => mha1SampleEntry,+ mha2SampleEntry: () => mha2SampleEntry,+ mhm1SampleEntry: () => mhm1SampleEntry,+ mhm2SampleEntry: () => mhm2SampleEntry,+ minfBox: () => minfBox,+ mjp2SampleEntry: () => mjp2SampleEntry,+ mjpgSampleEntry: () => mjpgSampleEntry,+ moofBox: () => moofBox,+ moovBox: () => moovBox,+ mp4aSampleEntry: () => mp4aSampleEntry,+ mp4sSampleEntry: () => mp4sSampleEntry,+ mp4vSampleEntry: () => mp4vSampleEntry,+ mskCBox: () => mskCBox,+ msrcTrackGroupTypeBox: () => msrcTrackGroupTypeBox,+ mvexBox: () => mvexBox,+ mvhdBox: () => mvhdBox,+ mvifSampleGroupEntry: () => mvifSampleGroupEntry,+ nmhdBox: () => nmhdBox,+ npckBox: () => npckBox,+ numpBox: () => numpBox,+ padbBox: () => padbBox,+ panoBox: () => panoBox,+ paspBox: () => paspBox,+ paylBox: () => paylBox,+ paytBox: () => paytBox,+ pdinBox: () => pdinBox,+ piffLsmBox: () => piffLsmBox,+ piffPsshBox: () => piffPsshBox,+ piffSencBox: () => piffSencBox,+ piffTencBox: () => piffTencBox,+ piffTfrfBox: () => piffTfrfBox,+ piffTfxdBox: () => piffTfxdBox,+ pitmBox: () => pitmBox,+ pixiBox: () => pixiBox,+ pmaxBox: () => pmaxBox,+ povdBox: () => povdBox,+ prdiBox: () => prdiBox,+ prfrBox: () => prfrBox,+ prftBox: () => prftBox,+ prgrBox: () => prgrBox,+ profBox: () => profBox,+ prolSampleGroupEntry: () => prolSampleGroupEntry,+ psshBox: () => psshBox,+ pymdBox: () => pymdBox,+ rapSampleGroupEntry: () => rapSampleGroupEntry,+ rashSampleGroupEntry: () => rashSampleGroupEntry,+ resvSampleEntry: () => resvSampleEntry,+ rinfBox: () => rinfBox,+ rollSampleGroupEntry: () => rollSampleGroupEntry,+ rtp_Box: () => rtp_Box,+ saioBox: () => saioBox,+ saizBox: () => saizBox,+ sbgpBox: () => sbgpBox,+ sbpmBox: () => sbpmBox,+ sbttSampleEntry: () => sbttSampleEntry,+ schiBox: () => schiBox,+ schmBox: () => schmBox,+ scifSampleGroupEntry: () => scifSampleGroupEntry,+ scnmSampleGroupEntry: () => scnmSampleGroupEntry,+ sdp_Box: () => sdp_Box,+ sdtpBox: () => sdtpBox,+ seigSampleGroupEntry: () => seigSampleGroupEntry,+ sencBox: () => sencBox,+ sgpdBox: () => sgpdBox,+ sidxBox: () => sidxBox,+ sinfBox: () => sinfBox,+ skipBox: () => skipBox,+ slidBox: () => slidBox,+ smhdBox: () => smhdBox,+ sratBox: () => sratBox,+ ssixBox: () => ssixBox,+ stblBox: () => stblBox,+ stcoBox: () => stcoBox,+ stdpBox: () => stdpBox,+ sterBox: () => sterBox,+ sthdBox: () => sthdBox,+ stppSampleEntry: () => stppSampleEntry,+ strdBox: () => strdBox,+ striBox: () => striBox,+ strkBox: () => strkBox,+ stsaSampleGroupEntry: () => stsaSampleGroupEntry,+ stscBox: () => stscBox,+ stsdBox: () => stsdBox,+ stsgBox: () => stsgBox,+ stshBox: () => stshBox,+ stssBox: () => stssBox,+ stszBox: () => stszBox,+ sttsBox: () => sttsBox,+ stviBox: () => stviBox,+ stxtSampleEntry: () => stxtSampleEntry,+ stypBox: () => stypBox,+ stz2Box: () => stz2Box,+ subsBox: () => subsBox,+ syncSampleGroupEntry: () => syncSampleGroupEntry,+ taicBox: () => taicBox,+ taptBox: () => taptBox,+ teleSampleGroupEntry: () => teleSampleGroupEntry,+ tencBox: () => tencBox,+ tfdtBox: () => tfdtBox,+ tfhdBox: () => tfhdBox,+ tfraBox: () => tfraBox,+ tkhdBox: () => tkhdBox,+ tmaxBox: () => tmaxBox,+ tminBox: () => tminBox,+ totlBox: () => totlBox,+ tpayBox: () => tpayBox,+ tpylBox: () => tpylBox,+ trafBox: () => trafBox,+ trakBox: () => trakBox,+ trefBox: () => trefBox,+ trepBox: () => trepBox,+ trexBox: () => trexBox,+ trgrBox: () => trgrBox,+ trpyBox: () => trpyBox,+ trunBox: () => trunBox,+ tsasSampleGroupEntry: () => tsasSampleGroupEntry,+ tsclSampleGroupEntry: () => tsclSampleGroupEntry,+ tselBox: () => tselBox,+ tsynBox: () => tsynBox,+ tx3gSampleEntry: () => tx3gSampleEntry,+ txtcBox: () => txtcBox,+ tycoBox: () => tycoBox,+ udesBox: () => udesBox,+ udtaBox: () => udtaBox,+ uncCBox: () => uncCBox,+ uncvSampleEntry: () => uncvSampleEntry,+ urlBox: () => urlBox,+ urnBox: () => urnBox,+ viprSampleGroupEntry: () => viprSampleGroupEntry,+ vmhdBox: () => vmhdBox,+ vp08SampleEntry: () => vp08SampleEntry,+ vp09SampleEntry: () => vp09SampleEntry,+ vpcCBox: () => vpcCBox,+ vttCBox: () => vttCBox,+ vttcBox: () => vttcBox,+ vvc1SampleEntry: () => vvc1SampleEntry,+ vvcCBox: () => vvcCBox,+ vvcNSampleEntry: () => vvcNSampleEntry,+ vvi1SampleEntry: () => vvi1SampleEntry,+ vvnCBox: () => vvnCBox,+ vvs1SampleEntry: () => vvs1SampleEntry,+ waveBox: () => waveBox,+ wbbrBox: () => wbbrBox,+ wvttSampleEntry: () => wvttSampleEntry,+ xmlBox: () => xmlBox+});++//#endregion+//#region entries/all.ts+const BoxParser = registerBoxes(all_boxes_exports);+registerDescriptors(descriptor_exports);++//#endregion+export { AudioSampleEntry, Box, BoxParser, DIFF_BOXES_PROP_NAMES, DIFF_PRIMITIVE_ARRAY_PROP_NAMES, DataStream, Descriptor, ES_Descriptor, Endianness, FullBox, HintSampleEntry, ISOFile, Log, MP4BoxBuffer, MPEG4DescriptorParser, MetadataSampleEntry, MultiBufferStream, SampleEntry, SampleGroupEntry, SampleGroupInfo, SingleItemTypeReferenceBox, SingleItemTypeReferenceBoxLarge, SubtitleSampleEntry, SystemSampleEntry, TX3GParser, TextSampleEntry, Textin4Parser, TrackGroupTypeBox, TrackReferenceTypeBox, VTTin4Parser, VisualSampleEntry, XMLSubtitlein4Parser, boxEqual, boxEqualFields, createFile };+//# sourceMappingURL=mp4box.all.mjs.map\ No newline at end of filediff --git a/src/chrome/vendor/mp4box/rolldown-runtime-w6R9maHv.mjs b/src/chrome/vendor/mp4box/rolldown-runtime-w6R9maHv.mjsnew file mode 100644index 000000000..862d566e4--- /dev/null+++ b/src/chrome/vendor/mp4box/rolldown-runtime-w6R9maHv.mjs@@ -0,0 +1,18 @@+//#region \0rolldown/runtime.js+var __defProp = Object.defineProperty;+var __exportAll = (all, no_symbols) => {+ let target = {};+ for (var name in all) {+ __defProp(target, name, {+ get: all[name],+ enumerable: true+ });+ }+ if (!no_symbols) {+ __defProp(target, Symbol.toStringTag, { value: "Module" });+ }+ return target;+};++//#endregion+export { __exportAll as t };\ No newline at end of filediff --git a/src/chrome/vendor/mp4box/styp-9TIZZDLN.mjs b/src/chrome/vendor/mp4box/styp-9TIZZDLN.mjsnew file mode 100644index 000000000..9fc4171ee--- /dev/null+++ b/src/chrome/vendor/mp4box/styp-9TIZZDLN.mjs@@ -0,0 +1,7225 @@+//#region src/constants.ts+const MAX_SIZE = Math.pow(2, 32);+const MAX_UINT32 = Math.pow(2, 32) - 1;+const TFHD_FLAG_DEFAULT_BASE_IS_MOOF = 131072;+const TRUN_FLAGS_FLAGS = 1024;+const TRUN_FLAGS_CTS_OFFSET = 2048;++//#endregion+//#region src/mp4boxbuffer.ts+var MP4BoxBuffer = class MP4BoxBuffer extends ArrayBuffer {+ constructor(byteLength) {+ super(byteLength);+ this.fileStart = 0;+ this.usedBytes = 0;+ }+ static fromArrayBuffer(buffer, fileStart) {+ const mp4BoxBuffer = new MP4BoxBuffer(buffer.byteLength);+ new Uint8Array(mp4BoxBuffer).set(new Uint8Array(buffer));+ mp4BoxBuffer.fileStart = fileStart;+ return mp4BoxBuffer;+ }+};++//#endregion+//#region src/DataStream.ts+let Endianness = /* @__PURE__ */ function(Endianness) {+ Endianness[Endianness["BIG_ENDIAN"] = 1] = "BIG_ENDIAN";+ Endianness[Endianness["LITTLE_ENDIAN"] = 2] = "LITTLE_ENDIAN";+ return Endianness;+}({});+var DataStream = class DataStream {+ static {+ this.ENDIANNESS = new Int8Array(new Int16Array([1]).buffer)[0] > 0 ? 2 : 1;+ }+ /**+ * DataStream reads scalars, arrays and structs of data from an ArrayBuffer.+ * It's like a file-like DataView on steroids.+ *+ * @param arrayBuffer ArrayBuffer to read from.+ * @param byteOffset Offset from arrayBuffer beginning for the DataStream.+ * @param endianness Endianness of the DataStream (default: BIG_ENDIAN).+ */+ constructor(arrayBuffer, byteOffset, endianness) {+ this._byteLength = 0;+ this.failurePosition = 0;+ this._dynamicSize = 1;+ this._byteOffset = byteOffset || 0;+ if (arrayBuffer instanceof ArrayBuffer) this.buffer = MP4BoxBuffer.fromArrayBuffer(arrayBuffer, 0);+ else if (arrayBuffer instanceof DataView) {+ this.dataView = arrayBuffer;+ if (byteOffset) this._byteOffset += byteOffset;+ } else this.buffer = new MP4BoxBuffer(arrayBuffer || 0);+ this.position = 0;+ this.endianness = endianness ? endianness : 1;+ }+ getPosition() {+ return this.position;+ }+ /**+ * Internal function to resize the DataStream buffer when required.+ * @param extra Number of bytes to add to the buffer allocation.+ */+ _realloc(extra) {+ if (!this._dynamicSize) return;+ const req = this._byteOffset + this.position + extra;+ let blen = this._buffer.byteLength;+ if (req <= blen) {+ if (req > this._byteLength) this._byteLength = req;+ return;+ }+ if (blen < 1) blen = 1;+ while (req > blen) blen *= 2;+ const buf = new MP4BoxBuffer(blen);+ const src = new Uint8Array(this._buffer);+ new Uint8Array(buf, 0, src.length).set(src);+ this.buffer = buf;+ this._byteLength = req;+ }+ /**+ * Internal function to trim the DataStream buffer when required.+ * Used for stripping out the extra bytes from the backing buffer when+ * the virtual byteLength is smaller than the buffer byteLength (happens after+ * growing the buffer with writes and not filling the extra space completely).+ */+ _trimAlloc() {+ if (this._byteLength === this._buffer.byteLength) return;+ const buf = new MP4BoxBuffer(this._byteLength);+ const dst = new Uint8Array(buf);+ const src = new Uint8Array(this._buffer, 0, dst.length);+ dst.set(src);+ this.buffer = buf;+ }+ /**+ * Returns the byte length of the DataStream object.+ * @type {number}+ */+ get byteLength() {+ return this._byteLength - this._byteOffset;+ }+ /**+ * Set/get the backing ArrayBuffer of the DataStream object.+ * The setter updates the DataView to point to the new buffer.+ * @type {Object}+ */+ get buffer() {+ this._trimAlloc();+ return this._buffer;+ }+ set buffer(value) {+ this._buffer = value;+ this._dataView = new DataView(value, this._byteOffset);+ this._byteLength = value.byteLength;+ }+ /**+ * Set/get the byteOffset of the DataStream object.+ * The setter updates the DataView to point to the new byteOffset.+ * @type {number}+ */+ get byteOffset() {+ return this._byteOffset;+ }+ set byteOffset(value) {+ this._byteOffset = value;+ this._dataView = new DataView(this._buffer, this._byteOffset);+ this._byteLength = this._buffer.byteLength;+ }+ /**+ * Set/get the byteOffset of the DataStream object.+ * The setter updates the DataView to point to the new byteOffset.+ * @type {number}+ */+ get dataView() {+ return this._dataView;+ }+ set dataView(value) {+ this._byteOffset = value.byteOffset;+ this._buffer = MP4BoxBuffer.fromArrayBuffer(value.buffer, 0);+ this._dataView = new DataView(this._buffer, this._byteOffset);+ this._byteLength = this._byteOffset + value.byteLength;+ }+ /**+ * Sets the DataStream read/write position to given position.+ * Clamps between 0 and DataStream length.+ *+ * @param pos Position to seek to.+ * @return+ */+ seek(pos) {+ const npos = Math.max(0, Math.min(this.byteLength, pos));+ this.position = isNaN(npos) || !isFinite(npos) ? 0 : npos;+ }+ /**+ * Returns true if the DataStream seek pointer is at the end of buffer and+ * there's no more data to read.+ *+ * @return True if the seek pointer is at the end of the buffer.+ */+ isEof() {+ return this.position >= this._byteLength;+ }+ #isTupleType(type) {+ return Array.isArray(type) && type.length === 3 && type[0] === "[]";+ }+ /**+ * Maps a Uint8Array into the DataStream buffer.+ *+ * Nice for quickly reading in data.+ *+ * @param length Number of elements to map.+ * @param e Endianness of the data to read.+ * @return Uint8Array to the DataStream backing buffer.+ */+ mapUint8Array(length) {+ this._realloc(length * 1);+ const arr = new Uint8Array(this._buffer, this.byteOffset + this.position, length);+ this.position += length * 1;+ return arr;+ }+ /**+ * Reads an Int32Array of desired length and endianness from the DataStream.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return The read Int32Array.+ */+ readInt32Array(length, endianness) {+ length = length === void 0 ? this.byteLength - this.position / 4 : length;+ const arr = new Int32Array(length);+ DataStream.memcpy(arr.buffer, 0, this.buffer, this.byteOffset + this.position, length * arr.BYTES_PER_ELEMENT);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += arr.byteLength;+ return arr;+ }+ /**+ * Reads an Int16Array of desired length and endianness from the DataStream.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return The read Int16Array.+ */+ readInt16Array(length, endianness) {+ length = length === void 0 ? this.byteLength - this.position / 2 : length;+ const arr = new Int16Array(length);+ DataStream.memcpy(arr.buffer, 0, this.buffer, this.byteOffset + this.position, length * arr.BYTES_PER_ELEMENT);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += arr.byteLength;+ return arr;+ }+ /**+ * Reads an Int8Array of desired length from the DataStream.+ *+ * @param length Number of elements to map.+ * @param e Endianness of the data to read.+ * @return The read Int8Array.+ */+ readInt8Array(length) {+ length = length === void 0 ? this.byteLength - this.position : length;+ const arr = new Int8Array(length);+ DataStream.memcpy(arr.buffer, 0, this.buffer, this.byteOffset + this.position, length * arr.BYTES_PER_ELEMENT);+ this.position += arr.byteLength;+ return arr;+ }+ /**+ * Reads a Uint32Array of desired length and endianness from the DataStream.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return The read Uint32Array.+ */+ readUint32Array(length, endianness) {+ length = length === void 0 ? this.byteLength - this.position / 4 : length;+ const arr = new Uint32Array(length);+ DataStream.memcpy(arr.buffer, 0, this.buffer, this.byteOffset + this.position, length * arr.BYTES_PER_ELEMENT);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += arr.byteLength;+ return arr;+ }+ /**+ * Reads a Uint16Array of desired length and endianness from the DataStream.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return The read Uint16Array.+ */+ readUint16Array(length, endianness) {+ length = length === void 0 ? this.byteLength - this.position / 2 : length;+ const arr = new Uint16Array(length);+ DataStream.memcpy(arr.buffer, 0, this.buffer, this.byteOffset + this.position, length * arr.BYTES_PER_ELEMENT);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += arr.byteLength;+ return arr;+ }+ /**+ * Reads a Uint8Array of desired length from the DataStream.+ *+ * @param length Number of elements to map.+ * @param e Endianness of the data to read.+ * @return The read Uint8Array.+ */+ readUint8Array(length) {+ length = length === void 0 ? this.byteLength - this.position : length;+ const arr = new Uint8Array(length);+ DataStream.memcpy(arr.buffer, 0, this.buffer, this.byteOffset + this.position, length * arr.BYTES_PER_ELEMENT);+ this.position += arr.byteLength;+ return arr;+ }+ /**+ * Reads a Float64Array of desired length and endianness from the DataStream.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return The read Float64Array.+ */+ readFloat64Array(length, endianness) {+ length = length === void 0 ? this.byteLength - this.position / 8 : length;+ const arr = new Float64Array(length);+ DataStream.memcpy(arr.buffer, 0, this.buffer, this.byteOffset + this.position, length * arr.BYTES_PER_ELEMENT);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += arr.byteLength;+ return arr;+ }+ /**+ * Reads a Float32Array of desired length and endianness from the DataStream.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return The read Float32Array.+ */+ readFloat32Array(length, endianness) {+ length = length === void 0 ? this.byteLength - this.position / 4 : length;+ const arr = new Float32Array(length);+ DataStream.memcpy(arr.buffer, 0, this.buffer, this.byteOffset + this.position, length * arr.BYTES_PER_ELEMENT);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += arr.byteLength;+ return arr;+ }+ /**+ * Reads a 32-bit int from the DataStream with the desired endianness.+ *+ * @param endianness Endianness of the number.+ * @return The read number.+ */+ readInt32(endianness) {+ const v = this._dataView.getInt32(this.position, (endianness ?? this.endianness) === 2);+ this.position += 4;+ return v;+ }+ /**+ * Reads a 16-bit int from the DataStream with the desired endianness.+ *+ * @param endianness Endianness of the number.+ * @return The read number.+ */+ readInt16(endianness) {+ const v = this._dataView.getInt16(this.position, (endianness ?? this.endianness) === 2);+ this.position += 2;+ return v;+ }+ /**+ * Reads an 8-bit int from the DataStream.+ *+ * @return The read number.+ */+ readInt8() {+ const v = this._dataView.getInt8(this.position);+ this.position += 1;+ return v;+ }+ /**+ * Reads a 32-bit unsigned int from the DataStream with the desired endianness.+ *+ * @param endianness Endianness of the number.+ * @return The read number.+ */+ readUint32(endianness) {+ const v = this._dataView.getUint32(this.position, (endianness ?? this.endianness) === 2);+ this.position += 4;+ return v;+ }+ /**+ * Reads a 16-bit unsigned int from the DataStream with the desired endianness.+ *+ * @param endianness Endianness of the number.+ * @return The read number.+ */+ readUint16(endianness) {+ const v = this._dataView.getUint16(this.position, (endianness ?? this.endianness) === 2);+ this.position += 2;+ return v;+ }+ /**+ * Reads an 8-bit unsigned int from the DataStream.+ *+ * @return The read number.+ */+ readUint8() {+ const v = this._dataView.getUint8(this.position);+ this.position += 1;+ return v;+ }+ /**+ * Reads a 32-bit float from the DataStream with the desired endianness.+ *+ * @param endianness Endianness of the number.+ * @return The read number.+ */+ readFloat32(endianness) {+ const value = this._dataView.getFloat32(this.position, (endianness ?? this.endianness) === 2);+ this.position += 4;+ return value;+ }+ /**+ * Reads a 64-bit float from the DataStream with the desired endianness.+ *+ * @param endianness Endianness of the number.+ * @return The read number.+ */+ readFloat64(endianness) {+ const value = this._dataView.getFloat64(this.position, (endianness ?? this.endianness) === 2);+ this.position += 8;+ return value;+ }+ /**+ * Copies byteLength bytes from the src buffer at srcOffset to the+ * dst buffer at dstOffset.+ *+ * @param dst Destination ArrayBuffer to write to.+ * @param dstOffset Offset to the destination ArrayBuffer.+ * @param src Source ArrayBuffer to read from.+ * @param srcOffset Offset to the source ArrayBuffer.+ * @param byteLength Number of bytes to copy.+ */+ static memcpy(dst, dstOffset, src, srcOffset, byteLength) {+ const dstU8 = new Uint8Array(dst, dstOffset, byteLength);+ const srcU8 = new Uint8Array(src, srcOffset, byteLength);+ dstU8.set(srcU8);+ }+ /**+ * Converts array to native endianness in-place.+ *+ * @param typedArray Typed array to convert.+ * @param endianness True if the data in the array is+ * little-endian. Set false for big-endian.+ * @return The converted typed array.+ */+ static arrayToNative(typedArray, endianness) {+ if (endianness === DataStream.ENDIANNESS) return typedArray;+ else return this.flipArrayEndianness(typedArray);+ }+ /**+ * Converts native endianness array to desired endianness in-place.+ *+ * @param typedArray Typed array to convert.+ * @param littleEndian True if the converted array should be+ * little-endian. Set false for big-endian.+ * @return The converted typed array.+ */+ static nativeToEndian(typedArray, littleEndian) {+ if (littleEndian && DataStream.ENDIANNESS === 2) return typedArray;+ else return this.flipArrayEndianness(typedArray);+ }+ /**+ * Flips typed array endianness in-place.+ *+ * @param typedArray Typed array to flip.+ * @return The converted typed array.+ */+ static flipArrayEndianness(typedArray) {+ const u8 = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);+ for (let i = 0; i < typedArray.byteLength; i += typedArray.BYTES_PER_ELEMENT) for (let j = i + typedArray.BYTES_PER_ELEMENT - 1, k = i; j > k; j--, k++) {+ const tmp = u8[k];+ u8[k] = u8[j];+ u8[j] = tmp;+ }+ return typedArray;+ }+ /**+ * Read a string of desired length and encoding from the DataStream.+ *+ * @param length The length of the string to read in bytes.+ * @param encoding The encoding of the string data in the DataStream.+ * Defaults to ASCII.+ * @return The read string.+ */+ readString(length, encoding) {+ if (encoding === void 0 || encoding === "ASCII") return fromCharCodeUint8(this.mapUint8Array(length === void 0 ? this.byteLength - this.position : length));+ else return new TextDecoder(encoding).decode(this.mapUint8Array(length));+ }+ /**+ * Read null-terminated string of desired length from the DataStream. Truncates+ * the returned string so that the null byte is not a part of it.+ *+ * @param length The length of the string to read.+ * @return The read string.+ */+ readCString(length) {+ let i = 0;+ const blen = this.byteLength - this.position;+ const u8 = new Uint8Array(this._buffer, this._byteOffset + this.position);+ const len = length !== void 0 ? Math.min(length, blen) : blen;+ for (; i < len && u8[i] !== 0; i++);+ const s = fromCharCodeUint8(this.mapUint8Array(i));+ if (length !== void 0) this.position += len - i;+ else if (i !== blen) this.position += 1;+ return s;+ }+ readInt64() {+ return this.readInt32() * MAX_SIZE + this.readUint32();+ }+ readUint64() {+ return this.readUint32() * MAX_SIZE + this.readUint32();+ }+ readUint24() {+ return (this.readUint8() << 16) + (this.readUint8() << 8) + this.readUint8();+ }+ /**+ * Saves the DataStream contents to the given filename.+ * Uses Chrome's anchor download property to initiate download.+ *+ * @param filename Filename to save as.+ * @return+ * @bundle DataStream-write.js+ */+ save(filename) {+ const blob = new Blob([this.buffer]);+ if (typeof window !== "undefined" && typeof document !== "undefined") if (window.URL && URL.createObjectURL) {+ const url = window.URL.createObjectURL(blob);+ const a = document.createElement("a");+ document.body.appendChild(a);+ a.setAttribute("href", url);+ a.setAttribute("download", filename);+ a.setAttribute("target", "_self");+ a.click();+ window.URL.revokeObjectURL(url);+ document.body.removeChild(a);+ } else throw new Error("DataStream.save: Can't create object URL.");+ return blob;+ }+ /** @bundle DataStream-write.js */+ get dynamicSize() {+ return this._dynamicSize;+ }+ /** @bundle DataStream-write.js */+ set dynamicSize(v) {+ if (!v) this._trimAlloc();+ this._dynamicSize = v;+ }+ /**+ * Internal function to trim the DataStream buffer when required.+ * Used for stripping out the first bytes when not needed anymore.+ *+ * @return+ * @bundle DataStream-write.js+ */+ shift(offset) {+ const buf = new MP4BoxBuffer(this._byteLength - offset);+ const dst = new Uint8Array(buf);+ const src = new Uint8Array(this._buffer, offset, dst.length);+ dst.set(src);+ this.buffer = buf;+ this.position -= offset;+ }+ /**+ * Writes an Int32Array of specified endianness to the DataStream.+ *+ * @param array The array to write.+ * @param endianness Endianness of the data to write.+ * @bundle DataStream-write.js+ */+ writeInt32Array(array, endianness) {+ this._realloc(array.length * 4);+ if (array instanceof Int32Array && this.byteOffset + this.position % array.BYTES_PER_ELEMENT === 0) {+ DataStream.memcpy(this._buffer, this.byteOffset + this.position, array.buffer, 0, array.byteLength);+ this.mapInt32Array(array.length, endianness);+ } else for (let i = 0; i < array.length; i++) this.writeInt32(array[i], endianness);+ }+ /**+ * Writes an Int16Array of specified endianness to the DataStream.+ *+ * @param array The array to write.+ * @param endianness Endianness of the data to write.+ * @bundle DataStream-write.js+ */+ writeInt16Array(array, endianness) {+ this._realloc(array.length * 2);+ if (array instanceof Int16Array && this.byteOffset + this.position % array.BYTES_PER_ELEMENT === 0) {+ DataStream.memcpy(this._buffer, this.byteOffset + this.position, array.buffer, 0, array.byteLength);+ this.mapInt16Array(array.length, endianness);+ } else for (let i = 0; i < array.length; i++) this.writeInt16(array[i], endianness);+ }+ /**+ * Writes an Int8Array to the DataStream.+ *+ * @param array The array to write.+ * @bundle DataStream-write.js+ */+ writeInt8Array(array) {+ this._realloc(array.length * 1);+ if (array instanceof Int8Array && this.byteOffset + this.position % array.BYTES_PER_ELEMENT === 0) {+ DataStream.memcpy(this._buffer, this.byteOffset + this.position, array.buffer, 0, array.byteLength);+ this.mapInt8Array(array.length);+ } else for (let i = 0; i < array.length; i++) this.writeInt8(array[i]);+ }+ /**+ * Writes a Uint32Array of specified endianness to the DataStream.+ *+ * @param array The array to write.+ * @param endianness Endianness of the data to write.+ * @bundle DataStream-write.js+ */+ writeUint32Array(array, endianness) {+ this._realloc(array.length * 4);+ if (array instanceof Uint32Array && this.byteOffset + this.position % array.BYTES_PER_ELEMENT === 0) {+ DataStream.memcpy(this._buffer, this.byteOffset + this.position, array.buffer, 0, array.byteLength);+ this.mapUint32Array(array.length, endianness);+ } else for (let i = 0; i < array.length; i++) this.writeUint32(array[i], endianness);+ }+ /**+ * Writes a Uint16Array of specified endianness to the DataStream.+ *+ * @param array The array to write.+ * @param endianness Endianness of the data to write.+ * @bundle DataStream-write.js+ */+ writeUint16Array(array, endianness) {+ this._realloc(array.length * 2);+ if (array instanceof Uint16Array && this.byteOffset + this.position % array.BYTES_PER_ELEMENT === 0) {+ DataStream.memcpy(this._buffer, this.byteOffset + this.position, array.buffer, 0, array.byteLength);+ this.mapUint16Array(array.length, endianness);+ } else for (let i = 0; i < array.length; i++) this.writeUint16(array[i], endianness);+ }+ /**+ * Writes a Uint8Array to the DataStream.+ *+ * @param array The array to write.+ * @bundle DataStream-write.js+ */+ writeUint8Array(array) {+ this._realloc(array.length * 1);+ if (array instanceof Uint8Array && this.byteOffset + this.position % array.BYTES_PER_ELEMENT === 0) {+ DataStream.memcpy(this._buffer, this.byteOffset + this.position, array.buffer, 0, array.byteLength);+ this.mapUint8Array(array.length);+ } else for (let i = 0; i < array.length; i++) this.writeUint8(array[i]);+ }+ /**+ * Writes a Float64Array of specified endianness to the DataStream.+ *+ * @param array The array to write.+ * @param endianness Endianness of the data to write.+ * @bundle DataStream-write.js+ */+ writeFloat64Array(array, endianness) {+ this._realloc(array.length * 8);+ if (array instanceof Float64Array && this.byteOffset + this.position % array.BYTES_PER_ELEMENT === 0) {+ DataStream.memcpy(this._buffer, this.byteOffset + this.position, array.buffer, 0, array.byteLength);+ this.mapFloat64Array(array.length, endianness);+ } else for (let i = 0; i < array.length; i++) this.writeFloat64(array[i], endianness);+ }+ /**+ * Writes a Float32Array of specified endianness to the DataStream.+ *+ * @param array The array to write.+ * @param endianness Endianness of the data to write.+ * @bundle DataStream-write.js+ */+ writeFloat32Array(array, endianness) {+ this._realloc(array.length * 4);+ if (array instanceof Float32Array && this.byteOffset + this.position % array.BYTES_PER_ELEMENT === 0) {+ DataStream.memcpy(this._buffer, this.byteOffset + this.position, array.buffer, 0, array.byteLength);+ this.mapFloat32Array(array.length, endianness);+ } else for (let i = 0; i < array.length; i++) this.writeFloat32(array[i], endianness);+ }+ /**+ * Writes a 64-bit int to the DataStream with the desired endianness.+ *+ * @param value Number to write.+ * @param endianness Endianness of the number.+ * @bundle DataStream-write.js+ */+ writeInt64(value, endianness) {+ this._realloc(8);+ this._dataView.setBigInt64(this.position, BigInt(value), (endianness ?? this.endianness) === 2);+ this.position += 8;+ }+ /**+ * Writes a 32-bit int to the DataStream with the desired endianness.+ *+ * @param value Number to write.+ * @param endianness Endianness of the number.+ * @bundle DataStream-write.js+ */+ writeInt32(value, endianness) {+ this._realloc(4);+ this._dataView.setInt32(this.position, value, (endianness ?? this.endianness) === 2);+ this.position += 4;+ }+ /**+ * Writes a 16-bit int to the DataStream with the desired endianness.+ *+ * @param value Number to write.+ * @param endianness Endianness of the number.+ * @bundle DataStream-write.js+ */+ writeInt16(value, endianness) {+ this._realloc(2);+ this._dataView.setInt16(this.position, value, (endianness ?? this.endianness) === 2);+ this.position += 2;+ }+ /**+ * Writes an 8-bit int to the DataStream.+ *+ * @param value Number to write.+ * @bundle DataStream-write.js+ */+ writeInt8(value) {+ this._realloc(1);+ this._dataView.setInt8(this.position, value);+ this.position += 1;+ }+ /**+ * Writes a 32-bit unsigned int to the DataStream with the desired endianness.+ *+ * @param value Number to write.+ * @param endianness Endianness of the number.+ * @bundle DataStream-write.js+ */+ writeUint32(value, endianness) {+ this._realloc(4);+ this._dataView.setUint32(this.position, value, (endianness ?? this.endianness) === 2);+ this.position += 4;+ }+ /**+ * Writes a 16-bit unsigned int to the DataStream with the desired endianness.+ *+ * @param value Number to write.+ * @param endianness Endianness of the number.+ * @bundle DataStream-write.js+ */+ writeUint16(value, endianness) {+ this._realloc(2);+ this._dataView.setUint16(this.position, value, (endianness ?? this.endianness) === 2);+ this.position += 2;+ }+ /**+ * Writes an 8-bit unsigned int to the DataStream.+ *+ * @param value Number to write.+ * @bundle DataStream-write.js+ */+ writeUint8(value) {+ this._realloc(1);+ this._dataView.setUint8(this.position, value);+ this.position += 1;+ }+ /**+ * Writes a 32-bit float to the DataStream with the desired endianness.+ *+ * @param value Number to write.+ * @param endianness Endianness of the number.+ * @bundle DataStream-write.js+ */+ writeFloat32(value, endianness) {+ this._realloc(4);+ this._dataView.setFloat32(this.position, value, (endianness ?? this.endianness) === 2);+ this.position += 4;+ }+ /**+ * Writes a 64-bit float to the DataStream with the desired endianness.+ *+ * @param value Number to write.+ * @param endianness Endianness of the number.+ * @bundle DataStream-write.js+ */+ writeFloat64(value, endianness) {+ this._realloc(8);+ this._dataView.setFloat64(this.position, value, (endianness ?? this.endianness) === 2);+ this.position += 8;+ }+ /**+ * Write a UCS-2 string of desired endianness to the DataStream. The+ * lengthOverride argument lets you define the number of characters to write.+ * If the string is shorter than lengthOverride, the extra space is padded with+ * zeroes.+ *+ * @param value The string to write.+ * @param endianness The endianness to use for the written string data.+ * @param lengthOverride The number of characters to write.+ * @bundle DataStream-write.js+ */+ writeUCS2String(value, endianness, lengthOverride) {+ if (lengthOverride === void 0) lengthOverride = value.length;+ let i;+ for (i = 0; i < value.length && i < lengthOverride; i++) this.writeUint16(value.charCodeAt(i), endianness);+ for (; i < lengthOverride; i++) this.writeUint16(0);+ }+ /**+ * Writes a string of desired length and encoding to the DataStream.+ *+ * @param value The string to write.+ * @param encoding The encoding for the written string data.+ * Defaults to ASCII.+ * @param length The number of characters to write.+ * @bundle DataStream-write.js+ */+ writeString(value, encoding, length) {+ let i = 0;+ if (encoding === void 0 || encoding === "ASCII") if (length !== void 0) {+ const len = Math.min(value.length, length);+ for (i = 0; i < len; i++) this.writeUint8(value.charCodeAt(i));+ for (; i < length; i++) this.writeUint8(0);+ } else for (i = 0; i < value.length; i++) this.writeUint8(value.charCodeAt(i));+ else this.writeUint8Array(new TextEncoder(encoding).encode(value.substring(0, length)));+ }+ /**+ * Writes a null-terminated string to DataStream and zero-pads it to length+ * bytes. If length is not given, writes the string followed by a zero.+ * If string is longer than length, the written part of the string does not have+ * a trailing zero.+ *+ * @param value The string to write.+ * @param length The number of characters to write.+ * @bundle DataStream-write.js+ */+ writeCString(value, length) {+ let i = 0;+ if (length !== void 0) {+ const len = Math.min(value.length, length);+ for (i = 0; i < len; i++) this.writeUint8(value.charCodeAt(i));+ for (; i < length; i++) this.writeUint8(0);+ } else {+ for (i = 0; i < value.length; i++) this.writeUint8(value.charCodeAt(i));+ this.writeUint8(0);+ }+ }+ /**+ * Writes a struct to the DataStream. Takes a structDefinition that gives the+ * types and a struct object that gives the values. Refer to readStruct for the+ * structure of structDefinition.+ *+ * @param structDefinition Type definition of the struct.+ * @param struct The struct data object.+ * @bundle DataStream-write.js+ */+ writeStruct(structDefinition, struct) {+ for (let i = 0; i < structDefinition.length; i++) {+ const [structName, structType] = structDefinition[i];+ const structValue = struct[structName];+ this.writeType(structType, structValue, struct);+ }+ }+ /**+ * Writes object v of type t to the DataStream.+ *+ * @param type Type of data to write.+ * @param value Value of data to write.+ * @param struct Struct to pass to write callback functions.+ * @bundle DataStream-write.js+ */+ writeType(type, value, struct) {+ if (typeof type === "function") return type(this, value);+ else if (typeof type === "object" && !(type instanceof Array)) return type.set(this, value, struct);+ let lengthOverride;+ let charset = "ASCII";+ const pos = this.position;+ let parsedType = type;+ if (typeof type === "string" && /:/.test(type)) {+ const tp = type.split(":");+ parsedType = tp[0];+ lengthOverride = parseInt(tp[1]);+ }+ if (typeof parsedType === "string" && /,/.test(parsedType)) {+ const tp = parsedType.split(",");+ parsedType = tp[0];+ charset = tp[1];+ }+ switch (parsedType) {+ case "uint8":+ this.writeUint8(value);+ break;+ case "int8":+ this.writeInt8(value);+ break;+ case "uint16":+ this.writeUint16(value, this.endianness);+ break;+ case "int16":+ this.writeInt16(value, this.endianness);+ break;+ case "uint32":+ this.writeUint32(value, this.endianness);+ break;+ case "int32":+ this.writeInt32(value, this.endianness);+ break;+ case "float32":+ this.writeFloat32(value, this.endianness);+ break;+ case "float64":+ this.writeFloat64(value, this.endianness);+ break;+ case "uint16be":+ this.writeUint16(value, 1);+ break;+ case "int16be":+ this.writeInt16(value, 1);+ break;+ case "uint32be":+ this.writeUint32(value, 1);+ break;+ case "int32be":+ this.writeInt32(value, 1);+ break;+ case "float32be":+ this.writeFloat32(value, 1);+ break;+ case "float64be":+ this.writeFloat64(value, 1);+ break;+ case "uint16le":+ this.writeUint16(value, 2);+ break;+ case "int16le":+ this.writeInt16(value, 2);+ break;+ case "uint32le":+ this.writeUint32(value, 2);+ break;+ case "int32le":+ this.writeInt32(value, 2);+ break;+ case "float32le":+ this.writeFloat32(value, 2);+ break;+ case "float64le":+ this.writeFloat64(value, 2);+ break;+ case "cstring":+ this.writeCString(value, lengthOverride);+ break;+ case "string":+ this.writeString(value, charset, lengthOverride);+ break;+ case "u16string":+ this.writeUCS2String(value, this.endianness, lengthOverride);+ break;+ case "u16stringle":+ this.writeUCS2String(value, 2, lengthOverride);+ break;+ case "u16stringbe":+ this.writeUCS2String(value, 1, lengthOverride);+ break;+ default: if (this.#isTupleType(parsedType)) {+ const [, ta] = parsedType;+ for (let i = 0; i < value.length; i++) this.writeType(ta, value[i]);+ break;+ } else {+ this.writeStruct(parsedType, value);+ break;+ }+ }+ if (lengthOverride) {+ this.position = pos;+ this._realloc(lengthOverride);+ this.position = pos + lengthOverride;+ }+ }+ /** @bundle DataStream-write.js */+ writeUint64(value) {+ const h = Math.floor(value / MAX_SIZE);+ this.writeUint32(h);+ this.writeUint32(value & 4294967295);+ }+ /** @bundle DataStream-write.js */+ writeUint24(value) {+ this.writeUint8((value & 16711680) >> 16);+ this.writeUint8((value & 65280) >> 8);+ this.writeUint8(value & 255);+ }+ /** @bundle DataStream-write.js */+ adjustUint32(position, value) {+ const pos = this.position;+ this.seek(position);+ this.writeUint32(value);+ this.seek(pos);+ }+ /**+ * Reads a struct of data from the DataStream. The struct is defined as+ * an array of [name, type]-pairs. See the example below:+ *+ * ```ts+ * ds.readStruct([+ * ['headerTag', 'uint32'], // Uint32 in DataStream endianness.+ * ['headerTag2', 'uint32be'], // Big-endian Uint32.+ * ['headerTag3', 'uint32le'], // Little-endian Uint32.+ * ['array', ['[]', 'uint32', 16]], // Uint32Array of length 16.+ * ['array2', ['[]', 'uint32', 'array2Length']] // Uint32Array of length array2Length+ * ]);+ * ```+ *+ * The possible values for the type are as follows:+ *+ * ## Number types+ *+ * Unsuffixed number types use DataStream endianness.+ * To explicitly specify endianness, suffix the type with+ * 'le' for little-endian or 'be' for big-endian,+ * e.g. 'int32be' for big-endian int32.+ *+ * - `uint8` -- 8-bit unsigned int+ * - `uint16` -- 16-bit unsigned int+ * - `uint32` -- 32-bit unsigned int+ * - `int8` -- 8-bit int+ * - `int16` -- 16-bit int+ * - `int32` -- 32-bit int+ * - `float32` -- 32-bit float+ * - `float64` -- 64-bit float+ *+ * ## String types+ *+ * - `cstring` -- ASCII string terminated by a zero byte.+ * - `string:N` -- ASCII string of length N.+ * - `string,CHARSET:N` -- String of byteLength N encoded with given CHARSET.+ * - `u16string:N` -- UCS-2 string of length N in DataStream endianness.+ * - `u16stringle:N` -- UCS-2 string of length N in little-endian.+ * - `u16stringbe:N` -- UCS-2 string of length N in big-endian.+ *+ * ## Complex types+ *+ * ### Struct+ * ```ts+ * [[name, type], [name_2, type_2], ..., [name_N, type_N]]+ * ```+ *+ * ### Callback function to read and return data+ * ```ts+ * function(dataStream, struct) {}+ * ```+ *+ * ### Getter/setter functions+ * to read and return data, handy for using the same struct definition+ * for reading and writing structs.+ * ```ts+ * {+ * get: function(dataStream, struct) {},+ * set: function(dataStream, struct) {}+ * }+ * ```+ *+ * ### Array+ * Array of given type and length. The length can be either+ * - a number+ * - a string that references a previously-read field+ * - `*`+ * - a callback: `function(struct, dataStream, type){}`+ *+ * If length is `*`, reads in as many elements as it can.+ * ```ts+ * ['[]', type, length]+ * ```+ *+ * @param structDefinition Struct definition object.+ * @return The read struct. Null if failed to read struct.+ * @bundle DataStream-read-struct.js+ */+ readStruct(structDefinition) {+ const struct = {};+ const p = this.position;+ for (let i = 0; i < structDefinition.length; i += 1) {+ const t = structDefinition[i][1];+ const v = this.readType(t, struct);+ if (!v) {+ if (this.failurePosition === 0) this.failurePosition = this.position;+ this.position = p;+ return;+ }+ struct[structDefinition[i][0]] = v;+ }+ return struct;+ }+ /**+ * Read UCS-2 string of desired length and endianness from the DataStream.+ *+ * @param length The length of the string to read.+ * @param endianness The endianness of the string data in the DataStream.+ * @return The read string.+ * @bundle DataStream-read-struct.js+ */+ readUCS2String(length, endianness) {+ return String.fromCharCode.apply(void 0, this.readUint16Array(length, endianness));+ }+ /**+ * Reads an object of type t from the DataStream, passing struct as the thus-far+ * read struct to possible callbacks that refer to it. Used by readStruct for+ * reading in the values, so the type is one of the readStruct types.+ *+ * @param type Type of the object to read.+ * @param struct Struct to refer to when resolving length references+ * and for calling callbacks.+ * @return Returns the object on successful read, null on unsuccessful.+ * @bundle DataStream-read-struct.js+ */+ readType(type, struct) {+ if (typeof type === "function") return type(this, struct);+ if (typeof type === "object" && !(type instanceof Array)) return type.get(this, struct);+ if (type instanceof Array && type.length !== 3) return this.readStruct(type);+ let value;+ let lengthOverride;+ let charset = "ASCII";+ const pos = this.position;+ let parsedType = type;+ if (typeof parsedType === "string" && /:/.test(parsedType)) {+ const tp = parsedType.split(":");+ parsedType = tp[0];+ lengthOverride = parseInt(tp[1]);+ }+ if (typeof parsedType === "string" && /,/.test(parsedType)) {+ const tp = parsedType.split(",");+ parsedType = tp[0];+ charset = tp[1];+ }+ switch (parsedType) {+ case "uint8":+ value = this.readUint8();+ break;+ case "int8":+ value = this.readInt8();+ break;+ case "uint16":+ value = this.readUint16(this.endianness);+ break;+ case "int16":+ value = this.readInt16(this.endianness);+ break;+ case "uint32":+ value = this.readUint32(this.endianness);+ break;+ case "int32":+ value = this.readInt32(this.endianness);+ break;+ case "float32":+ value = this.readFloat32(this.endianness);+ break;+ case "float64":+ value = this.readFloat64(this.endianness);+ break;+ case "uint16be":+ value = this.readUint16(1);+ break;+ case "int16be":+ value = this.readInt16(1);+ break;+ case "uint32be":+ value = this.readUint32(1);+ break;+ case "int32be":+ value = this.readInt32(1);+ break;+ case "float32be":+ value = this.readFloat32(1);+ break;+ case "float64be":+ value = this.readFloat64(1);+ break;+ case "uint16le":+ value = this.readUint16(2);+ break;+ case "int16le":+ value = this.readInt16(2);+ break;+ case "uint32le":+ value = this.readUint32(2);+ break;+ case "int32le":+ value = this.readInt32(2);+ break;+ case "float32le":+ value = this.readFloat32(2);+ break;+ case "float64le":+ value = this.readFloat64(2);+ break;+ case "cstring":+ value = this.readCString(lengthOverride);+ break;+ case "string":+ value = this.readString(lengthOverride, charset);+ break;+ case "u16string":+ value = this.readUCS2String(lengthOverride, this.endianness);+ break;+ case "u16stringle":+ value = this.readUCS2String(lengthOverride, 2);+ break;+ case "u16stringbe":+ value = this.readUCS2String(lengthOverride, 1);+ break;+ default: if (this.#isTupleType(parsedType)) {+ const [, ta, len] = parsedType;+ const length = typeof len === "function" ? len(struct, this, parsedType) : typeof len === "string" && struct[len] !== void 0 ? parseInt(struct[len]) : typeof len === "number" ? len : len === "*" ? void 0 : parseInt(len);+ if (typeof ta === "string") {+ const tap = ta.replace(/(le|be)$/, "");+ let endianness;+ if (/le$/.test(ta)) endianness = 2;+ else if (/be$/.test(ta)) endianness = 1;+ switch (tap) {+ case "uint8":+ value = this.readUint8Array(length);+ break;+ case "uint16":+ value = this.readUint16Array(length, endianness);+ break;+ case "uint32":+ value = this.readUint32Array(length, endianness);+ break;+ case "int8":+ value = this.readInt8Array(length);+ break;+ case "int16":+ value = this.readInt16Array(length, endianness);+ break;+ case "int32":+ value = this.readInt32Array(length, endianness);+ break;+ case "float32":+ value = this.readFloat32Array(length, endianness);+ break;+ case "float64":+ value = this.readFloat64Array(length, endianness);+ break;+ case "cstring":+ case "utf16string":+ case "string":+ if (!length) {+ value = [];+ while (!this.isEof()) {+ const u = this.readType(ta, struct);+ if (!u) break;+ value.push(u);+ }+ } else {+ value = new Array(length);+ for (let i = 0; i < length; i++) value[i] = this.readType(ta, struct);+ }+ break;+ }+ } else if (!length) {+ value = [];+ while (true) {+ const pos = this.position;+ try {+ const type = this.readType(ta, struct);+ if (!type) {+ this.position = pos;+ break;+ }+ value.push(type);+ } catch {+ this.position = pos;+ break;+ }+ }+ } else {+ value = new Array(length);+ for (let i = 0; i < length; i++) {+ const type = this.readType(ta, struct);+ if (!type) return;+ value[i] = type;+ }+ }+ break;+ }+ }+ if (lengthOverride) this.position = pos + lengthOverride;+ return value;+ }+ /**+ * Maps an Int32Array into the DataStream buffer, swizzling it to native+ * endianness in-place. The current offset from the start of the buffer needs to+ * be a multiple of element size, just like with typed array views.+ *+ * Nice for quickly reading in data. Warning: potentially modifies the buffer+ * contents.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return Int32Array to the DataStream backing buffer.+ * @bundle DataStream-map.js+ */+ mapInt32Array(length, endianness) {+ this._realloc(length * 4);+ const arr = new Int32Array(this._buffer, this.byteOffset + this.position, length);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += length * 4;+ return arr;+ }+ /**+ * Maps an Int16Array into the DataStream buffer, swizzling it to native+ * endianness in-place. The current offset from the start of the buffer needs to+ * be a multiple of element size, just like with typed array views.+ *+ * Nice for quickly reading in data. Warning: potentially modifies the buffer+ * contents.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return Int16Array to the DataStream backing buffer.+ * @bundle DataStream-map.js+ */+ mapInt16Array(length, endianness) {+ this._realloc(length * 2);+ const arr = new Int16Array(this._buffer, this.byteOffset + this.position, length);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += length * 2;+ return arr;+ }+ /**+ * Maps an Int8Array into the DataStream buffer.+ *+ * Nice for quickly reading in data.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return Int8Array to the DataStream backing buffer.+ * @bundle DataStream-map.js+ */+ mapInt8Array(length, _endianness) {+ this._realloc(length * 1);+ const arr = new Int8Array(this._buffer, this.byteOffset + this.position, length);+ this.position += length * 1;+ return arr;+ }+ /**+ * Maps a Uint32Array into the DataStream buffer, swizzling it to native+ * endianness in-place. The current offset from the start of the buffer needs to+ * be a multiple of element size, just like with typed array views.+ *+ * Nice for quickly reading in data. Warning: potentially modifies the buffer+ * contents.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return Uint32Array to the DataStream backing buffer.+ * @bundle DataStream-map.js+ */+ mapUint32Array(length, endianness) {+ this._realloc(length * 4);+ const arr = new Uint32Array(this._buffer, this.byteOffset + this.position, length);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += length * 4;+ return arr;+ }+ /**+ * Maps a Uint16Array into the DataStream buffer, swizzling it to native+ * endianness in-place. The current offset from the start of the buffer needs to+ * be a multiple of element size, just like with typed array views.+ *+ * Nice for quickly reading in data. Warning: potentially modifies the buffer+ * contents.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return Uint16Array to the DataStream backing buffer.+ * @bundle DataStream-map.js+ */+ mapUint16Array(length, endianness) {+ this._realloc(length * 2);+ const arr = new Uint16Array(this._buffer, this.byteOffset + this.position, length);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += length * 2;+ return arr;+ }+ /**+ * Maps a Float64Array into the DataStream buffer, swizzling it to native+ * endianness in-place. The current offset from the start of the buffer needs to+ * be a multiple of element size, just like with typed array views.+ *+ * Nice for quickly reading in data. Warning: potentially modifies the buffer+ * contents.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return Float64Array to the DataStream backing buffer.+ * @bundle DataStream-map.js+ */+ mapFloat64Array(length, endianness) {+ this._realloc(length * 8);+ const arr = new Float64Array(this._buffer, this.byteOffset + this.position, length);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += length * 8;+ return arr;+ }+ /**+ * Maps a Float32Array into the DataStream buffer, swizzling it to native+ * endianness in-place. The current offset from the start of the buffer needs to+ * be a multiple of element size, just like with typed array views.+ *+ * Nice for quickly reading in data. Warning: potentially modifies the buffer+ * contents.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return Float32Array to the DataStream backing buffer.+ * @bundle DataStream-map.js+ */+ mapFloat32Array(length, endianness) {+ this._realloc(length * 4);+ const arr = new Float32Array(this._buffer, this.byteOffset + this.position, length);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += length * 4;+ return arr;+ }+};+function fromCharCodeUint8(uint8arr) {+ const arr = [];+ for (let i = 0; i < uint8arr.length; i++) arr[i] = uint8arr[i];+ return String.fromCharCode.apply(void 0, arr);+}++//#endregion+//#region src/log.ts+const start = /* @__PURE__ */ new Date();+const LOG_LEVEL_ERROR = 4;+const LOG_LEVEL_WARNING = 3;+const LOG_LEVEL_INFO = 2;+const LOG_LEVEL_DEBUG = 1;+let log_level = LOG_LEVEL_ERROR;+const Log = {+ setLogLevel(level) {+ if (level === this.debug) log_level = LOG_LEVEL_DEBUG;+ else if (level === this.info) log_level = LOG_LEVEL_INFO;+ else if (level === this.warn) log_level = LOG_LEVEL_WARNING;+ else if (level === this.error) log_level = LOG_LEVEL_ERROR;+ else log_level = LOG_LEVEL_ERROR;+ },+ debug(module, msg) {+ if (console.debug === void 0) console.debug = console.log;+ if (LOG_LEVEL_DEBUG >= log_level) console.debug("[" + Log.getDurationString((/* @__PURE__ */ new Date()).getTime() - start.getTime(), 1e3) + "]", "[" + module + "]", msg);+ },+ log(module, _msg) {+ this.debug(module.msg);+ },+ info(module, msg) {+ if (LOG_LEVEL_INFO >= log_level) console.info("[" + Log.getDurationString((/* @__PURE__ */ new Date()).getTime() - start.getTime(), 1e3) + "]", "[" + module + "]", msg);+ },+ warn(module, msg) {+ if (LOG_LEVEL_WARNING >= log_level) console.warn("[" + Log.getDurationString((/* @__PURE__ */ new Date()).getTime() - start.getTime(), 1e3) + "]", "[" + module + "]", msg);+ },+ error(module, msg, isofile) {+ if (isofile?.onError) isofile.onError(module, msg);+ else if (LOG_LEVEL_ERROR >= log_level) console.error("[" + Log.getDurationString((/* @__PURE__ */ new Date()).getTime() - start.getTime(), 1e3) + "]", "[" + module + "]", msg);+ },+ getDurationString(duration, _timescale) {+ let neg;+ function pad(number, length) {+ const a = ("" + number).split(".");+ while (a[0].length < length) a[0] = "0" + a[0];+ return a.join(".");+ }+ if (duration < 0) {+ neg = true;+ duration = -duration;+ } else neg = false;+ let duration_sec = duration / (_timescale || 1);+ const hours = Math.floor(duration_sec / 3600);+ duration_sec -= hours * 3600;+ const minutes = Math.floor(duration_sec / 60);+ duration_sec -= minutes * 60;+ let msec = duration_sec * 1e3;+ duration_sec = Math.floor(duration_sec);+ msec -= duration_sec * 1e3;+ msec = Math.floor(msec);+ return (neg ? "-" : "") + hours + ":" + pad(minutes, 2) + ":" + pad(duration_sec, 2) + "." + pad(msec, 3);+ },+ printRanges(ranges) {+ const length = ranges.length;+ if (length > 0) {+ let str = "";+ for (let i = 0; i < length; i++) {+ if (i > 0) str += ",";+ str += "[" + Log.getDurationString(ranges.start(i)) + "," + Log.getDurationString(ranges.end(i)) + "]";+ }+ return str;+ } else return "(empty)";+ }+};++//#endregion+//#region src/buffer.ts+/**+* helper functions to concatenate two ArrayBuffer objects+* @param buffer1+* @param buffer2+* @return the concatenation of buffer1 and buffer2 in that order+*/+function concatBuffers(buffer1, buffer2) {+ Log.debug("ArrayBuffer", "Trying to create a new buffer of size: " + (buffer1.byteLength + buffer2.byteLength));+ const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);+ tmp.set(new Uint8Array(buffer1), 0);+ tmp.set(new Uint8Array(buffer2), buffer1.byteLength);+ return tmp.buffer;+}+/**+* MultiBufferStream is a class that acts as a SimpleStream for parsing+* It holds several, possibly non-contiguous ArrayBuffer objects, each with a fileStart property+* containing the offset for the buffer data in an original/virtual file+*+* It inherits also from DataStream for all read/write/alloc operations+*/+var MultiBufferStream = class extends DataStream {+ constructor(buffer) {+ super(/* @__PURE__ */ new ArrayBuffer(), 0);+ this.buffers = [];+ this.bufferIndex = -1;+ if (buffer) {+ this.insertBuffer(buffer);+ this.bufferIndex = 0;+ }+ }+ /***********************************************************************************+ * Methods for the managnement of the buffers *+ * (insertion, removal, concatenation, ...) *+ ***********************************************************************************/+ initialized() {+ if (this.bufferIndex > -1) return true;+ else if (this.buffers.length > 0) {+ const firstBuffer = this.buffers[0];+ if (firstBuffer.fileStart === 0) {+ this.buffer = firstBuffer;+ this.bufferIndex = 0;+ Log.debug("MultiBufferStream", "Stream ready for parsing");+ return true;+ } else {+ Log.warn("MultiBufferStream", "The first buffer should have a fileStart of 0");+ this.logBufferLevel();+ return false;+ }+ } else {+ Log.warn("MultiBufferStream", "No buffer to start parsing from");+ this.logBufferLevel();+ return false;+ }+ }+ /**+ * Reduces the size of a given buffer, but taking the part between offset and offset+newlength+ * @param {ArrayBuffer} buffer+ * @param {Number} offset the start of new buffer+ * @param {Number} newLength the length of the new buffer+ * @return {ArrayBuffer} the new buffer+ */+ reduceBuffer(buffer, offset, newLength) {+ const smallB = new Uint8Array(newLength);+ smallB.set(new Uint8Array(buffer, offset, newLength));+ smallB.buffer.fileStart = buffer.fileStart + offset;+ smallB.buffer.usedBytes = 0;+ return smallB.buffer;+ }+ /**+ * Inserts the new buffer in the sorted list of buffers,+ * making sure, it is not overlapping with existing ones (possibly reducing its size).+ * if the new buffer overrides/replaces the 0-th buffer (for instance because it is bigger),+ * updates the DataStream buffer for parsing+ */+ insertBuffer(ab) {+ let to_add = true;+ let i = 0;+ for (; i < this.buffers.length; i++) {+ const b = this.buffers[i];+ if (ab.fileStart <= b.fileStart) {+ if (ab.fileStart === b.fileStart) if (ab.byteLength > b.byteLength) {+ this.buffers.splice(i, 1);+ i--;+ continue;+ } else Log.warn("MultiBufferStream", "Buffer (fileStart: " + ab.fileStart + " - Length: " + ab.byteLength + ") already appended, ignoring");+ else {+ if (ab.fileStart + ab.byteLength <= b.fileStart) {} else ab = this.reduceBuffer(ab, 0, b.fileStart - ab.fileStart);+ Log.debug("MultiBufferStream", "Appending new buffer (fileStart: " + ab.fileStart + " - Length: " + ab.byteLength + ")");+ this.buffers.splice(i, 0, ab);+ if (i === 0) this.buffer = ab;+ }+ to_add = false;+ break;+ } else if (ab.fileStart < b.fileStart + b.byteLength) {+ const offset = b.fileStart + b.byteLength - ab.fileStart;+ const newLength = ab.byteLength - offset;+ if (newLength > 0) ab = this.reduceBuffer(ab, offset, newLength);+ else {+ to_add = false;+ break;+ }+ }+ }+ if (to_add) {+ Log.debug("MultiBufferStream", "Appending new buffer (fileStart: " + ab.fileStart + " - Length: " + ab.byteLength + ")");+ this.buffers.push(ab);+ if (i === 0) this.buffer = ab;+ }+ }+ /**+ * Displays the status of the buffers (number and used bytes)+ * @param {Object} info callback method for display+ */+ logBufferLevel(info) {+ const ranges = [];+ let bufferedString = "";+ let range;+ let used = 0;+ let total = 0;+ for (let i = 0; i < this.buffers.length; i++) {+ const buffer = this.buffers[i];+ if (i === 0) {+ range = {+ start: buffer.fileStart,+ end: buffer.fileStart + buffer.byteLength+ };+ ranges.push(range);+ bufferedString += "[" + range.start + "-";+ } else if (range.end === buffer.fileStart) range.end = buffer.fileStart + buffer.byteLength;+ else {+ range = {+ start: buffer.fileStart,+ end: buffer.fileStart + buffer.byteLength+ };+ bufferedString += ranges[ranges.length - 1].end - 1 + "], [" + range.start + "-";+ ranges.push(range);+ }+ used += buffer.usedBytes;+ total += buffer.byteLength;+ }+ if (ranges.length > 0) bufferedString += range.end - 1 + "]";+ const log = info ? Log.info : Log.debug;+ if (this.buffers.length === 0) log("MultiBufferStream", "No more buffer in memory");+ else log("MultiBufferStream", "" + this.buffers.length + " stored buffer(s) (" + used + "/" + total + " bytes), continuous ranges: " + bufferedString);+ }+ cleanBuffers() {+ for (let i = 0; i < this.buffers.length; i++) {+ const buffer = this.buffers[i];+ if (buffer.usedBytes === buffer.byteLength) {+ Log.debug("MultiBufferStream", "Removing buffer #" + i);+ this.buffers.splice(i, 1);+ i--;+ }+ }+ }+ mergeNextBuffer() {+ if (this.bufferIndex + 1 < this.buffers.length) {+ const next_buffer = this.buffers[this.bufferIndex + 1];+ if (next_buffer.fileStart === this.buffer.fileStart + this.buffer.byteLength) {+ const oldLength = this.buffer.byteLength;+ const oldUsedBytes = this.buffer.usedBytes;+ const oldFileStart = this.buffer.fileStart;+ this.buffers[this.bufferIndex] = concatBuffers(this.buffer, next_buffer);+ this.buffer = this.buffers[this.bufferIndex];+ this.buffers.splice(this.bufferIndex + 1, 1);+ this.buffer.usedBytes = oldUsedBytes;+ this.buffer.fileStart = oldFileStart;+ Log.debug("ISOFile", "Concatenating buffer for box parsing (length: " + oldLength + "->" + this.buffer.byteLength + ")");+ return true;+ } else return false;+ } else return false;+ }+ /*************************************************************************+ * Seek-related functions *+ *************************************************************************/+ /**+ * Finds the buffer that holds the given file position+ * @param {Boolean} fromStart indicates if the search should start from the current buffer (false)+ * or from the first buffer (true)+ * @param {Number} filePosition position in the file to seek to+ * @param {Boolean} markAsUsed indicates if the bytes in between the current position and the seek position+ * should be marked as used for garbage collection+ * @return {Number} the index of the buffer holding the seeked file position, -1 if not found.+ */+ findPosition(fromStart, filePosition, markAsUsed) {+ let index = -1;+ let i = fromStart === true ? 0 : this.bufferIndex;+ while (i < this.buffers.length) {+ const abuffer = this.buffers[i];+ if (abuffer && abuffer.fileStart <= filePosition) {+ index = i;+ if (markAsUsed) {+ if (abuffer.fileStart + abuffer.byteLength <= filePosition) abuffer.usedBytes = abuffer.byteLength;+ else abuffer.usedBytes = filePosition - abuffer.fileStart;+ this.logBufferLevel();+ }+ } else break;+ i++;+ }+ if (index === -1) return -1;+ const abuffer = this.buffers[index];+ if (abuffer.fileStart + abuffer.byteLength >= filePosition) {+ Log.debug("MultiBufferStream", "Found position in existing buffer #" + index);+ return index;+ } else return -1;+ }+ /**+ * Finds the largest file position contained in a buffer or in the next buffers if they are contiguous (no gap)+ * starting from the given buffer index or from the current buffer if the index is not given+ *+ * @param {Number} inputindex Index of the buffer to start from+ * @return {Number} The largest file position found in the buffers+ */+ findEndContiguousBuf(inputindex) {+ const index = inputindex !== void 0 ? inputindex : this.bufferIndex;+ let currentBuf = this.buffers[index];+ if (this.buffers.length > index + 1) for (let i = index + 1; i < this.buffers.length; i++) {+ const nextBuf = this.buffers[i];+ if (nextBuf.fileStart === currentBuf.fileStart + currentBuf.byteLength) currentBuf = nextBuf;+ else break;+ }+ return currentBuf.fileStart + currentBuf.byteLength;+ }+ /**+ * Returns the largest file position contained in the buffers, larger than the given position+ * @param {Number} pos the file position to start from+ * @return {Number} the largest position in the current buffer or in the buffer and the next contiguous+ * buffer that holds the given position+ */+ getEndFilePositionAfter(pos) {+ const index = this.findPosition(true, pos, false);+ if (index !== -1) return this.findEndContiguousBuf(index);+ else return pos;+ }+ /*************************************************************************+ * Garbage collection related functions *+ *************************************************************************/+ /**+ * Marks a given number of bytes as used in the current buffer for garbage collection+ * @param {Number} nbBytes+ */+ addUsedBytes(nbBytes) {+ this.buffer.usedBytes += nbBytes;+ this.logBufferLevel();+ }+ /**+ * Marks the entire current buffer as used, ready for garbage collection+ */+ setAllUsedBytes() {+ this.buffer.usedBytes = this.buffer.byteLength;+ this.logBufferLevel();+ }+ /*************************************************************************+ * Common API between MultiBufferStream and SimpleStream *+ *************************************************************************/+ /**+ * Tries to seek to a given file position+ * if possible, repositions the parsing from there and returns true+ * if not possible, does not change anything and returns false+ * @param {Number} filePosition position in the file to seek to+ * @param {Boolean} fromStart indicates if the search should start from the current buffer (false)+ * or from the first buffer (true)+ * @param {Boolean} markAsUsed indicates if the bytes in between the current position and the seek position+ * should be marked as used for garbage collection+ * @return {Boolean} true if the seek succeeded, false otherwise+ */+ seek(filePosition, fromStart, markAsUsed) {+ const index = this.findPosition(fromStart, filePosition, markAsUsed);+ if (index !== -1) {+ this.buffer = this.buffers[index];+ this.bufferIndex = index;+ this.position = filePosition - this.buffer.fileStart;+ Log.debug("MultiBufferStream", "Repositioning parser at buffer position: " + this.position);+ return true;+ } else {+ Log.debug("MultiBufferStream", "Position " + filePosition + " not found in buffered data");+ return false;+ }+ }+ /**+ * Returns the current position in the file+ * @return {Number} the position in the file+ */+ getPosition() {+ if (this.bufferIndex === -1 || this.buffers[this.bufferIndex] === void 0) return 0;+ return this.buffers[this.bufferIndex].fileStart + this.position;+ }+ /**+ * Returns the length of the current buffer+ * @return {Number} the length of the current buffer+ */+ getLength() {+ return this.byteLength;+ }+ getEndPosition() {+ if (this.bufferIndex === -1 || this.buffers[this.bufferIndex] === void 0) return 0;+ return this.buffers[this.bufferIndex].fileStart + this.byteLength;+ }+ getAbsoluteEndPosition() {+ if (this.buffers.length === 0) return 0;+ const lastBuffer = this.buffers[this.buffers.length - 1];+ return lastBuffer.fileStart + lastBuffer.byteLength;+ }+};++//#endregion+//#region src/box.ts+var Box = class {+ static {+ this.registryId = Symbol.for("BoxIdentifier");+ }+ #type;+ get type() {+ return this.constructor.fourcc ?? this.#type;+ }+ set type(value) {+ this.#type = value;+ }+ constructor(size = 0) {+ this.size = size;+ }+ addBox(box) {+ if (!this.boxes) this.boxes = [];+ this.boxes.push(box);+ if (this[box.type + "s"]) this[box.type + "s"].push(box);+ else this[box.type] = box;+ return box;+ }+ set(prop, value) {+ this[prop] = value;+ return this;+ }+ addEntry(value, _prop) {+ const prop = _prop || "entries";+ if (!this[prop]) this[prop] = [];+ this[prop].push(value);+ return this;+ }+ /** @bundle box-write.js */+ writeHeader(stream, msg) {+ this.size += 8;+ if (this.size > MAX_UINT32 || this.original_size === 1) this.size += 8;+ if (this.type === "uuid") this.size += 16;+ Log.debug("BoxWriter", "Writing box " + this.type + " of size: " + this.size + " at position " + stream.getPosition() + (msg || ""));+ if (this.original_size === 0) stream.writeUint32(0);+ else if (this.size > MAX_UINT32 || this.original_size === 1) stream.writeUint32(1);+ else {+ this.sizePosition = stream.getPosition();+ stream.writeUint32(this.size);+ }+ stream.writeString(this.type, void 0, 4);+ if (this.type === "uuid") {+ const uuidBytes = /* @__PURE__ */ new Uint8Array(16);+ for (let i = 0; i < 16; i++) uuidBytes[i] = parseInt(this.uuid.substring(i * 2, i * 2 + 2), 16);+ stream.writeUint8Array(uuidBytes);+ }+ if (this.size > MAX_UINT32 || this.original_size === 1) {+ this.sizePosition = stream.getPosition();+ stream.writeUint64(this.size);+ }+ }+ /** @bundle box-write.js */+ write(stream) {+ if (this.type === "mdat") {+ const box = this;+ if (box.stream) {+ this.size = box.stream.getAbsoluteEndPosition();+ this.writeHeader(stream);+ for (const buffer of box.stream.buffers) {+ const u8 = new Uint8Array(buffer);+ stream.writeUint8Array(u8);+ }+ } else if (box.data) {+ this.size = box.data.length;+ this.writeHeader(stream);+ stream.writeUint8Array(box.data);+ }+ } else {+ this.size = this.data ? this.data.length : 0;+ this.writeHeader(stream);+ if (this.data) stream.writeUint8Array(this.data);+ }+ }+ /** @bundle box-print.js */+ printHeader(output) {+ this.size += 8;+ if (this.size > MAX_UINT32) this.size += 8;+ if (this.type === "uuid") this.size += 16;+ output.log(output.indent + "size:" + this.size);+ output.log(output.indent + "type:" + this.type);+ }+ /** @bundle box-print.js */+ print(output) {+ this.printHeader(output);+ }+ /** @bundle box-parse.js */+ parse(stream) {+ if (this.type !== "mdat") this.data = stream.readUint8Array(this.size - this.hdr_size);+ else if (this.size === 0) stream.seek(stream.getEndPosition());+ else stream.seek(this.start + this.size);+ }+ /** @bundle box-parse.js */+ parseDataAndRewind(stream) {+ this.data = stream.readUint8Array(this.size - this.hdr_size);+ stream.seek(this.start + this.hdr_size);+ }+ /** @bundle box-parse.js */+ parseLanguage(stream) {+ this.language = stream.readUint16();+ const chars = [];+ chars[0] = this.language >> 10 & 31;+ chars[1] = this.language >> 5 & 31;+ chars[2] = this.language & 31;+ this.languageString = String.fromCharCode(chars[0] + 96, chars[1] + 96, chars[2] + 96);+ }+ /** @bundle isofile-advanced-creation.js */+ computeSize(stream_) {+ const stream = stream_ || new MultiBufferStream();+ this.write(stream);+ }+ isEndOfBox(stream) {+ return stream.getPosition() === this.start + this.size;+ }+};+var FullBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.flags = 0;+ this.version = 0;+ }+ /** @bundle box-write.js */+ writeHeader(stream) {+ this.size += 4;+ super.writeHeader(stream, " v=" + this.version + " f=" + this.flags);+ stream.writeUint8(this.version);+ stream.writeUint24(this.flags);+ }+ /** @bundle box-print.js */+ printHeader(output) {+ this.size += 4;+ super.printHeader(output);+ output.log(output.indent + "version:" + this.version);+ output.log(output.indent + "flags:" + this.flags);+ }+ /** @bundle box-parse.js */+ parseDataAndRewind(stream) {+ this.parseFullHeader(stream);+ this.data = stream.readUint8Array(this.size - this.hdr_size);+ this.hdr_size -= 4;+ stream.seek(this.start + this.hdr_size);+ }+ /** @bundle box-parse.js */+ parseFullHeader(stream) {+ this.version = stream.readUint8();+ this.flags = stream.readUint24();+ this.hdr_size += 4;+ }+ /** @bundle box-parse.js */+ parse(stream) {+ this.parseFullHeader(stream);+ this.data = stream.readUint8Array(this.size - this.hdr_size);+ }+};+var SampleGroupEntry = class {+ static {+ this.registryId = Symbol.for("SampleGroupEntryIdentifier");+ }+ constructor(grouping_type) {+ this.grouping_type = grouping_type;+ }+ /** @bundle writing/samplegroups/samplegroup.js */+ write(stream) {+ stream.writeUint8Array(this.data);+ }+ /** @bundle parsing/samplegroups/samplegroup.js */+ parse(stream) {+ Log.warn("BoxParser", `Unknown sample group type: '${this.grouping_type}'`);+ this.data = stream.readUint8Array(this.description_length);+ }+};+var TrackGroupTypeBox = class extends FullBox {+ /** @bundle parsing/TrackGroup.js */+ parse(stream) {+ this.parseFullHeader(stream);+ this.track_group_id = stream.readUint32();+ }+};+/** @bundle parsing/singleitemtypereference.js */+var SingleItemTypeReferenceBox = class extends Box {+ constructor(fourcc, size, box_name, hdr_size, start) {+ super(size);+ this.box_name = box_name;+ this.hdr_size = hdr_size;+ this.start = start;+ this.type = fourcc;+ }+ parse(stream) {+ this.from_item_ID = stream.readUint16();+ const count = stream.readUint16();+ this.references = [];+ for (let i = 0; i < count; i++) this.references[i] = { to_item_ID: stream.readUint16() };+ }+};+/** @bundle parsing/singleitemtypereferencelarge.js */+var SingleItemTypeReferenceBoxLarge = class extends Box {+ constructor(fourcc, size, box_name, hdr_size, start) {+ super(size);+ this.box_name = box_name;+ this.hdr_size = hdr_size;+ this.start = start;+ this.type = fourcc;+ }+ parse(stream) {+ this.from_item_ID = stream.readUint32();+ const count = stream.readUint16();+ this.references = [];+ for (let i = 0; i < count; i++) this.references[i] = { to_item_ID: stream.readUint32() };+ }+};+/** @bundle parsing/TrakReference.js */+var TrackReferenceTypeBox = class extends Box {+ constructor(fourcc, size, hdr_size, start) {+ super(size);+ this.hdr_size = hdr_size;+ this.start = start;+ this.type = fourcc;+ }+ parse(stream) {+ this.track_ids = stream.readUint32Array((this.size - this.hdr_size) / 4);+ }+ /** @bundle box-write.js */+ write(stream) {+ this.size = this.track_ids.length * 4;+ this.writeHeader(stream);+ stream.writeUint32Array(this.track_ids);+ }+};++//#endregion+//#region src/box-diff.ts+const DIFF_BOXES_PROP_NAMES = [+ "boxes",+ "entries",+ "references",+ "subsamples",+ "items",+ "item_infos",+ "extents",+ "associations",+ "subsegments",+ "ranges",+ "seekLists",+ "seekPoints",+ "esd",+ "levels"+];+const DIFF_PRIMITIVE_ARRAY_PROP_NAMES = [+ "compatible_brands",+ "matrix",+ "opcolor",+ "sample_counts",+ "sample_deltas",+ "first_chunk",+ "samples_per_chunk",+ "sample_sizes",+ "chunk_offsets",+ "sample_offsets",+ "sample_description_index",+ "sample_duration"+];+/** @bundle box-diff.js */+function boxEqualFields(box_a, box_b) {+ if (box_a && !box_b) return false;+ let prop;+ for (prop in box_a) if (DIFF_BOXES_PROP_NAMES.find((name) => name === prop)) continue;+ else if (box_a[prop] instanceof Box || box_b[prop] instanceof Box) continue;+ else if (typeof box_a[prop] === "undefined" || typeof box_b[prop] === "undefined") continue;+ else if (typeof box_a[prop] === "function" || typeof box_b[prop] === "function") continue;+ else if ("subBoxNames" in box_a && box_a.subBoxNames.indexOf(prop.slice(0, 4)) > -1 || "subBoxNames" in box_b && box_b.subBoxNames.indexOf(prop.slice(0, 4)) > -1) continue;+ else if (prop === "data" || prop === "start" || prop === "size" || prop === "creation_time" || prop === "modification_time") continue;+ else if (DIFF_PRIMITIVE_ARRAY_PROP_NAMES.find((name) => name === prop)) continue;+ else if (box_a[prop] !== box_b[prop]) return false;+ return true;+}+function boxEqual(box_a, box_b) {+ if (!boxEqualFields(box_a, box_b)) return false;+ for (let j = 0; j < DIFF_BOXES_PROP_NAMES.length; j++) {+ const name = DIFF_BOXES_PROP_NAMES[j];+ if (box_a[name] && box_b[name]) {+ if (!boxEqual(box_a[name], box_b[name])) return false;+ }+ }+ return true;+}++//#endregion+//#region src/registry.ts+function getRegistryId(boxClass) {+ let current = boxClass;+ while (current) {+ if ("registryId" in current) return current["registryId"];+ current = Object.getPrototypeOf(current);+ }+}+const isSampleGroupEntry = (value) => {+ const symbol = Symbol.for("SampleGroupEntryIdentifier");+ return getRegistryId(value) === symbol;+};+const isSampleEntry = (value) => {+ const symbol = Symbol.for("SampleEntryIdentifier");+ return getRegistryId(value) === symbol;+};+const isBox = (value) => {+ const symbol = Symbol.for("BoxIdentifier");+ return getRegistryId(value) === symbol;+};+const BoxRegistry = {+ uuid: {},+ sampleEntry: {},+ sampleGroupEntry: {},+ box: {}+};+function registerBoxes(registry) {+ const localRegistry = {+ uuid: {},+ sampleEntry: {},+ sampleGroupEntry: {},+ box: {}+ };+ for (const [key, value] of Object.entries(registry)) {+ if (isSampleGroupEntry(value)) {+ const groupingType = "grouping_type" in value ? value.grouping_type : void 0;+ if (!groupingType) throw new Error(`SampleGroupEntry class ${key} does not have a valid static grouping_type. Please ensure it is defined correctly.`);+ if (groupingType in localRegistry.sampleGroupEntry) throw new Error(`SampleGroupEntry class ${key} has a grouping_type that is already registered. Please ensure it is unique.`);+ localRegistry.sampleGroupEntry[groupingType] = value;+ continue;+ }+ if (isSampleEntry(value)) {+ const fourcc = "fourcc" in value ? value.fourcc : void 0;+ if (!fourcc) throw new Error(`SampleEntry class ${key} does not have a valid static fourcc. Please ensure it is defined correctly.`);+ if (fourcc in localRegistry.sampleEntry) throw new Error(`SampleEntry class ${key} has a fourcc that is already registered. Please ensure it is unique.`);+ localRegistry.sampleEntry[fourcc] = value;+ continue;+ }+ if (isBox(value)) {+ const fourcc = "fourcc" in value ? value.fourcc : void 0;+ const uuid = "uuid" in value ? value.uuid : void 0;+ if (fourcc === "uuid") {+ if (!uuid) throw new Error(`Box class ${key} has a fourcc of 'uuid' but does not have a valid uuid. Please ensure it is defined correctly.`);+ if (uuid in localRegistry.uuid) throw new Error(`Box class ${key} has a uuid that is already registered. Please ensure it is unique.`);+ localRegistry.uuid[uuid] = value;+ continue;+ }+ localRegistry.box[fourcc] = value;+ continue;+ }+ throw new Error(`Box class ${key} does not have a valid static fourcc, uuid, or grouping_type. Please ensure it is defined correctly.`);+ }+ BoxRegistry.uuid = { ...localRegistry.uuid };+ BoxRegistry.sampleEntry = { ...localRegistry.sampleEntry };+ BoxRegistry.sampleGroupEntry = { ...localRegistry.sampleGroupEntry };+ BoxRegistry.box = { ...localRegistry.box };+ return BoxRegistry;+}+const DescriptorRegistry = {};+function registerDescriptors(registry) {+ Object.entries(registry).forEach(([key, value]) => DescriptorRegistry[key] = value);+ return DescriptorRegistry;+}++//#endregion+//#region src/parser.ts+function parseUUID(stream) {+ return parseHex16(stream);+}+function parseHex16(stream) {+ let hex16 = "";+ for (let i = 0; i < 16; i++) {+ const hex = stream.readUint8().toString(16);+ hex16 += hex.length === 1 ? "0" + hex : hex;+ }+ return hex16;+}+function parseOneBox(stream, headerOnly, parentSize) {+ let box;+ let originalSize;+ const start = stream.getPosition();+ let hdr_size = 0;+ let uuid;+ if (stream.getEndPosition() - start < 8) {+ Log.debug("BoxParser", "Not enough data in stream to parse the type and size of the box");+ return { code: 0 };+ }+ if (parentSize && parentSize < 8) {+ Log.debug("BoxParser", "Not enough bytes left in the parent box to parse a new box");+ return { code: 0 };+ }+ let size = stream.readUint32();+ const type = stream.readString(4);+ if (type.length !== 4 || !/^[\x20-\x7E]{4}$/.test(type)) {+ Log.error("BoxParser", `Invalid box type: '${type}'`);+ return {+ code: -1,+ start,+ type+ };+ }+ let box_type = type;+ Log.debug("BoxParser", "Found box of type '" + type + "' and size " + size + " at position " + start);+ hdr_size = 8;+ if (type === "uuid") {+ if (stream.getEndPosition() - stream.getPosition() < 16 || parentSize - hdr_size < 16) {+ stream.seek(start);+ Log.debug("BoxParser", "Not enough bytes left in the parent box to parse a UUID box");+ return { code: 0 };+ }+ uuid = parseUUID(stream);+ hdr_size += 16;+ box_type = uuid;+ }+ if (size === 1) {+ if (stream.getEndPosition() - stream.getPosition() < 8 || parentSize && parentSize - hdr_size < 8) {+ stream.seek(start);+ Log.warn("BoxParser", "Not enough data in stream to parse the extended size of the \"" + type + "\" box");+ return { code: 0 };+ }+ originalSize = size;+ size = stream.readUint64();+ hdr_size += 8;+ } else if (size === 0) if (parentSize) size = parentSize;+ else if (type !== "mdat") {+ Log.error("BoxParser", "Unlimited box size not supported for type: '" + type + "'");+ box = new Box(size);+ box.type = type;+ return {+ code: 1,+ box,+ size: box.size+ };+ } else size = stream.getEndPosition() - start;+ if (size !== 0 && size < hdr_size) {+ Log.error("BoxParser", "Box of type " + type + " has an invalid size " + size + " (too small to be a box)");+ return {+ code: 0,+ type,+ size,+ hdr_size,+ start+ };+ }+ if (size !== 0 && parentSize && size > parentSize) {+ Log.error("BoxParser", "Box of type '" + type + "' has a size " + size + " greater than its container size " + parentSize);+ return {+ code: 0,+ type,+ size,+ hdr_size,+ start+ };+ }+ if (size !== 0 && start + size > stream.getEndPosition()) {+ stream.seek(start);+ Log.info("BoxParser", "Not enough data in stream to parse the entire '" + type + "' box");+ return {+ code: 0,+ type,+ size,+ hdr_size,+ start,+ original_size: originalSize+ };+ }+ if (headerOnly) return {+ code: 1,+ type,+ size,+ hdr_size,+ start+ };+ else if (type in BoxRegistry.box) box = new BoxRegistry.box[type](size);+ else if (type !== "uuid") {+ Log.warn("BoxParser", `Unknown box type: '${type}'`);+ box = new Box(size);+ box.type = type;+ box.has_unparsed_data = true;+ } else if (uuid in BoxRegistry.uuid) box = new BoxRegistry.uuid[uuid](size);+ else {+ Log.warn("BoxParser", `Unknown UUID box type: '${uuid}'`);+ box = new Box(size);+ box.type = type;+ box.uuid = uuid;+ box.has_unparsed_data = true;+ }+ box.original_size = originalSize;+ box.hdr_size = hdr_size;+ box.start = start;+ if (box.write === Box.prototype.write && box.type !== "mdat") {+ Log.info("BoxParser", "'" + box_type + "' box writing not yet implemented, keeping unparsed data in memory for later write");+ box.parseDataAndRewind(stream);+ }+ box.parse(stream);+ const diff = stream.getPosition() - (box.start + box.size);+ if (diff < 0) {+ Log.warn("BoxParser", "Parsing of box '" + box_type + "' did not read the entire indicated box data size (missing " + -diff + " bytes), seeking forward");+ stream.seek(box.start + box.size);+ } else if (diff > 0 && box.size !== 0) {+ Log.error("BoxParser", "Parsing of box '" + box_type + "' read " + diff + " more bytes than the indicated box data size, seeking backwards");+ stream.seek(box.start + box.size);+ }+ return {+ code: 1,+ box,+ size: box.size+ };+}++//#endregion+//#region src/containerBox.ts+var ContainerBox = class extends Box {+ /** @bundle box-write.js */+ write(stream) {+ this.size = 0;+ this.writeHeader(stream);+ if (this.boxes) {+ for (let i = 0; i < this.boxes.length; i++) if (this.boxes[i]) {+ this.boxes[i].write(stream);+ this.size += this.boxes[i].size;+ }+ }+ Log.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size);+ stream.adjustUint32(this.sizePosition, this.size);+ }+ /** @bundle box-print.js */+ print(output) {+ this.printHeader(output);+ for (let i = 0; i < this.boxes.length; i++) if (this.boxes[i]) {+ const prev_indent = output.indent;+ output.indent += " ";+ this.boxes[i].print(output);+ output.indent = prev_indent;+ }+ }+ /** @bundle box-parse.js */+ parse(stream) {+ let ret;+ while (stream.getPosition() < this.start + this.size) {+ ret = parseOneBox(stream, false, this.size - (stream.getPosition() - this.start));+ if (ret.code === 1) {+ const box = ret.box;+ if (!this.boxes) this.boxes = [];+ this.boxes.push(box);+ if (this.subBoxNames && this.subBoxNames.indexOf(box.type) !== -1) {+ const fourcc = this.subBoxNames[this.subBoxNames.indexOf(box.type)] + "s";+ if (!this[fourcc]) this[fourcc] = [];+ this[fourcc].push(box);+ } else {+ const box_type = box.type !== "uuid" ? box.type : box.uuid;+ if (this[box_type]) Log.warn("ContainerBox", `Box of type ${box_type} already exists in container box ${this.type}.`);+ else this[box_type] = box;+ }+ } else return;+ }+ }+};++//#endregion+//#region src/boxes/sampleentries/base.ts+var SampleEntry = class extends ContainerBox {+ static {+ this.registryId = Symbol.for("SampleEntryIdentifier");+ }+ constructor(size, hdr_size, start) {+ super(size);+ this.hdr_size = hdr_size;+ this.start = start;+ }+ /** @bundle box-codecs.js */+ isVideo() {+ return false;+ }+ /** @bundle box-codecs.js */+ isAudio() {+ return false;+ }+ /** @bundle box-codecs.js */+ isSubtitle() {+ return false;+ }+ /** @bundle box-codecs.js */+ isMetadata() {+ return false;+ }+ /** @bundle box-codecs.js */+ isHint() {+ return false;+ }+ /** @bundle box-codecs.js */+ getCodec() {+ return this.type.replace(".", "");+ }+ /** @bundle box-codecs.js */+ getWidth() {+ return "";+ }+ /** @bundle box-codecs.js */+ getHeight() {+ return "";+ }+ /** @bundle box-codecs.js */+ getChannelCount() {+ return "";+ }+ /** @bundle box-codecs.js */+ getSampleRate() {+ return "";+ }+ /** @bundle box-codecs.js */+ getSampleSize() {+ return "";+ }+ /** @bundle parsing/sampleentries/sampleentry.js */+ parseHeader(stream) {+ stream.readUint8Array(6);+ this.data_reference_index = stream.readUint16();+ this.hdr_size += 8;+ }+ /** @bundle parsing/sampleentries/sampleentry.js */+ parse(stream) {+ this.parseHeader(stream);+ this.data = stream.readUint8Array(this.size - this.hdr_size);+ }+ /** @bundle parsing/sampleentries/sampleentry.js */+ parseDataAndRewind(stream) {+ this.parseHeader(stream);+ this.data = stream.readUint8Array(this.size - this.hdr_size);+ this.hdr_size -= 8;+ stream.seek(this.start + this.hdr_size);+ }+ /** @bundle parsing/sampleentries/sampleentry.js */+ parseFooter(stream) {+ super.parse(stream);+ }+ /** @bundle writing/sampleentry.js */+ writeHeader(stream) {+ this.size = 8;+ super.writeHeader(stream);+ stream.writeUint8(0);+ stream.writeUint8(0);+ stream.writeUint8(0);+ stream.writeUint8(0);+ stream.writeUint8(0);+ stream.writeUint8(0);+ stream.writeUint16(this.data_reference_index);+ }+ /** @bundle writing/sampleentry.js */+ writeFooter(stream) {+ if (this.boxes) for (let i = 0; i < this.boxes.length; i++) {+ this.boxes[i].write(stream);+ this.size += this.boxes[i].size;+ }+ Log.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size);+ stream.adjustUint32(this.sizePosition, this.size);+ }+ /** @bundle writing/sampleentry.js */+ write(stream) {+ this.writeHeader(stream);+ stream.writeUint8Array(this.data);+ this.size += this.data.length;+ Log.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size);+ stream.adjustUint32(this.sizePosition, this.size);+ }+};+var HintSampleEntry = class extends SampleEntry {};+var MetadataSampleEntry = class extends SampleEntry {+ /** @bundle box-codecs.js */+ isMetadata() {+ return true;+ }+};+var SubtitleSampleEntry = class extends SampleEntry {+ /** @bundle box-codecs.js */+ isSubtitle() {+ return true;+ }+};+var TextSampleEntry = class extends SampleEntry {};+var VisualSampleEntry = class extends SampleEntry {+ parse(stream) {+ this.parseHeader(stream);+ stream.readUint16();+ stream.readUint16();+ stream.readUint32Array(3);+ this.width = stream.readUint16();+ this.height = stream.readUint16();+ this.horizresolution = stream.readUint32();+ this.vertresolution = stream.readUint32();+ stream.readUint32();+ this.frame_count = stream.readUint16();+ const compressorname_length = Math.min(31, stream.readUint8());+ this.compressorname = stream.readString(compressorname_length);+ if (compressorname_length < 31) stream.readString(31 - compressorname_length);+ this.depth = stream.readUint16();+ stream.readUint16();+ this.parseFooter(stream);+ }+ /** @bundle box-codecs.js */+ isVideo() {+ return true;+ }+ /** @bundle box-codecs.js */+ getWidth() {+ return this.width;+ }+ /** @bundle box-codecs.js */+ getHeight() {+ return this.height;+ }+ /** @bundle writing/sampleentries/sampleentry.js */+ write(stream) {+ this.writeHeader(stream);+ this.size += 70;+ stream.writeUint16(0);+ stream.writeUint16(0);+ stream.writeUint32(0);+ stream.writeUint32(0);+ stream.writeUint32(0);+ stream.writeUint16(this.width);+ stream.writeUint16(this.height);+ stream.writeUint32(this.horizresolution);+ stream.writeUint32(this.vertresolution);+ stream.writeUint32(0);+ stream.writeUint16(this.frame_count);+ stream.writeUint8(Math.min(31, this.compressorname.length));+ stream.writeString(this.compressorname, void 0, 31);+ stream.writeUint16(this.depth);+ stream.writeInt16(-1);+ this.writeFooter(stream);+ }+};+var AudioSampleEntry = class extends SampleEntry {+ parse(stream) {+ this.parseHeader(stream);+ this.version = stream.readUint16();+ stream.readUint16();+ stream.readUint32();+ this.channel_count = stream.readUint16();+ this.samplesize = stream.readUint16();+ stream.readUint16();+ stream.readUint16();+ this.samplerate = stream.readUint32() / 65536;+ if (stream.isofile?.ftyp?.major_brand.includes("qt")) {+ if (this.version === 1) this.extensions = stream.readUint8Array(16);+ else if (this.version === 2) this.extensions = stream.readUint8Array(36);+ }+ this.parseFooter(stream);+ }+ /** @bundle box-codecs.js */+ isAudio() {+ return true;+ }+ /** @bundle box-codecs.js */+ getChannelCount() {+ return this.channel_count;+ }+ /** @bundle box-codecs.js */+ getSampleRate() {+ return this.samplerate;+ }+ /** @bundle box-codecs.js */+ getSampleSize() {+ return this.samplesize;+ }+ /** @bundle writing/sampleentry.js */+ write(stream) {+ this.writeHeader(stream);+ this.size += 20;+ stream.writeUint32(0);+ stream.writeUint32(0);+ stream.writeUint16(this.channel_count);+ stream.writeUint16(this.samplesize);+ stream.writeUint16(0);+ stream.writeUint16(0);+ stream.writeUint32(this.samplerate << 16);+ this.writeFooter(stream);+ }+};+var SystemSampleEntry = class extends SampleEntry {+ parse(stream) {+ this.parseHeader(stream);+ this.parseFooter(stream);+ }+ /** @bundle writing/sampleentry.js */+ write(stream) {+ this.writeHeader(stream);+ this.writeFooter(stream);+ }+};++//#endregion+//#region src/boxes/displays/parameterSetArray.ts+var ParameterSetArray = class extends Array {+ toString() {+ let str = "<table class='inner-table'>";+ str += "<thead><tr><th>length</th><th>nalu_data</th></tr></thead>";+ str += "<tbody>";+ for (let i = 0; i < this.length; i++) {+ const nalu = this[i];+ str += "<tr>";+ str += "<td>" + nalu.length + "</td>";+ str += "<td>";+ str += nalu.data.reduce(function(str, byte) {+ return str + byte.toString(16).padStart(2, "0");+ }, "0x");+ str += "</td></tr>";+ }+ str += "</tbody></table>";+ return str;+ }+};++//#endregion+//#region src/boxes/avcC.ts+var avcCBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "AVCConfigurationBox";+ }+ static {+ this.fourcc = "avcC";+ }+ parse(stream) {+ this.configurationVersion = stream.readUint8();+ this.AVCProfileIndication = stream.readUint8();+ this.profile_compatibility = stream.readUint8();+ this.AVCLevelIndication = stream.readUint8();+ this.lengthSizeMinusOne = stream.readUint8() & 3;+ this.nb_SPS_nalus = stream.readUint8() & 31;+ let toparse = this.size - this.hdr_size - 6;+ this.SPS = new ParameterSetArray();+ for (let i = 0; i < this.nb_SPS_nalus; i++) {+ const length = stream.readUint16();+ this.SPS.push({+ length,+ data: stream.readUint8Array(length)+ });+ toparse -= 2 + length;+ }+ this.nb_PPS_nalus = stream.readUint8();+ toparse--;+ this.PPS = new ParameterSetArray();+ for (let i = 0; i < this.nb_PPS_nalus; i++) {+ const length = stream.readUint16();+ this.PPS.push({+ length,+ data: stream.readUint8Array(length)+ });+ toparse -= 2 + length;+ }+ if (toparse > 0) this.ext = stream.readUint8Array(toparse);+ }+ /** @bundle writing/avcC.js */+ write(stream) {+ this.size = 7;+ for (let i = 0; i < this.SPS.length; i++) this.size += 2 + this.SPS[i].length;+ for (let i = 0; i < this.PPS.length; i++) this.size += 2 + this.PPS[i].length;+ if (this.ext) this.size += this.ext.length;+ this.writeHeader(stream);+ stream.writeUint8(this.configurationVersion);+ stream.writeUint8(this.AVCProfileIndication);+ stream.writeUint8(this.profile_compatibility);+ stream.writeUint8(this.AVCLevelIndication);+ stream.writeUint8(this.lengthSizeMinusOne + 252);+ stream.writeUint8(this.SPS.length + 224);+ for (let i = 0; i < this.SPS.length; i++) {+ stream.writeUint16(this.SPS[i].length);+ stream.writeUint8Array(this.SPS[i].data);+ }+ stream.writeUint8(this.PPS.length);+ for (let i = 0; i < this.PPS.length; i++) {+ stream.writeUint16(this.PPS[i].length);+ stream.writeUint8Array(this.PPS[i].data);+ }+ if (this.ext) stream.writeUint8Array(this.ext);+ }+};++//#endregion+//#region src/boxes/defaults.ts+var mdatBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "MediaDataBox";+ }+ static {+ this.fourcc = "mdat";+ }+};+var idatBox = class extends Box {+ constructor(..._args2) {+ super(..._args2);+ this.box_name = "ItemDataBox";+ }+ static {+ this.fourcc = "idat";+ }+};+var freeBox = class extends Box {+ constructor(..._args3) {+ super(..._args3);+ this.box_name = "FreeSpaceBox";+ }+ static {+ this.fourcc = "free";+ }+};+var skipBox = class extends Box {+ constructor(..._args4) {+ super(..._args4);+ this.box_name = "FreeSpaceBox";+ }+ static {+ this.fourcc = "skip";+ }+};+var hmhdBox = class extends FullBox {+ constructor(..._args5) {+ super(..._args5);+ this.box_name = "HintMediaHeaderBox";+ }+ static {+ this.fourcc = "hmhd";+ }+};+var nmhdBox = class extends FullBox {+ constructor(..._args6) {+ super(..._args6);+ this.box_name = "NullMediaHeaderBox";+ }+ static {+ this.fourcc = "nmhd";+ }+};+var iodsBox = class extends FullBox {+ constructor(..._args7) {+ super(..._args7);+ this.box_name = "ObjectDescriptorBox";+ }+ static {+ this.fourcc = "iods";+ }+};+var xmlBox = class extends FullBox {+ constructor(..._args8) {+ super(..._args8);+ this.box_name = "XMLBox";+ }+ static {+ this.fourcc = "xml ";+ }+};+var bxmlBox = class extends FullBox {+ constructor(..._args9) {+ super(..._args9);+ this.box_name = "BinaryXMLBox";+ }+ static {+ this.fourcc = "bxml";+ }+};+var iproBox = class extends FullBox {+ constructor(..._args10) {+ super(..._args10);+ this.box_name = "ItemProtectionBox";+ this.sinfs = [];+ }+ static {+ this.fourcc = "ipro";+ }+ get protections() {+ return this.sinfs;+ }+};+var moovBox = class extends ContainerBox {+ constructor(..._args11) {+ super(..._args11);+ this.box_name = "MovieBox";+ this.traks = [];+ this.psshs = [];+ this.subBoxNames = ["trak", "pssh"];+ }+ static {+ this.fourcc = "moov";+ }+};+var trakBox = class extends ContainerBox {+ constructor(..._args12) {+ super(..._args12);+ this.box_name = "TrackBox";+ this.samples = [];+ }+ static {+ this.fourcc = "trak";+ }+};+var edtsBox = class extends ContainerBox {+ constructor(..._args13) {+ super(..._args13);+ this.box_name = "EditBox";+ }+ static {+ this.fourcc = "edts";+ }+};+var mdiaBox = class extends ContainerBox {+ constructor(..._args14) {+ super(..._args14);+ this.box_name = "MediaBox";+ }+ static {+ this.fourcc = "mdia";+ }+};+var minfBox = class extends ContainerBox {+ constructor(..._args15) {+ super(..._args15);+ this.box_name = "MediaInformationBox";+ }+ static {+ this.fourcc = "minf";+ }+};+var dinfBox = class extends ContainerBox {+ constructor(..._args16) {+ super(..._args16);+ this.box_name = "DataInformationBox";+ }+ static {+ this.fourcc = "dinf";+ }+};+var stblBox = class extends ContainerBox {+ constructor(..._args17) {+ super(..._args17);+ this.box_name = "SampleTableBox";+ this.sgpds = [];+ this.sbgps = [];+ this.subBoxNames = ["sgpd", "sbgp"];+ }+ static {+ this.fourcc = "stbl";+ }+};+var mvexBox = class extends ContainerBox {+ constructor(..._args18) {+ super(..._args18);+ this.box_name = "MovieExtendsBox";+ this.trexs = [];+ this.subBoxNames = ["trex"];+ }+ static {+ this.fourcc = "mvex";+ }+};+var moofBox = class extends ContainerBox {+ constructor(..._args19) {+ super(..._args19);+ this.box_name = "MovieFragmentBox";+ this.trafs = [];+ this.subBoxNames = ["traf"];+ }+ static {+ this.fourcc = "moof";+ }+};+var trafBox = class extends ContainerBox {+ constructor(..._args20) {+ super(..._args20);+ this.box_name = "TrackFragmentBox";+ this.truns = [];+ this.sgpds = [];+ this.sbgps = [];+ this.subBoxNames = [+ "trun",+ "sgpd",+ "sbgp"+ ];+ }+ static {+ this.fourcc = "traf";+ }+};+var vttcBox = class extends ContainerBox {+ constructor(..._args21) {+ super(..._args21);+ this.box_name = "VTTCueBox";+ }+ static {+ this.fourcc = "vttc";+ }+};+var mfraBox = class extends ContainerBox {+ constructor(..._args22) {+ super(..._args22);+ this.box_name = "MovieFragmentRandomAccessBox";+ this.tfras = [];+ this.subBoxNames = ["tfra"];+ }+ static {+ this.fourcc = "mfra";+ }+};+var mecoBox = class extends ContainerBox {+ constructor(..._args23) {+ super(..._args23);+ this.box_name = "AdditionalMetadataContainerBox";+ }+ static {+ this.fourcc = "meco";+ }+};+var hntiBox = class extends ContainerBox {+ constructor(..._args24) {+ super(..._args24);+ this.box_name = "trackhintinformation";+ this.subBoxNames = ["sdp ", "rtp "];+ }+ static {+ this.fourcc = "hnti";+ }+};+var hinfBox = class extends ContainerBox {+ constructor(..._args25) {+ super(..._args25);+ this.box_name = "hintstatisticsbox";+ this.maxrs = [];+ this.subBoxNames = ["maxr"];+ }+ static {+ this.fourcc = "hinf";+ }+};+var strkBox = class extends ContainerBox {+ constructor(..._args26) {+ super(..._args26);+ this.box_name = "SubTrackBox";+ }+ static {+ this.fourcc = "strk";+ }+};+var strdBox = class extends ContainerBox {+ constructor(..._args27) {+ super(..._args27);+ this.box_name = "SubTrackDefinitionBox";+ }+ static {+ this.fourcc = "strd";+ }+};+var sinfBox = class extends ContainerBox {+ constructor(..._args28) {+ super(..._args28);+ this.box_name = "ProtectionSchemeInfoBox";+ }+ static {+ this.fourcc = "sinf";+ }+};+var rinfBox = class extends ContainerBox {+ constructor(..._args29) {+ super(..._args29);+ this.box_name = "RestrictedSchemeInfoBox";+ }+ static {+ this.fourcc = "rinf";+ }+};+var schiBox = class extends ContainerBox {+ constructor(..._args30) {+ super(..._args30);+ this.box_name = "SchemeInformationBox";+ }+ static {+ this.fourcc = "schi";+ }+};+var trgrBox = class extends ContainerBox {+ constructor(..._args31) {+ super(..._args31);+ this.box_name = "TrackGroupBox";+ }+ static {+ this.fourcc = "trgr";+ }+};+var udtaBox = class extends ContainerBox {+ constructor(..._args32) {+ super(..._args32);+ this.box_name = "UserDataBox";+ this.kinds = [];+ this.strks = [];+ this.subBoxNames = ["kind", "strk"];+ }+ static {+ this.fourcc = "udta";+ }+};+var iprpBox = class extends ContainerBox {+ constructor(..._args33) {+ super(..._args33);+ this.box_name = "ItemPropertiesBox";+ this.ipmas = [];+ this.subBoxNames = ["ipma"];+ }+ static {+ this.fourcc = "iprp";+ }+};+var ipcoBox = class extends ContainerBox {+ constructor(..._args34) {+ super(..._args34);+ this.box_name = "ItemPropertyContainerBox";+ this.hvcCs = [];+ this.ispes = [];+ this.claps = [];+ this.irots = [];+ this.subBoxNames = [+ "hvcC",+ "ispe",+ "clap",+ "irot"+ ];+ }+ static {+ this.fourcc = "ipco";+ }+};+var grplBox = class extends ContainerBox {+ constructor(..._args35) {+ super(..._args35);+ this.box_name = "GroupsListBox";+ }+ static {+ this.fourcc = "grpl";+ }+};+var j2kHBox = class extends ContainerBox {+ constructor(..._args36) {+ super(..._args36);+ this.box_name = "J2KHeaderInfoBox";+ }+ static {+ this.fourcc = "j2kH";+ }+};+var etypBox = class extends ContainerBox {+ constructor(..._args37) {+ super(..._args37);+ this.box_name = "ExtendedTypeBox";+ this.tycos = [];+ this.subBoxNames = ["tyco"];+ }+ static {+ this.fourcc = "etyp";+ }+};+var povdBox = class extends ContainerBox {+ constructor(..._args38) {+ super(..._args38);+ this.box_name = "ProjectedOmniVideoBox";+ this.subBoxNames = ["prfr"];+ }+ static {+ this.fourcc = "povd";+ }+};++//#endregion+//#region src/boxes/dref.ts+var drefBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "DataReferenceBox";+ }+ static {+ this.fourcc = "dref";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.entries = [];+ const entry_count = stream.readUint32();+ for (let i = 0; i < entry_count; i++) {+ const ret = parseOneBox(stream, false, this.size - (stream.getPosition() - this.start));+ if (ret.code === 1) {+ const box = ret.box;+ this.entries.push(box);+ } else return;+ }+ }+ /** @bundle writing/dref.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 4;+ this.writeHeader(stream);+ stream.writeUint32(this.entries.length);+ for (let i = 0; i < this.entries.length; i++) {+ this.entries[i].write(stream);+ this.size += this.entries[i].size;+ }+ Log.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size);+ stream.adjustUint32(this.sizePosition, this.size);+ }+};++//#endregion+//#region src/boxes/elng.ts+var elngBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ExtendedLanguageBox";+ }+ static {+ this.fourcc = "elng";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.extended_language = stream.readString(this.size - this.hdr_size);+ }+ /** @bundle writing/elng.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = this.extended_language.length;+ this.writeHeader(stream);+ stream.writeString(this.extended_language);+ }+};++//#endregion+//#region src/boxes/ftyp.ts+var ftypBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "FileTypeBox";+ }+ static {+ this.fourcc = "ftyp";+ }+ parse(stream) {+ let toparse = this.size - this.hdr_size;+ this.major_brand = stream.readString(4);+ this.minor_version = stream.readUint32();+ const minor_version_str = String.fromCharCode(this.minor_version >> 24, this.minor_version >> 16 & 255, this.minor_version >> 8 & 255, this.minor_version & 255);+ if (minor_version_str.match("[a-zA-Z0-9]{4}")) this.minor_version = minor_version_str;+ toparse -= 8;+ this.compatible_brands = [];+ let i = 0;+ while (toparse >= 4) {+ this.compatible_brands[i] = stream.readString(4);+ toparse -= 4;+ i++;+ }+ }+ /** @bundle writing/ftyp.js */+ write(stream) {+ this.size = 8 + 4 * this.compatible_brands.length;+ this.writeHeader(stream);+ stream.writeString(this.major_brand, void 0, 4);+ if (typeof this.minor_version === "number") stream.writeUint32(this.minor_version);+ else stream.writeString(this.minor_version, void 0, 4);+ for (let i = 0; i < this.compatible_brands.length; i++) stream.writeString(this.compatible_brands[i], void 0, 4);+ }+};++//#endregion+//#region src/boxes/hdlr.ts+var hdlrBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "HandlerBox";+ }+ static {+ this.fourcc = "hdlr";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 0) {+ stream.readUint32();+ this.handler = stream.readString(4);+ stream.readUint32Array(3);+ if (!this.isEndOfBox(stream)) {+ const name_size = this.start + this.size - stream.getPosition();+ this.name = stream.readCString();+ const end = this.start + this.size - 1;+ stream.seek(end);+ if (stream.readUint8() !== 0 && name_size > 1) {+ Log.info("BoxParser", "Warning: hdlr name is not null-terminated, possibly length-prefixed string. Trimming first byte.");+ this.name = this.name.slice(1);+ }+ }+ }+ }+ /** @bundle writing/hldr.js */+ write(stream) {+ this.size = 20 + this.name.length + 1;+ this.version = 0;+ this.flags = 0;+ this.writeHeader(stream);+ stream.writeUint32(0);+ stream.writeString(this.handler, void 0, 4);+ stream.writeUint32Array([+ 0,+ 0,+ 0+ ]);+ stream.writeCString(this.name);+ }+};++//#endregion+//#region src/boxes/hvcC.ts+var hvcCBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "HEVCConfigurationBox";+ }+ static {+ this.fourcc = "hvcC";+ }+ parse(stream) {+ this.configurationVersion = stream.readUint8();+ let tmp_byte = stream.readUint8();+ this.general_profile_space = tmp_byte >> 6;+ this.general_tier_flag = (tmp_byte & 32) >> 5;+ this.general_profile_idc = tmp_byte & 31;+ this.general_profile_compatibility = stream.readUint32();+ this.general_constraint_indicator = stream.readUint8Array(6);+ this.general_level_idc = stream.readUint8();+ this.min_spatial_segmentation_idc = stream.readUint16() & 4095;+ this.parallelismType = stream.readUint8() & 3;+ this.chroma_format_idc = stream.readUint8() & 3;+ this.bit_depth_luma_minus8 = stream.readUint8() & 7;+ this.bit_depth_chroma_minus8 = stream.readUint8() & 7;+ this.avgFrameRate = stream.readUint16();+ tmp_byte = stream.readUint8();+ this.constantFrameRate = tmp_byte >> 6;+ this.numTemporalLayers = (tmp_byte & 13) >> 3;+ this.temporalIdNested = (tmp_byte & 4) >> 2;+ this.lengthSizeMinusOne = tmp_byte & 3;+ this.nalu_arrays = [];+ const numOfArrays = stream.readUint8();+ for (let i = 0; i < numOfArrays; i++) {+ const nalu_array = [];+ this.nalu_arrays.push(nalu_array);+ tmp_byte = stream.readUint8();+ nalu_array.completeness = (tmp_byte & 128) >> 7;+ nalu_array.nalu_type = tmp_byte & 63;+ const numNalus = stream.readUint16();+ for (let j = 0; j < numNalus; j++) {+ const length = stream.readUint16();+ nalu_array.push({ data: stream.readUint8Array(length) });+ }+ }+ }+ /** @bundle writing/write.js */+ write(stream) {+ this.size = 23;+ for (let i = 0; i < this.nalu_arrays.length; i++) {+ this.size += 3;+ for (let j = 0; j < this.nalu_arrays[i].length; j++) this.size += 2 + this.nalu_arrays[i][j].data.length;+ }+ this.writeHeader(stream);+ stream.writeUint8(this.configurationVersion);+ stream.writeUint8((this.general_profile_space << 6) + (this.general_tier_flag << 5) + this.general_profile_idc);+ stream.writeUint32(this.general_profile_compatibility);+ stream.writeUint8Array(this.general_constraint_indicator);+ stream.writeUint8(this.general_level_idc);+ stream.writeUint16(this.min_spatial_segmentation_idc + (15 << 24));+ stream.writeUint8(this.parallelismType + 252);+ stream.writeUint8(this.chroma_format_idc + 252);+ stream.writeUint8(this.bit_depth_luma_minus8 + 248);+ stream.writeUint8(this.bit_depth_chroma_minus8 + 248);+ stream.writeUint16(this.avgFrameRate);+ stream.writeUint8((this.constantFrameRate << 6) + (this.numTemporalLayers << 3) + (this.temporalIdNested << 2) + this.lengthSizeMinusOne);+ stream.writeUint8(this.nalu_arrays.length);+ for (let i = 0; i < this.nalu_arrays.length; i++) {+ stream.writeUint8((this.nalu_arrays[i].completeness << 7) + this.nalu_arrays[i].nalu_type);+ stream.writeUint16(this.nalu_arrays[i].length);+ for (let j = 0; j < this.nalu_arrays[i].length; j++) {+ stream.writeUint16(this.nalu_arrays[i][j].data.length);+ stream.writeUint8Array(this.nalu_arrays[i][j].data);+ }+ }+ }+};++//#endregion+//#region src/boxes/mdhd.ts+var mdhdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "MediaHeaderBox";+ }+ static {+ this.fourcc = "mdhd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 1) {+ this.creation_time = stream.readUint64();+ this.modification_time = stream.readUint64();+ this.timescale = stream.readUint32();+ this.duration = stream.readUint64();+ } else {+ this.creation_time = stream.readUint32();+ this.modification_time = stream.readUint32();+ this.timescale = stream.readUint32();+ this.duration = stream.readUint32();+ }+ this.parseLanguage(stream);+ stream.readUint16();+ }+ /** @bundle writing/mdhd.js */+ write(stream) {+ const useVersion1 = this.modification_time > MAX_UINT32 || this.creation_time > MAX_UINT32 || this.duration > MAX_UINT32 || this.version === 1;+ this.version = useVersion1 ? 1 : 0;+ this.size = 20;+ this.size += useVersion1 ? 12 : 0;+ this.flags = 0;+ this.writeHeader(stream);+ if (useVersion1) {+ stream.writeUint64(this.creation_time);+ stream.writeUint64(this.modification_time);+ stream.writeUint32(this.timescale);+ stream.writeUint64(this.duration);+ } else {+ stream.writeUint32(this.creation_time);+ stream.writeUint32(this.modification_time);+ stream.writeUint32(this.timescale);+ stream.writeUint32(this.duration);+ }+ stream.writeUint16(this.language);+ stream.writeUint16(0);+ }+};++//#endregion+//#region src/boxes/mehd.ts+var mehdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "MovieExtendsHeaderBox";+ }+ static {+ this.fourcc = "mehd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.flags & 1) {+ Log.warn("BoxParser", "mehd box incorrectly uses flags set to 1, converting version to 1");+ this.version = 1;+ }+ if (this.version === 1) this.fragment_duration = stream.readUint64();+ else this.fragment_duration = stream.readUint32();+ }+ /** @bundle writing/mehd.js */+ write(stream) {+ const useVersion1 = this.fragment_duration > MAX_UINT32 || this.version === 1;+ this.version = useVersion1 ? 1 : 0;+ this.size = 4;+ this.size += useVersion1 ? 4 : 0;+ this.flags = 0;+ this.writeHeader(stream);+ if (useVersion1) stream.writeUint64(this.fragment_duration);+ else stream.writeUint32(this.fragment_duration);+ }+};++//#endregion+//#region src/boxes/infe.ts+var infeBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ItemInfoEntry";+ }+ static {+ this.fourcc = "infe";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 0 || this.version === 1) {+ this.item_ID = stream.readUint16();+ this.item_protection_index = stream.readUint16();+ this.item_name = stream.readCString();+ this.content_type = stream.readCString();+ if (!this.isEndOfBox(stream)) this.content_encoding = stream.readCString();+ }+ if (this.version === 1) {+ this.extension_type = stream.readString(4);+ Log.warn("BoxParser", "Cannot parse extension type");+ stream.seek(this.start + this.size);+ return;+ }+ if (this.version >= 2) {+ if (this.version === 2) this.item_ID = stream.readUint16();+ else if (this.version === 3) this.item_ID = stream.readUint32();+ this.item_protection_index = stream.readUint16();+ this.item_type = stream.readString(4);+ this.item_name = stream.readCString();+ if (this.item_type === "mime") {+ this.content_type = stream.readCString();+ this.content_encoding = stream.readCString();+ } else if (this.item_type === "uri ") this.item_uri_type = stream.readCString();+ }+ }+};++//#endregion+//#region src/boxes/iinf.ts+var iinfBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ItemInfoBox";+ }+ static {+ this.fourcc = "iinf";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 0) this.entry_count = stream.readUint16();+ else this.entry_count = stream.readUint32();+ this.item_infos = [];+ for (let i = 0; i < this.entry_count; i++) {+ const ret = parseOneBox(stream, false, this.size - (stream.getPosition() - this.start));+ if (ret.code === 1) {+ const box = ret.box;+ if (box.type === "infe") this.item_infos[i] = box;+ else Log.error("BoxParser", "Expected 'infe' box, got " + ret.box.type, stream.isofile);+ } else return;+ }+ }+};++//#endregion+//#region src/boxes/iloc.ts+var ilocBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ItemLocationBox";+ }+ static {+ this.fourcc = "iloc";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ let byte;+ byte = stream.readUint8();+ this.offset_size = byte >> 4 & 15;+ this.length_size = byte & 15;+ byte = stream.readUint8();+ this.base_offset_size = byte >> 4 & 15;+ if (this.version === 1 || this.version === 2) this.index_size = byte & 15;+ else this.index_size = 0;+ this.items = [];+ let item_count = 0;+ if (this.version < 2) item_count = stream.readUint16();+ else if (this.version === 2) item_count = stream.readUint32();+ else throw new Error("version of iloc box not supported");+ for (let i = 0; i < item_count; i++) {+ let item_ID = 0;+ let construction_method = 0;+ let base_offset = 0;+ if (this.version < 2) item_ID = stream.readUint16();+ else if (this.version === 2) item_ID = stream.readUint32();+ else throw new Error("version of iloc box not supported");+ if (this.version === 1 || this.version === 2) construction_method = stream.readUint16() & 15;+ else construction_method = 0;+ const data_reference_index = stream.readUint16();+ switch (this.base_offset_size) {+ case 0:+ base_offset = 0;+ break;+ case 4:+ base_offset = stream.readUint32();+ break;+ case 8:+ base_offset = stream.readUint64();+ break;+ default: throw new Error("Error reading base offset size");+ }+ const extents = [];+ const extent_count = stream.readUint16();+ for (let j = 0; j < extent_count; j++) {+ let extent_index = 0;+ let extent_offset = 0;+ let extent_length = 0;+ if (this.version === 1 || this.version === 2) switch (this.index_size) {+ case 0:+ extent_index = 0;+ break;+ case 4:+ extent_index = stream.readUint32();+ break;+ case 8:+ extent_index = stream.readUint64();+ break;+ default: throw new Error("Error reading extent index");+ }+ switch (this.offset_size) {+ case 0:+ extent_offset = 0;+ break;+ case 4:+ extent_offset = stream.readUint32();+ break;+ case 8:+ extent_offset = stream.readUint64();+ break;+ default: throw new Error("Error reading extent index");+ }+ switch (this.length_size) {+ case 0:+ extent_length = 0;+ break;+ case 4:+ extent_length = stream.readUint32();+ break;+ case 8:+ extent_length = stream.readUint64();+ break;+ default: throw new Error("Error reading extent index");+ }+ extents.push({+ extent_index,+ extent_length,+ extent_offset+ });+ }+ this.items.push({+ base_offset,+ construction_method,+ item_ID,+ data_reference_index,+ extents+ });+ }+ }+};++//#endregion+//#region src/boxes/iref.ts+const REFERENCE_TYPE_NAMES = {+ auxl: "Auxiliary image item",+ base: "Pre-derived image item base",+ cdsc: "Item describes referenced item",+ dimg: "Derived image item",+ dpnd: "Item coding dependency",+ eroi: "Region",+ evir: "EVC slice",+ exbl: "Scalable image item",+ "fdl ": "File delivery",+ font: "Font item",+ iloc: "Item data location",+ mask: "Region mask",+ mint: "Data integrity",+ pred: "Predictively coded item",+ prem: "Pre-multiplied item",+ tbas: "HEVC tile track base item",+ text: "Text item",+ thmb: "Thumbnail image item"+};+var irefBox = class irefBox extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ItemReferenceBox";+ this.references = [];+ }+ static {+ this.fourcc = "iref";+ }+ static {+ this.allowed_types = [+ "auxl",+ "base",+ "cdsc",+ "dimg",+ "dpnd",+ "eroi",+ "evir",+ "exbl",+ "fdl ",+ "font",+ "iloc",+ "mask",+ "mint",+ "pred",+ "prem",+ "tbas",+ "text",+ "thmb"+ ];+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.references = [];+ while (stream.getPosition() < this.start + this.size) {+ const ret = parseOneBox(stream, true, this.size - (stream.getPosition() - this.start));+ if (ret.code === 1) {+ let name = "Unknown item reference";+ if (!irefBox.allowed_types.includes(ret.type)) Log.warn("BoxParser", `Unknown item reference type: '${ret.type}'`);+ else name = REFERENCE_TYPE_NAMES[ret.type];+ const box = this.version === 0 ? new SingleItemTypeReferenceBox(ret.type, ret.size, name, ret.hdr_size, ret.start) : new SingleItemTypeReferenceBoxLarge(ret.type, ret.size, name, ret.hdr_size, ret.start);+ if (box.write === Box.prototype.write && box.type !== "mdat") {+ Log.warn("BoxParser", box.type + " box writing not yet implemented, keeping unparsed data in memory for later write");+ box.parseDataAndRewind(stream);+ }+ box.parse(stream);+ this.references.push(box);+ } else return;+ }+ }+};++//#endregion+//#region src/boxes/pitm.ts+var pitmBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "PrimaryItemBox";+ }+ static {+ this.fourcc = "pitm";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 0) this.item_id = stream.readUint16();+ else this.item_id = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/meta.ts+var metaBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "MetaBox";+ this.isQT = false;+ }+ static {+ this.fourcc = "meta";+ }+ parse(stream) {+ const pos = stream.getPosition();+ if (this.size > 8) {+ stream.readUint32();+ switch (stream.readString(4)) {+ case "hdlr":+ case "mhdr":+ case "keys":+ case "ilst":+ case "ctry":+ case "lang":+ this.isQT = true;+ break;+ default: break;+ }+ stream.seek(pos);+ }+ if (!this.isQT) this.parseFullHeader(stream);+ ContainerBox.prototype.parse.call(this, stream);+ }+};++//#endregion+//#region src/boxes/mfhd.ts+var mfhdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "MovieFragmentHeaderBox";+ }+ static {+ this.fourcc = "mfhd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.sequence_number = stream.readUint32();+ }+ /** @bundle writing/mfhd.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 4;+ this.writeHeader(stream);+ stream.writeUint32(this.sequence_number);+ }+};++//#endregion+//#region src/boxes/mvhd.ts+var mvhdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "MovieHeaderBox";+ }+ static {+ this.fourcc = "mvhd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 1) {+ this.creation_time = stream.readUint64();+ this.modification_time = stream.readUint64();+ this.timescale = stream.readUint32();+ this.duration = stream.readUint64();+ } else {+ this.creation_time = stream.readUint32();+ this.modification_time = stream.readUint32();+ this.timescale = stream.readUint32();+ this.duration = stream.readUint32();+ }+ this.rate = stream.readUint32();+ this.volume = stream.readUint16() >> 8;+ stream.readUint16();+ stream.readUint32Array(2);+ this.matrix = stream.readInt32Array(9);+ stream.readUint32Array(6);+ this.next_track_id = stream.readUint32();+ }+ /** @bundle writing/mvhd.js */+ write(stream) {+ const useVersion1 = this.modification_time > MAX_UINT32 || this.creation_time > MAX_UINT32 || this.duration > MAX_UINT32 || this.version === 1;+ this.version = useVersion1 ? 1 : 0;+ this.size = 96;+ this.size += useVersion1 ? 12 : 0;+ this.flags = 0;+ this.writeHeader(stream);+ if (useVersion1) {+ stream.writeUint64(this.creation_time);+ stream.writeUint64(this.modification_time);+ stream.writeUint32(this.timescale);+ stream.writeUint64(this.duration);+ } else {+ stream.writeUint32(this.creation_time);+ stream.writeUint32(this.modification_time);+ stream.writeUint32(this.timescale);+ stream.writeUint32(this.duration);+ }+ stream.writeUint32(this.rate);+ stream.writeUint16(this.volume << 8);+ stream.writeUint16(0);+ stream.writeUint32(0);+ stream.writeUint32(0);+ stream.writeInt32Array(this.matrix);+ stream.writeUint32(0);+ stream.writeUint32(0);+ stream.writeUint32(0);+ stream.writeUint32(0);+ stream.writeUint32(0);+ stream.writeUint32(0);+ stream.writeUint32(this.next_track_id);+ }+ /** @bundle box-print.js */+ print(output) {+ super.printHeader(output);+ output.log(output.indent + "creation_time: " + this.creation_time);+ output.log(output.indent + "modification_time: " + this.modification_time);+ output.log(output.indent + "timescale: " + this.timescale);+ output.log(output.indent + "duration: " + this.duration);+ output.log(output.indent + "rate: " + this.rate);+ output.log(output.indent + "volume: " + (this.volume >> 8));+ output.log(output.indent + "matrix: " + this.matrix.join(", "));+ output.log(output.indent + "next_track_id: " + this.next_track_id);+ }+};++//#endregion+//#region src/boxes/sampleentries/mett.ts+var mettSampleEntry = class extends MetadataSampleEntry {+ static {+ this.fourcc = "mett";+ }+ parse(stream) {+ this.parseHeader(stream);+ this.content_encoding = stream.readCString();+ this.mime_format = stream.readCString();+ this.parseFooter(stream);+ }+};++//#endregion+//#region src/boxes/sampleentries/metx.ts+var metxSampleEntry = class extends MetadataSampleEntry {+ static {+ this.fourcc = "metx";+ }+ parse(stream) {+ this.parseHeader(stream);+ this.content_encoding = stream.readCString();+ this.namespace = stream.readCString();+ this.schema_location = stream.readCString();+ this.parseFooter(stream);+ }+};++//#endregion+//#region src/boxes/av1C.ts+var av1CBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "AV1CodecConfigurationBox";+ }+ static {+ this.fourcc = "av1C";+ }+ parse(stream) {+ let tmp = stream.readUint8();+ if ((tmp >> 7 & 1) !== 1) {+ Log.error("BoxParser", "av1C marker problem", stream.isofile);+ return;+ }+ this.version = tmp & 127;+ if (this.version !== 1) {+ Log.error("BoxParser", "av1C version " + this.version + " not supported", stream.isofile);+ return;+ }+ tmp = stream.readUint8();+ this.seq_profile = tmp >> 5 & 7;+ this.seq_level_idx_0 = tmp & 31;+ tmp = stream.readUint8();+ this.seq_tier_0 = tmp >> 7 & 1;+ this.high_bitdepth = tmp >> 6 & 1;+ this.twelve_bit = tmp >> 5 & 1;+ this.monochrome = tmp >> 4 & 1;+ this.chroma_subsampling_x = tmp >> 3 & 1;+ this.chroma_subsampling_y = tmp >> 2 & 1;+ this.chroma_sample_position = tmp & 3;+ tmp = stream.readUint8();+ this.reserved_1 = tmp >> 5 & 7;+ if (this.reserved_1 !== 0) {+ Log.error("BoxParser", "av1C reserved_1 parsing problem", stream.isofile);+ return;+ }+ this.initial_presentation_delay_present = tmp >> 4 & 1;+ if (this.initial_presentation_delay_present === 1) this.initial_presentation_delay_minus_one = tmp & 15;+ else {+ this.reserved_2 = tmp & 15;+ if (this.reserved_2 !== 0) {+ Log.error("BoxParser", "av1C reserved_2 parsing problem", stream.isofile);+ return;+ }+ }+ const configOBUs_length = this.size - this.hdr_size - 4;+ this.configOBUs = stream.readUint8Array(configOBUs_length);+ }+};++//#endregion+//#region src/boxes/esds.ts+var esdsBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ElementaryStreamDescriptorBox";+ }+ static {+ this.fourcc = "esds";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const esd_data = stream.readUint8Array(this.size - this.hdr_size);+ if ("MPEG4DescriptorParser" in DescriptorRegistry) {+ const esd_parser = new DescriptorRegistry.MPEG4DescriptorParser();+ this.esd = esd_parser.parseOneDescriptor(new DataStream(esd_data.buffer, 0));+ }+ }+};++//#endregion+//#region src/boxes/qt/wave.ts+var waveBox = class extends ContainerBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "siDecompressionParamBox";+ }+ static {+ this.fourcc = "wave";+ }+};++//#endregion+//#region src/boxes/lvcC.ts+var lvcCBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "LCEVCConfigurationBox";+ }+ static {+ this.fourcc = "lvcC";+ }+ parse(stream) {+ this.configurationVersion = stream.readUint8();+ if (this.configurationVersion !== 1) {+ Log.error("BoxParser", "lvcC version " + this.configurationVersion + " not supported", stream.isofile);+ return;+ }+ this.LCEVCProfileIndication = stream.readUint8();+ this.LCEVCLevelIndication = stream.readUint8();+ let tmp_byte = stream.readUint8();+ this.chroma_format_idc = tmp_byte >> 6 & 3;+ this.bit_depth_luma_minus8 = tmp_byte >> 3 & 7;+ this.bit_depth_chroma_minus8 = tmp_byte & 7;+ tmp_byte = stream.readUint8();+ this.lengthSizeMinusOne = tmp_byte >> 6 & 3;+ let reserved = tmp_byte & 63;+ if (reserved !== 63) {+ Log.error("BoxParser", "lvcC reserved parsing problem", stream.isofile);+ return;+ }+ this.pic_width_in_luma_samples = stream.readUint32();+ this.pic_height_in_luma_samples = stream.readUint32();+ tmp_byte = stream.readUint8();+ this.sc_in_stream = tmp_byte >> 7 & 1;+ this.gc_in_stream = tmp_byte >> 6 & 1;+ this.ai_in_stream = tmp_byte >> 5 & 1;+ reserved = tmp_byte & 31;+ if (reserved !== 31) {+ Log.error("BoxParser", "lvcC reserved parsing problem", stream.isofile);+ return;+ }+ this.nalu_arrays = [];+ const numOfArrays = stream.readUint8();+ for (let i = 0; i < numOfArrays; i++) {+ const nalu_array = [];+ this.nalu_arrays.push(nalu_array);+ tmp_byte = stream.readUint8();+ reserved = tmp_byte >> 6 & 3;+ if (reserved !== 0) {+ Log.error("BoxParser", "lvcC reserved parsing problem", stream.isofile);+ return;+ }+ nalu_array.nalu_type = tmp_byte & 63;+ const numOfNalus = stream.readUint16();+ for (let j = 0; j < numOfNalus; j++) {+ const length = stream.readUint16();+ nalu_array.push({ data: stream.readUint8Array(length) });+ }+ }+ }+};++//#endregion+//#region src/boxes/vpcC.ts+var vpcCBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "VPCodecConfigurationRecord";+ }+ static {+ this.fourcc = "vpcC";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 1) {+ this.profile = stream.readUint8();+ this.level = stream.readUint8();+ const tmp = stream.readUint8();+ this.bitDepth = tmp >> 4;+ this.chromaSubsampling = tmp >> 1 & 7;+ this.videoFullRangeFlag = tmp & 1;+ this.colourPrimaries = stream.readUint8();+ this.transferCharacteristics = stream.readUint8();+ this.matrixCoefficients = stream.readUint8();+ this.codecIntializationDataSize = stream.readUint16();+ this.codecIntializationData = stream.readUint8Array(this.codecIntializationDataSize);+ } else {+ this.profile = stream.readUint8();+ this.level = stream.readUint8();+ let tmp = stream.readUint8();+ this.bitDepth = tmp >> 4 & 15;+ this.colorSpace = tmp & 15;+ tmp = stream.readUint8();+ this.chromaSubsampling = tmp >> 4 & 15;+ this.transferFunction = tmp >> 1 & 7;+ this.videoFullRangeFlag = tmp & 1;+ this.codecIntializationDataSize = stream.readUint16();+ this.codecIntializationData = stream.readUint8Array(this.codecIntializationDataSize);+ }+ }+};++//#endregion+//#region src/boxes/vvcC.ts+var vvcCBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "VvcConfigurationBox";+ }+ static {+ this.fourcc = "vvcC";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const bitReader = {+ held_bits: void 0,+ num_held_bits: 0,+ stream_read_1_bytes: function(strm) {+ this.held_bits = strm.readUint8();+ this.num_held_bits = 8;+ },+ stream_read_2_bytes: function(strm) {+ this.held_bits = strm.readUint16();+ this.num_held_bits = 16;+ },+ extract_bits: function(num_bits) {+ const ret = this.held_bits >> this.num_held_bits - num_bits & (1 << num_bits) - 1;+ this.num_held_bits -= num_bits;+ return ret;+ }+ };+ bitReader.stream_read_1_bytes(stream);+ bitReader.extract_bits(5);+ this.lengthSizeMinusOne = bitReader.extract_bits(2);+ this.ptl_present_flag = bitReader.extract_bits(1);+ if (this.ptl_present_flag) {+ bitReader.stream_read_2_bytes(stream);+ this.ols_idx = bitReader.extract_bits(9);+ this.num_sublayers = bitReader.extract_bits(3);+ this.constant_frame_rate = bitReader.extract_bits(2);+ this.chroma_format_idc = bitReader.extract_bits(2);+ bitReader.stream_read_1_bytes(stream);+ this.bit_depth_minus8 = bitReader.extract_bits(3);+ bitReader.extract_bits(5);+ bitReader.stream_read_2_bytes(stream);+ bitReader.extract_bits(2);+ this.num_bytes_constraint_info = bitReader.extract_bits(6);+ this.general_profile_idc = bitReader.extract_bits(7);+ this.general_tier_flag = bitReader.extract_bits(1);+ this.general_level_idc = stream.readUint8();+ bitReader.stream_read_1_bytes(stream);+ this.ptl_frame_only_constraint_flag = bitReader.extract_bits(1);+ this.ptl_multilayer_enabled_flag = bitReader.extract_bits(1);+ this.general_constraint_info = new Uint8Array(this.num_bytes_constraint_info);+ if (this.num_bytes_constraint_info) {+ for (let i = 0; i < this.num_bytes_constraint_info - 1; i++) {+ const cnstr1 = bitReader.extract_bits(6);+ bitReader.stream_read_1_bytes(stream);+ const cnstr2 = bitReader.extract_bits(2);+ this.general_constraint_info[i] = cnstr1 << 2 | cnstr2;+ }+ this.general_constraint_info[this.num_bytes_constraint_info - 1] = bitReader.extract_bits(6);+ } else bitReader.extract_bits(6);+ if (this.num_sublayers > 1) {+ bitReader.stream_read_1_bytes(stream);+ this.ptl_sublayer_present_mask = 0;+ for (let j = this.num_sublayers - 2; j >= 0; --j) {+ const val = bitReader.extract_bits(1);+ this.ptl_sublayer_present_mask |= val << j;+ }+ for (let j = this.num_sublayers; j <= 8 && this.num_sublayers > 1; ++j) bitReader.extract_bits(1);+ this.sublayer_level_idc = [];+ for (let j = this.num_sublayers - 2; j >= 0; --j) if (this.ptl_sublayer_present_mask & 1 << j) this.sublayer_level_idc[j] = stream.readUint8();+ }+ this.ptl_num_sub_profiles = stream.readUint8();+ this.general_sub_profile_idc = [];+ if (this.ptl_num_sub_profiles) for (let i = 0; i < this.ptl_num_sub_profiles; i++) this.general_sub_profile_idc.push(stream.readUint32());+ this.max_picture_width = stream.readUint16();+ this.max_picture_height = stream.readUint16();+ this.avg_frame_rate = stream.readUint16();+ }+ const VVC_NALU_OPI = 12;+ const VVC_NALU_DEC_PARAM = 13;+ this.nalu_arrays = [];+ const num_of_arrays = stream.readUint8();+ for (let i = 0; i < num_of_arrays; i++) {+ const nalu_array = [];+ this.nalu_arrays.push(nalu_array);+ bitReader.stream_read_1_bytes(stream);+ nalu_array.completeness = bitReader.extract_bits(1);+ bitReader.extract_bits(2);+ nalu_array.nalu_type = bitReader.extract_bits(5);+ let numNalus = 1;+ if (nalu_array.nalu_type !== VVC_NALU_DEC_PARAM && nalu_array.nalu_type !== VVC_NALU_OPI) numNalus = stream.readUint16();+ for (let j = 0; j < numNalus; j++) {+ const len = stream.readUint16();+ nalu_array.push({+ data: stream.readUint8Array(len),+ length: len+ });+ }+ }+ }+};++//#endregion+//#region src/boxes/colr.ts+var colrBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ColourInformationBox";+ }+ static {+ this.fourcc = "colr";+ }+ parse(stream) {+ this.colour_type = stream.readString(4);+ if (this.colour_type === "nclx") {+ this.colour_primaries = stream.readUint16();+ this.transfer_characteristics = stream.readUint16();+ this.matrix_coefficients = stream.readUint16();+ const tmp = stream.readUint8();+ this.full_range_flag = tmp >> 7;+ } else if (this.colour_type === "rICC") this.ICC_profile = stream.readUint8Array(this.size - 4);+ else if (this.colour_type === "prof") this.ICC_profile = stream.readUint8Array(this.size - 4);+ }+};++//#endregion+//#region src/boxes/sampleentries/sampleentry.ts+/** @bundle box-codecs.js */+function decimalToHex(d, padding) {+ let hex = Number(d).toString(16);+ padding = typeof padding === "undefined" ? 2 : padding;+ while (hex.length < padding) hex = "0" + hex;+ return hex;+}+var avcCSampleEntryBase = class extends VisualSampleEntry {+ /** @bundle box-codecs.js */+ getCodec() {+ const baseCodec = super.getCodec();+ if (this.avcC) return `${baseCodec}.${decimalToHex(this.avcC.AVCProfileIndication)}${decimalToHex(this.avcC.profile_compatibility)}${decimalToHex(this.avcC.AVCLevelIndication)}`;+ else return baseCodec;+ }+};+var avc1SampleEntry = class extends avcCSampleEntryBase {+ constructor(..._args) {+ super(..._args);+ this.box_name = "AVCSampleEntry";+ }+ static {+ this.fourcc = "avc1";+ }+};+var avc2SampleEntry = class extends avcCSampleEntryBase {+ constructor(..._args2) {+ super(..._args2);+ this.box_name = "AVC2SampleEntry";+ }+ static {+ this.fourcc = "avc2";+ }+};+var avc3SampleEntry = class extends avcCSampleEntryBase {+ constructor(..._args3) {+ super(..._args3);+ this.box_name = "AVCSampleEntry";+ }+ static {+ this.fourcc = "avc3";+ }+};+var avc4SampleEntry = class extends avcCSampleEntryBase {+ constructor(..._args4) {+ super(..._args4);+ this.box_name = "AVC2SampleEntry";+ }+ static {+ this.fourcc = "avc4";+ }+};+var av01SampleEntry = class extends VisualSampleEntry {+ constructor(..._args5) {+ super(..._args5);+ this.box_name = "AV1SampleEntry";+ }+ static {+ this.fourcc = "av01";+ }+ /** @bundle box-codecs.js */+ getCodec() {+ const baseCodec = super.getCodec();+ const level_idx_0 = this.av1C.seq_level_idx_0;+ const level = level_idx_0 < 10 ? "0" + level_idx_0 : level_idx_0;+ let bitdepth;+ if (this.av1C.seq_profile === 2 && this.av1C.high_bitdepth === 1) bitdepth = this.av1C.twelve_bit === 1 ? "12" : "10";+ else if (this.av1C.seq_profile <= 2) bitdepth = this.av1C.high_bitdepth === 1 ? "10" : "08";+ return baseCodec + "." + this.av1C.seq_profile + "." + level + (this.av1C.seq_tier_0 ? "H" : "M") + "." + bitdepth;+ }+};+var dav1SampleEntry = class extends VisualSampleEntry {+ static {+ this.fourcc = "dav1";+ }+};+var hvcCSampleEntryBase = class extends VisualSampleEntry {+ /** @bundle box-codecs.js */+ getCodec() {+ let baseCodec = super.getCodec();+ if (this.hvcC) {+ baseCodec += ".";+ switch (this.hvcC.general_profile_space) {+ case 0:+ baseCodec += "";+ break;+ case 1:+ baseCodec += "A";+ break;+ case 2:+ baseCodec += "B";+ break;+ case 3:+ baseCodec += "C";+ break;+ }+ baseCodec += this.hvcC.general_profile_idc;+ baseCodec += ".";+ let val = this.hvcC.general_profile_compatibility;+ let reversed = 0;+ for (let i = 0; i < 32; i++) {+ reversed |= val & 1;+ if (i === 31) break;+ reversed <<= 1;+ val >>= 1;+ }+ baseCodec += decimalToHex(reversed, 0);+ baseCodec += ".";+ if (this.hvcC.general_tier_flag === 0) baseCodec += "L";+ else baseCodec += "H";+ baseCodec += this.hvcC.general_level_idc;+ let hasByte = false;+ let constraint_string = "";+ for (let i = 5; i >= 0; i--) if (this.hvcC.general_constraint_indicator[i] || hasByte) {+ constraint_string = "." + decimalToHex(this.hvcC.general_constraint_indicator[i], 0) + constraint_string;+ hasByte = true;+ }+ baseCodec += constraint_string;+ }+ return baseCodec;+ }+};+var hvc1SampleEntry = class extends hvcCSampleEntryBase {+ constructor(..._args6) {+ super(..._args6);+ this.box_name = "HEVCSampleEntry";+ }+ static {+ this.fourcc = "hvc1";+ }+};+var hvc2SampleEntry = class extends hvcCSampleEntryBase {+ static {+ this.fourcc = "hvc2";+ }+};+var hev1SampleEntry = class extends hvcCSampleEntryBase {+ constructor(..._args7) {+ super(..._args7);+ this.box_name = "HEVCSampleEntry";+ this.colrs = [];+ this.subBoxNames = ["colr"];+ }+ static {+ this.fourcc = "hev1";+ }+};+var hev2SampleEntry = class extends hvcCSampleEntryBase {+ static {+ this.fourcc = "hev2";+ }+};+var hvt1SampleEntry = class extends VisualSampleEntry {+ constructor(..._args8) {+ super(..._args8);+ this.box_name = "HEVCTileSampleSampleEntry";+ }+ static {+ this.fourcc = "hvt1";+ }+};+var lhe1SampleEntry = class extends VisualSampleEntry {+ constructor(..._args9) {+ super(..._args9);+ this.box_name = "LHEVCSampleEntry";+ }+ static {+ this.fourcc = "lhe1";+ }+};+var lhv1SampleEntry = class extends VisualSampleEntry {+ constructor(..._args10) {+ super(..._args10);+ this.box_name = "LHEVCSampleEntry";+ }+ static {+ this.fourcc = "lhv1";+ }+};+var lvc1SampleEntry = class extends VisualSampleEntry {+ constructor(..._args11) {+ super(..._args11);+ this.box_name = "LCEVCSampleEntry";+ }+ static {+ this.fourcc = "lvc1";+ }+ /** @bundle box-codecs.js */+ getCodec() {+ let baseCodec = super.getCodec();+ if (this.lvcC) {+ baseCodec += ".";+ baseCodec += "vprf";+ baseCodec += this.lvcC.LCEVCProfileIndication;+ baseCodec += ".";+ baseCodec += "vlev";+ baseCodec += this.lvcC.LCEVCLevelIndication;+ }+ return baseCodec;+ }+};+var dvh1SampleEntry = class extends VisualSampleEntry {+ static {+ this.fourcc = "dvh1";+ }+};+var dvheSampleEntry = class extends VisualSampleEntry {+ static {+ this.fourcc = "dvhe";+ }+};+/** @babel box-codecs.js */+var vvcCSampleEntryBase = class extends VisualSampleEntry {+ getCodec() {+ let baseCodec = super.getCodec();+ if (this.vvcC) {+ baseCodec += "." + this.vvcC.general_profile_idc;+ if (this.vvcC.general_tier_flag) baseCodec += ".H";+ else baseCodec += ".L";+ baseCodec += this.vvcC.general_level_idc;+ let constraint_string = "";+ if (this.vvcC.general_constraint_info) {+ const bytes = [];+ let byte = 0;+ byte |= this.vvcC.ptl_frame_only_constraint_flag << 7;+ byte |= this.vvcC.ptl_multilayer_enabled_flag << 6;+ let last_nonzero;+ for (let i = 0; i < this.vvcC.general_constraint_info.length; ++i) {+ byte |= this.vvcC.general_constraint_info[i] >> 2 & 63;+ bytes.push(byte);+ if (byte) last_nonzero = i;+ byte = this.vvcC.general_constraint_info[i] >> 2 & 3;+ }+ if (last_nonzero === void 0) constraint_string = ".CA";+ else {+ constraint_string = ".C";+ const base32_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";+ let held_bits = 0;+ let num_held_bits = 0;+ for (let i = 0; i <= last_nonzero; ++i) {+ held_bits = held_bits << 8 | bytes[i];+ num_held_bits += 8;+ while (num_held_bits >= 5) {+ const val = held_bits >> num_held_bits - 5 & 31;+ constraint_string += base32_chars[val];+ num_held_bits -= 5;+ held_bits &= (1 << num_held_bits) - 1;+ }+ }+ if (num_held_bits) {+ held_bits <<= 5 - num_held_bits;+ constraint_string += base32_chars[held_bits & 31];+ }+ }+ }+ baseCodec += constraint_string;+ }+ return baseCodec;+ }+};+var vvc1SampleEntry = class extends vvcCSampleEntryBase {+ constructor(..._args12) {+ super(..._args12);+ this.box_name = "VvcSampleEntry";+ }+ static {+ this.fourcc = "vvc1";+ }+};+var vvi1SampleEntry = class extends vvcCSampleEntryBase {+ constructor(..._args13) {+ super(..._args13);+ this.box_name = "VvcSampleEntry";+ }+ static {+ this.fourcc = "vvi1";+ }+};+var vvs1SampleEntry = class extends VisualSampleEntry {+ constructor(..._args14) {+ super(..._args14);+ this.box_name = "VvcSampleEntry";+ }+ static {+ this.fourcc = "vvs1";+ }+};+var vvcNSampleEntry = class extends VisualSampleEntry {+ constructor(..._args15) {+ super(..._args15);+ this.box_name = "VvcNonVCLSampleEntry";+ }+ static {+ this.fourcc = "vvcN";+ }+};+var vpcCSampleEntryBase = class extends VisualSampleEntry {+ getCodec() {+ const baseCodec = super.getCodec();+ let level = this.vpcC.level;+ if (level === 0) level = "00";+ let bitDepth = this.vpcC.bitDepth;+ if (bitDepth === 8) bitDepth = "08";+ return `${baseCodec}.0${this.vpcC.profile}.${level}.${bitDepth}`;+ }+};+var vp08SampleEntry = class extends vpcCSampleEntryBase {+ static {+ this.fourcc = "vp08";+ }+};+var vp09SampleEntry = class extends vpcCSampleEntryBase {+ static {+ this.fourcc = "vp09";+ }+};+var avs3SampleEntry = class extends VisualSampleEntry {+ static {+ this.fourcc = "avs3";+ }+};+var j2kiSampleEntry = class extends VisualSampleEntry {+ constructor(..._args16) {+ super(..._args16);+ this.box_name = "J2KSampleEntry";+ }+ static {+ this.fourcc = "j2ki";+ }+};+var mjp2SampleEntry = class extends VisualSampleEntry {+ static {+ this.fourcc = "mjp2";+ }+};+var mjpgSampleEntry = class extends VisualSampleEntry {+ static {+ this.fourcc = "mjpg";+ }+};+var uncvSampleEntry = class extends VisualSampleEntry {+ constructor(..._args17) {+ super(..._args17);+ this.box_name = "UncompressedVideoSampleEntry";+ }+ static {+ this.fourcc = "uncv";+ }+};+var mp4vSampleEntry = class extends VisualSampleEntry {+ constructor(..._args18) {+ super(..._args18);+ this.box_name = "MP4VisualSampleEntry";+ }+ static {+ this.fourcc = "mp4v";+ }+};+var mp4aSampleEntry = class extends AudioSampleEntry {+ constructor(..._args19) {+ super(..._args19);+ this.box_name = "MP4AudioSampleEntry";+ }+ static {+ this.fourcc = "mp4a";+ }+ getCodec() {+ const baseCodec = super.getCodec();+ const esds = this.esds ?? this.wave?.esds;+ if (esds && esds.esd) {+ const oti = esds.esd.getOTI();+ const dsi = esds.esd.getAudioConfig();+ return baseCodec + "." + decimalToHex(oti) + (dsi ? "." + dsi : "");+ } else return baseCodec;+ }+};+var m4aeSampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "m4ae";+ }+};+var ac_3SampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "ac-3";+ }+};+var ac_4SampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "ac-4";+ }+};+var ec_3SampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "ec-3";+ }+};+var OpusSampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "Opus";+ }+};+var mha1SampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "mha1";+ }+};+var mha2SampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "mha2";+ }+};+var mhm1SampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "mhm1";+ }+};+var mhm2SampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "mhm2";+ }+};+var fLaCSampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "fLaC";+ }+};+var encvSampleEntry = class extends VisualSampleEntry {+ static {+ this.fourcc = "encv";+ }+};+var encaSampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "enca";+ }+};+var encuSampleEntry = class extends SubtitleSampleEntry {+ constructor(..._args20) {+ super(..._args20);+ this.subBoxNames = ["sinf"];+ this.sinfs = [];+ }+ static {+ this.fourcc = "encu";+ }+};+var encsSampleEntry = class extends SystemSampleEntry {+ constructor(..._args21) {+ super(..._args21);+ this.subBoxNames = ["sinf"];+ this.sinfs = [];+ }+ static {+ this.fourcc = "encs";+ }+};+var mp4sSampleEntry = class extends SystemSampleEntry {+ static {+ this.fourcc = "mp4s";+ }+};+var enctSampleEntry = class extends TextSampleEntry {+ constructor(..._args22) {+ super(..._args22);+ this.subBoxNames = ["sinf"];+ this.sinfs = [];+ }+ static {+ this.fourcc = "enct";+ }+};+var encmSampleEntry = class extends MetadataSampleEntry {+ constructor(..._args23) {+ super(..._args23);+ this.subBoxNames = ["sinf"];+ this.sinfs = [];+ }+ static {+ this.fourcc = "encm";+ }+};+var resvSampleEntry = class extends VisualSampleEntry {+ constructor(..._args24) {+ super(..._args24);+ this.box_name = "RestrictedVideoSampleEntry";+ }+ static {+ this.fourcc = "resv";+ }+};++//#endregion+//#region src/boxes/sampleentries/sbtt.ts+var sbttSampleEntry = class extends SubtitleSampleEntry {+ static {+ this.fourcc = "sbtt";+ }+ parse(stream) {+ this.parseHeader(stream);+ this.content_encoding = stream.readCString();+ this.mime_format = stream.readCString();+ this.parseFooter(stream);+ }+};++//#endregion+//#region src/boxes/sampleentries/stpp.ts+var stppSampleEntry = class extends SubtitleSampleEntry {+ static {+ this.fourcc = "stpp";+ }+ parse(stream) {+ this.parseHeader(stream);+ this.namespace = stream.readCString();+ this.schema_location = stream.readCString();+ this.auxiliary_mime_types = stream.readCString();+ this.parseFooter(stream);+ }+ /** @bundle writing/sampleentry.js */+ write(stream) {+ this.writeHeader(stream);+ this.size += this.namespace.length + 1 + this.schema_location.length + 1 + this.auxiliary_mime_types.length + 1;+ stream.writeCString(this.namespace);+ stream.writeCString(this.schema_location);+ stream.writeCString(this.auxiliary_mime_types);+ this.writeFooter(stream);+ }+};++//#endregion+//#region src/boxes/sampleentries/stxt.ts+var stxtSampleEntry = class extends SubtitleSampleEntry {+ static {+ this.fourcc = "stxt";+ }+ parse(stream) {+ this.parseHeader(stream);+ this.content_encoding = stream.readCString();+ this.mime_format = stream.readCString();+ this.parseFooter(stream);+ }+ getCodec() {+ const baseCodec = super.getCodec();+ if (this.mime_format) return baseCodec + "." + this.mime_format;+ else return baseCodec;+ }+};++//#endregion+//#region src/boxes/sampleentries/tx3g.ts+var tx3gSampleEntry = class extends SubtitleSampleEntry {+ static {+ this.fourcc = "tx3g";+ }+ parse(stream) {+ this.parseHeader(stream);+ this.displayFlags = stream.readUint32();+ this.horizontal_justification = stream.readInt8();+ this.vertical_justification = stream.readInt8();+ this.bg_color_rgba = stream.readUint8Array(4);+ this.box_record = stream.readInt16Array(4);+ this.style_record = stream.readUint8Array(12);+ this.parseFooter(stream);+ }+};++//#endregion+//#region src/boxes/sampleentries/wvtt.ts+var wvttSampleEntry = class extends MetadataSampleEntry {+ static {+ this.fourcc = "wvtt";+ }+ parse(stream) {+ this.parseHeader(stream);+ this.parseFooter(stream);+ }+};++//#endregion+//#region src/boxes/sbgp.ts+var sbgpBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SampleToGroupBox";+ }+ static {+ this.fourcc = "sbgp";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.grouping_type = stream.readString(4);+ if (this.version === 1) this.grouping_type_parameter = stream.readUint32();+ else this.grouping_type_parameter = 0;+ this.entries = [];+ const entry_count = stream.readUint32();+ for (let i = 0; i < entry_count; i++) this.entries.push({+ sample_count: stream.readInt32(),+ group_description_index: stream.readInt32()+ });+ }+ /** @bundle writing/sbgp.js */+ write(stream) {+ if (this.grouping_type_parameter) this.version = 1;+ else this.version = 0;+ this.flags = 0;+ this.size = 8 + 8 * this.entries.length + (this.version === 1 ? 4 : 0);+ this.writeHeader(stream);+ stream.writeString(this.grouping_type, void 0, 4);+ if (this.version === 1) stream.writeUint32(this.grouping_type_parameter);+ stream.writeUint32(this.entries.length);+ for (let i = 0; i < this.entries.length; i++) {+ const entry = this.entries[i];+ stream.writeInt32(entry.sample_count);+ stream.writeInt32(entry.group_description_index);+ }+ }+};++//#endregion+//#region src/boxes/sdtp.ts+var sdtpBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SampleDependencyTypeBox";+ }+ static {+ this.fourcc = "sdtp";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const count = this.size - this.hdr_size;+ this.is_leading = [];+ this.sample_depends_on = [];+ this.sample_is_depended_on = [];+ this.sample_has_redundancy = [];+ for (let i = 0; i < count; i++) {+ const tmp_byte = stream.readUint8();+ this.is_leading[i] = tmp_byte >> 6;+ this.sample_depends_on[i] = tmp_byte >> 4 & 3;+ this.sample_is_depended_on[i] = tmp_byte >> 2 & 3;+ this.sample_has_redundancy[i] = tmp_byte & 3;+ }+ }+};++//#endregion+//#region src/boxes/sgpd.ts+var sgpdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SampleGroupDescriptionBox";+ }+ static {+ this.fourcc = "sgpd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.grouping_type = stream.readString(4);+ Log.debug("BoxParser", "Found Sample Groups of type " + this.grouping_type);+ if (this.version === 1) this.default_length = stream.readUint32();+ else this.default_length = 0;+ if (this.version >= 2) this.default_group_description_index = stream.readUint32();+ this.entries = [];+ const entry_count = stream.readUint32();+ for (let i = 0; i < entry_count; i++) {+ let entry;+ if (this.grouping_type in BoxRegistry.sampleGroupEntry) entry = new BoxRegistry.sampleGroupEntry[this.grouping_type](this.grouping_type);+ else entry = new SampleGroupEntry(this.grouping_type);+ this.entries.push(entry);+ if (this.version === 1) if (this.default_length === 0) entry.description_length = stream.readUint32();+ else entry.description_length = this.default_length;+ else entry.description_length = this.default_length;+ if (entry.write === SampleGroupEntry.prototype.write) {+ Log.info("BoxParser", "SampleGroup for type " + this.grouping_type + " writing not yet implemented, keeping unparsed data in memory for later write");+ entry.data = stream.readUint8Array(entry.description_length);+ stream.seek(stream.getPosition() - entry.description_length);+ }+ entry.parse(stream);+ }+ }+ /** @bundle writing/sgpd.js */+ write(stream) {+ this.flags = 0;+ this.size = 12;+ for (let i = 0; i < this.entries.length; i++) {+ const entry = this.entries[i];+ if (this.version === 1) {+ if (this.default_length === 0) this.size += 4;+ this.size += entry.data.length;+ }+ }+ this.writeHeader(stream);+ stream.writeString(this.grouping_type, void 0, 4);+ if (this.version === 1) stream.writeUint32(this.default_length);+ if (this.version >= 2) stream.writeUint32(this.default_sample_description_index);+ stream.writeUint32(this.entries.length);+ for (let i = 0; i < this.entries.length; i++) {+ const entry = this.entries[i];+ if (this.version === 1) {+ if (this.default_length === 0) stream.writeUint32(entry.description_length);+ }+ entry.write(stream);+ }+ }+};++//#endregion+//#region src/boxes/sidx.ts+var sidxBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CompressedSegmentIndexBox";+ }+ static {+ this.fourcc = "sidx";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.reference_ID = stream.readUint32();+ this.timescale = stream.readUint32();+ if (this.version === 0) {+ this.earliest_presentation_time = stream.readUint32();+ this.first_offset = stream.readUint32();+ } else {+ this.earliest_presentation_time = stream.readUint64();+ this.first_offset = stream.readUint64();+ }+ stream.readUint16();+ this.references = [];+ const count = stream.readUint16();+ for (let i = 0; i < count; i++) {+ const type = stream.readUint32();+ const subsegment_duration = stream.readUint32();+ const sap = stream.readUint32();+ this.references.push({+ reference_type: type >> 31 & 1,+ referenced_size: type & 2147483647,+ subsegment_duration,+ starts_with_SAP: sap >> 31 & 1,+ SAP_type: sap >> 28 & 7,+ SAP_delta_time: sap & 268435455+ });+ }+ }+ /** @bundle writing/sidx.js */+ write(stream) {+ const useVersion1 = this.earliest_presentation_time > MAX_UINT32 || this.first_offset > MAX_UINT32 || this.version === 1;+ this.version = useVersion1 ? 1 : 0;+ this.size = 12 + 12 * this.references.length;+ this.size += useVersion1 ? 16 : 8;+ this.flags = 0;+ this.writeHeader(stream);+ stream.writeUint32(this.reference_ID);+ stream.writeUint32(this.timescale);+ if (useVersion1) {+ stream.writeUint64(this.earliest_presentation_time);+ stream.writeUint64(this.first_offset);+ } else {+ stream.writeUint32(this.earliest_presentation_time);+ stream.writeUint32(this.first_offset);+ }+ stream.writeUint16(0);+ stream.writeUint16(this.references.length);+ for (let i = 0; i < this.references.length; i++) {+ const ref = this.references[i];+ stream.writeUint32(ref.reference_type << 31 | ref.referenced_size);+ stream.writeUint32(ref.subsegment_duration);+ stream.writeUint32(ref.starts_with_SAP << 31 | ref.SAP_type << 28 | ref.SAP_delta_time);+ }+ }+};++//#endregion+//#region src/boxes/smhd.ts+var smhdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SoundMediaHeaderBox";+ }+ static {+ this.fourcc = "smhd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.balance = stream.readUint16();+ stream.readUint16();+ }+ /** @bundle writing/smhd.js */+ write(stream) {+ this.version = 0;+ this.size = 4;+ this.writeHeader(stream);+ stream.writeUint16(this.balance);+ stream.writeUint16(0);+ }+};++//#endregion+//#region src/boxes/stco.ts+var stcoBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ChunkOffsetBox";+ }+ static {+ this.fourcc = "stco";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const entry_count = stream.readUint32();+ this.chunk_offsets = [];+ if (this.version === 0) for (let i = 0; i < entry_count; i++) this.chunk_offsets.push(stream.readUint32());+ }+ /** @bundle writings/stco.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 4 + 4 * this.chunk_offsets.length;+ this.writeHeader(stream);+ stream.writeUint32(this.chunk_offsets.length);+ stream.writeUint32Array(this.chunk_offsets);+ }+ /** @bundle box-unpack.js */+ unpack(samples) {+ for (let i = 0; i < this.chunk_offsets.length; i++) samples[i].offset = this.chunk_offsets[i];+ }+};++//#endregion+//#region src/boxes/sthd.ts+var sthdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SubtitleMediaHeaderBox";+ }+ static {+ this.fourcc = "sthd";+ }+};++//#endregion+//#region src/boxes/stsc.ts+var stscBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SampleToChunkBox";+ }+ static {+ this.fourcc = "stsc";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const entry_count = stream.readUint32();+ this.first_chunk = [];+ this.samples_per_chunk = [];+ this.sample_description_index = [];+ if (this.version === 0) for (let i = 0; i < entry_count; i++) {+ this.first_chunk.push(stream.readUint32());+ this.samples_per_chunk.push(stream.readUint32());+ this.sample_description_index.push(stream.readUint32());+ }+ }+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 4 + 12 * this.first_chunk.length;+ this.writeHeader(stream);+ stream.writeUint32(this.first_chunk.length);+ for (let i = 0; i < this.first_chunk.length; i++) {+ stream.writeUint32(this.first_chunk[i]);+ stream.writeUint32(this.samples_per_chunk[i]);+ stream.writeUint32(this.sample_description_index[i]);+ }+ }+ unpack(samples) {+ let l = 0;+ let m = 0;+ for (let i = 0; i < this.first_chunk.length; i++) for (let j = 0; j < (i + 1 < this.first_chunk.length ? this.first_chunk[i + 1] : Infinity); j++) {+ m++;+ for (let k = 0; k < this.samples_per_chunk[i]; k++) {+ if (samples[l]) {+ samples[l].description_index = this.sample_description_index[i];+ samples[l].chunk_index = m;+ } else return;+ l++;+ }+ }+ }+};++//#endregion+//#region src/boxes/stsd.ts+var stsdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SampleDescriptionBox";+ }+ static {+ this.fourcc = "stsd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.entries = [];+ const entryCount = stream.readUint32();+ for (let i = 1; i <= entryCount; i++) {+ const ret = parseOneBox(stream, true, this.size - (stream.getPosition() - this.start));+ if (ret.code === 1) {+ let box;+ if (ret.type in BoxRegistry.sampleEntry) {+ box = new BoxRegistry.sampleEntry[ret.type](ret.size);+ box.hdr_size = ret.hdr_size;+ box.start = ret.start;+ } else {+ Log.warn("BoxParser", `Unknown sample entry type: '${ret.type}'`);+ box = new SampleEntry(ret.size, ret.hdr_size, ret.start);+ box.type = ret.type;+ }+ if (box.write === SampleEntry.prototype.write) {+ Log.info("BoxParser", "SampleEntry " + box.type + " box writing not yet implemented, keeping unparsed data in memory for later write");+ box.parseDataAndRewind(stream);+ }+ box.parse(stream);+ this.entries.push(box);+ } else return;+ }+ }+ /** @bundle writing/stsd.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 0;+ this.writeHeader(stream);+ stream.writeUint32(this.entries.length);+ this.size += 4;+ for (let i = 0; i < this.entries.length; i++) {+ this.entries[i].write(stream);+ this.size += this.entries[i].size;+ }+ Log.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size);+ stream.adjustUint32(this.sizePosition, this.size);+ }+};++//#endregion+//#region src/boxes/stsz.ts+var stszBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SampleSizeBox";+ }+ static {+ this.fourcc = "stsz";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.sample_sizes = [];+ if (this.version === 0) {+ this.sample_size = stream.readUint32();+ this.sample_count = stream.readUint32();+ for (let i = 0; i < this.sample_count; i++) if (this.sample_size === 0) this.sample_sizes.push(stream.readUint32());+ else this.sample_sizes[i] = this.sample_size;+ }+ }+ /** @bundle writing/stsz.js */+ write(stream) {+ let constant = true;+ this.version = 0;+ this.flags = 0;+ if (this.sample_sizes.length > 0 && this.sample_size === 0) constant = false;+ this.size = 8;+ if (!constant) this.size += 4 * this.sample_sizes.length;+ this.writeHeader(stream);+ stream.writeUint32(this.sample_size);+ stream.writeUint32(this.sample_sizes.length);+ if (!constant) stream.writeUint32Array(this.sample_sizes);+ }+ /** @bundle box-unpack.js */+ unpack(samples) {+ for (let i = 0; i < this.sample_sizes.length; i++) samples[i].size = this.sample_sizes[i];+ }+};++//#endregion+//#region src/boxes/stts.ts+var sttsBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TimeToSampleBox";+ this.sample_counts = [];+ this.sample_deltas = [];+ }+ static {+ this.fourcc = "stts";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const entry_count = stream.readUint32();+ this.sample_counts.length = 0;+ this.sample_deltas.length = 0;+ if (this.version === 0) for (let i = 0; i < entry_count; i++) {+ this.sample_counts.push(stream.readUint32());+ let delta = stream.readInt32();+ if (delta < 0) {+ Log.warn("BoxParser", "File uses negative stts sample delta, using value 1 instead, sync may be lost!");+ delta = 1;+ }+ this.sample_deltas.push(delta);+ }+ }+ /** @bundle writing/stts.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 4 + 8 * this.sample_counts.length;+ this.writeHeader(stream);+ stream.writeUint32(this.sample_counts.length);+ for (let i = 0; i < this.sample_counts.length; i++) {+ stream.writeUint32(this.sample_counts[i]);+ stream.writeUint32(this.sample_deltas[i]);+ }+ }+ /** @bundle box-unpack.js */+ unpack(samples) {+ let k = 0;+ for (let i = 0; i < this.sample_counts.length; i++) for (let j = 0; j < this.sample_counts[i]; j++) {+ if (k === 0) samples[k].dts = 0;+ else samples[k].dts = samples[k - 1].dts + this.sample_deltas[i];+ k++;+ }+ }+};++//#endregion+//#region src/boxes/tfdt.ts+var tfdtBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackFragmentBaseMediaDecodeTimeBox";+ }+ static {+ this.fourcc = "tfdt";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 1) this.baseMediaDecodeTime = stream.readUint64();+ else this.baseMediaDecodeTime = stream.readUint32();+ }+ /** @bundle writing/tdft.js */+ write(stream) {+ const useVersion1 = this.baseMediaDecodeTime > MAX_UINT32 || this.version === 1;+ this.version = useVersion1 ? 1 : 0;+ this.size = 4;+ this.size += useVersion1 ? 4 : 0;+ this.flags = 0;+ this.writeHeader(stream);+ if (useVersion1) stream.writeUint64(this.baseMediaDecodeTime);+ else stream.writeUint32(this.baseMediaDecodeTime);+ }+};++//#endregion+//#region src/boxes/tfhd.ts+var tfhdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackFragmentHeaderBox";+ }+ static {+ this.fourcc = "tfhd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ let readBytes = 0;+ this.track_id = stream.readUint32();+ if (this.size - this.hdr_size > readBytes && this.flags & 1) {+ this.base_data_offset = stream.readUint64();+ readBytes += 8;+ } else this.base_data_offset = 0;+ if (this.size - this.hdr_size > readBytes && this.flags & 2) {+ this.default_sample_description_index = stream.readUint32();+ readBytes += 4;+ } else this.default_sample_description_index = 0;+ if (this.size - this.hdr_size > readBytes && this.flags & 8) {+ this.default_sample_duration = stream.readUint32();+ readBytes += 4;+ } else this.default_sample_duration = 0;+ if (this.size - this.hdr_size > readBytes && this.flags & 16) {+ this.default_sample_size = stream.readUint32();+ readBytes += 4;+ } else this.default_sample_size = 0;+ if (this.size - this.hdr_size > readBytes && this.flags & 32) {+ this.default_sample_flags = stream.readUint32();+ readBytes += 4;+ } else this.default_sample_flags = 0;+ }+ /** @bundle writing/tfhd.js */+ write(stream) {+ this.version = 0;+ this.size = 4;+ if (this.flags & 1) this.size += 8;+ if (this.flags & 2) this.size += 4;+ if (this.flags & 8) this.size += 4;+ if (this.flags & 16) this.size += 4;+ if (this.flags & 32) this.size += 4;+ this.writeHeader(stream);+ stream.writeUint32(this.track_id);+ if (this.flags & 1) stream.writeUint64(this.base_data_offset);+ if (this.flags & 2) stream.writeUint32(this.default_sample_description_index);+ if (this.flags & 8) stream.writeUint32(this.default_sample_duration);+ if (this.flags & 16) stream.writeUint32(this.default_sample_size);+ if (this.flags & 32) stream.writeUint32(this.default_sample_flags);+ }+};++//#endregion+//#region src/boxes/tkhd.ts+var tkhdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackHeaderBox";+ this.layer = 0;+ this.alternate_group = 0;+ }+ static {+ this.fourcc = "tkhd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 1) {+ this.creation_time = stream.readUint64();+ this.modification_time = stream.readUint64();+ this.track_id = stream.readUint32();+ stream.readUint32();+ this.duration = stream.readUint64();+ } else {+ this.creation_time = stream.readUint32();+ this.modification_time = stream.readUint32();+ this.track_id = stream.readUint32();+ stream.readUint32();+ this.duration = stream.readUint32();+ }+ stream.readUint32Array(2);+ this.layer = stream.readInt16();+ this.alternate_group = stream.readInt16();+ this.volume = stream.readInt16() >> 8;+ stream.readUint16();+ this.matrix = stream.readInt32Array(9);+ this.width = stream.readUint32();+ this.height = stream.readUint32();+ }+ write(stream) {+ const useVersion1 = this.modification_time > MAX_UINT32 || this.creation_time > MAX_UINT32 || this.duration > MAX_UINT32 || this.version === 1;+ this.version = useVersion1 ? 1 : 0;+ this.size = 80;+ this.size += useVersion1 ? 12 : 0;+ this.flags = this.flags ?? 3;+ this.writeHeader(stream);+ if (useVersion1) {+ stream.writeUint64(this.creation_time);+ stream.writeUint64(this.modification_time);+ stream.writeUint32(this.track_id);+ stream.writeUint32(0);+ stream.writeUint64(this.duration);+ } else {+ stream.writeUint32(this.creation_time);+ stream.writeUint32(this.modification_time);+ stream.writeUint32(this.track_id);+ stream.writeUint32(0);+ stream.writeUint32(this.duration);+ }+ stream.writeUint32Array([0, 0]);+ stream.writeInt16(this.layer);+ stream.writeInt16(this.alternate_group);+ stream.writeInt16(this.volume << 8);+ stream.writeInt16(0);+ stream.writeInt32Array(this.matrix);+ stream.writeUint32(this.width);+ stream.writeUint32(this.height);+ }+ /** @bundle box-print.js */+ print(output) {+ super.printHeader(output);+ output.log(output.indent + "creation_time: " + this.creation_time);+ output.log(output.indent + "modification_time: " + this.modification_time);+ output.log(output.indent + "track_id: " + this.track_id);+ output.log(output.indent + "duration: " + this.duration);+ output.log(output.indent + "volume: " + (this.volume >> 8));+ output.log(output.indent + "matrix: " + this.matrix.join(", "));+ output.log(output.indent + "layer: " + this.layer);+ output.log(output.indent + "alternate_group: " + this.alternate_group);+ output.log(output.indent + "width: " + this.width);+ output.log(output.indent + "height: " + this.height);+ }+};++//#endregion+//#region src/boxes/trex.ts+var trexBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackExtendsBox";+ }+ static {+ this.fourcc = "trex";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.track_id = stream.readUint32();+ this.default_sample_description_index = stream.readUint32();+ this.default_sample_duration = stream.readUint32();+ this.default_sample_size = stream.readUint32();+ this.default_sample_flags = stream.readUint32();+ }+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 20;+ this.writeHeader(stream);+ stream.writeUint32(this.track_id);+ stream.writeUint32(this.default_sample_description_index);+ stream.writeUint32(this.default_sample_duration);+ stream.writeUint32(this.default_sample_size);+ stream.writeUint32(this.default_sample_flags);+ }+};++//#endregion+//#region src/boxes/trun.ts+var trunBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackRunBox";+ this.sample_duration = [];+ this.sample_size = [];+ this.sample_flags = [];+ this.sample_composition_time_offset = [];+ }+ static {+ this.fourcc = "trun";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ let readBytes = 0;+ this.sample_count = stream.readUint32();+ readBytes += 4;+ if (this.size - this.hdr_size > readBytes && this.flags & 1) {+ this.data_offset = stream.readInt32();+ readBytes += 4;+ } else this.data_offset = 0;+ if (this.size - this.hdr_size > readBytes && this.flags & 4) {+ this.first_sample_flags = stream.readUint32();+ readBytes += 4;+ } else this.first_sample_flags = 0;+ this.sample_duration = [];+ this.sample_size = [];+ this.sample_flags = [];+ this.sample_composition_time_offset = [];+ if (this.size - this.hdr_size > readBytes) for (let i = 0; i < this.sample_count; i++) {+ if (this.flags & 256) this.sample_duration[i] = stream.readUint32();+ if (this.flags & 512) this.sample_size[i] = stream.readUint32();+ if (this.flags & 1024) this.sample_flags[i] = stream.readUint32();+ if (this.flags & 2048) if (this.version === 0) this.sample_composition_time_offset[i] = stream.readUint32();+ else this.sample_composition_time_offset[i] = stream.readInt32();+ }+ }+ /** @bundle writing/trun.js */+ write(stream) {+ this.size = 4;+ if (this.flags & 1) this.size += 4;+ if (this.flags & 4) this.size += 4;+ if (this.flags & 256) this.size += 4 * this.sample_duration.length;+ if (this.flags & 512) this.size += 4 * this.sample_size.length;+ if (this.flags & 1024) this.size += 4 * this.sample_flags.length;+ if (this.flags & 2048) this.size += 4 * this.sample_composition_time_offset.length;+ this.writeHeader(stream);+ stream.writeUint32(this.sample_count);+ if (this.flags & 1) {+ this.data_offset_position = stream.getPosition();+ stream.writeInt32(this.data_offset);+ }+ if (this.flags & 4) stream.writeUint32(this.first_sample_flags);+ for (let i = 0; i < this.sample_count; i++) {+ if (this.flags & 256) stream.writeUint32(this.sample_duration[i]);+ if (this.flags & 512) stream.writeUint32(this.sample_size[i]);+ if (this.flags & 1024) stream.writeUint32(this.sample_flags[i]);+ if (this.flags & 2048) if (this.version === 0) stream.writeUint32(this.sample_composition_time_offset[i]);+ else stream.writeInt32(this.sample_composition_time_offset[i]);+ }+ }+};++//#endregion+//#region src/boxes/url.ts+var urlBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "DataEntryUrlBox";+ }+ static {+ this.fourcc = "url ";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.flags !== 1) this.location = stream.readCString();+ }+ /** @bundle writing/url.js */+ write(stream) {+ this.version = 0;+ if (this.location) {+ this.flags = 0;+ this.size = this.location.length + 1;+ } else {+ this.flags = 1;+ this.size = 0;+ }+ this.writeHeader(stream);+ if (this.location) stream.writeCString(this.location);+ }+};++//#endregion+//#region src/boxes/vmhd.ts+var vmhdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "VideoMediaHeaderBox";+ }+ static {+ this.fourcc = "vmhd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.graphicsmode = stream.readUint16();+ this.opcolor = stream.readUint16Array(3);+ }+ /** @bundle writing/vmhd.js */+ write(stream) {+ this.version = 0;+ this.size = 8;+ this.writeHeader(stream);+ stream.writeUint16(this.graphicsmode);+ stream.writeUint16Array(this.opcolor);+ }+};++//#endregion+//#region src/isofile.ts+var SampleGroupInfo = class {+ constructor(grouping_type, grouping_type_parameter, sbgp) {+ this.grouping_type = grouping_type;+ this.grouping_type_parameter = grouping_type_parameter;+ this.sbgp = sbgp;+ this.last_sample_in_run = -1;+ this.entry_index = -1;+ }+};+var ISOFile = class ISOFile {+ constructor(stream, discardMdatData = true) {+ this.boxes = [];+ this.mdats = [];+ this.moofs = [];+ this.isProgressive = false;+ this.moovStartFound = false;+ this.moovStartSent = false;+ this.readySent = false;+ this.sampleListBuilt = false;+ this.fragmentedTracks = [];+ this.extractedTracks = [];+ this.isFragmentationInitialized = false;+ this.sampleProcessingStarted = false;+ this.nextMoofNumber = 0;+ this.itemListBuilt = false;+ this.sidxSent = false;+ this.items = [];+ this.entity_groups = [];+ this.itemsDataSize = 0;+ this.lastMoofIndex = 0;+ this.samplesDataSize = 0;+ this.lastBoxStartPosition = 0;+ this.nextParsePosition = 0;+ this.discardMdatData = true;+ this.discardMdatData = discardMdatData;+ if (stream) {+ this.stream = stream;+ this.parse();+ } else this.stream = new MultiBufferStream();+ this.stream.isofile = this;+ }+ setSegmentOptions(id, user, opts) {+ const { sizePerSegment = Number.MAX_SAFE_INTEGER, rapAlignement = true, normalizeAudioSampleEntriesForMSE = true } = opts;+ let nbSamples = opts.nbSamples ?? opts.nbSamplesPerFragment ?? 1e3;+ const nbSamplesPerFragment = opts.nbSamplesPerFragment ?? nbSamples;+ if (nbSamples <= 0 || nbSamplesPerFragment <= 0 || sizePerSegment <= 0) {+ Log.error("ISOFile", `Invalid segment options: nbSamples=${nbSamples}, nbSamplesPerFragment=${nbSamplesPerFragment}, sizePerSegment=${sizePerSegment}`);+ return;+ }+ if (nbSamples < nbSamplesPerFragment) {+ Log.warn("ISOFile", `nbSamples (${nbSamples}) is less than nbSamplesPerFragment (${nbSamplesPerFragment}), setting nbSamples to nbSamplesPerFragment`);+ nbSamples = nbSamplesPerFragment;+ }+ if (this.fragmentedTracks.some((track) => track.nb_samples !== nbSamples)) {+ Log.error("ISOFile", `Cannot set segment options for track ${id}: nbSamples (${nbSamples}) does not match existing tracks`);+ return;+ }+ const trak = this.getTrackById(id);+ if (trak) {+ const fragTrack = {+ id,+ user,+ trak,+ segmentStream: void 0,+ nb_samples: nbSamples,+ nb_samples_per_fragment: nbSamplesPerFragment,+ size_per_segment: sizePerSegment,+ rapAlignement,+ normalizeAudioSampleEntriesForMSE,+ state: {+ lastFragmentSampleNumber: 0,+ lastSegmentSampleNumber: 0,+ accumulatedSize: 0+ }+ };+ this.fragmentedTracks.push(fragTrack);+ trak.nextSample = 0;+ }+ if (this.discardMdatData) Log.warn("ISOFile", "Segmentation options set but discardMdatData is true, samples will not be segmented");+ }+ unsetSegmentOptions(id) {+ let index = -1;+ for (let i = 0; i < this.fragmentedTracks.length; i++) if (this.fragmentedTracks[i].id === id) index = i;+ if (index > -1) this.fragmentedTracks.splice(index, 1);+ }+ setExtractionOptions(id, user, { nbSamples: nb_samples = 1e3 } = {}) {+ const trak = this.getTrackById(id);+ if (trak) {+ this.extractedTracks.push({+ id,+ user,+ trak,+ nb_samples,+ samples: []+ });+ trak.nextSample = 0;+ }+ if (this.discardMdatData) Log.warn("ISOFile", "Extraction options set but discardMdatData is true, samples will not be extracted");+ }+ unsetExtractionOptions(id) {+ let index = -1;+ for (let i = 0; i < this.extractedTracks.length; i++) if (this.extractedTracks[i].id === id) index = i;+ if (index > -1) this.extractedTracks.splice(index, 1);+ }+ parse() {+ const parseBoxHeadersOnly = false;+ if (this.restoreParsePosition) {+ if (!this.restoreParsePosition()) return;+ }+ while (true) if (this.hasIncompleteMdat && this.hasIncompleteMdat()) if (this.processIncompleteMdat()) continue;+ else return;+ else {+ if (this.saveParsePosition) this.saveParsePosition();+ const ret = parseOneBox(this.stream, parseBoxHeadersOnly);+ if (ret.code === 0) if (this.processIncompleteBox) if (this.processIncompleteBox(ret)) continue;+ else return;+ else return;+ else if (ret.code === 1) {+ const box = ret.box;+ this.boxes.push(box);+ if (box.type === "uuid") {+ if (this[box.uuid] !== void 0) Log.warn("ISOFile", "Duplicate Box of uuid: " + box.uuid + ", overriding previous occurrence");+ this[box.uuid] = box;+ } else switch (box.type) {+ case "mdat":+ this.mdats.push(box);+ this.transferMdatData(box);+ break;+ case "moof":+ this.moofs.push(box);+ break;+ case "free":+ case "skip": break;+ case "moov":+ this.moovStartFound = true;+ if (this.mdats.length === 0) this.isProgressive = true;+ default:+ if (this[box.type] !== void 0) if (Array.isArray(this[box.type + "s"])) {+ Log.info("ISOFile", `Found multiple boxes of type ${box.type} in ISOFile, adding to array`);+ this[box.type + "s"].push(box);+ } else {+ Log.warn("ISOFile", `Found multiple boxes of type ${box.type} but no array exists. Creating array dynamically.`);+ this[box.type + "s"] = [this[box.type], box];+ }+ else {+ this[box.type] = box;+ if (Array.isArray(this[box.type + "s"])) this[box.type + "s"].push(box);+ }+ break;+ }+ if (this.updateUsedBytes) this.updateUsedBytes(box, ret);+ } else if (ret.code === -1) {+ Log.error("ISOFile", `Invalid data found while parsing box of type '${ret.type}' at position ${ret.start}. Aborting parsing.`, this);+ break;+ }+ }+ }+ checkBuffer(ab) {+ if (!ab) throw new Error("Buffer must be defined and non empty");+ if (ab.byteLength === 0) {+ Log.warn("ISOFile", "Ignoring empty buffer (fileStart: " + ab.fileStart + ")");+ this.stream.logBufferLevel();+ return false;+ }+ Log.info("ISOFile", "Processing buffer (fileStart: " + ab.fileStart + ")");+ ab.usedBytes = 0;+ this.stream.insertBuffer(ab);+ this.stream.logBufferLevel();+ if (!this.stream.initialized()) {+ Log.warn("ISOFile", "Not ready to start parsing");+ return false;+ }+ return true;+ }+ /**+ * Processes a new ArrayBuffer (with a fileStart property)+ * Returns the next expected file position, or undefined if not ready to parse+ */+ appendBuffer(ab, last) {+ let nextFileStart;+ if (!this.checkBuffer(ab)) return;+ this.parse();+ if (this.moovStartFound && !this.moovStartSent) {+ this.moovStartSent = true;+ if (this.onMoovStart) this.onMoovStart();+ }+ if (this.moov) {+ if (!this.sampleListBuilt) {+ this.buildSampleLists();+ this.sampleListBuilt = true;+ }+ this.updateSampleLists();+ if (this.onReady && !this.readySent) {+ this.readySent = true;+ this.onReady(this.getInfo());+ }+ this.processSamples(last);+ if (this.nextSeekPosition) {+ nextFileStart = this.nextSeekPosition;+ this.nextSeekPosition = void 0;+ } else nextFileStart = this.nextParsePosition;+ if (this.stream.getEndFilePositionAfter) nextFileStart = this.stream.getEndFilePositionAfter(nextFileStart);+ } else if (this.nextParsePosition) nextFileStart = this.nextParsePosition;+ else nextFileStart = 0;+ if (this.sidx) {+ if (this.onSidx && !this.sidxSent) {+ this.onSidx(this.sidx);+ this.sidxSent = true;+ }+ }+ if (this.meta) {+ if (this.flattenItemInfo && !this.itemListBuilt) {+ this.flattenItemInfo();+ this.itemListBuilt = true;+ }+ if (this.processItems) this.processItems(this.onItem);+ }+ if (this.stream.cleanBuffers) {+ Log.info("ISOFile", "Done processing buffer (fileStart: " + ab.fileStart + ") - next buffer to fetch should have a fileStart position of " + nextFileStart);+ this.stream.logBufferLevel();+ this.stream.cleanBuffers();+ this.stream.logBufferLevel(true);+ Log.info("ISOFile", "Sample data size in memory: " + this.getAllocatedSampleDataSize());+ }+ return nextFileStart;+ }+ getFragmentDuration() {+ const mvex = this.getBox("mvex");+ if (!mvex) return;+ if (mvex.mehd) return {+ num: mvex.mehd.fragment_duration,+ den: this.moov.mvhd.timescale+ };+ const traks = this.getBoxes("trak", false);+ let maximum = {+ num: 0,+ den: 1+ };+ for (const trak of traks) {+ const duration = trak.samples_duration;+ const timescale = trak.mdia.mdhd.timescale;+ if (duration && timescale) {+ if (duration / timescale > maximum.num / maximum.den) maximum = {+ num: duration,+ den: timescale+ };+ }+ }+ return maximum;+ }+ getInfo() {+ if (!this.moov) return {+ hasMoov: false,+ mime: ""+ };+ const _1904 = (/* @__PURE__ */ new Date("1904-01-01T00:00:00Z")).getTime();+ const isFragmented = this.getBox("mvex") !== void 0;+ const movie = {+ hasMoov: true,+ duration: this.moov.mvhd.duration,+ timescale: this.moov.mvhd.timescale,+ isFragmented,+ fragment_duration: this.getFragmentDuration(),+ isProgressive: this.isProgressive,+ hasIOD: this.moov.iods !== void 0,+ brands: [this.ftyp.major_brand].concat(this.ftyp.compatible_brands),+ created: new Date(_1904 + this.moov.mvhd.creation_time * 1e3),+ modified: new Date(_1904 + this.moov.mvhd.modification_time * 1e3),+ tracks: [],+ audioTracks: [],+ videoTracks: [],+ subtitleTracks: [],+ metadataTracks: [],+ hintTracks: [],+ otherTracks: [],+ mime: ""+ };+ for (let i = 0; i < this.moov.traks.length; i++) {+ const trak = this.moov.traks[i];+ const sample_desc = trak.mdia.minf.stbl.stsd.entries[0];+ const size = trak.samples_size;+ const track_timescale = trak.mdia.mdhd.timescale;+ const samples_duration = trak.samples_duration;+ const track = {+ samples_duration,+ bitrate: size * 8 * track_timescale / samples_duration,+ size,+ timescale: track_timescale,+ alternate_group: trak.tkhd.alternate_group,+ codec: sample_desc.getCodec(),+ created: new Date(_1904 + trak.tkhd.creation_time * 1e3),+ cts_shift: trak.mdia.minf.stbl.cslg,+ duration: trak.mdia.mdhd.duration,+ id: trak.tkhd.track_id,+ kind: trak.udta && trak.udta.kinds.length ? trak.udta.kinds[0] : {+ schemeURI: "",+ value: ""+ },+ language: trak.mdia.elng ? trak.mdia.elng.extended_language : trak.mdia.mdhd.languageString,+ layer: trak.tkhd.layer,+ matrix: trak.tkhd.matrix,+ modified: new Date(_1904 + trak.tkhd.modification_time * 1e3),+ movie_duration: trak.tkhd.duration,+ movie_timescale: movie.timescale,+ name: trak.mdia.hdlr.name,+ nb_samples: trak.samples.length,+ references: [],+ track_height: trak.tkhd.height / 65536,+ track_width: trak.tkhd.width / 65536,+ volume: trak.tkhd.volume+ };+ movie.tracks.push(track);+ if (trak.tref) for (let j = 0; j < trak.tref.references.length; j++) track.references.push({+ type: trak.tref.references[j].type,+ track_ids: trak.tref.references[j].track_ids+ });+ if (trak.edts !== void 0 && trak.edts.elst !== void 0) track.edits = trak.edts.elst.entries;+ if (sample_desc instanceof AudioSampleEntry) {+ track.type = "audio";+ movie.audioTracks.push(track);+ track.audio = {+ sample_rate: sample_desc.getSampleRate(),+ channel_count: sample_desc.getChannelCount(),+ sample_size: sample_desc.getSampleSize()+ };+ } else if (sample_desc instanceof VisualSampleEntry) {+ track.type = "video";+ movie.videoTracks.push(track);+ track.video = {+ width: sample_desc.getWidth(),+ height: sample_desc.getHeight()+ };+ } else if (sample_desc instanceof SubtitleSampleEntry) {+ track.type = "subtitles";+ movie.subtitleTracks.push(track);+ } else if (sample_desc instanceof HintSampleEntry) {+ track.type = "metadata";+ movie.hintTracks.push(track);+ } else if (sample_desc instanceof MetadataSampleEntry) {+ track.type = "metadata";+ movie.metadataTracks.push(track);+ } else {+ track.type = "metadata";+ movie.otherTracks.push(track);+ }+ }+ if (movie.videoTracks && movie.videoTracks.length > 0) movie.mime += "video/mp4; codecs=\"";+ else if (movie.audioTracks && movie.audioTracks.length > 0) movie.mime += "audio/mp4; codecs=\"";+ else movie.mime += "application/mp4; codecs=\"";+ for (let i = 0; i < movie.tracks.length; i++) {+ if (i !== 0) movie.mime += ",";+ movie.mime += movie.tracks[i].codec;+ }+ movie.mime += "\"; profiles=\"";+ movie.mime += this.ftyp.compatible_brands.join();+ movie.mime += "\"";+ return movie;+ }+ setNextSeekPositionFromSample(sample) {+ if (!sample) return;+ if (this.nextSeekPosition) this.nextSeekPosition = Math.min(sample.offset + sample.alreadyRead, this.nextSeekPosition);+ else this.nextSeekPosition = sample.offset + sample.alreadyRead;+ }+ processSamples(last) {+ if (!this.sampleProcessingStarted) return;+ if (this.isFragmentationInitialized && this.onSegment !== void 0) {+ const consumedTracks = /* @__PURE__ */ new Set();+ while (consumedTracks.size < this.fragmentedTracks.length && this.fragmentedTracks.some((track) => track.trak.nextSample < track.trak.samples.length) && this.sampleProcessingStarted) for (const fragTrak of this.fragmentedTracks) {+ const trak = fragTrak.trak;+ if (!consumedTracks.has(fragTrak.id)) {+ const sample = trak.nextSample < trak.samples.length ? this.getSample(trak, trak.nextSample) : void 0;+ if (!sample) {+ this.setNextSeekPositionFromSample(trak.samples[trak.nextSample]);+ consumedTracks.add(fragTrak.id);+ continue;+ }+ fragTrak.state.accumulatedSize += sample.size;+ const sampleNum = trak.nextSample + 1;+ const isFragmentOverdue = sampleNum - fragTrak.state.lastFragmentSampleNumber > fragTrak.nb_samples_per_fragment;+ const isSegmentOverdue = sampleNum - fragTrak.state.lastSegmentSampleNumber > fragTrak.nb_samples;+ let isFragmentBoundary = isFragmentOverdue || sampleNum % fragTrak.nb_samples_per_fragment === 0;+ let isSegmentBoundary = isSegmentOverdue || sampleNum % fragTrak.nb_samples === 0;+ let isSizeBoundary = fragTrak.state.accumulatedSize >= fragTrak.size_per_segment;+ const isRAP = !fragTrak.rapAlignement || sample.is_sync;+ const isFlush = last || trak.nextSample + 1 >= trak.samples.length;+ if (isFlush && !isRAP) Log.warn("ISOFile", "Flushing track #" + fragTrak.id + " at sample #" + trak.nextSample + " which is not a RAP, this may lead to playback issues");+ isFragmentBoundary = isFragmentBoundary && isRAP;+ isSegmentBoundary = isSegmentBoundary && isRAP;+ isSizeBoundary = isSizeBoundary && isRAP;+ if (isFragmentBoundary || isSizeBoundary || isFlush) {+ if (isFragmentOverdue) Log.warn("ISOFile", "Fragment on track #" + fragTrak.id + " is overdue, creating it with samples [" + fragTrak.state.lastFragmentSampleNumber + ", " + trak.nextSample + "]");+ else Log.debug("ISOFile", "Creating media fragment on track #" + fragTrak.id + " for samples [" + fragTrak.state.lastFragmentSampleNumber + ", " + trak.nextSample + "]");+ const result = this.createFragment(fragTrak.id, fragTrak.state.lastFragmentSampleNumber, trak.nextSample, fragTrak.segmentStream);+ if (result) {+ fragTrak.segmentStream = result;+ fragTrak.state.lastFragmentSampleNumber = trak.nextSample + 1;+ } else {+ consumedTracks.add(fragTrak.id);+ continue;+ }+ }+ if (isSegmentBoundary || isSizeBoundary || isFlush) {+ if (isSegmentOverdue) Log.warn("ISOFile", "Segment on track #" + fragTrak.id + " is overdue, sending it with samples [" + Math.max(0, trak.nextSample - fragTrak.nb_samples) + ", " + (trak.nextSample - 1) + "]");+ else Log.info("ISOFile", "Sending fragmented data on track #" + fragTrak.id + " for samples [" + Math.max(0, trak.nextSample - fragTrak.nb_samples) + ", " + (trak.nextSample - 1) + "]");+ Log.info("ISOFile", "Sample data size in memory: " + this.getAllocatedSampleDataSize());+ if (this.onSegment) this.onSegment(fragTrak.id, fragTrak.user, fragTrak.segmentStream.buffer, trak.nextSample + 1, last || trak.nextSample + 1 >= trak.samples.length);+ fragTrak.segmentStream = void 0;+ fragTrak.state.accumulatedSize = 0;+ fragTrak.state.lastSegmentSampleNumber = trak.nextSample + 1;+ }+ trak.nextSample++;+ }+ }+ }+ if (this.onSamples !== void 0) for (let i = 0; i < this.extractedTracks.length; i++) {+ const extractTrak = this.extractedTracks[i];+ const trak = extractTrak.trak;+ while (trak.nextSample < trak.samples.length && this.sampleProcessingStarted) {+ Log.debug("ISOFile", "Exporting on track #" + extractTrak.id + " sample #" + trak.nextSample);+ const sample = this.getSample(trak, trak.nextSample);+ if (sample) {+ trak.nextSample++;+ extractTrak.samples.push(sample);+ } else {+ this.setNextSeekPositionFromSample(trak.samples[trak.nextSample]);+ break;+ }+ if (trak.nextSample % extractTrak.nb_samples === 0 || trak.nextSample >= trak.samples.length) {+ Log.debug("ISOFile", "Sending samples on track #" + extractTrak.id + " for sample " + trak.nextSample);+ if (this.onSamples) this.onSamples(extractTrak.id, extractTrak.user, extractTrak.samples);+ extractTrak.samples = [];+ if (extractTrak !== this.extractedTracks[i]) break;+ }+ }+ }+ }+ getBox(type) {+ const result = this.getBoxes(type, true);+ return result.length ? result[0] : void 0;+ }+ getBoxes(type, returnEarly) {+ const result = [];+ const sweep = (root) => {+ if (root instanceof Box && root.type && root.type === type) result.push(root);+ const inner = [];+ if (root["boxes"]) inner.push(...root.boxes);+ if (root["entries"]) inner.push(...root["entries"]);+ if (root["item_infos"]) inner.push(...root["item_infos"]);+ if (root["references"]) inner.push(...root["references"]);+ for (const box of inner) {+ if (result.length && returnEarly) return;+ sweep(box);+ }+ };+ sweep(this);+ return result;+ }+ getTrackSamplesInfo(track_id) {+ const track = this.getTrackById(track_id);+ if (track) return track.samples;+ }+ getTrackSample(track_id, number) {+ const track = this.getTrackById(track_id);+ return this.getSample(track, number);+ }+ releaseUsedSamples(id, sampleNum) {+ let size = 0;+ const trak = this.getTrackById(id);+ if (!trak.lastValidSample) trak.lastValidSample = 0;+ for (let i = trak.lastValidSample; i < sampleNum; i++) size += this.releaseSample(trak, i);+ Log.info("ISOFile", "Track #" + id + " released samples up to " + sampleNum + " (released size: " + size + ", remaining: " + this.samplesDataSize + ")");+ trak.lastValidSample = sampleNum;+ }+ start() {+ this.sampleProcessingStarted = true;+ this.processSamples(false);+ }+ stop() {+ this.sampleProcessingStarted = false;+ }+ flush() {+ Log.info("ISOFile", "Flushing remaining samples");+ this.updateSampleLists();+ this.processSamples(true);+ this.stream.cleanBuffers();+ this.stream.logBufferLevel(true);+ }+ seekTrack(time, useRap, trak) {+ let rap_seek_sample_num = 0;+ let seek_sample_num = 0;+ let timescale;+ if (trak.samples.length === 0) {+ Log.info("ISOFile", "No sample in track, cannot seek! Using time " + Log.getDurationString(0, 1) + " and offset: 0");+ return {+ offset: 0,+ time: 0+ };+ }+ for (let j = 0; j < trak.samples.length; j++) {+ const sample = trak.samples[j];+ if (j === 0) {+ seek_sample_num = 0;+ timescale = sample.timescale;+ } else if (sample.cts > time * sample.timescale) {+ seek_sample_num = j - 1;+ break;+ }+ if (useRap && sample.is_sync) rap_seek_sample_num = j;+ }+ if (useRap) seek_sample_num = rap_seek_sample_num;+ time = trak.samples[seek_sample_num].cts;+ trak.nextSample = seek_sample_num;+ this.resetFragmentedTrackStateAfterSeek(trak, seek_sample_num);+ this.resetExtractedTrackStateAfterSeek(trak);+ while (trak.samples[seek_sample_num].alreadyRead === trak.samples[seek_sample_num].size) {+ if (!trak.samples[seek_sample_num + 1]) break;+ seek_sample_num++;+ }+ const seek_offset = trak.samples[seek_sample_num].offset + trak.samples[seek_sample_num].alreadyRead;+ Log.info("ISOFile", "Seeking to " + (useRap ? "RAP" : "") + " sample #" + trak.nextSample + " on track " + trak.tkhd.track_id + ", time " + Log.getDurationString(time, timescale) + " and offset: " + seek_offset);+ return {+ offset: seek_offset,+ time: time / timescale+ };+ }+ resetFragmentedTrackStateAfterSeek(trak, seekSampleNumber) {+ const fragTrack = this.fragmentedTracks.find((t) => t.trak === trak);+ if (!fragTrack) return;+ fragTrack.state.lastFragmentSampleNumber = seekSampleNumber;+ fragTrack.state.lastSegmentSampleNumber = seekSampleNumber;+ fragTrack.state.accumulatedSize = 0;+ fragTrack.segmentStream = void 0;+ }+ resetExtractedTrackStateAfterSeek(trak) {+ const extractTrack = this.extractedTracks.find((t) => t.trak === trak);+ if (!extractTrack) return;+ extractTrack.samples = [];+ }+ getTrackDuration(trak) {+ if (!trak.samples) return Infinity;+ const sample = trak.samples[trak.samples.length - 1];+ return (sample.cts + sample.duration) / sample.timescale;+ }+ seek(time, useRap) {+ const moov = this.moov;+ let seek_info = {+ offset: Infinity,+ time: Infinity+ };+ if (!this.moov) throw new Error("Cannot seek: moov not received!");+ else {+ for (let i = 0; i < moov.traks.length; i++) {+ const trak = moov.traks[i];+ if (time > this.getTrackDuration(trak)) continue;+ const trak_seek_info = this.seekTrack(time, useRap, trak);+ if (trak_seek_info.offset < seek_info.offset) seek_info.offset = trak_seek_info.offset;+ if (trak_seek_info.time < seek_info.time) seek_info.time = trak_seek_info.time;+ }+ Log.info("ISOFile", "Seeking at time " + Log.getDurationString(seek_info.time, 1) + " needs a buffer with a fileStart position of " + seek_info.offset);+ if (seek_info.offset === Infinity) seek_info = {+ offset: this.nextParsePosition,+ time: 0+ };+ else seek_info.offset = this.stream.getEndFilePositionAfter(seek_info.offset);+ Log.info("ISOFile", "Adjusted seek position (after checking data already in buffer): " + seek_info.offset);+ return seek_info;+ }+ }+ equal(b) {+ let box_index = 0;+ while (box_index < this.boxes.length && box_index < b.boxes.length) {+ const a_box = this.boxes[box_index];+ const b_box = b.boxes[box_index];+ if (!boxEqual(a_box, b_box)) return false;+ box_index++;+ }+ return true;+ }+ /**+ * Rewrite the entire file+ * @bundle isofile-write.js+ */+ write(outstream) {+ for (let i = 0; i < this.boxes.length; i++) this.boxes[i].write(outstream);+ }+ /** @bundle isofile-write.js */+ createFragment(track_id, sampleStart, sampleEnd, existingStream) {+ if (sampleEnd < sampleStart) {+ Log.warn("ISOFile", `Skipping fragment creation on track #${track_id}: invalid sample range [${sampleStart}, ${sampleEnd}]`);+ return existingStream || new DataStream();+ }+ const samples = [];+ for (let i = sampleStart; i <= sampleEnd; i++) {+ const trak = this.getTrackById(track_id);+ const sample = this.getSample(trak, i);+ if (!sample) {+ this.setNextSeekPositionFromSample(trak.samples[i]);+ return;+ }+ samples.push(sample);+ }+ const stream = existingStream || new DataStream();+ const moof = this.createMoof(samples);+ moof.write(stream);+ moof.trafs[0].truns[0].data_offset = moof.size + 8;+ Log.debug("MP4Box", "Adjusting data_offset with new value " + moof.trafs[0].truns[0].data_offset);+ stream.adjustUint32(moof.trafs[0].truns[0].data_offset_position, moof.trafs[0].truns[0].data_offset);+ const mdat = new mdatBox();+ mdat.stream = new MultiBufferStream();+ let offset = 0;+ for (const sample of samples) if (sample.data) {+ const mp4Buffer = MP4BoxBuffer.fromArrayBuffer(sample.data.buffer, offset);+ mdat.stream.insertBuffer(mp4Buffer);+ offset += sample.data.byteLength;+ }+ mdat.write(stream);+ return stream;+ }+ /**+ * Modify the file and create the initialization segment+ * @bundle isofile-write.js+ */+ static writeInitializationSegment(ftyp, moov, total_duration, normalizeAudioSampleEntryTrackIds) {+ Log.debug("ISOFile", "Generating initialization segment");+ const stream = new DataStream();+ ftyp.write(stream);+ const restoreCallbacks = ISOFile.normalizeAudioSampleEntriesForMSEFragmentedInit(moov.traks, normalizeAudioSampleEntryTrackIds);+ try {+ const mvex = moov.addBox(new mvexBox());+ if (total_duration) {+ const mehd = mvex.addBox(new mehdBox());+ mehd.fragment_duration = total_duration;+ }+ for (let i = 0; i < moov.traks.length; i++) {+ const trex = mvex.addBox(new trexBox());+ trex.track_id = moov.traks[i].tkhd.track_id;+ trex.default_sample_description_index = 1;+ trex.default_sample_duration = moov.traks[i].samples[0]?.duration ?? 0;+ trex.default_sample_size = 0;+ trex.default_sample_flags = 65536;+ }+ moov.write(stream);+ } finally {+ for (let i = restoreCallbacks.length - 1; i >= 0; i--) restoreCallbacks[i]();+ }+ return stream.buffer;+ }+ /** @bundle isofile-write.js */+ save(name) {+ const stream = new DataStream();+ stream.isofile = this;+ this.write(stream);+ return stream.save(name);+ }+ /** @bundle isofile-write.js */+ getBuffer() {+ const stream = new DataStream();+ stream.isofile = this;+ this.write(stream);+ return stream;+ }+ /** @bundle isofile-write.js */+ static normalizeAudioSampleEntriesForMSEFragmentedInit(traks, normalizeAudioSampleEntryTrackIds) {+ const restoreCallbacks = [];+ for (const trak of traks) {+ if (!normalizeAudioSampleEntryTrackIds?.has(trak.tkhd.track_id)) continue;+ for (const sampleEntry of trak.mdia.minf.stbl.stsd?.entries ?? []) {+ if (!(sampleEntry instanceof mp4aSampleEntry)) continue;+ const esds = sampleEntry.wave?.esds;+ if (sampleEntry.esds || !esds) continue;+ const previousEsds = sampleEntry.esds;+ const previousWave = sampleEntry.wave;+ const previousBoxes = sampleEntry.boxes;+ restoreCallbacks.push(() => {+ sampleEntry.esds = previousEsds;+ sampleEntry.wave = previousWave;+ sampleEntry.boxes = previousBoxes;+ });+ const boxesWithoutWave = Array.isArray(sampleEntry.boxes) ? sampleEntry.boxes.filter((box) => box?.type !== "wave" && box?.type !== "esds") : [];+ sampleEntry.esds = esds;+ sampleEntry.boxes = [...boxesWithoutWave, esds];+ sampleEntry.wave = void 0;+ }+ }+ return restoreCallbacks;+ }+ initializeSegmentation(mode) {+ if (!this.onSegment) Log.warn("MP4Box", "No segmentation callback set!");+ if (mode !== void 0 && mode !== "combined" && mode !== "per-track") throw new Error(`Invalid segmentation mode: ${mode}`);+ if (!this.isFragmentationInitialized) {+ this.isFragmentationInitialized = true;+ this.resetTables();+ }+ const tracksToInitialize = [];+ for (const fragmentedTrack of this.fragmentedTracks) {+ const trak = this.getTrackById(fragmentedTrack.id);+ if (!trak) {+ Log.warn("ISOFile", `Track with id ${fragmentedTrack.id} not found, skipping fragmentation initialization`);+ continue;+ }+ tracksToInitialize.push({+ id: fragmentedTrack.id,+ user: fragmentedTrack.user,+ trak+ });+ }+ const fragmentDuration = this.moov?.mvex?.mehd?.fragment_duration;+ const normalizeAudioSampleEntryTrackIds = new Set(this.fragmentedTracks.filter((track) => track.normalizeAudioSampleEntriesForMSE !== false).map((track) => track.id));+ if (mode === "per-track") return tracksToInitialize.map(({ id, user, trak }) => {+ const moov = new moovBox();+ moov.addBox(this.moov.mvhd);+ moov.addBox(trak);+ return {+ id,+ user,+ buffer: ISOFile.writeInitializationSegment(this.ftyp, moov, fragmentDuration, normalizeAudioSampleEntryTrackIds)+ };+ });+ const moov = new moovBox();+ moov.addBox(this.moov.mvhd);+ for (const track of tracksToInitialize) moov.addBox(track.trak);+ return {+ tracks: tracksToInitialize.map(({ id, user }) => ({+ id,+ user+ })),+ buffer: ISOFile.writeInitializationSegment(this.ftyp, moov, fragmentDuration, normalizeAudioSampleEntryTrackIds)+ };+ }+ /**+ * Resets all sample tables+ * @bundle isofile-sample-processing.js+ */+ resetTables() {+ this.initial_duration = this.moov.mvhd.duration;+ this.moov.mvhd.duration = 0;+ for (let i = 0; i < this.moov.traks.length; i++) {+ const trak = this.moov.traks[i];+ trak.tkhd.duration = 0;+ trak.mdia.mdhd.duration = 0;+ const stco = trak.mdia.minf.stbl.stco || trak.mdia.minf.stbl.co64;+ stco.chunk_offsets = [];+ const stsc = trak.mdia.minf.stbl.stsc;+ stsc.first_chunk = [];+ stsc.samples_per_chunk = [];+ stsc.sample_description_index = [];+ const stsz = trak.mdia.minf.stbl.stsz || trak.mdia.minf.stbl.stz2;+ stsz.sample_sizes = [];+ const stts = trak.mdia.minf.stbl.stts;+ stts.sample_counts = [];+ stts.sample_deltas = [];+ const ctts = trak.mdia.minf.stbl.ctts;+ if (ctts) {+ ctts.sample_counts = [];+ ctts.sample_offsets = [];+ }+ const stss = trak.mdia.minf.stbl.stss;+ const k = trak.mdia.minf.stbl.boxes.indexOf(stss);+ if (k !== -1) trak.mdia.minf.stbl.boxes[k] = void 0;+ }+ }+ /** @bundle isofile-sample-processing.js */+ static initSampleGroups(trak, traf, sbgps, trak_sgpds, traf_sgpds) {+ if (traf) traf.sample_groups_info = [];+ if (!trak.sample_groups_info) trak.sample_groups_info = [];+ for (let k = 0; k < sbgps.length; k++) {+ const sample_group_key = sbgps[k].grouping_type + "/" + sbgps[k].grouping_type_parameter;+ const sample_group_info = new SampleGroupInfo(sbgps[k].grouping_type, sbgps[k].grouping_type_parameter, sbgps[k]);+ if (traf) traf.sample_groups_info[sample_group_key] = sample_group_info;+ if (!trak.sample_groups_info[sample_group_key]) trak.sample_groups_info[sample_group_key] = sample_group_info;+ for (let l = 0; l < trak_sgpds.length; l++) if (trak_sgpds[l].grouping_type === sbgps[k].grouping_type) {+ sample_group_info.description = trak_sgpds[l];+ sample_group_info.description.used = true;+ }+ if (traf_sgpds) {+ for (let l = 0; l < traf_sgpds.length; l++) if (traf_sgpds[l].grouping_type === sbgps[k].grouping_type) {+ sample_group_info.fragment_description = traf_sgpds[l];+ sample_group_info.fragment_description.used = true;+ sample_group_info.is_fragment = true;+ }+ }+ }+ if (!traf) {+ for (let k = 0; k < trak_sgpds.length; k++) if (!trak_sgpds[k].used && trak_sgpds[k].version >= 2) {+ const sample_group_key = trak_sgpds[k].grouping_type + "/0";+ const sample_group_info = new SampleGroupInfo(trak_sgpds[k].grouping_type, 0);+ if (!trak.sample_groups_info[sample_group_key]) trak.sample_groups_info[sample_group_key] = sample_group_info;+ }+ } else if (traf_sgpds) {+ for (let k = 0; k < traf_sgpds.length; k++) if (!traf_sgpds[k].used && traf_sgpds[k].version >= 2) {+ const sample_group_key = traf_sgpds[k].grouping_type + "/0";+ const sample_group_info = new SampleGroupInfo(traf_sgpds[k].grouping_type, 0);+ sample_group_info.is_fragment = true;+ if (!traf.sample_groups_info[sample_group_key]) traf.sample_groups_info[sample_group_key] = sample_group_info;+ }+ }+ }+ /** @bundle isofile-sample-processing.js */+ static setSampleGroupProperties(trak, sample, sample_number, sample_groups_info) {+ sample.sample_groups = [];+ for (const k in sample_groups_info) {+ sample.sample_groups[k] = {+ grouping_type: sample_groups_info[k].grouping_type,+ grouping_type_parameter: sample_groups_info[k].grouping_type_parameter+ };+ if (sample_number >= sample_groups_info[k].last_sample_in_run) {+ if (sample_groups_info[k].last_sample_in_run < 0) sample_groups_info[k].last_sample_in_run = 0;+ sample_groups_info[k].entry_index++;+ if (sample_groups_info[k].entry_index <= sample_groups_info[k].sbgp.entries.length - 1) sample_groups_info[k].last_sample_in_run += sample_groups_info[k].sbgp.entries[sample_groups_info[k].entry_index].sample_count;+ }+ if (sample_groups_info[k].entry_index <= sample_groups_info[k].sbgp.entries.length - 1) sample.sample_groups[k].group_description_index = sample_groups_info[k].sbgp.entries[sample_groups_info[k].entry_index].group_description_index;+ else sample.sample_groups[k].group_description_index = -1;+ if (sample.sample_groups[k].group_description_index !== 0) {+ let description;+ if (sample_groups_info[k].fragment_description) description = sample_groups_info[k].fragment_description;+ else description = sample_groups_info[k].description;+ if (sample.sample_groups[k].group_description_index > 0) {+ let index;+ if (sample.sample_groups[k].group_description_index > 65535) index = (sample.sample_groups[k].group_description_index >> 16) - 1;+ else index = sample.sample_groups[k].group_description_index - 1;+ if (description && index >= 0) sample.sample_groups[k].description = description.entries[index];+ } else if (description && description.version >= 2) {+ if (description.default_group_description_index > 0) sample.sample_groups[k].description = description.entries[description.default_group_description_index - 1];+ }+ }+ }+ }+ /** @bundle isofile-sample-processing.js */+ static process_sdtp(sdtp, sample, number) {+ if (!sample) return;+ if (sdtp) {+ sample.is_leading = sdtp.is_leading[number];+ sample.depends_on = sdtp.sample_depends_on[number];+ sample.is_depended_on = sdtp.sample_is_depended_on[number];+ sample.has_redundancy = sdtp.sample_has_redundancy[number];+ } else {+ sample.is_leading = 0;+ sample.depends_on = 0;+ sample.is_depended_on = 0;+ sample.has_redundancy = 0;+ }+ }+ buildSampleLists() {+ for (let i = 0; i < this.moov.traks.length; i++) this.buildTrakSampleLists(this.moov.traks[i]);+ }+ buildTrakSampleLists(trak) {+ let j;+ let chunk_run_index;+ let chunk_index;+ let last_chunk_in_run;+ let offset_in_chunk;+ let last_sample_in_chunk;+ trak.samples = [];+ trak.samples_duration = 0;+ trak.samples_size = 0;+ const stco = trak.mdia.minf.stbl.stco || trak.mdia.minf.stbl.co64;+ const stsc = trak.mdia.minf.stbl.stsc;+ const stsz = trak.mdia.minf.stbl.stsz || trak.mdia.minf.stbl.stz2;+ const stts = trak.mdia.minf.stbl.stts;+ const ctts = trak.mdia.minf.stbl.ctts;+ const stss = trak.mdia.minf.stbl.stss;+ const stsd = trak.mdia.minf.stbl.stsd;+ const subs = trak.mdia.minf.stbl.subs;+ const stdp = trak.mdia.minf.stbl.stdp;+ const sbgps = trak.mdia.minf.stbl.sbgps;+ const sgpds = trak.mdia.minf.stbl.sgpds;+ let last_sample_in_stts_run = -1;+ let stts_run_index = -1;+ let last_sample_in_ctts_run = -1;+ let ctts_run_index = -1;+ let last_stss_index = 0;+ let subs_entry_index = 0;+ let last_subs_sample_index = 0;+ ISOFile.initSampleGroups(trak, void 0, sbgps, sgpds);+ if (typeof stsz === "undefined") return;+ for (j = 0; j < stsz.sample_sizes.length; j++) {+ const sample = {+ number: j,+ track_id: trak.tkhd.track_id,+ timescale: trak.mdia.mdhd.timescale,+ alreadyRead: 0,+ size: stsz.sample_sizes[j]+ };+ trak.samples[j] = sample;+ trak.samples_size += sample.size;+ if (j === 0) {+ chunk_index = 1;+ chunk_run_index = 0;+ sample.chunk_index = chunk_index;+ sample.chunk_run_index = chunk_run_index;+ last_sample_in_chunk = stsc.samples_per_chunk[chunk_run_index];+ offset_in_chunk = 0;+ if (chunk_run_index + 1 < stsc.first_chunk.length) last_chunk_in_run = stsc.first_chunk[chunk_run_index + 1] - 1;+ else last_chunk_in_run = Infinity;+ } else if (j < last_sample_in_chunk) {+ sample.chunk_index = chunk_index;+ sample.chunk_run_index = chunk_run_index;+ } else {+ chunk_index++;+ sample.chunk_index = chunk_index;+ offset_in_chunk = 0;+ if (chunk_index <= last_chunk_in_run) {} else {+ chunk_run_index++;+ if (chunk_run_index + 1 < stsc.first_chunk.length) last_chunk_in_run = stsc.first_chunk[chunk_run_index + 1] - 1;+ else last_chunk_in_run = Infinity;+ }+ sample.chunk_run_index = chunk_run_index;+ last_sample_in_chunk += stsc.samples_per_chunk[chunk_run_index];+ }+ sample.description_index = stsc.sample_description_index[sample.chunk_run_index] - 1;+ sample.description = stsd.entries[sample.description_index];+ sample.offset = stco.chunk_offsets[sample.chunk_index - 1] + offset_in_chunk;+ offset_in_chunk += sample.size;+ if (j > last_sample_in_stts_run) {+ stts_run_index++;+ if (last_sample_in_stts_run < 0) last_sample_in_stts_run = 0;+ last_sample_in_stts_run += stts.sample_counts[stts_run_index];+ }+ if (j > 0) {+ trak.samples[j - 1].duration = stts.sample_deltas[stts_run_index];+ trak.samples_duration += trak.samples[j - 1].duration;+ sample.dts = trak.samples[j - 1].dts + trak.samples[j - 1].duration;+ } else sample.dts = 0;+ if (ctts) {+ if (j >= last_sample_in_ctts_run) {+ ctts_run_index++;+ if (last_sample_in_ctts_run < 0) last_sample_in_ctts_run = 0;+ last_sample_in_ctts_run += ctts.sample_counts[ctts_run_index];+ }+ sample.cts = trak.samples[j].dts + ctts.sample_offsets[ctts_run_index];+ } else sample.cts = sample.dts;+ if (stss) {+ if (j === stss.sample_numbers[last_stss_index] - 1) {+ sample.is_sync = true;+ last_stss_index++;+ } else {+ sample.is_sync = false;+ sample.degradation_priority = 0;+ }+ if (subs) {+ if (subs.entries[subs_entry_index].sample_delta + last_subs_sample_index === j + 1) {+ sample.subsamples = subs.entries[subs_entry_index].subsamples;+ last_subs_sample_index += subs.entries[subs_entry_index].sample_delta;+ subs_entry_index++;+ }+ }+ } else sample.is_sync = true;+ ISOFile.process_sdtp(trak.mdia.minf.stbl.sdtp, sample, sample.number);+ if (stdp) sample.degradation_priority = stdp.priority[j];+ else sample.degradation_priority = 0;+ if (subs) {+ if (subs.entries[subs_entry_index].sample_delta + last_subs_sample_index === j) {+ sample.subsamples = subs.entries[subs_entry_index].subsamples;+ last_subs_sample_index += subs.entries[subs_entry_index].sample_delta;+ }+ }+ if (sbgps.length > 0 || sgpds.length > 0) ISOFile.setSampleGroupProperties(trak, sample, j, trak.sample_groups_info);+ }+ if (j > 0) {+ trak.samples[j - 1].duration = Math.max(trak.mdia.mdhd.duration - trak.samples[j - 1].dts, 0);+ trak.samples_duration += trak.samples[j - 1].duration;+ }+ }+ /**+ * Update sample list when new 'moof' boxes are received+ * @bundle isofile-sample-processing.js+ */+ updateSampleLists() {+ let default_sample_description_index;+ let default_sample_duration;+ let default_sample_size;+ let default_sample_flags;+ let last_run_position;+ if (this.moov === void 0) return;+ while (this.lastMoofIndex < this.moofs.length) {+ const box = this.moofs[this.lastMoofIndex];+ this.lastMoofIndex++;+ if (box.type === "moof") {+ const moof = box;+ for (let i = 0; i < moof.trafs.length; i++) {+ const traf = moof.trafs[i];+ const trak = this.getTrackById(traf.tfhd.track_id);+ const trex = this.getTrexById(traf.tfhd.track_id);+ if (traf.tfhd.flags & 2) default_sample_description_index = traf.tfhd.default_sample_description_index;+ else default_sample_description_index = trex ? trex.default_sample_description_index : 1;+ if (traf.tfhd.flags & 8) default_sample_duration = traf.tfhd.default_sample_duration;+ else default_sample_duration = trex ? trex.default_sample_duration : 0;+ if (traf.tfhd.flags & 16) default_sample_size = traf.tfhd.default_sample_size;+ else default_sample_size = trex ? trex.default_sample_size : 0;+ if (traf.tfhd.flags & 32) default_sample_flags = traf.tfhd.default_sample_flags;+ else default_sample_flags = trex ? trex.default_sample_flags : 0;+ traf.sample_number = 0;+ if (traf.sbgps.length > 0) ISOFile.initSampleGroups(trak, traf, traf.sbgps, trak.mdia.minf.stbl.sgpds, traf.sgpds);+ for (let j = 0; j < traf.truns.length; j++) {+ const trun = traf.truns[j];+ for (let k = 0; k < trun.sample_count; k++) {+ const description_index = default_sample_description_index - 1;+ let sample_flags = default_sample_flags;+ if (trun.flags & 1024) sample_flags = trun.sample_flags[k];+ else if (k === 0 && trun.flags & 4) sample_flags = trun.first_sample_flags;+ let size = default_sample_size;+ if (trun.flags & 512) size = trun.sample_size[k];+ trak.samples_size += size;+ let duration = default_sample_duration;+ if (trun.flags & 256) duration = trun.sample_duration[k];+ trak.samples_duration += duration;+ let dts;+ if (trak.first_traf_merged || k > 0) dts = trak.samples[trak.samples.length - 1].dts + trak.samples[trak.samples.length - 1].duration;+ else {+ if (traf.tfdt) dts = traf.tfdt.baseMediaDecodeTime;+ else dts = 0;+ trak.first_traf_merged = true;+ }+ let cts = dts;+ if (trun.flags & 2048) cts = dts + trun.sample_composition_time_offset[k];+ const bdop = traf.tfhd.flags & 1 ? true : false;+ const dbim = traf.tfhd.flags & 131072 ? true : false;+ const dop = trun.flags & 1 ? true : false;+ let bdo = 0;+ if (!bdop) if (!dbim) if (j === 0) bdo = moof.start;+ else bdo = last_run_position;+ else bdo = moof.start;+ else bdo = traf.tfhd.base_data_offset;+ let offset;+ if (j === 0 && k === 0) if (dop) offset = bdo + trun.data_offset;+ else offset = bdo;+ else offset = last_run_position;+ last_run_position = offset + size;+ const number_in_traf = traf.sample_number;+ traf.sample_number++;+ const sample = {+ cts,+ description_index,+ description: trak.mdia.minf.stbl.stsd.entries[description_index],+ dts,+ duration,+ moof_number: this.lastMoofIndex,+ number_in_traf,+ number: trak.samples.length,+ offset,+ size,+ timescale: trak.mdia.mdhd.timescale,+ track_id: trak.tkhd.track_id,+ is_sync: sample_flags >> 16 & 1 ? false : true,+ is_leading: sample_flags >> 26 & 3,+ depends_on: sample_flags >> 24 & 3,+ is_depended_on: sample_flags >> 22 & 3,+ has_redundancy: sample_flags >> 20 & 3,+ degradation_priority: sample_flags & 65535+ };+ traf.first_sample_index = trak.samples.length;+ trak.samples.push(sample);+ if (traf.sbgps.length > 0 || traf.sgpds.length > 0 || trak.mdia.minf.stbl.sbgps.length > 0 || trak.mdia.minf.stbl.sgpds.length > 0) ISOFile.setSampleGroupProperties(trak, sample, sample.number_in_traf, traf.sample_groups_info);+ }+ }+ if (traf.subs) {+ trak.has_fragment_subsamples = true;+ let sample_index = traf.first_sample_index;+ for (let j = 0; j < traf.subs.entries.length; j++) {+ sample_index += traf.subs.entries[j].sample_delta;+ const sample = trak.samples[sample_index - 1];+ sample.subsamples = traf.subs.entries[j].subsamples;+ }+ }+ }+ }+ }+ }+ /**+ * Try to get sample data for a given sample:+ * returns null if not found+ * returns the same sample if already requested+ *+ * @bundle isofile-sample-processing.js+ */+ getSample(trak, sampleNum) {+ const sample = trak.samples[sampleNum];+ if (!this.moov) return;+ if (!sample.data) {+ sample.data = new Uint8Array(sample.size);+ sample.alreadyRead = 0;+ this.samplesDataSize += sample.size;+ Log.debug("ISOFile", "Allocating sample #" + sampleNum + " on track #" + trak.tkhd.track_id + " of size " + sample.size + " (total: " + this.samplesDataSize + ")");+ } else if (sample.alreadyRead === sample.size) return sample;+ while (true) {+ let stream = this.stream;+ let index = stream.findPosition(true, sample.offset + sample.alreadyRead, false);+ let buffer;+ let fileStart;+ if (index > -1) {+ buffer = stream.buffers[index];+ fileStart = buffer.fileStart;+ } else for (const mdat of this.mdats) {+ if (!mdat.stream) {+ Log.debug("ISOFile", "mdat stream not yet fully read for #" + this.mdats.indexOf(mdat) + " mdat");+ continue;+ }+ index = mdat.stream.findPosition(true, sample.offset + sample.alreadyRead - mdat.start - mdat.hdr_size, false);+ if (index > -1) {+ stream = mdat.stream;+ buffer = mdat.stream.buffers[index];+ fileStart = mdat.start + mdat.hdr_size + buffer.fileStart;+ break;+ }+ }+ if (buffer) {+ const lengthAfterStart = buffer.byteLength - (sample.offset + sample.alreadyRead - fileStart);+ if (sample.size - sample.alreadyRead <= lengthAfterStart) {+ Log.debug("ISOFile", "Getting sample #" + sampleNum + " data (alreadyRead: " + sample.alreadyRead + " offset: " + (sample.offset + sample.alreadyRead - fileStart) + " read size: " + (sample.size - sample.alreadyRead) + " full size: " + sample.size + ")");+ DataStream.memcpy(sample.data.buffer, sample.alreadyRead, buffer, sample.offset + sample.alreadyRead - fileStart, sample.size - sample.alreadyRead);+ buffer.usedBytes += sample.size - sample.alreadyRead;+ stream.logBufferLevel();+ sample.alreadyRead = sample.size;+ return sample;+ } else {+ if (lengthAfterStart === 0) return;+ Log.debug("ISOFile", "Getting sample #" + sampleNum + " partial data (alreadyRead: " + sample.alreadyRead + " offset: " + (sample.offset + sample.alreadyRead - fileStart) + " read size: " + lengthAfterStart + " full size: " + sample.size + ")");+ DataStream.memcpy(sample.data.buffer, sample.alreadyRead, buffer, sample.offset + sample.alreadyRead - fileStart, lengthAfterStart);+ sample.alreadyRead += lengthAfterStart;+ buffer.usedBytes += lengthAfterStart;+ stream.logBufferLevel();+ }+ } else return;+ }+ }+ /**+ * Release the memory used to store the data of the sample+ *+ * @bundle isofile-sample-processing.js+ */+ releaseSample(trak, sampleNum) {+ const sample = trak.samples[sampleNum];+ if (sample.data) {+ this.samplesDataSize -= sample.size;+ sample.data = void 0;+ sample.alreadyRead = 0;+ return sample.size;+ } else return 0;+ }+ /** @bundle isofile-sample-processing.js */+ getAllocatedSampleDataSize() {+ return this.samplesDataSize;+ }+ /**+ * Builds the MIME Type 'codecs' sub-parameters for the whole file+ *+ * @bundle isofile-sample-processing.js+ */+ getCodecs() {+ let codecs = "";+ for (let i = 0; i < this.moov.traks.length; i++) {+ const trak = this.moov.traks[i];+ if (i > 0) codecs += ",";+ codecs += trak.mdia.minf.stbl.stsd.entries[0].getCodec();+ }+ return codecs;+ }+ /**+ * Helper function+ *+ * @bundle isofile-sample-processing.js+ */+ getTrexById(id) {+ if (!this.moov || !this.moov.mvex) return;+ for (let i = 0; i < this.moov.mvex.trexs.length; i++) {+ const trex = this.moov.mvex.trexs[i];+ if (trex.track_id === id) return trex;+ }+ }+ /**+ * Helper function+ *+ * @bundle isofile-sample-processing.js+ */+ getTrackById(id) {+ if (!this.moov) return;+ for (let j = 0; j < this.moov.traks.length; j++) {+ const trak = this.moov.traks[j];+ if (trak.tkhd.track_id === id) return trak;+ }+ }+ /** @bundle isofile-item-processing.js */+ flattenItemInfo() {+ const items = this.items;+ const entity_groups = this.entity_groups;+ const meta = this.meta;+ if (!meta || !meta.hdlr || !meta.iinf) return;+ for (let i = 0; i < meta.iinf.item_infos.length; i++) {+ const id = meta.iinf.item_infos[i].item_ID;+ items[id] = {+ id,+ name: meta.iinf.item_infos[i].item_name,+ ref_to: [],+ content_type: meta.iinf.item_infos[i].content_type,+ content_encoding: meta.iinf.item_infos[i].content_encoding,+ item_uri_type: meta.iinf.item_infos[i].item_uri_type,+ type: meta.iinf.item_infos[i].item_type ? meta.iinf.item_infos[i].item_type : "mime",+ protection: meta.iinf.item_infos[i].item_protection_index > 0 ? meta.ipro.protections[meta.iinf.item_infos[i].item_protection_index - 1] : void 0+ };+ }+ if (meta.grpl) for (let i = 0; i < meta.grpl.boxes.length; i++) {+ const entityGroup = meta.grpl.boxes[i];+ entity_groups[entityGroup.group_id] = {+ id: entityGroup.group_id,+ entity_ids: entityGroup.entity_ids,+ type: entityGroup.type+ };+ }+ if (meta.iloc) for (let i = 0; i < meta.iloc.items.length; i++) {+ const itemloc = meta.iloc.items[i];+ const item = items[itemloc.item_ID];+ if (itemloc.data_reference_index !== 0) {+ Log.warn("Item storage with reference to other files: not supported");+ item.source = meta.dinf.boxes[itemloc.data_reference_index - 1];+ }+ item.extents = [];+ item.size = 0;+ for (let j = 0; j < itemloc.extents.length; j++) {+ item.extents[j] = {+ offset: itemloc.extents[j].extent_offset + itemloc.base_offset,+ length: itemloc.extents[j].extent_length,+ alreadyRead: 0+ };+ if (itemloc.construction_method === 1) item.extents[j].offset += meta.idat.start + meta.idat.hdr_size;+ item.size += item.extents[j].length;+ }+ }+ if (meta.pitm) {+ const id = meta.pitm.item_id;+ if (!items[id]) Log.warn("ISOFile", "Primary item_id #" + id + " does not exist in items");+ else items[id].primary = true;+ }+ if (meta.iref) for (let i = 0; i < meta.iref.references.length; i++) {+ const ref = meta.iref.references[i];+ for (let j = 0; j < ref.references.length; j++) items[ref.from_item_ID].ref_to.push({+ type: ref.type,+ id: ref.references[j]+ });+ }+ if (meta.iprp) for (let k = 0; k < meta.iprp.ipmas.length; k++) {+ const ipma = meta.iprp.ipmas[k];+ for (let i = 0; i < ipma.associations.length; i++) {+ const association = ipma.associations[i];+ const item = items[association.id] ?? entity_groups[association.id];+ if (item) {+ if (item.properties === void 0) item.properties = { boxes: [] };+ for (let j = 0; j < association.props.length; j++) {+ const propEntry = association.props[j];+ if (propEntry.property_index > 0 && propEntry.property_index - 1 < meta.iprp.ipco.boxes.length) {+ const propbox = meta.iprp.ipco.boxes[propEntry.property_index - 1];+ item.properties[propbox.type] = propbox;+ item.properties.boxes.push(propbox);+ }+ }+ }+ }+ }+ }+ /** @bundle isofile-item-processing.js */+ getItem(item_id) {+ if (!this.meta) return;+ const item = this.items[item_id];+ if (!item.data && item.size) {+ item.data = new Uint8Array(item.size);+ item.alreadyRead = 0;+ this.itemsDataSize += item.size;+ Log.debug("ISOFile", "Allocating item #" + item_id + " of size " + item.size + " (total: " + this.itemsDataSize + ")");+ } else if (item.alreadyRead === item.size) return item;+ for (let i = 0; i < item.extents.length; i++) {+ const extent = item.extents[i];+ if (extent.alreadyRead === extent.length) continue;+ else {+ const index = this.stream.findPosition(true, extent.offset + extent.alreadyRead, false);+ if (index > -1) {+ const buffer = this.stream.buffers[index];+ const lengthAfterStart = buffer.byteLength - (extent.offset + extent.alreadyRead - buffer.fileStart);+ if (extent.length - extent.alreadyRead <= lengthAfterStart) {+ Log.debug("ISOFile", "Getting item #" + item_id + " extent #" + i + " data (alreadyRead: " + extent.alreadyRead + " offset: " + (extent.offset + extent.alreadyRead - buffer.fileStart) + " read size: " + (extent.length - extent.alreadyRead) + " full extent size: " + extent.length + " full item size: " + item.size + ")");+ DataStream.memcpy(item.data.buffer, item.alreadyRead, buffer, extent.offset + extent.alreadyRead - buffer.fileStart, extent.length - extent.alreadyRead);+ if (!this.parsingMdat || this.discardMdatData) buffer.usedBytes += extent.length - extent.alreadyRead;+ this.stream.logBufferLevel();+ item.alreadyRead += extent.length - extent.alreadyRead;+ extent.alreadyRead = extent.length;+ } else {+ Log.debug("ISOFile", "Getting item #" + item_id + " extent #" + i + " partial data (alreadyRead: " + extent.alreadyRead + " offset: " + (extent.offset + extent.alreadyRead - buffer.fileStart) + " read size: " + lengthAfterStart + " full extent size: " + extent.length + " full item size: " + item.size + ")");+ DataStream.memcpy(item.data.buffer, item.alreadyRead, buffer, extent.offset + extent.alreadyRead - buffer.fileStart, lengthAfterStart);+ extent.alreadyRead += lengthAfterStart;+ item.alreadyRead += lengthAfterStart;+ if (!this.parsingMdat || this.discardMdatData) buffer.usedBytes += lengthAfterStart;+ this.stream.logBufferLevel();+ return;+ }+ } else return;+ }+ }+ if (item.alreadyRead === item.size) return item;+ }+ /**+ * Release the memory used to store the data of the item+ *+ * @bundle isofile-item-processing.js+ */+ releaseItem(item_id) {+ const item = this.items[item_id];+ if (item.data) {+ this.itemsDataSize -= item.size;+ item.data = void 0;+ item.alreadyRead = 0;+ for (let i = 0; i < item.extents.length; i++) {+ const extent = item.extents[i];+ extent.alreadyRead = 0;+ }+ return item.size;+ } else return 0;+ }+ /** @bundle isofile-item-processing.js */+ processItems(callback) {+ for (const i in this.items) {+ const item = this.items[i];+ this.getItem(item.id);+ if (callback && !item.sent) {+ callback(item);+ item.sent = true;+ item.data = void 0;+ }+ }+ }+ /** @bundle isofile-item-processing.js */+ hasItem(name) {+ for (const i in this.items) {+ const item = this.items[i];+ if (item.name === name) return item.id;+ }+ return -1;+ }+ /** @bundle isofile-item-processing.js */+ getMetaHandler() {+ if (this.meta) return this.meta.hdlr.handler;+ }+ /** @bundle isofile-item-processing.js */+ getPrimaryItem() {+ if (this.meta && this.meta.pitm) return this.getItem(this.meta.pitm.item_id);+ }+ /** @bundle isofile-item-processing.js */+ itemToFragmentedTrackFile({ itemId } = {}) {+ let item;+ if (itemId) item = this.getItem(itemId);+ else item = this.getPrimaryItem();+ if (!item) return;+ const file = new ISOFile();+ file.discardMdatData = false;+ const trackOptions = {+ type: item.type,+ description_boxes: item.properties.boxes+ };+ if (item.properties.ispe) {+ trackOptions.width = item.properties.ispe.image_width;+ trackOptions.height = item.properties.ispe.image_height;+ }+ const trackId = file.addTrack(trackOptions);+ if (trackId) {+ file.addSample(trackId, item.data);+ return file;+ }+ }+ /** @bundle isofile-advanced-parsing.js */+ processIncompleteBox(ret) {+ if (ret.type === "mdat") {+ const box = new mdatBox(ret.size);+ this.parsingMdat = box;+ this.boxes.push(box);+ this.mdats.push(box);+ box.start = ret.start;+ box.hdr_size = ret.hdr_size;+ box.original_size = ret.original_size;+ this.stream.addUsedBytes(box.hdr_size);+ this.lastBoxStartPosition = box.start + box.size;+ if (this.stream.seek(box.start + box.size, false, this.discardMdatData)) {+ this.transferMdatData();+ this.parsingMdat = void 0;+ return true;+ } else {+ if (!this.moovStartFound) this.nextParsePosition = box.start + box.size;+ else this.nextParsePosition = this.stream.findEndContiguousBuf();+ return false;+ }+ } else {+ if (ret.type === "moov") {+ this.moovStartFound = true;+ if (this.mdats.length === 0) this.isProgressive = true;+ }+ if (this.stream.mergeNextBuffer ? this.stream.mergeNextBuffer() : false) {+ this.nextParsePosition = this.stream.getEndPosition();+ return true;+ } else {+ if (!ret.type) this.nextParsePosition = this.stream.getEndPosition();+ else if (this.moovStartFound) this.nextParsePosition = this.stream.getEndPosition();+ else this.nextParsePosition = this.stream.getPosition() + ret.size;+ return false;+ }+ }+ }+ /** @bundle isofile-advanced-parsing.js */+ hasIncompleteMdat() {+ return this.parsingMdat !== void 0;+ }+ /**+ * Transfer the data of the mdat box to its stream+ * @param mdat the mdat box to use+ */+ transferMdatData(inMdat) {+ const mdat = inMdat ?? this.parsingMdat;+ if (this.discardMdatData) {+ Log.debug("ISOFile", "Discarding 'mdat' data, not transferring it to the mdat box stream");+ return;+ }+ if (!mdat) {+ Log.warn("ISOFile", "Cannot transfer 'mdat' data, no mdat box is being parsed");+ return;+ }+ const startBufferIndex = this.stream.findPosition(true, mdat.start + mdat.hdr_size, false);+ const endBufferIndex = this.stream.findPosition(true, mdat.start + mdat.size, false);+ if (startBufferIndex === -1 || endBufferIndex === -1) {+ Log.warn("ISOFile", "Cannot transfer 'mdat' data, start or end buffer not found");+ return;+ }+ mdat.stream = new MultiBufferStream();+ for (let i = startBufferIndex; i <= endBufferIndex; i++) {+ const buffer = this.stream.buffers[i];+ const startOffset = i === startBufferIndex ? mdat.start + mdat.hdr_size - buffer.fileStart : 0;+ const endOffset = i === endBufferIndex ? mdat.start + mdat.size - buffer.fileStart : buffer.byteLength;+ if (endOffset > startOffset) {+ Log.debug("ISOFile", "Transferring 'mdat' data from buffer #" + i + " (" + startOffset + " to " + endOffset + ")");+ const transferSize = endOffset - startOffset;+ const newBuffer = new MP4BoxBuffer(transferSize);+ const lastPosition = mdat.stream.getAbsoluteEndPosition();+ DataStream.memcpy(newBuffer, 0, buffer, startOffset, transferSize);+ newBuffer.fileStart = lastPosition;+ mdat.stream.insertBuffer(newBuffer);+ buffer.usedBytes += transferSize;+ }+ }+ }+ /** @bundle isofile-advanced-parsing.js */+ processIncompleteMdat() {+ const box = this.parsingMdat;+ if (this.stream.seek(box.start + box.size, false, this.discardMdatData)) {+ Log.debug("ISOFile", "Found 'mdat' end in buffered data");+ this.transferMdatData();+ this.parsingMdat = void 0;+ return true;+ } else {+ this.nextParsePosition = this.stream.findEndContiguousBuf();+ return false;+ }+ }+ /** @bundle isofile-advanced-parsing.js */+ restoreParsePosition() {+ return this.stream.seek(this.lastBoxStartPosition, true, this.discardMdatData);+ }+ /** @bundle isofile-advanced-parsing.js */+ saveParsePosition() {+ this.lastBoxStartPosition = this.stream.getPosition();+ }+ /** @bundle isofile-advanced-parsing.js */+ updateUsedBytes(box, _ret) {+ if (this.stream.addUsedBytes) if (box.type === "mdat") {+ this.stream.addUsedBytes(box.hdr_size);+ if (this.discardMdatData) this.stream.addUsedBytes(box.size - box.hdr_size);+ } else this.stream.addUsedBytes(box.size);+ }+ /** @bundle isofile-advanced-creation.js */+ addBox(box) {+ return Box.prototype.addBox.call(this, box);+ }+ /** @bundle isofile-advanced-creation.js */+ init(options = {}) {+ const ftyp = this.addBox(new ftypBox());+ ftyp.major_brand = options.brands && options.brands[0] || "iso4";+ ftyp.minor_version = 0;+ ftyp.compatible_brands = options.brands || ["iso4"];+ const moov = this.addBox(new moovBox());+ moov.addBox(new mvexBox());+ const mvhd = moov.addBox(new mvhdBox());+ mvhd.timescale = options.timescale || 600;+ mvhd.rate = options.rate || 65536;+ mvhd.creation_time = 0;+ mvhd.modification_time = 0;+ mvhd.duration = options.duration || 0;+ mvhd.volume = options.width ? 0 : 256;+ mvhd.matrix = [+ 65536,+ 0,+ 0,+ 0,+ 65536,+ 0,+ 0,+ 0,+ 1073741824+ ];+ mvhd.next_track_id = 1;+ return this;+ }+ /** @bundle isofile-advanced-creation.js */+ addTrack(_options = {}) {+ if (!this.moov) this.init(_options);+ const options = _options || {};+ options.width = options.width || 320;+ options.height = options.height || 320;+ options.id = options.id || this.moov.mvhd.next_track_id;+ options.type = options.type || "avc1";+ const trak = this.moov.addBox(new trakBox());+ this.moov.mvhd.next_track_id = options.id + 1;+ const tkhd = trak.addBox(new tkhdBox());+ tkhd.flags = 1 | 2 | 4;+ tkhd.creation_time = 0;+ tkhd.modification_time = 0;+ tkhd.track_id = options.id;+ tkhd.duration = options.duration || 0;+ tkhd.layer = options.layer || 0;+ tkhd.alternate_group = 0;+ tkhd.volume = 1;+ tkhd.matrix = [+ 65536,+ 0,+ 0,+ 0,+ 65536,+ 0,+ 0,+ 0,+ 1073741824+ ];+ tkhd.width = options.width << 16;+ tkhd.height = options.height << 16;+ const mdia = trak.addBox(new mdiaBox());+ const mdhd = mdia.addBox(new mdhdBox());+ mdhd.creation_time = 0;+ mdhd.modification_time = 0;+ mdhd.timescale = options.timescale || 1;+ mdhd.duration = options.media_duration || 0;+ mdhd.language = options.language || "und";+ const hdlr = mdia.addBox(new hdlrBox());+ hdlr.handler = options.hdlr || "vide";+ hdlr.name = options.name || "Track created with MP4Box.js";+ const elng = mdia.addBox(new elngBox());+ elng.extended_language = options.language || "fr-FR";+ const minf = mdia.addBox(new minfBox());+ const sampleEntry = BoxRegistry.sampleEntry[options.type];+ if (!sampleEntry) return;+ const sample_description_entry = new sampleEntry();+ sample_description_entry.data_reference_index = 1;+ if (sample_description_entry instanceof VisualSampleEntry) {+ const sde = sample_description_entry;+ const vmhd = minf.addBox(new vmhdBox());+ vmhd.graphicsmode = 0;+ vmhd.opcolor = [+ 0,+ 0,+ 0+ ];+ sde.width = options.width;+ sde.height = options.height;+ sde.horizresolution = 72 << 16;+ sde.vertresolution = 72 << 16;+ sde.frame_count = 1;+ sde.compressorname = options.type + " Compressor";+ sde.depth = 24;+ if (options.avcDecoderConfigRecord) sde.addBox(new avcCBox(options.avcDecoderConfigRecord.byteLength)).parse(new DataStream(options.avcDecoderConfigRecord));+ else if (options.hevcDecoderConfigRecord) sde.addBox(new hvcCBox(options.hevcDecoderConfigRecord.byteLength)).parse(new DataStream(options.hevcDecoderConfigRecord));+ } else if (sample_description_entry instanceof AudioSampleEntry) {+ const sde = sample_description_entry;+ const smhd = minf.addBox(new smhdBox());+ smhd.balance = options.balance || 0;+ sde.channel_count = options.channel_count || 2;+ sde.samplesize = options.samplesize || 16;+ sde.samplerate = options.samplerate || 65536;+ } else if (sample_description_entry instanceof HintSampleEntry) minf.addBox(new hmhdBox());+ else if (sample_description_entry instanceof SubtitleSampleEntry) {+ minf.addBox(new sthdBox());+ if (sample_description_entry instanceof stppSampleEntry) {+ sample_description_entry.namespace = options.namespace || "nonamespace";+ sample_description_entry.schema_location = options.schema_location || "";+ sample_description_entry.auxiliary_mime_types = options.auxiliary_mime_types || "";+ }+ } else if (sample_description_entry instanceof MetadataSampleEntry) minf.addBox(new nmhdBox());+ else if (sample_description_entry instanceof SystemSampleEntry) minf.addBox(new nmhdBox());+ else minf.addBox(new nmhdBox());+ if (options.description) sample_description_entry.addBox.call(sample_description_entry, options.description);+ if (options.description_boxes) options.description_boxes.forEach(function(b) {+ sample_description_entry.addBox.call(sample_description_entry, b);+ });+ const dref = minf.addBox(new dinfBox()).addBox(new drefBox());+ const url = new urlBox();+ url.flags = 1;+ dref.addEntry(url);+ const stbl = minf.addBox(new stblBox());+ stbl.addBox(new stsdBox()).addEntry(sample_description_entry);+ const stts = stbl.addBox(new sttsBox());+ stts.sample_counts = [];+ stts.sample_deltas = [];+ const stsc = stbl.addBox(new stscBox());+ stsc.first_chunk = [];+ stsc.samples_per_chunk = [];+ stsc.sample_description_index = [];+ const stco = stbl.addBox(new stcoBox());+ stco.chunk_offsets = [];+ const stsz = stbl.addBox(new stszBox());+ stsz.sample_sizes = [];+ const trex = this.moov.mvex.addBox(new trexBox());+ trex.track_id = options.id;+ trex.default_sample_description_index = options.default_sample_description_index || 1;+ trex.default_sample_duration = options.default_sample_duration || 0;+ trex.default_sample_size = options.default_sample_size || 0;+ trex.default_sample_flags = options.default_sample_flags || 0;+ this.buildTrakSampleLists(trak);+ return options.id;+ }+ /** @bundle isofile-advanced-creation.js */+ addSample(track_id, data, { sample_description_index, duration = 1, cts = 0, dts = 0, is_sync = false, is_leading = 0, depends_on = 0, is_depended_on = 0, has_redundancy = 0, degradation_priority = 0, subsamples, offset = 0 } = {}) {+ const trak = this.getTrackById(track_id);+ if (trak === void 0) return;+ const descriptionIndex = sample_description_index ? sample_description_index - 1 : 0;+ const sample = {+ number: trak.samples.length,+ track_id: trak.tkhd.track_id,+ timescale: trak.mdia.mdhd.timescale,+ description_index: descriptionIndex,+ description: trak.mdia.minf.stbl.stsd.entries[descriptionIndex],+ data,+ size: data.byteLength,+ alreadyRead: data.byteLength,+ duration,+ cts,+ dts,+ is_sync,+ is_leading,+ depends_on,+ is_depended_on,+ has_redundancy,+ degradation_priority,+ offset,+ subsamples+ };+ trak.samples.push(sample);+ trak.samples_size += sample.size;+ trak.samples_duration += sample.duration;+ if (trak.first_dts === void 0) trak.first_dts = dts;+ this.processSamples();+ const moof = this.addBox(this.createMoof([sample]));+ moof.computeSize();+ moof.trafs[0].truns[0].data_offset = moof.size + 8;+ const mdat = this.addBox(new mdatBox());+ mdat.data = new Uint8Array(data);+ return sample;+ }+ /** @bundle isofile-advanced-creation.js */+ createMoof(samples) {+ if (samples.length === 0) return;+ if (samples.some((s) => s.track_id !== samples[0].track_id)) throw new Error("Cannot create moof for samples from different tracks: " + samples.map((s) => s.track_id).join(", "));+ const trackId = samples[0].track_id;+ const trak = this.getTrackById(trackId);+ if (!trak) throw new Error("Cannot create moof for non-existing track: " + trackId);+ const moof = new moofBox();+ const mfhd = moof.addBox(new mfhdBox());+ mfhd.sequence_number = ++this.nextMoofNumber;+ const traf = moof.addBox(new trafBox());+ const tfhd = traf.addBox(new tfhdBox());+ tfhd.track_id = trackId;+ tfhd.flags = TFHD_FLAG_DEFAULT_BASE_IS_MOOF;+ const tfdt = traf.addBox(new tfdtBox());+ tfdt.baseMediaDecodeTime = samples[0].dts - (trak.first_dts || 0);+ const trun = traf.addBox(new trunBox());+ trun.flags = 1 | 256 | 512 | TRUN_FLAGS_FLAGS | TRUN_FLAGS_CTS_OFFSET;+ trun.data_offset = 0;+ trun.first_sample_flags = 0;+ trun.sample_count = samples.length;+ for (const sample of samples) {+ let sample_flags = 0;+ if (sample.is_sync) sample_flags = 1 << 25;+ else sample_flags = 65536;+ trun.sample_duration.push(sample.duration);+ trun.sample_size.push(sample.size);+ trun.sample_flags.push(sample_flags);+ trun.sample_composition_time_offset.push(sample.cts - sample.dts);+ }+ return moof;+ }+ /** @bundle box-print.js */+ print(output) {+ output.indent = "";+ for (let i = 0; i < this.boxes.length; i++) if (this.boxes[i]) this.boxes[i].print(output);+ }+};++//#endregion+//#region src/create-file.ts+function createFile(keepMdatData = false, stream) {+ return new ISOFile(stream, !keepMdatData);+}++//#endregion+//#region src/boxes/emsg.ts+var emsgBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "EventMessageBox";+ }+ static {+ this.fourcc = "emsg";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 1) {+ this.timescale = stream.readUint32();+ this.presentation_time = stream.readUint64();+ this.event_duration = stream.readUint32();+ this.id = stream.readUint32();+ this.scheme_id_uri = stream.readCString();+ this.value = stream.readCString();+ } else {+ this.scheme_id_uri = stream.readCString();+ this.value = stream.readCString();+ this.timescale = stream.readUint32();+ this.presentation_time_delta = stream.readUint32();+ this.event_duration = stream.readUint32();+ this.id = stream.readUint32();+ }+ let message_size = this.size - this.hdr_size - (16 + (this.scheme_id_uri.length + 1) + (this.value.length + 1));+ if (this.version === 1) message_size -= 4;+ this.message_data = stream.readUint8Array(message_size);+ }+ /** @bundle writing/emsg.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 16 + this.message_data.length + (this.scheme_id_uri.length + 1) + (this.value.length + 1);+ this.writeHeader(stream);+ stream.writeCString(this.scheme_id_uri);+ stream.writeCString(this.value);+ stream.writeUint32(this.timescale);+ stream.writeUint32(this.presentation_time_delta);+ stream.writeUint32(this.event_duration);+ stream.writeUint32(this.id);+ stream.writeUint8Array(this.message_data);+ }+};++//#endregion+//#region src/boxes/ssix.ts+var ssixBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CompressedSubsegmentIndexBox";+ }+ static {+ this.fourcc = "ssix";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.subsegments = [];+ const subsegment_count = stream.readUint32();+ for (let i = 0; i < subsegment_count; i++) {+ const subsegment = {};+ this.subsegments.push(subsegment);+ subsegment.ranges = [];+ const range_count = stream.readUint32();+ for (let j = 0; j < range_count; j++) {+ const range = {};+ subsegment.ranges.push(range);+ range.level = stream.readUint8();+ range.range_size = stream.readUint24();+ }+ }+ }+};++//#endregion+//#region src/boxes/styp.ts+var stypBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SegmentTypeBox";+ }+ static {+ this.fourcc = "styp";+ }+ parse(stream) {+ let toparse = this.size - this.hdr_size;+ this.major_brand = stream.readString(4);+ this.minor_version = stream.readUint32();+ toparse -= 8;+ this.compatible_brands = [];+ let i = 0;+ while (toparse >= 4) {+ this.compatible_brands[i] = stream.readString(4);+ toparse -= 4;+ i++;+ }+ }+ write(stream) {+ this.size = 8 + 4 * this.compatible_brands.length;+ this.writeHeader(stream);+ stream.writeString(this.major_brand, void 0, 4);+ stream.writeUint32(this.minor_version);+ for (let i = 0; i < this.compatible_brands.length; i++) stream.writeString(this.compatible_brands[i], void 0, 4);+ }+};++//#endregion+export { hvc2SampleEntry as $, SingleItemTypeReferenceBoxLarge as $n, hinfBox as $t, OpusSampleEntry as A, xmlBox as An, metxSampleEntry as At, dvh1SampleEntry as B, ContainerBox as Bn, mehdBox as Bt, sdtpBox as C, strdBox as Cn, colrBox as Ct, stxtSampleEntry as D, trgrBox as Dn, waveBox as Dt, tx3gSampleEntry as E, trakBox as En, lvcCBox as Et, avc2SampleEntry as F, SampleEntry as Fn, pitmBox as Ft, encsSampleEntry as G, DIFF_BOXES_PROP_NAMES as Gn, elngBox as Gt, ec_3SampleEntry as H, parseOneBox as Hn, hvcCBox as Ht, avc3SampleEntry as I, SubtitleSampleEntry as In, irefBox as It, encvSampleEntry as J, boxEqualFields as Jn, dinfBox as Jt, enctSampleEntry as K, DIFF_PRIMITIVE_ARRAY_PROP_NAMES as Kn, drefBox as Kt, avc4SampleEntry as L, SystemSampleEntry as Ln, ilocBox as Lt, ac_4SampleEntry as M, AudioSampleEntry as Mn, mvhdBox as Mt, av01SampleEntry as N, HintSampleEntry as Nn, mfhdBox as Nt, stppSampleEntry as O, udtaBox as On, esdsBox as Ot, avc1SampleEntry as P, MetadataSampleEntry as Pn, metaBox as Pt, hvc1SampleEntry as Q, SingleItemTypeReferenceBox as Qn, grplBox as Qt, avs3SampleEntry as R, TextSampleEntry as Rn, iinfBox as Rt, sgpdBox as S, stblBox as Sn, vvs1SampleEntry as St, wvttSampleEntry as T, trafBox as Tn, vpcCBox as Tt, encaSampleEntry as U, registerBoxes as Un, hdlrBox as Ut, dvheSampleEntry as V, parseHex16 as Vn, mdhdBox as Vt, encmSampleEntry as W, registerDescriptors as Wn, ftypBox as Wt, hev1SampleEntry as X, FullBox as Xn, etypBox as Xt, fLaCSampleEntry as Y, Box as Yn, edtsBox as Yt, hev2SampleEntry as Z, SampleGroupEntry as Zn, freeBox as Zt, stscBox as _, povdBox as _n, vp08SampleEntry as _t, ISOFile as a, iproBox as an, Endianness as ar, m4aeSampleEntry as at, smhdBox as b, sinfBox as bn, vvcNSampleEntry as bt, urlBox as c, mdatBox as cn, mhm1SampleEntry as ct, tkhdBox as d, mfraBox as dn, mjpgSampleEntry as dt, hmhdBox as en, TrackGroupTypeBox as er, hvt1SampleEntry as et, tfhdBox as f, minfBox as fn, mp4aSampleEntry as ft, stsdBox as g, nmhdBox as gn, uncvSampleEntry as gt, stszBox as h, mvexBox as hn, resvSampleEntry as ht, createFile as i, ipcoBox as in, DataStream as ir, lvc1SampleEntry as it, ac_3SampleEntry as j, avcCBox as jn, mettSampleEntry as jt, sbttSampleEntry as k, vttcBox as kn, av1CBox as kt, trunBox as l, mdiaBox as ln, mhm2SampleEntry as lt, sttsBox as m, moovBox as mn, mp4vSampleEntry as mt, ssixBox as n, idatBox as nn, MultiBufferStream as nr, lhe1SampleEntry as nt, SampleGroupInfo as o, iprpBox as on, MP4BoxBuffer as or, mha1SampleEntry as ot, tfdtBox as p, moofBox as pn, mp4sSampleEntry as pt, encuSampleEntry as q, boxEqual as qn, bxmlBox as qt, emsgBox as r, iodsBox as rn, Log as rr, lhv1SampleEntry as rt, vmhdBox as s, j2kHBox as sn, MAX_UINT32 as sr, mha2SampleEntry as st, stypBox as t, hntiBox as tn, TrackReferenceTypeBox as tr, j2kiSampleEntry as tt, trexBox as u, mecoBox as un, mjp2SampleEntry as ut, sthdBox as v, rinfBox as vn, vp09SampleEntry as vt, sbgpBox as w, strkBox as wn, vvcCBox as wt, sidxBox as x, skipBox as xn, vvi1SampleEntry as xt, stcoBox as y, schiBox as yn, vvc1SampleEntry as yt, dav1SampleEntry as z, VisualSampleEntry as zn, infeBox as zt };+//# sourceMappingURL=styp-9TIZZDLN.mjs.map\ No newline at end of filediff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.jsindex 01f036163..1c7750da2 100644--- a/src/firefox/src/agent/agent.js+++ b/src/firefox/src/agent/agent.js@@ -7295,6 +7295,9 @@ export class Agent extends LoopDetector {if (data.unverifiedStepConfirmation) {display.unverifiedStepConfirmation = normalizeUnverifiedStepConfirmation(data.unverifiedStepConfirmation);}+ if (data.videoLengthConfirmation) {+ display.videoLengthConfirmation = record(data.videoLengthConfirmation, ['estimatedSeconds', 'totalSeconds', 'clipCount', 'maxSeconds']);+ }if (data.researchEscalation) display.researchEscalation = record(data.researchEscalation, ['engine', 'request'], 6000);if (data.workflowHealing) {const target = value => record(value, ['role', 'name', 'label', 'ariaLabel', 'placeholder',@@ -29717,6 +29720,50 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dclick: `Click this control on ${host}?` }[step?.action] || `Submit this on ${host}?`;}+ /**+ * video-length-cap: the requested video needs longer than WebBrain makes+ * (generative-media.js MAX_VIDEO_SECONDS), so before any clip is submitted+ * the user decides on WebBrain's card whether the shorter version the model+ * planned is worth generating. Each clip is billed, so the card never times+ * out and never goes ahead on its own; an unattended scheduled run cannot+ * ask and generates nothing. Returns 'once', 'deny', 'unavailable', or null+ * when Stop or a correction cancelled the card.+ */+ async _promptVideoLengthConfirmation(tabId, details = {}, onUpdate = null) {+ const seconds = value => Math.max(0, Math.round(Number(value) || 0));+ const confirmation = {+ estimatedSeconds: seconds(details.estimatedSeconds),+ totalSeconds: seconds(details.totalSeconds),+ clipCount: seconds(details.clipCount),+ maxSeconds: seconds(details.maxSeconds),+ };+ if (this.scheduledRunPolicies.get(tabId)?.requireConsequentialConfirmation === false) return 'unavailable';+ if (typeof onUpdate !== 'function') return 'unavailable';+ const clarifyId = `video_length_${secureRandomBase36Token(12)}`;+ const tabPending = this._pendingClarifications.get(tabId) || new Map();+ this._pendingClarifications.set(tabId, tabPending);+ const responsePromise = new Promise((resolve) => {+ tabPending.set(clarifyId, { resolve, ts: Date.now(), timer: null, settled: false, timeoutSec: 0, deadlineTs: 0, onUpdate });+ });+ const clock = value => (value < 60 ? `${value} s` : `${Math.floor(value / 60)}:${String(value % 60).padStart(2, '0')}`);+ try {+ onUpdate('clarify', {+ promptKind: 'video_length',+ clarifyId,+ // English for traces and surfaces without the side panel's localized copy.+ question: `This video needs about ${clock(confirmation.estimatedSeconds)}, but WebBrain makes videos up to `+ + `${clock(confirmation.maxSeconds)}. Generate a ${clock(confirmation.totalSeconds)} version from ${confirmation.clipCount} clips instead?`,+ videoLengthConfirmation: confirmation,+ options: ['once', 'deny'],+ });+ } catch { /* UI emit must never break the run */ }+ const response = await responsePromise;+ tabPending.delete(clarifyId);+ if (tabPending.size === 0 && this._pendingClarifications.get(tabId) === tabPending) this._pendingClarifications.delete(tabId);+ if (response?.cancelled) return null;+ return String(response?.answer || '').trim().toLowerCase() === 'once' ? 'once' : 'deny';+ }+// What an unverified-step card shows: text the guard already holds (a// composer snapshot) or the field read now. The digest binds the user's// answer to exactly this content; the text is bounded page content that@@ -39752,8 +39799,15 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d_limitToolResult(result, maxResultChars = STANDARD_TOOL_RESULT_CHARS) {maxResultChars = Number(maxResultChars) === 16000 ? 16000 : STANDARD_TOOL_RESULT_CHARS;// Inline media is rendered for the user; base64 bytes have no value in model context.+ // The model never sees the media, so it may report only what WebBrain knows.if (result?.success && result?.provider && (result.inlineMedia || /^data:(image|video|audio)\//.test(result.url || ''))) {- result = { ...result, url: undefined, mediaId: undefined, inlineMedia: true, note: 'Generated media is displayed in the chat with a save link. Tell the user it is ready; do not invent a hosted URL.' };+ const clips = Array.isArray(result.clips)+ ? result.clips.map(({ mediaId: _mediaId, ...clip }) => clip) : undefined;+ const note = 'Generated media is displayed in the chat with a save link. Tell the user it is ready. You have not seen it: '+ + 'describe it only by what you asked for and by its durationSeconds and clipCount when present, never by its contents; '+ + 'do not invent a hosted URL.'+ + (result.joined === false ? ' Its clips could not be joined into one file, so the chat shows them one after another.' : '');+ result = { ...result, url: undefined, mediaId: undefined, clips, inlineMedia: true, note };}const windowSafeResult = isReadPageWindowResult(result)? fitReadPageWindowResult(result, maxResultChars)@@ -43623,7 +43677,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn await this._restrictedDomainScreenshotFallback(tabId, name, args.url, result);}if (name === 'generate_image') {- return await generateImage(args, { signal: executionContext?._contentActionAbortSignal, ...(executionContext?.imageGenConfig ? { config: executionContext.imageGenConfig } : {}) });+ return await generateImage(args, {+ signal: executionContext?._contentActionAbortSignal,+ ...(executionContext?.imageGenConfig ? { config: executionContext.imageGenConfig } : {}),+ onProgress: message => onUpdate?.('tool_progress', { name, message }),+ confirmVideoLength: details => this._promptVideoLengthConfirmation(tabId, details, onUpdate),+ });}if (name === 'read_page_source') {const result = await readPageSource(args.url, args, { tabId, signal: executionContext?._contentActionAbortSignal });diff --git a/src/firefox/src/agent/generative-media.js b/src/firefox/src/agent/generative-media.jsindex ffbf00b49..5beabe33a 100644--- a/src/firefox/src/agent/generative-media.js+++ b/src/firefox/src/agent/generative-media.js@@ -1,9 +1,16 @@import { runFalGeneration, FAL_AUTH_PROBE_URL } from './fal-media.js';-import { storeGeneratedMedia } from '../generated-media-store.js';+import { MAX_JOINED_VIDEO_BYTES, storeGeneratedMedia, storeGeneratedMediaBlob } from '../generated-media-store.js';import { IMAGE_GEN_MODEL_KEY, MEDIA_PROVIDERS, mediaProvider, normalizeMediaModel, comfyBaseUrl, parseMediaJson, validateMediaConfig, bindMediaPrompt } from './media-config.js';+import { VideoJoinError, joinMp4Clips, mp4DurationSeconds } from './video-join.js';const GENERATION_TIMEOUT_MS = 600000;const MAX_INLINE_BYTES = 20 * 1024 * 1024;+// A video made of scenes: at most two minutes, one clip per scene or several+// when a scene is longer than the model's longest clip.+export const MAX_VIDEO_SECONDS = 120;+export const MAX_VIDEO_CLIPS = 24;+const VIDEO_CLIP_CONCURRENCY = 3;+const VIDEO_ARGUMENTS = ['duration', 'aspect_ratio', 'resolution', 'scenes', 'estimated_duration'];const INLINE_MEDIA = /^data:(image\/(?:png|jpeg|webp|gif)|audio\/(?:mpeg|wav|ogg)|video\/mp4);base64,[A-Za-z0-9+/=\s]+$/;export function safeMediaUrl(value) {@@ -100,22 +107,271 @@ async function mediaResponse(response, label) {return url;}-async function openRouterMediaType(model, headers, request) {+// The catalog entry lists what a video model accepts (supported_durations,+// supported_resolutions, supported_aspect_ratios).+async function openRouterMediaModel(model, headers, request) {for (const kind of ['images', 'videos']) {const catalog = await jsonResponse(await request(`https://openrouter.ai/api/v1/${kind}/models`, { headers }), `OpenRouter ${kind} models`);- if (catalog.data?.some(item => item.id === model)) return kind;+ const entry = Array.isArray(catalog.data) ? catalog.data.find(item => item?.id === model) : null;+ if (entry) return { kind, entry };}throw new Error('The selected OpenRouter model is not in the image or video generation catalog.');}-export async function runMediaGeneration({ prompt, config, fetchImpl = fetch, signal, timeoutMs = GENERATION_TIMEOUT_MS, pollIntervalMs }) {+async function openRouterMediaType(model, headers, request) {+ return (await openRouterMediaModel(model, headers, request)).kind;+}++function formatSeconds(seconds) {+ const whole = Math.round(seconds);+ return whole < 60 ? `${whole} s` : `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, '0')}`;+}++function videoArguments(args) {+ const video = {};+ for (const key of VIDEO_ARGUMENTS) if (args?.[key] !== undefined) video[key] = args[key];+ return Object.keys(video).length ? video : null;+}++function supportedValues(entry, key) {+ const values = entry?.[key];+ return Array.isArray(values) && values.length ? values : null;+}++function clipDurations(entry) {+ const values = supportedValues(entry, 'supported_durations');+ if (!values) return null;+ const durations = [...new Set(values.map(Number).filter(value => Number.isInteger(value) && value > 0))].sort((a, b) => a - b);+ return durations.length ? durations : null;+}++// aspect_ratio and resolution, checked against the model's catalog entry so an+// unsupported value fails before a paid submission.+function videoShape(entry, video) {+ const shape = {};+ for (const [name, key] of [['aspect_ratio', 'supported_aspect_ratios'], ['resolution', 'supported_resolutions']]) {+ if (video?.[name] === undefined) continue;+ const supported = supportedValues(entry, key);+ if (supported && !supported.some(value => String(value) === String(video[name]))) {+ throw new Error(`This video model does not support ${name} "${video[name]}". Supported: ${supported.join(', ')}.`);+ }+ shape[name] = String(video[name]);+ }+ return shape;+}++/**+ * The clips for a video described as scenes. A scene longer than the model's+ * longest clip becomes several clips, and every clip length rounds up to one+ * the model offers. Refuses more than `maxSeconds` in total or `maxClips`.+ */+export function planVideoClips(scenes, durations, { maxSeconds = MAX_VIDEO_SECONDS, maxClips = MAX_VIDEO_CLIPS } = {}) {+ if (!durations?.length) {+ throw new Error('This video model does not list the clip lengths it supports, so WebBrain cannot make a video from scenes with it. Generate one clip instead.');+ }+ const longest = durations[durations.length - 1];+ const clips = [];+ scenes.forEach((scene, index) => {+ const prompt = String(scene?.prompt || '').trim();+ if (!prompt) throw new Error(`Scene ${index + 1} needs a prompt.`);+ const parts = Math.ceil(scene.duration / longest);+ const each = Math.ceil(scene.duration / parts);+ for (let part = 1; part <= parts; part++) {+ clips.push({+ prompt: parts > 1 ? `${prompt} (part ${part} of ${parts})` : prompt,+ duration: durations.find(value => value >= each) ?? longest,+ });+ }+ });+ const total = clips.reduce((sum, clip) => sum + clip.duration, 0);+ if (clips.length > maxClips) {+ throw new Error(`These scenes need ${clips.length} clips and WebBrain makes at most ${maxClips}. Use fewer, longer scenes.`);+ }+ if (total > maxSeconds) {+ throw new Error(`These scenes come to ${total} s with this model's clip lengths (${durations.join(', ')} s), and WebBrain makes videos up to ${maxSeconds} s. Shorten or merge scenes.`);+ }+ return { clips, total };+}++// What one generate_image call asks a video model for: one clip, or the+// clips of its scenes.+function planVideo(prompt, video, entry) {+ const durations = clipDurations(entry);+ const shape = videoShape(entry, video);+ const scenes = Array.isArray(video?.scenes) ? video.scenes : null;+ if (scenes?.length) {+ if (video.duration !== undefined) throw new Error('With scenes, give each scene its duration instead of duration.');+ if (video.estimated_duration === undefined) {+ throw new Error('With scenes, give estimated_duration: how many seconds the requested video needs before fitting it to the 120 s maximum.');+ }+ const { clips, total } = planVideoClips(scenes, durations);+ return {+ scenes: true,+ total,+ estimated: video.estimated_duration,+ shape,+ // Every clip carries the shared look so the scenes match.+ clips: clips.map((clip, index) => ({ ...clip, prompt: `${prompt}\n\nScene ${index + 1} of ${clips.length}: ${clip.prompt}` })),+ };+ }+ const longest = durations?.[durations.length - 1];+ const wanted = video?.duration ?? video?.estimated_duration;+ if (wanted !== undefined && longest && wanted > longest) {+ throw new Error(`A ${formatSeconds(wanted)} video needs more than one clip: this model makes clips of up to ${longest} s. Describe it as scenes of up to ${longest} s each, ${MAX_VIDEO_SECONDS} s in total, with estimated_duration.`);+ }+ let duration;+ if (video?.duration !== undefined) {+ if (durations && !durations.includes(video.duration)) {+ throw new Error(`This video model does not make ${video.duration} s clips. Supported: ${durations.join(', ')} s.`);+ }+ duration = video.duration;+ } else if (wanted !== undefined && durations) {+ duration = durations.find(value => value >= wanted) ?? longest;+ }+ return { scenes: false, shape, clips: [{ prompt, ...(duration !== undefined ? { duration } : {}) }] };+}++function videoRequestBody(model, clip, shape) {+ return { model, prompt: clip.prompt, ...(clip.duration !== undefined ? { duration: clip.duration } : {}), ...shape };+}++// Submits one OpenRouter video job, polls it and returns the content response.+async function openRouterVideoJob({ base, headers, request, signal, pollMs, body }) {+ const res = await request(base, { method: 'POST', headers, body: JSON.stringify(body) });+ const queued = await jsonResponse(res, 'OpenRouter video submit');+ if (!/^[A-Za-z0-9_-]+$/.test(queued.id || '')) throw new Error('OpenRouter returned an invalid video job ID.');+ // Construct authenticated paths ourselves; returned URLs cannot select a key recipient.+ const jobUrl = `${base}/${queued.id}`;+ let waitMs = pollDelay(res, pollMs);+ while (true) {+ await delay(waitMs, signal);+ const statusRes = await request(jobUrl, { headers });+ const status = await jsonResponse(statusRes, 'OpenRouter video status');+ waitMs = pollDelay(statusRes, pollMs);+ if (status.status === 'completed') return request(`${jobUrl}/content?index=0`, { headers });+ if (!['pending', 'in_progress'].includes(status.status)) throw new Error(`OpenRouter video generation ${status.status || 'returned an unknown status'}.`);+ }+}++function dataUrlBytes(url) {+ const match = /^data:([^;]+);base64,([A-Za-z0-9+/=\s]+)$/.exec(url || '');+ if (!match) return null;+ const binary = atob(match[2].replace(/\s+/g, ''));+ return { bytes: Uint8Array.from(binary, char => char.charCodeAt(0)), mime: match[1] };+}++// A clip that will be joined is kept as bytes, not as a data URL.+async function videoBytes(response, label) {+ const mime = (response.headers?.get?.('Content-Type') || '').split(';')[0].trim();+ if (response.ok && mime === 'video/mp4') {+ const bytes = new Uint8Array(await response.arrayBuffer());+ if (bytes.length > MAX_INLINE_BYTES) throw new Error('A generated clip exceeds the 20 MB inline limit.');+ return bytes;+ }+ const decoded = dataUrlBytes(await mediaResponse(response, label));+ if (decoded?.mime !== 'video/mp4') throw new Error(`${label} did not return an MP4 video.`);+ return decoded.bytes;+}++// Runs `task` for each item, `limit` at a time. The first failure stops the+// others; Stop aborts them all with its own reason.+async function mapWithConcurrency(items, limit, signal, task) {+ const controller = new AbortController();+ const onAbort = () => controller.abort(signal.reason);+ if (signal?.aborted) onAbort(); else signal?.addEventListener('abort', onAbort, { once: true });+ const results = new Array(items.length);+ let next = 0;+ const worker = async () => {+ while (next < items.length && !controller.signal.aborted) {+ const index = next++;+ try { results[index] = await task(items[index], index, controller.signal); }+ catch (error) {+ if (!controller.signal.aborted) controller.abort(error);+ throw signal?.aborted ? signal.reason : error;+ }+ }+ };+ try {+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));+ controller.signal.throwIfAborted();+ return results;+ } finally { signal?.removeEventListener('abort', onAbort); }+}++async function runOpenRouter({ text, model, config, video, fetchImpl, signal, timeoutMs, pollMs, onProgress, confirmVideoLength }) {+ const headers = { Authorization: `Bearer ${config.apiKey}`, 'Content-Type': 'application/json' };+ // One bounded operation: its own deadline, aborted by Stop as well.+ const bounded = async (parent, task) => {+ const operation = operationSignal(parent, timeoutMs);+ const request = (url, init = {}) => {+ operation.signal.throwIfAborted();+ return fetchImpl(url, { ...init, signal: operation.signal, redirect: 'error', credentials: 'omit' });+ };+ try { return await task(request, operation.signal); }+ catch (error) { throw operation.signal.aborted ? operation.signal.reason : error; }+ finally { operation.dispose(); }+ };+ const base = 'https://openrouter.ai/api/v1/videos';+ let plan = null;+ const single = await bounded(signal, async (request, jobSignal) => {+ const { kind, entry } = await openRouterMediaModel(model, headers, request);+ if (kind === 'images') {+ if (video) throw new Error('Video length, aspect ratio, resolution and scenes need a video model; the selected OpenRouter model makes images.');+ const res = await request('https://openrouter.ai/api/v1/images', { method: 'POST', headers, body: JSON.stringify({ model, prompt: text }) });+ return { url: await mediaResponse(res, 'OpenRouter generation'), model };+ }+ plan = planVideo(text, video, entry);+ if (plan.scenes) return null;+ const res = await openRouterVideoJob({ base, headers, request, signal: jobSignal, pollMs, body: videoRequestBody(model, plan.clips[0], plan.shape) });+ return { url: await mediaResponse(res, 'OpenRouter video download'), model };+ });+ if (single) return single;++ // A video longer than WebBrain makes: the user decides on its card whether a+ // shorter version is worth generating, before anything is submitted. The+ // card is outside the generation deadline.+ const lengthDetails = { estimatedSeconds: plan.estimated, totalSeconds: plan.total, clipCount: plan.clips.length, maxSeconds: MAX_VIDEO_SECONDS };+ if (plan.estimated > MAX_VIDEO_SECONDS) {+ const answer = typeof confirmVideoLength === 'function' ? await confirmVideoLength(lengthDetails) : 'unavailable';+ signal?.throwIfAborted?.();+ if (answer !== 'once') return { declined: true, answer: answer || 'cancelled', model, ...lengthDetails };+ }+ onProgress?.(`Generating ${plan.clips.length} video clips…`);+ let ready = 0;+ const clips = await mapWithConcurrency(plan.clips, VIDEO_CLIP_CONCURRENCY, signal, async (clip, index, groupSignal) => {+ for (let attempt = 1; ; attempt++) {+ try {+ const bytes = await bounded(groupSignal, async (request, jobSignal) => videoBytes(+ await openRouterVideoJob({ base, headers, request, signal: jobSignal, pollMs, body: videoRequestBody(model, clip, plan.shape) }),+ 'OpenRouter video download'));+ ready += 1;+ onProgress?.(`Video clips: ${ready} of ${plan.clips.length} ready`);+ return bytes;+ } catch (error) {+ // One retry per clip; a second failure, Stop or another clip's failure ends the video.+ if (groupSignal.aborted || attempt >= 2) {+ throw groupSignal.aborted ? (groupSignal.reason ?? error) : new Error(`Clip ${index + 1} of ${plan.clips.length} failed: ${error.message}`);+ }+ }+ }+ });+ return { clips, model, ...lengthDetails };+}++export async function runMediaGeneration({ prompt, config, video = null, fetchImpl = fetch, signal, timeoutMs = GENERATION_TIMEOUT_MS, pollIntervalMs, onProgress, confirmVideoLength }) {const provider = validateMediaConfig(config);const text = String(prompt || '').trim();if (!text) throw new Error('prompt is required.');+ if (video && provider !== 'openrouter') {+ throw new Error(`Video length, aspect ratio, resolution and scenes work with OpenRouter video models. Omit them to use the ${MEDIA_PROVIDERS[provider].label} default.`);+ }if (provider === 'fal') return runFalGeneration({ prompt: text, config, fetchImpl, signal, timeoutMs });- const operation = operationSignal(signal, timeoutMs);const pollMs = pollIntervalMs ?? (provider === 'openrouter' ? 30000 : 2000);const model = provider === 'comfyui' ? 'ComfyUI workflow' : normalizeMediaModel(config.model);+ if (provider === 'openrouter') {+ return runOpenRouter({ text, model, config, video, fetchImpl, signal, timeoutMs, pollMs, onProgress, confirmVideoLength });+ }+ const operation = operationSignal(signal, timeoutMs);const request = (url, init = {}) => {operation.signal.throwIfAborted();return fetchImpl(url, { ...init, signal: operation.signal, redirect: 'error', credentials: 'omit' });@@ -123,32 +379,6 @@ export async function runMediaGeneration({ prompt, config, fetchImpl = fetch, silet cancelUrl = '', cancelInit;let completed = false;try {- if (provider === 'openrouter') {- const headers = { Authorization: `Bearer ${config.apiKey}`, 'Content-Type': 'application/json' };- const kind = await openRouterMediaType(model, headers, request);- const base = `https://openrouter.ai/api/v1/${kind}`;- const res = await request(base, {- method: 'POST', headers,- body: JSON.stringify({ model, prompt: text }),- });- if (kind === 'images') return { url: await mediaResponse(res, 'OpenRouter generation'), model };- const queued = await jsonResponse(res, 'OpenRouter video submit');- if (!/^[A-Za-z0-9_-]+$/.test(queued.id || '')) throw new Error('OpenRouter returned an invalid video job ID.');- // Construct authenticated paths ourselves; returned URLs cannot select a key recipient.- const jobUrl = `${base}/${queued.id}`;- let waitMs = pollDelay(res, pollMs);- while (true) {- await delay(waitMs, operation.signal);- const statusRes = await request(jobUrl, { headers });- const status = await jsonResponse(statusRes, 'OpenRouter video status');- waitMs = pollDelay(statusRes, pollMs);- if (status.status === 'completed') {- const result = await request(`${jobUrl}/content?index=0`, { headers });- return { url: await mediaResponse(result, 'OpenRouter video download'), model };- }- if (!['pending', 'in_progress'].includes(status.status)) throw new Error(`OpenRouter video generation ${status.status || 'returned an unknown status'}.`);- }- }if (provider === 'comfyrouter') {const base = `https://api.comfy.org/v2/models/${model}/requests`;const headers = { 'X-API-Key': config.apiKey, 'Content-Type': 'application/json' };@@ -215,17 +445,68 @@ export async function readMediaConfig() {return stored?.[IMAGE_GEN_MODEL_KEY];}+const roundSeconds = seconds => (Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds * 10) / 10 : undefined);++function declinedVideoMessage({ answer, estimatedSeconds, totalSeconds }) {+ const length = `The video needs about ${formatSeconds(estimatedSeconds)}, and WebBrain makes videos up to ${formatSeconds(MAX_VIDEO_SECONDS)}`;+ if (answer === 'deny') return `${length}. The user chose not to generate the ${formatSeconds(totalSeconds)} version, so nothing was generated. Ask what they would like instead.`;+ if (answer === 'unavailable') return `${length}. This run could not ask the user whether a ${formatSeconds(totalSeconds)} version is wanted, so nothing was generated. Tell the user.`;+ return `${length}. The question about a ${formatSeconds(totalSeconds)} version was withdrawn before an answer, so nothing was generated.`;+}++// Joins a video's clips into one stored asset. Clips that cannot be joined+// losslessly are stored one by one and shown in order.+async function storeVideoClips(clips, onProgress) {+ if (clips.length > 1) {+ try {+ onProgress?.(`Joining ${clips.length} clips…`);+ const joined = joinMp4Clips(clips, { maxBytes: MAX_JOINED_VIDEO_BYTES });+ const asset = await storeGeneratedMediaBlob(new Blob([joined.bytes], { type: 'video/mp4' }), { maxBytes: MAX_JOINED_VIDEO_BYTES });+ return { ...asset, durationSeconds: roundSeconds(joined.durationSeconds), clipCount: clips.length };+ } catch (error) {+ if (!(error instanceof VideoJoinError)) throw error;+ }+ }+ const stored = [];+ for (const bytes of clips) {+ const asset = await storeGeneratedMediaBlob(new Blob([bytes], { type: 'video/mp4' }));+ stored.push({ mediaId: asset.mediaId, mimeType: asset.mimeType, durationSeconds: roundSeconds(mp4DurationSeconds(bytes)) });+ }+ const durationSeconds = roundSeconds(stored.reduce((sum, clip) => sum + (clip.durationSeconds || 0), 0));+ if (stored.length === 1) return { ...stored[0], inlineMedia: true, durationSeconds, clipCount: 1 };+ return { inlineMedia: true, mimeType: 'video/mp4', clips: stored, clipCount: stored.length, durationSeconds, joined: false };+}++/**+ * The generate_image tool. `options.onProgress(message)` reports progress of+ * a video made of scenes, and `options.confirmVideoLength(details)` asks the+ * user when the requested video is longer than WebBrain makes ('once' to go+ * ahead; 'deny', 'unavailable' or null otherwise).+ */export async function generateImage(args, options = {}) {const fetchImpl = typeof options === 'function' ? options : options.fetchImpl || fetch;try {const config = Object.hasOwn(options, 'config') ? options.config : await readMediaConfig();if (!config) throw new Error('Configure Generative Media in Providers → Generative.');- const result = await runMediaGeneration({ prompt: args?.prompt, config, fetchImpl, signal: options.signal });+ const provider = mediaProvider(config);+ const result = await runMediaGeneration({+ prompt: args?.prompt, video: videoArguments(args), config, fetchImpl, signal: options.signal,+ onProgress: options.onProgress, confirmVideoLength: options.confirmVideoLength,+ });+ if (result.declined) {+ return { success: false, declined: true, provider, model: result.model, error: declinedVideoMessage(result) };+ }+ if (Array.isArray(result.clips)) {+ return { success: true, model: result.model, provider, ...(await storeVideoClips(result.clips, options.onProgress)) };+ }if (result.url.startsWith('data:')) {const asset = await storeGeneratedMedia(result.url);- return { success: true, model: result.model, provider: mediaProvider(config), ...asset };+ // A clip's real length, so the agent can say how long the video is.+ const video = asset.mimeType === 'video/mp4' ? dataUrlBytes(result.url) : null;+ const durationSeconds = video ? roundSeconds(mp4DurationSeconds(video.bytes)) : undefined;+ return { success: true, model: result.model, provider, ...asset, ...(durationSeconds ? { durationSeconds } : {}) };}- return { success: true, ...result, provider: mediaProvider(config) };+ return { success: true, ...result, provider };} catch (error) { return { success: false, error: error.message }; }}diff --git a/src/firefox/src/agent/guard-policy.js b/src/firefox/src/agent/guard-policy.jsindex c6e939d09..31b4f230e 100644--- a/src/firefox/src/agent/guard-policy.js+++ b/src/firefox/src/agent/guard-policy.js@@ -354,6 +354,9 @@ export const GUARDS = Object.freeze({summary: "The upload selector matched several file inputs (now or on the previous attempt, until an inspection runs)." },"upload-source-validation": { class: "infra", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",summary: "The local upload path is missing/unreadable (inconclusive probes pass as unverified), or the file bytes do not match, or cannot be verified against, the input accept types." },+ "video-length-cap": { class: "permission_gate", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "generate_image scenes over 120 s or 24 clips are refused before submission, and an estimate over 120 s asks the user on WebBrain's card before the shorter version is generated (an unattended run generates nothing).",+ mustNotBlock: "test/generative-media-video.mjs#a video of two minutes or less generates without asking" },"viewport-inspection-budget": { class: "permission_gate", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",summary: "inspect_viewport is skipped once the user-configured maxScreenshotsPerTurn budget is used up." },"webmcp-frame-binding": { class: "host_check", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",diff --git a/src/firefox/src/agent/scheduler.js b/src/firefox/src/agent/scheduler.jsindex 9c730f18f..1c9eba5cc 100644--- a/src/firefox/src/agent/scheduler.js+++ b/src/firefox/src/agent/scheduler.js@@ -187,6 +187,17 @@ function normalizePendingClarify(data, now = Date.now()) {if (unverifiedStep.guardId || unverifiedStep.action) {pending.unverifiedStepConfirmation = normalizeUnverifiedStepConfirmation(unverifiedStep);}+ // WebBrain's card about a video longer than it makes: the lengths it shows.+ const videoLength = asObject(obj.videoLengthConfirmation);+ if (Number(videoLength.estimatedSeconds) > 0) {+ const whole = value => Math.max(0, Math.min(86400, Math.round(Number(value) || 0)));+ pending.videoLengthConfirmation = {+ estimatedSeconds: whole(videoLength.estimatedSeconds),+ totalSeconds: whole(videoLength.totalSeconds),+ clipCount: whole(videoLength.clipCount),+ maxSeconds: whole(videoLength.maxSeconds),+ };+ }return pending;}diff --git a/src/firefox/src/agent/tools.js b/src/firefox/src/agent/tools.jsindex 02367b020..1ecbd5c2d 100644--- a/src/firefox/src/agent/tools.js+++ b/src/firefox/src/agent/tools.js@@ -35,7 +35,8 @@ const DONE_REQUIRED = ['summary'];const DONE_REQUIRED_WITH_OUTCOME = ['summary', 'outcome'];export const SYSTEM_PROMPT_GENERATIVE_MEDIA = `GENERATIVE MEDIA:-- generate_image: Create media (usually an image, sometimes video/audio) directly from a text prompt through the user's configured generative-media provider. When the user asks to GENERATE media ("generate an image of a red apple", "make a logo", "create a video clip"), call this tool — do NOT navigate to third-party image sites (Midjourney, DALL·E, Bing Images, etc.). Not available in Ask mode.`;+- generate_image: Create media (usually an image, sometimes video/audio) directly from a text prompt through the user's configured generative-media provider. When the user asks to GENERATE media ("generate an image of a red apple", "make a logo", "create a video clip"), call this tool — do NOT navigate to third-party image sites (Midjourney, DALL·E, Bing Images, etc.). Not available in Ask mode.+- Videos: estimate how long the requested video should run. One that needs more than one clip (an explainer, a story) is one call with scenes, at most 120 s in total, and estimated_duration set to the full length it needs; WebBrain joins the clips into one video and asks the user first when that estimate is longer than 120 s. You never see the result: report its length and clip count from the tool result, not its contents.`;export const SYSTEM_PROMPT_BATCHING = `BATCHING:- Use browser_batch for predictable steps on the current page with targets you already observed, such as filling known fields or opening a menu and choosing a known item. A navigation followed by a page read can also share one batch.@@ -1342,11 +1343,27 @@ export const AGENT_TOOLS = [type: 'function',function: {name: 'generate_image',- description: 'Generate media (usually an image) from a text prompt using the user\'s configured generative media provider (Providers → Generative). Supports fal.ai, OpenRouter, Comfy Router and local ComfyUI workflows; generation may take several minutes. Returns a media URL or inline media displayed in the chat. Not available in Ask mode.',+ description: 'Generate media (usually an image) from a text prompt using the user\'s configured generative media provider (Providers → Generative). Supports fal.ai, OpenRouter, Comfy Router and local ComfyUI workflows; generation may take several minutes. Returns a media URL or inline media displayed in the chat. With an OpenRouter video model, estimate how long the requested video should run (estimated_duration): one clip can set duration, aspect_ratio and resolution; a longer video passes scenes, which WebBrain fits to the model\'s clip lengths and joins into one video of up to 120 s, asking the user first when the estimate is longer. Not available in Ask mode.',parameters: {type: 'object',properties: {- prompt: { type: 'string', description: 'Text prompt describing the media to generate.' },+ prompt: { type: 'string', description: 'Text prompt describing the media to generate. With scenes: the look, subject and style every clip shares.' },+ estimated_duration: { type: 'integer', minimum: 1, description: 'Video only: seconds the requested video needs, estimated before fitting it to the 120 s maximum. Required with scenes.' },+ duration: { type: 'integer', minimum: 1, description: 'Video only: seconds for a single clip.' },+ aspect_ratio: { type: 'string', description: 'Video only, for example "16:9" or "9:16".' },+ resolution: { type: 'string', description: 'Video only, for example "720p".' },+ scenes: {+ type: 'array',+ description: 'Video only: the scenes of a video longer than one clip, in order, at most 120 seconds in total.',+ items: {+ type: 'object',+ properties: {+ prompt: { type: 'string', description: 'What this scene shows.' },+ duration: { type: 'integer', minimum: 1, description: 'Seconds.' },+ },+ required: ['prompt', 'duration'],+ },+ },},required: ['prompt'],},diff --git a/src/firefox/src/agent/video-join.js b/src/firefox/src/agent/video-join.jsnew file mode 100644index 000000000..5e430fb98--- /dev/null+++ b/src/firefox/src/agent/video-join.js@@ -0,0 +1,405 @@+// Joins generated MP4 clips into one MP4 without re-encoding.+//+// Clips from one video model share their codec setup, so their samples can be+// laid end to end: the joiner keeps the first clip's sample descriptions+// (stsd) and writes new sample tables for the combined timeline. Clips whose+// tracks or codec setup differ cannot be joined this way (`clips_incompatible`);+// the caller then shows them one after another instead. mp4box.js parses the+// input. The output is a plain (not fragmented) MP4 with moov before mdat.+//+// Shared byte for byte by the Chrome and Firefox builds.++import { createFile, MP4BoxBuffer } from '../../vendor/mp4box/mp4box.all.mjs';++export class VideoJoinError extends Error {+ constructor(message, code) {+ super(message);+ this.name = 'VideoJoinError';+ this.code = code;+ }+}++const incompatible = reason => new VideoJoinError(`The clips cannot be joined into one file: ${reason}.`, 'clips_incompatible');+const MEDIA_HEADER_TYPES = new Set(['vmhd', 'smhd', 'nmhd', 'sthd', 'hmhd']);+const MAX_UINT32 = 2 ** 32 - 1;++function toArrayBuffer(input) {+ if (input instanceof ArrayBuffer) return input;+ if (ArrayBuffer.isView(input)) return input.buffer.slice(input.byteOffset, input.byteOffset + input.byteLength);+ throw new VideoJoinError('Expected MP4 bytes.', 'not_mp4');+}++function sameBytes(a, b) {+ if (!a || !b || a.length !== b.length) return false;+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;+ return true;+}++function rawBox(bytes, box) {+ return box && Number.isInteger(box.start) && Number.isInteger(box.size) && box.size > 0+ ? bytes.subarray(box.start, box.start + box.size) : null;+}++// esds: ES_Descriptor (tag 3), then DecoderConfigDescriptor (tag 4) whose+// bufferSizeDB, maxBitrate and avgBitrate follow objectTypeIndication and+// streamType.+function blankEsdsBitrates(bytes, box, blank) {+ const end = box.start + box.size;+ let p = box.start + 12;+ const skipLength = () => {+ for (let i = 0; i < 4 && p < end; i++) if (!(bytes[p++] & 0x80)) break;+ };+ if (bytes[p++] !== 0x03) return;+ skipLength();+ p += 2;+ const flags = bytes[p++];+ if (flags & 0x80) p += 2;+ if (flags & 0x40) p += 1 + bytes[p];+ if (flags & 0x20) p += 2;+ if (bytes[p++] !== 0x04) return;+ skipLength();+ if (p + 13 <= end) blank(p + 2, p + 13);+}++// The sample description with this encode's bitrate figures blanked: every+// clip reports its own, and they do not change how the samples decode.+function sampleDescriptionKey(bytes, stsd) {+ const key = bytes.slice(stsd.start, stsd.start + stsd.size);+ const blank = (from, to) => key.fill(0, from - stsd.start, to - stsd.start);+ for (const entry of stsd.entries || []) {+ for (const child of entry.boxes || []) {+ if (!Number.isInteger(child.start) || !(child.size > 8)+ || child.start < stsd.start || child.start + child.size > stsd.start + stsd.size) continue;+ if (child.type === 'btrt') blank(child.start + 8, child.start + child.size);+ if (child.type === 'esds') blankEsdsBitrates(bytes, child, blank);+ }+ }+ return key;+}++function readTrack(trak, movieTimescale, bytes) {+ const mdia = trak?.mdia, minf = mdia?.minf, stbl = minf?.stbl;+ const handler = mdia?.hdlr?.handler;+ const timescale = mdia?.mdhd?.timescale;+ const samples = Array.isArray(trak?.samples) ? trak.samples : [];+ if (!stbl?.stsd || !(timescale > 0) || !samples.length) throw incompatible('a track has no samples');+ if ((stbl.stsd.entries?.length || 0) !== 1 || samples.some(sample => sample.description_index !== 0)) {+ throw incompatible('a track switches codec settings');+ }+ // Reordered frames (B-frames) are shown after they are decoded, so the+ // track's picture ends at its last composition time, not its last decode time.+ const compositionEnd = samples.reduce((end, sample) => Math.max(end, sample.cts + sample.duration), 0);+ // One edit that skips the codec's start-up delay is normal. Empty edits or+ // several edits describe a timeline these tables cannot carry over.+ const edits = trak.edts?.elst?.entries || [];+ if (edits.length > 1 || edits.some(edit => edit.media_time < 0 || edit.media_rate_integer !== 1)) {+ throw incompatible('a track has a complex edit list');+ }+ // Without an edit the track is shown from its first composition time+ // (fragmented files from some encoders start video after a B-frame delay).+ const mediaTime = edits.length ? edits[0].media_time : samples.reduce((min, sample) => Math.min(min, sample.cts), Infinity);+ const editDuration = edits.length && edits[0].segment_duration > 0+ ? Math.round(edits[0].segment_duration * timescale / movieTimescale) : compositionEnd - mediaTime;+ return {+ handler,+ timescale,+ samples,+ mediaTime,+ presented: Math.max(0, Math.min(editDuration, compositionEnd - mediaTime)),+ hasEdit: edits.length > 0,+ tkhd: trak.tkhd,+ language: mdia.mdhd.language,+ stsd: rawBox(bytes, stbl.stsd),+ stsdKey: sampleDescriptionKey(bytes, stbl.stsd),+ hdlr: rawBox(bytes, mdia.hdlr),+ mediaHeader: rawBox(bytes, (minf.boxes || []).find(box => MEDIA_HEADER_TYPES.has(box.type))),+ dinf: rawBox(bytes, (minf.boxes || []).find(box => box.type === 'dinf')),+ };+}++function parseClip(input) {+ const arrayBuffer = toArrayBuffer(input);+ const bytes = new Uint8Array(arrayBuffer);+ const file = createFile();+ let failed = false;+ file.onError = () => { failed = true; };+ try {+ file.appendBuffer(MP4BoxBuffer.fromArrayBuffer(arrayBuffer, 0));+ file.flush();+ } catch { failed = true; }+ const moov = file.moov;+ const movieTimescale = moov?.mvhd?.timescale;+ if (failed || !(movieTimescale > 0) || !Array.isArray(moov.traks) || !moov.traks.length) {+ throw new VideoJoinError('The clip is not a readable MP4 file.', 'not_mp4');+ }+ // Video first, then audio; other tracks (timed metadata) are not carried over.+ const order = { vide: 0, soun: 1 };+ const tracks = moov.traks+ .filter(trak => Object.hasOwn(order, trak.mdia?.hdlr?.handler))+ .map(trak => readTrack(trak, movieTimescale, bytes))+ .sort((a, b) => order[a.handler] - order[b.handler]);+ if (!tracks.length) throw incompatible('a clip has no video or audio track');+ const timing = tracks[0];+ return {+ bytes,+ movieTimescale,+ matrix: moov.mvhd.matrix,+ ftyp: rawBox(bytes, (file.boxes || []).find(box => box.type === 'ftyp')),+ tracks,+ duration: timing.presented / timing.timescale,+ };+}++/** Presented length of an MP4 in seconds, or null when it is not one. */+export function mp4DurationSeconds(input) {+ try { return parseClip(input).duration; } catch { return null; }+}++// Lays out one output track: each clip's samples in order, with the previous+// clip's last sample lengthened or shortened so that this clip starts where+// the timeline says. At each join the audio follows the picture: a later+// clip's codec start-up frames are dropped, and so are the previous clip's+// frames that would mostly play after this clip's audio begins (padding, or+// audio longer than the picture). Video frames are never dropped.+function joinTrack(clips, index, starts) {+ const first = clips[0].tracks[index];+ const samples = [];+ const chunks = [];+ clips.forEach((clip, clipIndex) => {+ const track = clip.tracks[index];+ const audio = track.handler === 'soun';+ const kept = audio && clipIndex > 0+ ? track.samples.filter(sample => sample.cts + sample.duration / 2 >= track.mediaTime)+ : track.samples;+ if (!kept.length) throw incompatible('a clip has an empty track');+ if (samples.length) {+ const target = Math.round(starts[clipIndex] * track.timescale) + (kept[0].dts - track.mediaTime) + first.mediaTime;+ const previous = chunks[chunks.length - 1];+ while (audio && previous.count > 1+ && samples[samples.length - 1].dts + samples[samples.length - 1].duration / 2 >= target) {+ previous.count -= 1;+ previous.size -= samples.pop().size;+ }+ const last = samples[samples.length - 1];+ last.duration = Math.max(1, target - last.dts);+ }+ let dts = samples.length ? samples[samples.length - 1].dts + samples[samples.length - 1].duration : 0;+ chunks.push({ clipIndex, first: samples.length, count: kept.length, size: 0, offset: 0 });+ const chunk = chunks[chunks.length - 1];+ for (const sample of kept) {+ samples.push({+ dts,+ duration: sample.duration,+ offset: sample.cts - sample.dts,+ size: sample.size,+ source: sample.offset,+ sync: sample.is_sync !== false,+ clipIndex,+ });+ chunk.size += sample.size;+ dts += sample.duration;+ }+ });+ const mediaDuration = samples.reduce((sum, sample) => sum + sample.duration, 0);+ return { first, samples, chunks, mediaDuration };+}++class Writer {+ constructor() {+ this.buffer = new Uint8Array(1 << 16);+ this.view = new DataView(this.buffer.buffer);+ this.position = 0;+ }+ ensure(length) {+ if (this.position + length <= this.buffer.length) return;+ let size = this.buffer.length * 2;+ while (size < this.position + length) size *= 2;+ const next = new Uint8Array(size);+ next.set(this.buffer.subarray(0, this.position));+ this.buffer = next;+ this.view = new DataView(next.buffer);+ }+ u8(value) { this.ensure(1); this.view.setUint8(this.position, value); this.position += 1; }+ u16(value) { this.ensure(2); this.view.setUint16(this.position, value); this.position += 2; }+ i16(value) { this.ensure(2); this.view.setInt16(this.position, value); this.position += 2; }+ u32(value) { this.ensure(4); this.view.setUint32(this.position, value); this.position += 4; }+ i32(value) { this.ensure(4); this.view.setInt32(this.position, value); this.position += 4; }+ bytes(value) { this.ensure(value.length); this.buffer.set(value, this.position); this.position += value.length; }+ type(value) { for (let i = 0; i < 4; i++) this.u8(value.charCodeAt(i)); }+ box(type, body) {+ const start = this.position;+ this.u32(0);+ this.type(type);+ body();+ this.view.setUint32(start, this.position - start);+ }+ full(type, version, flags, body) {+ this.box(type, () => { this.u32(((version & 255) << 24 | (flags & 0xffffff)) >>> 0); body(); });+ }+ result() { return this.buffer.slice(0, this.position); }+}++function runs(values) {+ const out = [];+ for (const value of values) {+ const last = out[out.length - 1];+ if (last && last.value === value) last.count += 1;+ else out.push({ value, count: 1 });+ }+ return out;+}++function writeMatrix(writer, matrix) {+ const values = matrix && matrix.length === 9 ? matrix : [0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x40000000];+ for (const value of values) writer.i32(value);+}++function writeSampleTable(writer, track) {+ const { first, samples, chunks } = track;+ writer.box('stbl', () => {+ writer.bytes(first.stsd);+ const durations = runs(samples.map(sample => sample.duration));+ writer.full('stts', 0, 0, () => {+ writer.u32(durations.length);+ for (const run of durations) { writer.u32(run.count); writer.u32(run.value); }+ });+ if (samples.some(sample => sample.offset !== 0)) {+ const negative = samples.some(sample => sample.offset < 0);+ const offsets = runs(samples.map(sample => sample.offset));+ writer.full('ctts', negative ? 1 : 0, 0, () => {+ writer.u32(offsets.length);+ for (const run of offsets) { writer.u32(run.count); if (negative) writer.i32(run.value); else writer.u32(run.value); }+ });+ }+ if (samples.some(sample => !sample.sync)) {+ const sync = samples.flatMap((sample, i) => (sample.sync ? [i + 1] : []));+ writer.full('stss', 0, 0, () => { writer.u32(sync.length); for (const number of sync) writer.u32(number); });+ }+ const perChunk = runs(chunks.map(chunk => chunk.count));+ writer.full('stsc', 0, 0, () => {+ writer.u32(perChunk.length);+ let chunkNumber = 1;+ for (const run of perChunk) { writer.u32(chunkNumber); writer.u32(run.value); writer.u32(1); chunkNumber += run.count; }+ });+ writer.full('stsz', 0, 0, () => {+ writer.u32(0);+ writer.u32(samples.length);+ for (const sample of samples) writer.u32(sample.size);+ });+ writer.full('stco', 0, 0, () => { writer.u32(chunks.length); for (const chunk of chunks) writer.u32(chunk.offset); });+ });+}++function writeMovie(clips, tracks, totalSeconds) {+ const movieTimescale = clips[0].movieTimescale;+ const movieDuration = Math.round(totalSeconds * movieTimescale);+ const writer = new Writer();+ writer.box('moov', () => {+ writer.full('mvhd', 0, 0, () => {+ writer.u32(0); writer.u32(0);+ writer.u32(movieTimescale); writer.u32(movieDuration);+ writer.u32(0x00010000); writer.u16(0x0100); writer.u16(0); writer.u32(0); writer.u32(0);+ writeMatrix(writer, clips[0].matrix);+ for (let i = 0; i < 6; i++) writer.u32(0);+ writer.u32(tracks.length + 1);+ });+ tracks.forEach((track, index) => {+ const { first } = track;+ writer.box('trak', () => {+ writer.full('tkhd', 0, first.tkhd?.flags ?? 3, () => {+ writer.u32(0); writer.u32(0);+ writer.u32(index + 1); writer.u32(0);+ writer.u32(movieDuration);+ writer.u32(0); writer.u32(0);+ writer.i16(first.tkhd?.layer || 0); writer.i16(first.tkhd?.alternate_group || 0);+ writer.u16(((first.tkhd?.volume || 0) & 255) << 8); writer.u16(0);+ writeMatrix(writer, first.tkhd?.matrix);+ writer.u32(first.tkhd?.width >>> 0 || 0); writer.u32(first.tkhd?.height >>> 0 || 0);+ });+ if (first.hasEdit) {+ writer.box('edts', () => writer.full('elst', 0, 0, () => {+ writer.u32(1); writer.u32(movieDuration); writer.i32(first.mediaTime); writer.i16(1); writer.i16(0);+ }));+ }+ writer.box('mdia', () => {+ writer.full('mdhd', 0, 0, () => {+ writer.u32(0); writer.u32(0);+ writer.u32(first.timescale); writer.u32(track.mediaDuration);+ writer.u16(first.language & 0x7fff); writer.u16(0);+ });+ writer.bytes(first.hdlr);+ writer.box('minf', () => {+ if (first.mediaHeader) writer.bytes(first.mediaHeader);+ if (first.dinf) writer.bytes(first.dinf);+ writeSampleTable(writer, track);+ });+ });+ });+ });+ });+ return writer.result();+}++/**+ * Joins MP4 clips (ArrayBuffer or typed array each) in order. Returns+ * `{ bytes, durationSeconds }`; throws VideoJoinError with `clips_incompatible`+ * when their tracks or codec setup differ, `not_mp4` for unreadable input and+ * `too_large` above `maxBytes`.+ */+export function joinMp4Clips(inputs, { maxBytes = Infinity } = {}) {+ if (!Array.isArray(inputs) || !inputs.length) throw new VideoJoinError('No clips to join.', 'not_mp4');+ const clips = inputs.map(parseClip);+ const reference = clips[0];+ for (const clip of clips.slice(1)) {+ if (clip.tracks.length !== reference.tracks.length) throw incompatible('the clips have different tracks');+ clip.tracks.forEach((track, index) => {+ const expected = reference.tracks[index];+ if (track.handler !== expected.handler || track.timescale !== expected.timescale || !sameBytes(track.stsdKey, expected.stsdKey)) {+ throw incompatible('the clips use different codec settings');+ }+ });+ }+ const starts = [];+ let totalSeconds = 0;+ for (const clip of clips) { starts.push(totalSeconds); totalSeconds += clip.duration; }+ const tracks = reference.tracks.map((_track, index) => joinTrack(clips, index, starts));+ const payload = tracks.reduce((sum, track) => sum + track.chunks.reduce((size, chunk) => size + chunk.size, 0), 0);+ const ftyp = reference.ftyp || (() => {+ const writer = new Writer();+ writer.box('ftyp', () => { writer.type('isom'); writer.u32(0x200); for (const brand of ['isom', 'iso2', 'mp41']) writer.type(brand); });+ return writer.result();+ })();+ // Chunk offsets do not change the size of the movie box, so lay out with a+ // provisional box, then write it again with the real offsets.+ let moov = writeMovie(clips, tracks, totalSeconds);+ const total = ftyp.length + moov.length + 8 + payload;+ if (total > maxBytes) throw new VideoJoinError('The joined video is larger than WebBrain can keep in the chat.', 'too_large');+ if (total > MAX_UINT32) throw new VideoJoinError('The joined video is too large.', 'too_large');+ let offset = ftyp.length + moov.length + 8;+ const ordered = [];+ clips.forEach((_clip, clipIndex) => tracks.forEach(track => {+ const chunk = track.chunks.find(candidate => candidate.clipIndex === clipIndex);+ if (!chunk) return;+ chunk.offset = offset;+ offset += chunk.size;+ ordered.push({ track, chunk });+ }));+ moov = writeMovie(clips, tracks, totalSeconds);+ const out = new Uint8Array(total);+ out.set(ftyp, 0);+ out.set(moov, ftyp.length);+ const view = new DataView(out.buffer);+ let position = ftyp.length + moov.length;+ view.setUint32(position, 8 + payload);+ out.set([0x6d, 0x64, 0x61, 0x74], position + 4);+ position += 8;+ for (const { track, chunk } of ordered) {+ const source = clips[chunk.clipIndex].bytes;+ for (let i = chunk.first; i < chunk.first + chunk.count; i++) {+ const sample = track.samples[i];+ out.set(source.subarray(sample.source, sample.source + sample.size), position);+ position += sample.size;+ }+ }+ return { bytes: out, durationSeconds: totalSeconds };+}diff --git a/src/firefox/src/generated-media-store.js b/src/firefox/src/generated-media-store.jsindex 5d8b27c5b..3ef3b11cb 100644--- a/src/firefox/src/generated-media-store.js+++ b/src/firefox/src/generated-media-store.js@@ -2,6 +2,8 @@const DB_NAME = 'webbrain_generated_media';const STORE_NAME = 'assets';const MAX_BYTES = 20 * 1024 * 1024;+// A video joined from its scenes' clips: up to two minutes of generated video.+export const MAX_JOINED_VIDEO_BYTES = 160 * 1024 * 1024;const MEDIA_MIME = /^(image\/(?:png|jpeg|webp|gif)|audio\/(?:mpeg|wav|ogg)|video\/mp4)$/;async function openDB() {@@ -19,7 +21,14 @@ export async function storeGeneratedMedia(dataUrl) {const binary = atob(match[2]);if (binary.length > MAX_BYTES) throw new Error('Generated media exceeds the 20 MB inline limit.');const bytes = Uint8Array.from(binary, char => char.charCodeAt(0));- const blob = new Blob([bytes], { type: match[1] });+ return storeGeneratedMediaBlob(new Blob([bytes], { type: match[1] }));+}++// `maxBytes` above 20 MB is for a joined video only.+export async function storeGeneratedMediaBlob(blob, { maxBytes = MAX_BYTES } = {}) {+ if (!(blob instanceof Blob) || !MEDIA_MIME.test(blob.type)) throw new Error('Unsupported generated media.');+ const limit = Math.min(maxBytes, blob.type === 'video/mp4' ? MAX_JOINED_VIDEO_BYTES : MAX_BYTES);+ if (blob.size > limit) throw new Error(`Generated media exceeds the ${Math.round(limit / 1024 / 1024)} MB inline limit.`);const id = crypto.randomUUID();const db = await openDB();try {@@ -42,7 +51,8 @@ export async function loadGeneratedMedia(id) {const request = db.transaction(STORE_NAME, 'readonly').objectStore(STORE_NAME).get(id);request.onsuccess = () => {const blob = request.result?.blob;- resolve(blob instanceof Blob && MEDIA_MIME.test(blob.type) && blob.size <= MAX_BYTES ? blob : null);+ const limit = blob?.type === 'video/mp4' ? MAX_JOINED_VIDEO_BYTES : MAX_BYTES;+ resolve(blob instanceof Blob && MEDIA_MIME.test(blob.type) && blob.size <= limit ? blob : null);};request.onerror = () => reject(request.error);});diff --git a/src/firefox/src/run-ui-journal.js b/src/firefox/src/run-ui-journal.jsindex cf21371a4..f01795778 100644--- a/src/firefox/src/run-ui-journal.js+++ b/src/firefox/src/run-ui-journal.js@@ -101,6 +101,16 @@ function compactRunUiToolResult(result, name) {if (typeof source[key] === 'string') compacted[key] = source[key];}if (source.inlineMedia === true) compacted.inlineMedia = true;+ for (const key of ['durationSeconds', 'clipCount']) {+ if (Number.isFinite(source[key])) compacted[key] = source[key];+ }+ // Clips of a video that could not be joined into one file, shown in order.+ if (source.joined === false && Array.isArray(source.clips)) {+ compacted.joined = false;+ compacted.clips = source.clips.slice(0, 24).flatMap(clip => (typeof clip?.mediaId === 'string'+ ? [{ mediaId: clip.mediaId, mimeType: String(clip.mimeType || ''), ...(Number.isFinite(clip.durationSeconds) ? { durationSeconds: clip.durationSeconds } : {}) }]+ : []));+ }}if (Object.keys(compacted).length === 0) {try {diff --git a/src/firefox/src/ui/generated-media-view.js b/src/firefox/src/ui/generated-media-view.jsindex 55f2ff4aa..9cf21095e 100644--- a/src/firefox/src/ui/generated-media-view.js+++ b/src/firefox/src/ui/generated-media-view.js@@ -46,6 +46,11 @@ async function hydrateStoredMedia(wrapper, t) {// A synchronous placeholder keeps the asset handle in chat snapshots even if// the panel closes before the IndexedDB read finishes.export function appendGeneratedMedia(container, result, t) {+ // A video whose clips could not be joined into one file: its clips in order.+ if (container && result?.success && Array.isArray(result.clips) && !result.mediaId && typeof result.url !== 'string') {+ return Promise.all(result.clips.slice(0, 24)+ .map(clip => appendGeneratedMedia(container, { success: true, mediaId: clip?.mediaId }, t)));+ }if (!container || !result?.success || (!result.mediaId && typeof result.url !== 'string')) return;const wrapper = document.createElement('div');wrapper.className = 'generated-media';diff --git a/src/firefox/src/ui/locales/ar.js b/src/firefox/src/ui/locales/ar.jsindex 959d20c79..c9a4073dc 100644--- a/src/firefox/src/ui/locales/ar.js+++ b/src/firefox/src/ui/locales/ar.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "يسأل الموقع: “{dialog}”","sp.delete.delete": "حذف","sp.delete.dont_delete": "عدم الحذف",+ "sp.video_length.question": "يحتاج هذا الفيديو إلى نحو {estimate}، لكن WebBrain ينشئ مقاطع فيديو حتى {max}.",+ "sp.video_length.offer": "هل تريد إنشاء نسخة مدتها {total} من {clips} مقاطع بدلاً من ذلك؟",+ "sp.video_length.generate": "إنشاء نسخة {total}",+ "sp.video_length.dont": "عدم الإنشاء",+ "sp.video_length.seconds": "{seconds} ث","sp.unverified.question.commit": "هل تريد إيداع هذا على {host}؟","sp.unverified.question.submit": "هل تريد إرسال هذا على {host}؟","sp.unverified.question.publish": "هل تريد نشر هذا على {host}؟",diff --git a/src/firefox/src/ui/locales/bn.js b/src/firefox/src/ui/locales/bn.jsindex 8ce9778e2..14dc3e25b 100644--- a/src/firefox/src/ui/locales/bn.js+++ b/src/firefox/src/ui/locales/bn.js@@ -458,6 +458,11 @@ export default {"sp.delete.site_asks": "সাইটটি জিজ্ঞেস করছে: “{dialog}”","sp.delete.delete": "মুছুন","sp.delete.dont_delete": "মুছবেন না",+ "sp.video_length.question": "এই ভিডিওর জন্য প্রায় {estimate} দরকার, কিন্তু WebBrain সর্বোচ্চ {max} দৈর্ঘ্যের ভিডিও তৈরি করে।",+ "sp.video_length.offer": "এর বদলে {clips}টি ক্লিপ থেকে {total} দৈর্ঘ্যের একটি সংস্করণ তৈরি করবেন?",+ "sp.video_length.generate": "{total} সংস্করণ তৈরি করুন",+ "sp.video_length.dont": "তৈরি করবেন না",+ "sp.video_length.seconds": "{seconds} সে.","sp.unverified.question.commit": "{host}-এ এটি কমিট করবেন?","sp.unverified.question.submit": "{host}-এ এটি জমা দেবেন?","sp.unverified.question.publish": "{host}-এ এটি প্রকাশ করবেন?",diff --git a/src/firefox/src/ui/locales/de.js b/src/firefox/src/ui/locales/de.jsindex 98e4eda0e..093b907ce 100644--- a/src/firefox/src/ui/locales/de.js+++ b/src/firefox/src/ui/locales/de.js@@ -476,6 +476,11 @@ export default {"sp.delete.site_asks": "Die Website fragt: „{dialog}“","sp.delete.delete": "Löschen","sp.delete.dont_delete": "Nicht löschen",+ "sp.video_length.question": "Dieses Video bräuchte etwa {estimate}, WebBrain erstellt aber Videos bis {max}.",+ "sp.video_length.offer": "Stattdessen eine {total}-Version aus {clips} Clips erstellen?",+ "sp.video_length.generate": "{total}-Version erstellen",+ "sp.video_length.dont": "Nicht erstellen",+ "sp.video_length.seconds": "{seconds} s","sp.unverified.question.commit": "Das auf {host} committen?","sp.unverified.question.submit": "Das auf {host} absenden?","sp.unverified.question.publish": "Das auf {host} veröffentlichen?",diff --git a/src/firefox/src/ui/locales/en.js b/src/firefox/src/ui/locales/en.jsindex c0154d3a5..1c6cf387e 100644--- a/src/firefox/src/ui/locales/en.js+++ b/src/firefox/src/ui/locales/en.js@@ -463,6 +463,11 @@ export default {"sp.delete.site_asks": "The site asks: “{dialog}”","sp.delete.delete": "Delete","sp.delete.dont_delete": "Don’t delete",+ "sp.video_length.question": "This video needs about {estimate}, but WebBrain makes videos up to {max}.",+ "sp.video_length.offer": "Generate a {total} version from {clips} clips instead?",+ "sp.video_length.generate": "Generate {total} version",+ "sp.video_length.dont": "Don’t generate",+ "sp.video_length.seconds": "{seconds} s","sp.unverified.question.commit": "Commit this on {host}?","sp.unverified.question.submit": "Submit this on {host}?","sp.unverified.question.publish": "Publish this on {host}?",diff --git a/src/firefox/src/ui/locales/es.js b/src/firefox/src/ui/locales/es.jsindex 847fa4a07..79822efe9 100644--- a/src/firefox/src/ui/locales/es.js+++ b/src/firefox/src/ui/locales/es.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "El sitio pregunta: «{dialog}»","sp.delete.delete": "Eliminar","sp.delete.dont_delete": "No eliminar",+ "sp.video_length.question": "Este vídeo necesita unos {estimate}, pero WebBrain crea vídeos de hasta {max}.",+ "sp.video_length.offer": "¿Generar en su lugar una versión de {total} a partir de {clips} clips?",+ "sp.video_length.generate": "Generar versión de {total}",+ "sp.video_length.dont": "No generar",+ "sp.video_length.seconds": "{seconds} s","sp.unverified.question.commit": "¿Hacer commit de esto en {host}?","sp.unverified.question.submit": "¿Enviar esto en {host}?","sp.unverified.question.publish": "¿Publicar esto en {host}?",diff --git a/src/firefox/src/ui/locales/fa.js b/src/firefox/src/ui/locales/fa.jsindex da4187034..f860b5e12 100644--- a/src/firefox/src/ui/locales/fa.js+++ b/src/firefox/src/ui/locales/fa.js@@ -458,6 +458,11 @@ export default {"sp.delete.site_asks": "سایت میپرسد: «{dialog}»","sp.delete.delete": "حذف","sp.delete.dont_delete": "حذف نکن",+ "sp.video_length.question": "این ویدیو حدود {estimate} زمان نیاز دارد، اما WebBrain ویدیوهایی تا {max} میسازد.",+ "sp.video_length.offer": "بهجای آن نسخهای {total} از {clips} کلیپ ساخته شود؟",+ "sp.video_length.generate": "ساخت نسخهٔ {total}",+ "sp.video_length.dont": "نساز",+ "sp.video_length.seconds": "{seconds} ثانیه","sp.unverified.question.commit": "این در {host} کامیت شود؟","sp.unverified.question.submit": "این در {host} ارسال شود؟","sp.unverified.question.publish": "این در {host} منتشر شود؟",diff --git a/src/firefox/src/ui/locales/fr.js b/src/firefox/src/ui/locales/fr.jsindex 76077c88e..db55e7b54 100644--- a/src/firefox/src/ui/locales/fr.js+++ b/src/firefox/src/ui/locales/fr.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "Le site demande : « {dialog} »","sp.delete.delete": "Supprimer","sp.delete.dont_delete": "Ne pas supprimer",+ "sp.video_length.question": "Cette vidéo nécessite environ {estimate}, mais WebBrain crée des vidéos de {max} maximum.",+ "sp.video_length.offer": "Générer plutôt une version de {total} à partir de {clips} clips ?",+ "sp.video_length.generate": "Générer la version de {total}",+ "sp.video_length.dont": "Ne pas générer",+ "sp.video_length.seconds": "{seconds} s","sp.unverified.question.commit": "Valider (commit) ceci sur {host} ?","sp.unverified.question.submit": "Envoyer ceci sur {host} ?","sp.unverified.question.publish": "Publier ceci sur {host} ?",diff --git a/src/firefox/src/ui/locales/he.js b/src/firefox/src/ui/locales/he.jsindex 8583ef131..cc9a4470b 100644--- a/src/firefox/src/ui/locales/he.js+++ b/src/firefox/src/ui/locales/he.js@@ -449,6 +449,11 @@ export default {"sp.delete.site_asks": "האתר שואל: \"{dialog}\"","sp.delete.delete": "למחוק","sp.delete.dont_delete": "לא למחוק",+ "sp.video_length.question": "הסרטון הזה דורש כ-{estimate}, אבל WebBrain יוצר סרטונים של עד {max}.",+ "sp.video_length.offer": "ליצור במקום זאת גרסה של {total} מ-{clips} קטעים?",+ "sp.video_length.generate": "יצירת גרסה של {total}",+ "sp.video_length.dont": "לא ליצור",+ "sp.video_length.seconds": "{seconds} שנ׳","sp.unverified.question.commit": "לבצע commit לזה ב-{host}?","sp.unverified.question.submit": "לשלוח את זה ב-{host}?","sp.unverified.question.publish": "לפרסם את זה ב-{host}?",diff --git a/src/firefox/src/ui/locales/hi.js b/src/firefox/src/ui/locales/hi.jsindex 943357786..a6765d1a8 100644--- a/src/firefox/src/ui/locales/hi.js+++ b/src/firefox/src/ui/locales/hi.js@@ -458,6 +458,11 @@ export default {"sp.delete.site_asks": "साइट पूछ रही है: “{dialog}”","sp.delete.delete": "हटाएँ","sp.delete.dont_delete": "न हटाएँ",+ "sp.video_length.question": "इस वीडियो के लिए लगभग {estimate} चाहिए, लेकिन WebBrain अधिकतम {max} तक के वीडियो बनाता है।",+ "sp.video_length.offer": "इसके बजाय {clips} क्लिप से {total} का संस्करण बनाएँ?",+ "sp.video_length.generate": "{total} संस्करण बनाएँ",+ "sp.video_length.dont": "न बनाएँ",+ "sp.video_length.seconds": "{seconds} से.","sp.unverified.question.commit": "{host} पर इसे कमिट करें?","sp.unverified.question.submit": "{host} पर इसे सबमिट करें?","sp.unverified.question.publish": "{host} पर इसे प्रकाशित करें?",diff --git a/src/firefox/src/ui/locales/id.js b/src/firefox/src/ui/locales/id.jsindex dd91741f3..3f15d3d65 100644--- a/src/firefox/src/ui/locales/id.js+++ b/src/firefox/src/ui/locales/id.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "Situs bertanya: “{dialog}”","sp.delete.delete": "Hapus","sp.delete.dont_delete": "Jangan hapus",+ "sp.video_length.question": "Video ini membutuhkan sekitar {estimate}, tetapi WebBrain membuat video hingga {max}.",+ "sp.video_length.offer": "Buat versi {total} dari {clips} klip sebagai gantinya?",+ "sp.video_length.generate": "Buat versi {total}",+ "sp.video_length.dont": "Jangan buat",+ "sp.video_length.seconds": "{seconds} dtk","sp.unverified.question.commit": "Commit ini di {host}?","sp.unverified.question.submit": "Kirim ini di {host}?","sp.unverified.question.publish": "Publikasikan ini di {host}?",diff --git a/src/firefox/src/ui/locales/ja.js b/src/firefox/src/ui/locales/ja.jsindex a3cc16b21..16c6d3a10 100644--- a/src/firefox/src/ui/locales/ja.js+++ b/src/firefox/src/ui/locales/ja.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "サイトの確認:「{dialog}」","sp.delete.delete": "削除する","sp.delete.dont_delete": "削除しない",+ "sp.video_length.question": "この動画には約{estimate}必要ですが、WebBrainが作成できる動画は最長{max}です。",+ "sp.video_length.offer": "代わりに{clips}本のクリップから{total}の動画を作成しますか?",+ "sp.video_length.generate": "{total}版を作成",+ "sp.video_length.dont": "作成しない",+ "sp.video_length.seconds": "{seconds}秒","sp.unverified.question.commit": "{host} でこれをコミットしますか?","sp.unverified.question.submit": "{host} でこれを送信しますか?","sp.unverified.question.publish": "{host} でこれを公開しますか?",diff --git a/src/firefox/src/ui/locales/ko.js b/src/firefox/src/ui/locales/ko.jsindex 024843c25..d0e1c5660 100644--- a/src/firefox/src/ui/locales/ko.js+++ b/src/firefox/src/ui/locales/ko.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "사이트 확인 메시지: “{dialog}”","sp.delete.delete": "삭제","sp.delete.dont_delete": "삭제하지 않기",+ "sp.video_length.question": "이 동영상에는 약 {estimate} 분량이 필요하지만 WebBrain은 최대 {max} 길이까지 동영상을 만듭니다.",+ "sp.video_length.offer": "대신 클립 {clips}개로 {total} 버전을 만들까요?",+ "sp.video_length.generate": "{total} 버전 만들기",+ "sp.video_length.dont": "만들지 않기",+ "sp.video_length.seconds": "{seconds}초","sp.unverified.question.commit": "{host}에서 이 내용을 커밋할까요?","sp.unverified.question.submit": "{host}에서 이 내용을 제출할까요?","sp.unverified.question.publish": "{host}에서 이 내용을 게시할까요?",diff --git a/src/firefox/src/ui/locales/ms.js b/src/firefox/src/ui/locales/ms.jsindex 56cfc7b0d..43750ea56 100644--- a/src/firefox/src/ui/locales/ms.js+++ b/src/firefox/src/ui/locales/ms.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "Laman bertanya: “{dialog}”","sp.delete.delete": "Padam","sp.delete.dont_delete": "Jangan padam",+ "sp.video_length.question": "Video ini memerlukan kira-kira {estimate}, tetapi WebBrain menghasilkan video sehingga {max}.",+ "sp.video_length.offer": "Jana versi {total} daripada {clips} klip sebagai ganti?",+ "sp.video_length.generate": "Jana versi {total}",+ "sp.video_length.dont": "Jangan jana",+ "sp.video_length.seconds": "{seconds} saat","sp.unverified.question.commit": "Commit ini di {host}?","sp.unverified.question.submit": "Serahkan ini di {host}?","sp.unverified.question.publish": "Terbitkan ini di {host}?",diff --git a/src/firefox/src/ui/locales/nl.js b/src/firefox/src/ui/locales/nl.jsindex e071a27d6..0d639ccae 100644--- a/src/firefox/src/ui/locales/nl.js+++ b/src/firefox/src/ui/locales/nl.js@@ -446,6 +446,11 @@ export default {"sp.delete.site_asks": "De site vraagt: ‘{dialog}’","sp.delete.delete": "Verwijderen","sp.delete.dont_delete": "Niet verwijderen",+ "sp.video_length.question": "Deze video heeft ongeveer {estimate} nodig, maar WebBrain maakt video's van maximaal {max}.",+ "sp.video_length.offer": "In plaats daarvan een versie van {total} uit {clips} clips maken?",+ "sp.video_length.generate": "Versie van {total} maken",+ "sp.video_length.dont": "Niet maken",+ "sp.video_length.seconds": "{seconds} s","sp.unverified.question.commit": "Dit committen op {host}?","sp.unverified.question.submit": "Dit versturen op {host}?","sp.unverified.question.publish": "Dit publiceren op {host}?",diff --git a/src/firefox/src/ui/locales/pl.js b/src/firefox/src/ui/locales/pl.jsindex 5dc547a32..e6506d540 100644--- a/src/firefox/src/ui/locales/pl.js+++ b/src/firefox/src/ui/locales/pl.js@@ -349,6 +349,11 @@ export default {"sp.delete.site_asks": "Strona pyta: „{dialog}”","sp.delete.delete": "Usuń","sp.delete.dont_delete": "Nie usuwaj",+ "sp.video_length.question": "Ten film wymaga około {estimate}, ale WebBrain tworzy filmy o długości do {max}.",+ "sp.video_length.offer": "Zamiast tego utworzyć wersję {total} (liczba klipów: {clips})?",+ "sp.video_length.generate": "Utwórz wersję {total}",+ "sp.video_length.dont": "Nie twórz",+ "sp.video_length.seconds": "{seconds} s","sp.unverified.question.commit": "Zatwierdzić (commit) to w {host}?","sp.unverified.question.submit": "Wysłać to w {host}?","sp.unverified.question.publish": "Opublikować to w {host}?",diff --git a/src/firefox/src/ui/locales/pt.js b/src/firefox/src/ui/locales/pt.jsindex e294c6721..0f7242809 100644--- a/src/firefox/src/ui/locales/pt.js+++ b/src/firefox/src/ui/locales/pt.js@@ -458,6 +458,11 @@ export default {"sp.delete.site_asks": "O site pergunta: “{dialog}”","sp.delete.delete": "Excluir","sp.delete.dont_delete": "Não excluir",+ "sp.video_length.question": "Este vídeo precisa de cerca de {estimate}, mas o WebBrain cria vídeos de até {max}.",+ "sp.video_length.offer": "Gerar uma versão de {total} com {clips} clipes em vez disso?",+ "sp.video_length.generate": "Gerar versão de {total}",+ "sp.video_length.dont": "Não gerar",+ "sp.video_length.seconds": "{seconds} s","sp.unverified.question.commit": "Fazer commit disto em {host}?","sp.unverified.question.submit": "Enviar isto em {host}?","sp.unverified.question.publish": "Publicar isto em {host}?",diff --git a/src/firefox/src/ui/locales/ru.js b/src/firefox/src/ui/locales/ru.jsindex 10ee326d5..64edc3525 100644--- a/src/firefox/src/ui/locales/ru.js+++ b/src/firefox/src/ui/locales/ru.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "Сайт спрашивает: «{dialog}»","sp.delete.delete": "Удалить","sp.delete.dont_delete": "Не удалять",+ "sp.video_length.question": "Этому видео нужно около {estimate}, но WebBrain создаёт видео длиной не более {max}.",+ "sp.video_length.offer": "Создать вместо этого версию на {total} из {clips} клипов?",+ "sp.video_length.generate": "Создать версию на {total}",+ "sp.video_length.dont": "Не создавать",+ "sp.video_length.seconds": "{seconds} с","sp.unverified.question.commit": "Закоммитить это на {host}?","sp.unverified.question.submit": "Отправить это на {host}?","sp.unverified.question.publish": "Опубликовать это на {host}?",diff --git a/src/firefox/src/ui/locales/th.js b/src/firefox/src/ui/locales/th.jsindex f85a58e88..a46a24d23 100644--- a/src/firefox/src/ui/locales/th.js+++ b/src/firefox/src/ui/locales/th.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "เว็บไซต์ถามว่า: “{dialog}”","sp.delete.delete": "ลบ","sp.delete.dont_delete": "ไม่ลบ",+ "sp.video_length.question": "วิดีโอนี้ต้องใช้เวลาประมาณ {estimate} แต่ WebBrain สร้างวิดีโอได้ยาวสูงสุด {max}",+ "sp.video_length.offer": "สร้างเวอร์ชัน {total} จาก {clips} คลิปแทนหรือไม่",+ "sp.video_length.generate": "สร้างเวอร์ชัน {total}",+ "sp.video_length.dont": "ไม่สร้าง",+ "sp.video_length.seconds": "{seconds} วินาที","sp.unverified.question.commit": "คอมมิตสิ่งนี้บน {host} ไหม?","sp.unverified.question.submit": "ส่งสิ่งนี้บน {host} ไหม?","sp.unverified.question.publish": "เผยแพร่สิ่งนี้บน {host} ไหม?",diff --git a/src/firefox/src/ui/locales/tl.js b/src/firefox/src/ui/locales/tl.jsindex 8730ef203..903347061 100644--- a/src/firefox/src/ui/locales/tl.js+++ b/src/firefox/src/ui/locales/tl.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "Tanong ng site: “{dialog}”","sp.delete.delete": "Burahin","sp.delete.dont_delete": "Huwag burahin",+ "sp.video_length.question": "Kailangan ng video na ito ng mga {estimate}, pero hanggang {max} lang ang ginagawang video ng WebBrain.",+ "sp.video_length.offer": "Gumawa na lang ng {total} na bersyon mula sa {clips} clip?",+ "sp.video_length.generate": "Gumawa ng {total} na bersyon",+ "sp.video_length.dont": "Huwag gumawa",+ "sp.video_length.seconds": "{seconds} seg","sp.unverified.question.commit": "I-commit ito sa {host}?","sp.unverified.question.submit": "Isumite ito sa {host}?","sp.unverified.question.publish": "I-publish ito sa {host}?",diff --git a/src/firefox/src/ui/locales/tr.js b/src/firefox/src/ui/locales/tr.jsindex 393ccab47..3f2f4e349 100644--- a/src/firefox/src/ui/locales/tr.js+++ b/src/firefox/src/ui/locales/tr.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "Site soruyor: “{dialog}”","sp.delete.delete": "Sil","sp.delete.dont_delete": "Silme",+ "sp.video_length.question": "Bu video yaklaşık {estimate} gerektiriyor, ancak WebBrain en fazla {max} uzunluğunda video üretiyor.",+ "sp.video_length.offer": "Bunun yerine {clips} klipten {total} uzunluğunda bir sürüm üretilsin mi?",+ "sp.video_length.generate": "{total} sürümünü üret",+ "sp.video_length.dont": "Üretme",+ "sp.video_length.seconds": "{seconds} sn","sp.unverified.question.commit": "{host} üzerinde bu commit edilsin mi?","sp.unverified.question.submit": "{host} üzerinde bu gönderilsin mi?","sp.unverified.question.publish": "{host} üzerinde bu yayınlansın mı?",diff --git a/src/firefox/src/ui/locales/uk.js b/src/firefox/src/ui/locales/uk.jsindex 5e284837d..3929e8259 100644--- a/src/firefox/src/ui/locales/uk.js+++ b/src/firefox/src/ui/locales/uk.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "Сайт питає: «{dialog}»","sp.delete.delete": "Видалити","sp.delete.dont_delete": "Не видаляти",+ "sp.video_length.question": "Цьому відео потрібно приблизно {estimate}, але WebBrain створює відео тривалістю до {max}.",+ "sp.video_length.offer": "Створити натомість версію на {total} з {clips} кліпів?",+ "sp.video_length.generate": "Створити версію на {total}",+ "sp.video_length.dont": "Не створювати",+ "sp.video_length.seconds": "{seconds} с","sp.unverified.question.commit": "Закомітити це на {host}?","sp.unverified.question.submit": "Надіслати це на {host}?","sp.unverified.question.publish": "Опублікувати це на {host}?",diff --git a/src/firefox/src/ui/locales/vi.js b/src/firefox/src/ui/locales/vi.jsindex 161c10b83..6a3685a9c 100644--- a/src/firefox/src/ui/locales/vi.js+++ b/src/firefox/src/ui/locales/vi.js@@ -458,6 +458,11 @@ export default {"sp.delete.site_asks": "Trang web hỏi: “{dialog}”","sp.delete.delete": "Xóa","sp.delete.dont_delete": "Không xóa",+ "sp.video_length.question": "Video này cần khoảng {estimate}, nhưng WebBrain chỉ tạo video dài tối đa {max}.",+ "sp.video_length.offer": "Thay vào đó, tạo bản {total} từ {clips} đoạn clip?",+ "sp.video_length.generate": "Tạo bản {total}",+ "sp.video_length.dont": "Không tạo",+ "sp.video_length.seconds": "{seconds} giây","sp.unverified.question.commit": "Commit nội dung này trên {host}?","sp.unverified.question.submit": "Gửi nội dung này trên {host}?","sp.unverified.question.publish": "Đăng nội dung này trên {host}?",diff --git a/src/firefox/src/ui/locales/zh.js b/src/firefox/src/ui/locales/zh.jsindex ddc34501a..1db4ebb0b 100644--- a/src/firefox/src/ui/locales/zh.js+++ b/src/firefox/src/ui/locales/zh.js@@ -90,6 +90,11 @@ export default {"sp.delete.site_asks": "网站询问:“{dialog}”","sp.delete.delete": "删除","sp.delete.dont_delete": "不删除",+ "sp.video_length.question": "这个视频大约需要 {estimate},但 WebBrain 最多只能生成 {max} 的视频。",+ "sp.video_length.offer": "改为用 {clips} 个片段生成 {total} 的版本?",+ "sp.video_length.generate": "生成 {total} 版本",+ "sp.video_length.dont": "不生成",+ "sp.video_length.seconds": "{seconds} 秒","sp.unverified.question.commit": "要在 {host} 上提交(commit)这些内容吗?","sp.unverified.question.submit": "要在 {host} 上提交这些内容吗?","sp.unverified.question.publish": "要在 {host} 上发布这些内容吗?",diff --git a/src/firefox/src/ui/sidepanel.js b/src/firefox/src/ui/sidepanel.jsindex 4e95c76b8..e1af08974 100644--- a/src/firefox/src/ui/sidepanel.js+++ b/src/firefox/src/ui/sidepanel.js@@ -6548,7 +6548,8 @@ function rebindClarifyCards() {// Restart countdown after HTML restore when timeout metadata survived on// the card. Skip permission/form-submit cards (they never auto-timeout).if (card.dataset.permission === '1' || card.dataset.submitConfirmation === '1'- || card.dataset.recipientConfirmation === '1' || card.dataset.mutationConfirmation === '1') return;+ || card.dataset.recipientConfirmation === '1' || card.dataset.mutationConfirmation === '1'+ || card.dataset.videoLengthConfirmation === '1') return;const deadlineTs = Number(card.dataset.deadlineTs);if (!Number.isFinite(deadlineTs) || deadlineTs <= 0) return;const firstOption = card.dataset.firstOption@@ -11167,7 +11168,7 @@ function renderClarifyCard(data) {card.dataset.memorySource = scheduledJobId? 'scheduled_clarification': data.workflowHealing || data.pendingReconciliation === true || data.recipientConfirmation- || data.mutationConfirmation || data.unverifiedStepConfirmation+ || data.mutationConfirmation || data.unverifiedStepConfirmation || data.videoLengthConfirmation? '': data.submitConfirmation? 'form_confirmation'@@ -11394,6 +11395,44 @@ function renderClarifyCard(data) {return;}+ // Video length: the requested video needs longer than WebBrain makes, so+ // the user decides whether the shorter version is worth its clips. Fixed+ // choices return stable values ('once'/'deny'); the card never times out.+ if (data.videoLengthConfirmation) {+ card.dataset.videoLengthConfirmation = '1';+ const video = data.videoLengthConfirmation || {};+ const clock = value => {+ const seconds = Math.max(0, Math.round(Number(value) || 0));+ return seconds < 60 ? t('sp.video_length.seconds', { seconds }) : `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;+ };+ qEl.textContent = t('sp.video_length.question', { estimate: clock(video.estimatedSeconds), max: clock(video.maxSeconds) });+ const offerEl = document.createElement('div');+ offerEl.className = 'clarify-reason';+ offerEl.textContent = t('sp.video_length.offer', {+ total: clock(video.totalSeconds),+ clips: Math.max(1, Math.round(Number(video.clipCount) || 1)),+ });+ card.appendChild(offerEl);+ const optionsEl = document.createElement('div');+ optionsEl.className = 'clarify-options';+ for (const [value, label] of [['once', t('sp.video_length.generate', { total: clock(video.totalSeconds) })], ['deny', t('sp.video_length.dont')]]) {+ const b = document.createElement('button');+ b.type = 'button';+ b.className = 'clarify-option';+ b.textContent = String(label).slice(0, 200);+ b.dataset.value = value;+ b.addEventListener('click', () => {+ card.dataset.answerLabel = b.textContent;+ submitClarify(card, tabId, clarifyId, value, 'option');+ });+ optionsEl.appendChild(b);+ }+ card.appendChild(optionsEl);+ content.appendChild(card);+ scrollToBottom({ force: true });+ return;+ }+// Unverifiable step: one of WebBrain's checks could not verify a commit,// publish or submit, so it asks instead of refusing. The text is what the// page showed when WebBrain asked: page content, shown as text only@@ -11742,7 +11781,8 @@ function lockClarifyCardFromAuto(data) {// of a quality check: it locks on the timeout's answer like a question.const unverifiedStep = card.dataset.unverifiedStepConfirmation === '1';if (card.dataset.permission === '1' || card.dataset.submitConfirmation === '1'- || card.dataset.recipientConfirmation === '1' || card.dataset.mutationConfirmation === '1') return;+ || card.dataset.recipientConfirmation === '1' || card.dataset.mutationConfirmation === '1'+ || card.dataset.videoLengthConfirmation === '1') return;clearClarifyCountdown(card);card.classList.add('clarify-answered');for (const el of card.querySelectorAll('button, input')) {diff --git a/src/firefox/vendor/mp4box/LICENSE b/src/firefox/vendor/mp4box/LICENSEnew file mode 100644index 000000000..dccb790ea--- /dev/null+++ b/src/firefox/vendor/mp4box/LICENSE@@ -0,0 +1,24 @@+Copyright (c) 2012. Telecom ParisTech/TSI/MM/GPAC Cyril Concolato+All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:+ * Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.+ * Redistributions in binary form must reproduce the above copyright+ notice, this list of conditions and the following disclaimer in the+ documentation and/or other materials provided with the distribution.+ * Neither the name of the copyright holder nor the+ names of its contributors may be used to endorse or promote products+ derived from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/src/firefox/vendor/mp4box/README.webbrain.md b/src/firefox/vendor/mp4box/README.webbrain.mdnew file mode 100644index 000000000..cb5788f5c--- /dev/null+++ b/src/firefox/vendor/mp4box/README.webbrain.md@@ -0,0 +1,18 @@+# Vendored mp4box.js++- Package: `mp4box`+- Version: `2.4.1`+- Upstream: <https://github.com/gpac/mp4box.js>+- Files: `dist/mp4box.all.mjs`, `dist/styp-9TIZZDLN.mjs` and+ `dist/rolldown-runtime-w6R9maHv.mjs` from the published npm package,+ unmodified (the entry file imports the other two by these names)+- SHA-256:+ - `mp4box.all.mjs`: `34fa8fd681e8b63998ca9e4c3b477830dd11310c8aaedc37ecb8f49c5452d259`+ - `styp-9TIZZDLN.mjs`: `ae15acb79233251b72af7f7cc9f47e7f47cadb209206753b7000b502a2391049`+ - `rolldown-runtime-w6R9maHv.mjs`: `183552fe973134bce551888434b581d5a2cb695a82d8907e2cd9d2b61e12ce24`+- License: BSD-3-Clause (see `LICENSE`)++WebBrain uses `createFile` and `MP4BoxBuffer` only to parse generated MP4+clips: their sample tables, edit lists and codec configuration. The joined file+is written by `src/agent/video-join.js`. The dependency is bundled with the+extension; no executable code is fetched at runtime.diff --git a/src/firefox/vendor/mp4box/mp4box.all.mjs b/src/firefox/vendor/mp4box/mp4box.all.mjsnew file mode 100644index 000000000..1de72dcfd--- /dev/null+++ b/src/firefox/vendor/mp4box/mp4box.all.mjs@@ -0,0 +1,3427 @@+import { t as __exportAll } from "./rolldown-runtime-w6R9maHv.mjs";+import { $ as hvc2SampleEntry, $n as SingleItemTypeReferenceBoxLarge, $t as hinfBox, A as OpusSampleEntry, An as xmlBox, At as metxSampleEntry, B as dvh1SampleEntry, Bn as ContainerBox, Bt as mehdBox, C as sdtpBox, Cn as strdBox, Ct as colrBox, D as stxtSampleEntry, Dn as trgrBox, Dt as waveBox, E as tx3gSampleEntry, En as trakBox, Et as lvcCBox, F as avc2SampleEntry, Fn as SampleEntry, Ft as pitmBox, G as encsSampleEntry, Gn as DIFF_BOXES_PROP_NAMES, Gt as elngBox, H as ec_3SampleEntry, Hn as parseOneBox, Ht as hvcCBox, I as avc3SampleEntry, In as SubtitleSampleEntry, It as irefBox, J as encvSampleEntry, Jn as boxEqualFields, Jt as dinfBox, K as enctSampleEntry, Kn as DIFF_PRIMITIVE_ARRAY_PROP_NAMES, Kt as drefBox, L as avc4SampleEntry, Ln as SystemSampleEntry, Lt as ilocBox, M as ac_4SampleEntry, Mn as AudioSampleEntry, Mt as mvhdBox, N as av01SampleEntry, Nn as HintSampleEntry, Nt as mfhdBox, O as stppSampleEntry, On as udtaBox, Ot as esdsBox, P as avc1SampleEntry, Pn as MetadataSampleEntry, Pt as metaBox, Q as hvc1SampleEntry, Qn as SingleItemTypeReferenceBox, Qt as grplBox, R as avs3SampleEntry, Rn as TextSampleEntry, Rt as iinfBox, S as sgpdBox, Sn as stblBox, St as vvs1SampleEntry, T as wvttSampleEntry, Tn as trafBox, Tt as vpcCBox, U as encaSampleEntry, Un as registerBoxes, Ut as hdlrBox, V as dvheSampleEntry, Vn as parseHex16, Vt as mdhdBox, W as encmSampleEntry, Wn as registerDescriptors, Wt as ftypBox, X as hev1SampleEntry, Xn as FullBox, Xt as etypBox, Y as fLaCSampleEntry, Yn as Box, Yt as edtsBox, Z as hev2SampleEntry, Zn as SampleGroupEntry, Zt as freeBox, _ as stscBox, _n as povdBox, _t as vp08SampleEntry, a as ISOFile, an as iproBox, ar as Endianness, at as m4aeSampleEntry, b as smhdBox, bn as sinfBox, bt as vvcNSampleEntry, c as urlBox, cn as mdatBox, ct as mhm1SampleEntry, d as tkhdBox, dn as mfraBox, dt as mjpgSampleEntry, en as hmhdBox, er as TrackGroupTypeBox, et as hvt1SampleEntry, f as tfhdBox, fn as minfBox, ft as mp4aSampleEntry, g as stsdBox, gn as nmhdBox, gt as uncvSampleEntry, h as stszBox, hn as mvexBox, ht as resvSampleEntry, i as createFile, in as ipcoBox, ir as DataStream, it as lvc1SampleEntry, j as ac_3SampleEntry, jn as avcCBox, jt as mettSampleEntry, k as sbttSampleEntry, kn as vttcBox, kt as av1CBox, l as trunBox, ln as mdiaBox, lt as mhm2SampleEntry, m as sttsBox, mn as moovBox, mt as mp4vSampleEntry, n as ssixBox, nn as idatBox, nr as MultiBufferStream, nt as lhe1SampleEntry, o as SampleGroupInfo, on as iprpBox, or as MP4BoxBuffer, ot as mha1SampleEntry, p as tfdtBox, pn as moofBox, pt as mp4sSampleEntry, q as encuSampleEntry, qn as boxEqual, qt as bxmlBox, r as emsgBox, rn as iodsBox, rr as Log, rt as lhv1SampleEntry, s as vmhdBox, sn as j2kHBox, sr as MAX_UINT32, st as mha2SampleEntry, t as stypBox, tn as hntiBox, tr as TrackReferenceTypeBox, tt as j2kiSampleEntry, u as trexBox, un as mecoBox, ut as mjp2SampleEntry, v as sthdBox, vn as rinfBox, vt as vp09SampleEntry, w as sbgpBox, wn as strkBox, wt as vvcCBox, x as sidxBox, xn as skipBox, xt as vvi1SampleEntry, y as stcoBox, yn as schiBox, yt as vvc1SampleEntry, z as dav1SampleEntry, zn as VisualSampleEntry, zt as infeBox } from "./styp-9TIZZDLN.mjs";++//#region src/descriptor.ts+var descriptor_exports = /* @__PURE__ */ __exportAll({+ Descriptor: () => Descriptor,+ ES_Descriptor: () => ES_Descriptor,+ MPEG4DescriptorParser: () => MPEG4DescriptorParser+});+const ES_DescrTag = 3;+const DecoderConfigDescrTag = 4;+const DecSpecificInfoTag = 5;+const SLConfigDescrTag = 6;+var Descriptor = class Descriptor {+ constructor(tag, size) {+ this.tag = tag;+ this.size = size;+ this.descs = [];+ }+ parse(stream) {+ this.data = stream.readUint8Array(this.size);+ }+ findDescriptor(tag) {+ for (let i = 0; i < this.descs.length; i++) if (this.descs[i].tag === tag) return this.descs[i];+ }+ parseOneDescriptor(stream) {+ let size = 0;+ const tag = stream.readUint8();+ let byteRead = stream.readUint8();+ while (byteRead & 128) {+ size = (size << 7) + (byteRead & 127);+ byteRead = stream.readUint8();+ }+ size = (size << 7) + (byteRead & 127);+ Log.debug("Descriptor", "Found " + (descTagToName[tag] || "Descriptor " + tag) + ", size " + size + " at position " + stream.getPosition());+ const desc = descTagToName[tag] ? new DESCRIPTOR_CLASSES[descTagToName[tag]](size) : new Descriptor(size);+ desc.parse(stream);+ return desc;+ }+ parseRemainingDescriptors(stream) {+ const start = stream.getPosition();+ while (stream.getPosition() < start + this.size) {+ const desc = this.parseOneDescriptor?.(stream);+ this.descs.push(desc);+ }+ }+};+var ES_Descriptor = class extends Descriptor {+ constructor(size) {+ super(ES_DescrTag, size);+ }+ parse(stream) {+ this.ES_ID = stream.readUint16();+ this.flags = stream.readUint8();+ this.size -= 3;+ if (this.flags & 128) {+ this.dependsOn_ES_ID = stream.readUint16();+ this.size -= 2;+ } else this.dependsOn_ES_ID = 0;+ if (this.flags & 64) {+ const l = stream.readUint8();+ this.URL = stream.readString(l);+ this.size -= l + 1;+ } else this.URL = "";+ if (this.flags & 32) {+ this.OCR_ES_ID = stream.readUint16();+ this.size -= 2;+ } else this.OCR_ES_ID = 0;+ this.parseRemainingDescriptors(stream);+ }+ getOTI() {+ const dcd = this.findDescriptor(DecoderConfigDescrTag);+ if (dcd) return dcd.oti;+ else return 0;+ }+ getAudioConfig() {+ const dcd = this.findDescriptor(DecoderConfigDescrTag);+ if (!dcd) return;+ const dsi = dcd.findDescriptor(DecSpecificInfoTag);+ if (dsi && dsi.data) {+ let audioObjectType = (dsi.data[0] & 248) >> 3;+ if (audioObjectType === 31 && dsi.data.length >= 2) audioObjectType = 32 + ((dsi.data[0] & 7) << 3) + ((dsi.data[1] & 224) >> 5);+ return audioObjectType;+ }+ }+};+var DecoderConfigDescriptor = class extends Descriptor {+ constructor(size) {+ super(DecoderConfigDescrTag, size);+ }+ parse(stream) {+ this.oti = stream.readUint8();+ this.streamType = stream.readUint8();+ this.upStream = (this.streamType >> 1 & 1) !== 0;+ this.streamType = this.streamType >>> 2;+ this.bufferSize = stream.readUint24();+ this.maxBitrate = stream.readUint32();+ this.avgBitrate = stream.readUint32();+ this.size -= 13;+ this.parseRemainingDescriptors(stream);+ }+};+var DecoderSpecificInfo = class extends Descriptor {+ constructor(size) {+ super(DecSpecificInfoTag, size);+ }+};+var SLConfigDescriptor = class extends Descriptor {+ constructor(size) {+ super(SLConfigDescrTag, size);+ }+};+const DESCRIPTOR_CLASSES = {+ Descriptor,+ ES_Descriptor,+ DecoderConfigDescriptor,+ DecoderSpecificInfo,+ SLConfigDescriptor+};+const descTagToName = {+ [ES_DescrTag]: "ES_Descriptor",+ [DecoderConfigDescrTag]: "DecoderConfigDescriptor",+ [DecSpecificInfoTag]: "DecoderSpecificInfo",+ [SLConfigDescrTag]: "SLConfigDescriptor"+};+var MPEG4DescriptorParser = class {+ constructor() {+ this.parseOneDescriptor = Descriptor.prototype.parseOneDescriptor;+ }+ getDescriptorName(tag) {+ return descTagToName[tag];+ }+};++//#endregion+//#region src/text-mp4.ts+var VTTin4Parser = class {+ parseSample(data) {+ const cues = [];+ const stream = new MultiBufferStream(MP4BoxBuffer.fromArrayBuffer(data.buffer, 0));+ while (!stream.isEof()) {+ const cue = parseOneBox(stream, false);+ if (cue.code === 1 && cue.box?.type === "vttc") cues.push(cue.box);+ }+ return cues;+ }+ getText(startTime, endTime, data) {+ function pad(value, width) {+ const string = value.toString();+ if (string.length >= width) return string;+ return new Array(width - string.length + 1).join("0") + string;+ }+ function secToTimestamp(insec) {+ const h = Math.floor(insec / 3600);+ const m = Math.floor((insec - h * 3600) / 60);+ const s = Math.floor(insec - h * 3600 - m * 60);+ const ms = Math.floor((insec - h * 3600 - m * 60 - s) * 1e3);+ return "" + pad(h, 2) + ":" + pad(m, 2) + ":" + pad(s, 2) + "." + pad(ms, 3);+ }+ const cues = this.parseSample(data);+ let string = "";+ for (let i = 0; i < cues.length; i++) {+ const cueIn4 = cues[i];+ string += secToTimestamp(startTime) + " --> " + secToTimestamp(endTime) + "\r\n";+ string += cueIn4.payl.text;+ }+ return string;+ }+};+var XMLSubtitlein4Parser = class {+ parseSample(sample) {+ const res = {+ resources: [],+ documentString: "",+ document: void 0+ };+ const stream = new DataStream(sample.data.buffer);+ if (!sample.subsamples || sample.subsamples.length === 0) res.documentString = stream.readString(sample.data.length);+ else {+ res.documentString = stream.readString(sample.subsamples[0].size);+ if (sample.subsamples.length > 1) for (let i = 1; i < sample.subsamples.length; i++) res.resources[i] = stream.readUint8Array(sample.subsamples[i].size);+ }+ if (typeof DOMParser !== "undefined") res.document = new DOMParser().parseFromString(res.documentString, "application/xml");+ return res;+ }+};+var Textin4Parser = class {+ parseSample(sample) {+ return new DataStream(sample.data.buffer).readString(sample.data.length);+ }+ parseConfig(data) {+ const stream = new DataStream(data.buffer);+ stream.readUint32();+ return stream.readCString();+ }+};+var TX3GParser = class {+ parseSample(sample) {+ const stream = new DataStream(sample.data.buffer);+ const size = stream.readUint16();+ if (size === 0) return;+ return stream.readString(size);+ }+};++//#endregion+//#region src/boxes/a1lx.ts+var a1lxBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "AV1LayeredImageIndexingProperty";+ }+ static {+ this.fourcc = "a1lx";+ }+ parse(stream) {+ const FieldLength = ((stream.readUint8() & 1) + 1) * 16;+ this.layer_size = [];+ for (let i = 0; i < 3; i++) if (FieldLength === 16) this.layer_size[i] = stream.readUint16();+ else this.layer_size[i] = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/a1op.ts+var a1opBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "OperatingPointSelectorProperty";+ }+ static {+ this.fourcc = "a1op";+ }+ parse(stream) {+ this.op_index = stream.readUint8();+ }+};++//#endregion+//#region src/boxes/auxC.ts+var auxCBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "AuxiliaryTypeProperty";+ }+ static {+ this.fourcc = "auxC";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.aux_type = stream.readCString();+ const aux_subtype_length = this.size - this.hdr_size - (this.aux_type.length + 1);+ this.aux_subtype = stream.readUint8Array(aux_subtype_length);+ }+};++//#endregion+//#region src/boxes/btrt.ts+var btrtBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "BitRateBox";+ }+ static {+ this.fourcc = "btrt";+ }+ parse(stream) {+ this.bufferSizeDB = stream.readUint32();+ this.maxBitrate = stream.readUint32();+ this.avgBitrate = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/ccst.ts+var ccstBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CodingConstraintsBox";+ }+ static {+ this.fourcc = "ccst";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const flags = stream.readUint8();+ this.all_ref_pics_intra = (flags & 128) === 128;+ this.intra_pred_used = (flags & 64) === 64;+ this.max_ref_per_pic = (flags & 63) >> 2;+ stream.readUint24();+ }+};++//#endregion+//#region src/boxes/cdef.ts+var cdefBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ComponentDefinitionBox";+ }+ static {+ this.fourcc = "cdef";+ }+ parse(stream) {+ this.channel_count = stream.readUint16();+ this.channel_indexes = [];+ this.channel_types = [];+ this.channel_associations = [];+ for (let i = 0; i < this.channel_count; i++) {+ this.channel_indexes.push(stream.readUint16());+ this.channel_types.push(stream.readUint16());+ this.channel_associations.push(stream.readUint16());+ }+ }+};++//#endregion+//#region src/boxes/clap.ts+var clapBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CleanApertureBox";+ }+ static {+ this.fourcc = "clap";+ }+ parse(stream) {+ this.cleanApertureWidthN = stream.readUint32();+ this.cleanApertureWidthD = stream.readUint32();+ this.cleanApertureHeightN = stream.readUint32();+ this.cleanApertureHeightD = stream.readUint32();+ this.horizOffN = stream.readUint32();+ this.horizOffD = stream.readUint32();+ this.vertOffN = stream.readUint32();+ this.vertOffD = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/clli.ts+var clliBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ContentLightLevelBox";+ }+ static {+ this.fourcc = "clli";+ }+ parse(stream) {+ this.max_content_light_level = stream.readUint16();+ this.max_pic_average_light_level = stream.readUint16();+ }+};++//#endregion+//#region src/boxes/cmex.ts+var cmexBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CameraExtrinsicMatrixProperty";+ }+ static {+ this.fourcc = "cmex";+ }+ parse(stream) {+ if (this.flags & 1) this.pos_x = stream.readInt32();+ if (this.flags & 2) this.pos_y = stream.readInt32();+ if (this.flags & 4) this.pos_z = stream.readInt32();+ if (this.flags & 8) {+ if (this.version === 0) if (this.flags & 16) {+ this.quat_x = stream.readInt32();+ this.quat_y = stream.readInt32();+ this.quat_z = stream.readInt32();+ } else {+ this.quat_x = stream.readInt16();+ this.quat_y = stream.readInt16();+ this.quat_z = stream.readInt16();+ }+ else if (this.version === 1) {}+ }+ if (this.flags & 32) this.id = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/cmin.ts+var cminBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CameraIntrinsicMatrixProperty";+ }+ static {+ this.fourcc = "cmin";+ }+ parse(stream) {+ this.focal_length_x = stream.readInt32();+ this.principal_point_x = stream.readInt32();+ this.principal_point_y = stream.readInt32();+ if (this.flags & 1) {+ this.focal_length_y = stream.readInt32();+ this.skew_factor = stream.readInt32();+ }+ }+};++//#endregion+//#region src/boxes/cmpC.ts+var cmpCBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CompressionConfigurationBox";+ }+ static {+ this.fourcc = "cmpC";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.compression_type = stream.readString(4);+ this.compressed_unit_type = stream.readUint8();+ }+};++//#endregion+//#region src/boxes/cmpd.ts+var cmpdBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ComponentDefinitionBox";+ }+ static {+ this.fourcc = "cmpd";+ }+ parse(stream) {+ this.component_count = stream.readUint32();+ this.component_types = [];+ this.component_type_urls = [];+ for (let i = 0; i < this.component_count; i++) {+ const component_type = stream.readUint16();+ this.component_types.push(component_type);+ if (component_type >= 32768) this.component_type_urls.push(stream.readCString());+ }+ }+};++//#endregion+//#region src/boxes/co64.ts+var co64Box = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ChunkLargeOffsetBox";+ }+ static {+ this.fourcc = "co64";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const entry_count = stream.readUint32();+ this.chunk_offsets = [];+ if (this.version === 0) for (let i = 0; i < entry_count; i++) this.chunk_offsets.push(stream.readUint64());+ }+ /** @bundle writing/co64.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 4 + 8 * this.chunk_offsets.length;+ this.writeHeader(stream);+ stream.writeUint32(this.chunk_offsets.length);+ for (let i = 0; i < this.chunk_offsets.length; i++) stream.writeUint64(this.chunk_offsets[i]);+ }+};++//#endregion+//#region src/boxes/CoLL.ts+var CoLLBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ContentLightLevelBox";+ }+ static {+ this.fourcc = "CoLL";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.maxCLL = stream.readUint16();+ this.maxFALL = stream.readUint16();+ }+};++//#endregion+//#region src/boxes/covi.ts+var SphereRegion = class {+ toString() {+ let s = "centre_azimuth: ";+ s += this.centre_azimuth;+ s += " (";+ s += this.centre_azimuth * 2 ** -16;+ s += "°), centre_elevation: ";+ s += this.centre_elevation;+ s += " (";+ s += this.centre_elevation * 2 ** -16;+ s += "°), centre_tilt: ";+ s += this.centre_tilt;+ s += " (";+ s += this.centre_tilt * 2 ** -16;+ s += "°)";+ if (this.range_included_flag) {+ s += ", azimuth_range: ";+ s += this.azimuth_range;+ s += " (";+ s += this.azimuth_range * 2 ** -16;+ s += "°), elevation_range: ";+ s += this.elevation_range;+ s += " (";+ s += this.elevation_range * 2 ** -16;+ s += "°)";+ }+ if (this.interpolate_included_flag) {+ s += ", interpolate: ";+ s += this.interpolate;+ }+ return s;+ }+};+var CoverageSphereRegion = class {+ toString() {+ let s = "";+ if (this.view_idc) {+ s += "view_idc: ";+ s += this.view_idc;+ s += ", ";+ }+ s += "sphere_region: {";+ s += this.sphere_region;+ s += "}";+ return s;+ }+};+var coviBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CoverageInformationBox";+ }+ static {+ this.fourcc = "covi";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.coverage_shape_type = stream.readUint8();+ const num_regions = stream.readUint8();+ const f = stream.readInt8();+ const view_idc_presence_flag = f & 128;+ if (view_idc_presence_flag) this.default_view_idc = (f & 96) >> 5;+ this.coverage_regions = new Array();+ for (let i = 0; i < num_regions; i++) {+ const region = new CoverageSphereRegion();+ if (view_idc_presence_flag) region.view_idc = stream.readUint8() >> 6;+ region.sphere_region = this.parseSphereRegion(stream, true, true);+ this.coverage_regions.push(region);+ }+ }+ parseSphereRegion(stream, range_included_flag, interpolate_included_flag) {+ const sphere_region = new SphereRegion();+ sphere_region.centre_azimuth = stream.readInt32();+ sphere_region.centre_elevation = stream.readInt32();+ sphere_region.centre_tilt = stream.readInt32();+ sphere_region.range_included_flag = range_included_flag;+ if (range_included_flag) {+ sphere_region.azimuth_range = stream.readUint32();+ sphere_region.elevation_range = stream.readUint32();+ }+ sphere_region.interpolate_included_flag = interpolate_included_flag;+ if (interpolate_included_flag) sphere_region.interpolate = (stream.readUint8() & 128) === 128;+ return sphere_region;+ }+};++//#endregion+//#region src/boxes/cprt.ts+var cprtBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CopyrightBox";+ }+ static {+ this.fourcc = "cprt";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.parseLanguage(stream);+ this.notice = stream.readCString();+ }+};++//#endregion+//#region src/boxes/csch.ts+var cschBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CompatibleSchemeTypeBox";+ }+ static {+ this.fourcc = "csch";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.scheme_type = stream.readString(4);+ this.scheme_version = stream.readUint32();+ if (this.flags & 1) this.scheme_uri = stream.readCString();+ }+};++//#endregion+//#region src/boxes/cslg.ts+const INT32_MAX = 2147483647;+var cslgBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CompositionToDecodeBox";+ }+ static {+ this.fourcc = "cslg";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 0) {+ this.compositionToDTSShift = stream.readInt32();+ this.leastDecodeToDisplayDelta = stream.readInt32();+ this.greatestDecodeToDisplayDelta = stream.readInt32();+ this.compositionStartTime = stream.readInt32();+ this.compositionEndTime = stream.readInt32();+ } else if (this.version === 1) {+ this.compositionToDTSShift = stream.readInt64();+ this.leastDecodeToDisplayDelta = stream.readInt64();+ this.greatestDecodeToDisplayDelta = stream.readInt64();+ this.compositionStartTime = stream.readInt64();+ this.compositionEndTime = stream.readInt64();+ }+ }+ /** @bundle writing/cslg.js */+ write(stream) {+ this.version = 0;+ if (this.compositionToDTSShift > INT32_MAX || this.leastDecodeToDisplayDelta > INT32_MAX || this.greatestDecodeToDisplayDelta > INT32_MAX || this.compositionStartTime > INT32_MAX || this.compositionEndTime > INT32_MAX) this.version = 1;+ this.flags = 0;+ if (this.version === 0) {+ this.size = 20;+ this.writeHeader(stream);+ stream.writeInt32(this.compositionToDTSShift);+ stream.writeInt32(this.leastDecodeToDisplayDelta);+ stream.writeInt32(this.greatestDecodeToDisplayDelta);+ stream.writeInt32(this.compositionStartTime);+ stream.writeInt32(this.compositionEndTime);+ } else if (this.version === 1) {+ this.size = 40;+ this.writeHeader(stream);+ stream.writeInt64(this.compositionToDTSShift);+ stream.writeInt64(this.leastDecodeToDisplayDelta);+ stream.writeInt64(this.greatestDecodeToDisplayDelta);+ stream.writeInt64(this.compositionStartTime);+ stream.writeInt64(this.compositionEndTime);+ }+ }+};++//#endregion+//#region src/boxes/ctts.ts+var cttsBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CompositionOffsetBox";+ }+ static {+ this.fourcc = "ctts";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const entry_count = stream.readUint32();+ this.sample_counts = [];+ this.sample_offsets = [];+ if (this.version === 0) for (let i = 0; i < entry_count; i++) {+ this.sample_counts.push(stream.readUint32());+ const value = stream.readInt32();+ if (value < 0) Log.warn("BoxParser", "ctts box uses negative values without using version 1");+ this.sample_offsets.push(value);+ }+ else if (this.version === 1) for (let i = 0; i < entry_count; i++) {+ this.sample_counts.push(stream.readUint32());+ this.sample_offsets.push(stream.readInt32());+ }+ }+ /** @bundle writing/ctts.js */+ write(stream) {+ this.version = this.sample_offsets.some((offset) => offset < 0) ? 1 : 0;+ this.flags = 0;+ this.size = 4 + 8 * this.sample_counts.length;+ this.writeHeader(stream);+ stream.writeUint32(this.sample_counts.length);+ for (let i = 0; i < this.sample_counts.length; i++) {+ stream.writeUint32(this.sample_counts[i]);+ if (this.version === 1) stream.writeInt32(this.sample_offsets[i]);+ else stream.writeUint32(this.sample_offsets[i]);+ }+ }+ /** @bundle box-unpack.js */+ unpack(samples) {+ let k = 0;+ for (let i = 0; i < this.sample_counts.length; i++) for (let j = 0; j < this.sample_counts[i]; j++) {+ samples[k].pts = samples[k].dts + this.sample_offsets[i];+ k++;+ }+ }+};++//#endregion+//#region src/boxes/dac3.ts+var dac3Box = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "AC3SpecificBox";+ }+ static {+ this.fourcc = "dac3";+ }+ parse(stream) {+ const tmp_byte1 = stream.readUint8();+ const tmp_byte2 = stream.readUint8();+ const tmp_byte3 = stream.readUint8();+ this.fscod = tmp_byte1 >> 6;+ this.bsid = tmp_byte1 >> 1 & 31;+ this.bsmod = (tmp_byte1 & 1) << 2 | tmp_byte2 >> 6 & 3;+ this.acmod = tmp_byte2 >> 3 & 7;+ this.lfeon = tmp_byte2 >> 2 & 1;+ this.bit_rate_code = tmp_byte2 & 3 | tmp_byte3 >> 5 & 7;+ }+};++//#endregion+//#region src/boxes/dec3.ts+var dec3Box = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "EC3SpecificBox";+ }+ static {+ this.fourcc = "dec3";+ }+ parse(stream) {+ const tmp_16 = stream.readUint16();+ this.data_rate = tmp_16 >> 3;+ this.num_ind_sub = tmp_16 & 7;+ this.ind_subs = [];+ for (let i = 0; i < this.num_ind_sub + 1; i++) {+ const tmp_byte1 = stream.readUint8();+ const tmp_byte2 = stream.readUint8();+ const tmp_byte3 = stream.readUint8();+ const ind_sub = {+ fscod: tmp_byte1 >> 6,+ bsid: tmp_byte1 >> 1 & 31,+ bsmod: (tmp_byte1 & 1) << 4 | tmp_byte2 >> 4 & 15,+ acmod: tmp_byte2 >> 1 & 7,+ lfeon: tmp_byte2 & 1,+ num_dep_sub: tmp_byte3 >> 1 & 15+ };+ this.ind_subs.push(ind_sub);+ if (ind_sub.num_dep_sub > 0) ind_sub.chan_loc = (tmp_byte3 & 1) << 8 | stream.readUint8();+ }+ }+};++//#endregion+//#region src/boxes/dfLa.ts+var dfLaBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "FLACSpecificBox";+ }+ static {+ this.fourcc = "dfLa";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const BLOCKTYPE_MASK = 127;+ const LASTMETADATABLOCKFLAG_MASK = 128;+ const boxesFound = [];+ const knownBlockTypes = [+ "STREAMINFO",+ "PADDING",+ "APPLICATION",+ "SEEKTABLE",+ "VORBIS_COMMENT",+ "CUESHEET",+ "PICTURE",+ "RESERVED"+ ];+ let flagAndType;+ do {+ flagAndType = stream.readUint8();+ const type = Math.min(flagAndType & BLOCKTYPE_MASK, knownBlockTypes.length - 1);+ if (!type) {+ stream.readUint8Array(13);+ this.samplerate = stream.readUint32() >> 12;+ stream.readUint8Array(20);+ } else stream.readUint8Array(stream.readUint24());+ boxesFound.push(knownBlockTypes[type]);+ } while (flagAndType & LASTMETADATABLOCKFLAG_MASK);+ this.numMetadataBlocks = boxesFound.length + " (" + boxesFound.join(", ") + ")";+ }+};++//#endregion+//#region src/boxes/dimm.ts+var dimmBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintimmediateBytesSent";+ }+ static {+ this.fourcc = "dimm";+ }+ parse(stream) {+ this.bytessent = stream.readUint64();+ }+};++//#endregion+//#region src/boxes/dmax.ts+var dmax = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintlongestpacket";+ }+ static {+ this.fourcc = "dmax";+ }+ parse(stream) {+ this.time = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/dmed.ts+var dmedBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintmediaBytesSent";+ }+ static {+ this.fourcc = "dmed";+ }+ parse(stream) {+ this.bytessent = stream.readUint64();+ }+};++//#endregion+//#region src/boxes/dOps.ts+var dOpsBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "OpusSpecificBox";+ }+ static {+ this.fourcc = "dOps";+ }+ parse(stream) {+ this.Version = stream.readUint8();+ this.OutputChannelCount = stream.readUint8();+ this.PreSkip = stream.readUint16();+ this.InputSampleRate = stream.readUint32();+ this.OutputGain = stream.readInt16();+ this.ChannelMappingFamily = stream.readUint8();+ if (this.ChannelMappingFamily !== 0) {+ this.StreamCount = stream.readUint8();+ this.CoupledCount = stream.readUint8();+ this.ChannelMapping = [];+ for (let i = 0; i < this.OutputChannelCount; i++) this.ChannelMapping[i] = stream.readUint8();+ }+ }+ write(stream) {+ this.size = 11;+ if (this.ChannelMappingFamily !== 0) this.size += 2 + this.OutputChannelCount;+ this.writeHeader(stream);+ stream.writeUint8(this.Version);+ stream.writeUint8(this.OutputChannelCount);+ stream.writeUint16(this.PreSkip);+ stream.writeUint32(this.InputSampleRate);+ stream.writeInt16(this.OutputGain);+ stream.writeUint8(this.ChannelMappingFamily);+ if (this.ChannelMappingFamily !== 0) {+ stream.writeUint8(this.StreamCount);+ stream.writeUint8(this.CoupledCount);+ for (let i = 0; i < this.OutputChannelCount; i++) stream.writeUint8(this.ChannelMapping[i]);+ }+ }+};++//#endregion+//#region src/boxes/drep.ts+var drepBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintrepeatedBytesSent";+ }+ static {+ this.fourcc = "drep";+ }+ parse(stream) {+ this.bytessent = stream.readUint64();+ }+};++//#endregion+//#region src/boxes/elst.ts+var elstBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "EditListBox";+ }+ static {+ this.fourcc = "elst";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.entries = [];+ const entry_count = stream.readUint32();+ for (let i = 0; i < entry_count; i++) {+ const entry = {+ segment_duration: this.version === 1 ? stream.readUint64() : stream.readUint32(),+ media_time: this.version === 1 ? stream.readInt64() : stream.readInt32(),+ media_rate_integer: stream.readInt16(),+ media_rate_fraction: stream.readInt16()+ };+ this.entries.push(entry);+ }+ }+ /** @bundle writing/elst.js */+ write(stream) {+ const useVersion1 = this.entries.some((entry) => entry.segment_duration > MAX_UINT32 || entry.media_time > MAX_UINT32) || this.version === 1;+ this.version = useVersion1 ? 1 : 0;+ this.size = 4 + 12 * this.entries.length;+ this.size += useVersion1 ? 8 * this.entries.length : 0;+ this.writeHeader(stream);+ stream.writeUint32(this.entries.length);+ for (let i = 0; i < this.entries.length; i++) {+ const entry = this.entries[i];+ if (useVersion1) {+ stream.writeUint64(entry.segment_duration);+ stream.writeInt64(entry.media_time);+ } else {+ stream.writeUint32(entry.segment_duration);+ stream.writeInt32(entry.media_time);+ }+ stream.writeInt16(entry.media_rate_integer);+ stream.writeInt16(entry.media_rate_fraction);+ }+ }+};++//#endregion+//#region src/boxes/EntityToGroup/base.ts+var EntityToGroup = class extends FullBox {+ parse(stream) {+ this.parseFullHeader(stream);+ this.group_id = stream.readUint32();+ this.num_entities_in_group = stream.readUint32();+ this.entity_ids = [];+ for (let i = 0; i < this.num_entities_in_group; i++) {+ const entity_id = stream.readUint32();+ this.entity_ids.push(entity_id);+ }+ }+};++//#endregion+//#region src/boxes/EntityToGroup/index.ts+var aebrBox = class extends EntityToGroup {+ constructor(..._args) {+ super(..._args);+ this.box_name = "Auto exposure bracketing";+ }+ static {+ this.fourcc = "aebr";+ }+};+var afbrBox = class extends EntityToGroup {+ constructor(..._args2) {+ super(..._args2);+ this.box_name = "Flash exposure information";+ }+ static {+ this.fourcc = "afbr";+ }+};+var albcBox = class extends EntityToGroup {+ constructor(..._args3) {+ super(..._args3);+ this.box_name = "Album collection";+ }+ static {+ this.fourcc = "albc";+ }+};+var altrBox = class extends EntityToGroup {+ constructor(..._args4) {+ super(..._args4);+ this.box_name = "Alternative entity";+ }+ static {+ this.fourcc = "altr";+ }+};+var brstBox = class extends EntityToGroup {+ constructor(..._args5) {+ super(..._args5);+ this.box_name = "Burst image";+ }+ static {+ this.fourcc = "brst";+ }+};+var dobrBox = class extends EntityToGroup {+ constructor(..._args6) {+ super(..._args6);+ this.box_name = "Depth of field bracketing";+ }+ static {+ this.fourcc = "dobr";+ }+};+var eqivBox = class extends EntityToGroup {+ constructor(..._args7) {+ super(..._args7);+ this.box_name = "Equivalent entity";+ }+ static {+ this.fourcc = "eqiv";+ }+};+var favcBox = class extends EntityToGroup {+ constructor(..._args8) {+ super(..._args8);+ this.box_name = "Favorites collection";+ }+ static {+ this.fourcc = "favc";+ }+};+var fobrBox = class extends EntityToGroup {+ constructor(..._args9) {+ super(..._args9);+ this.box_name = "Focus bracketing";+ }+ static {+ this.fourcc = "fobr";+ }+};+var iaugBox = class extends EntityToGroup {+ constructor(..._args10) {+ super(..._args10);+ this.box_name = "Image item with an audio track";+ }+ static {+ this.fourcc = "iaug";+ }+};+var panoBox = class extends EntityToGroup {+ constructor(..._args11) {+ super(..._args11);+ this.box_name = "Panorama";+ }+ static {+ this.fourcc = "pano";+ }+};+var slidBox = class extends EntityToGroup {+ constructor(..._args12) {+ super(..._args12);+ this.box_name = "Slideshow";+ }+ static {+ this.fourcc = "slid";+ }+};+var sterBox = class extends EntityToGroup {+ constructor(..._args13) {+ super(..._args13);+ this.box_name = "Stereo";+ }+ static {+ this.fourcc = "ster";+ }+};+var tsynBox = class extends EntityToGroup {+ constructor(..._args14) {+ super(..._args14);+ this.box_name = "Time-synchronized capture";+ }+ static {+ this.fourcc = "tsyn";+ }+};+var wbbrBox = class extends EntityToGroup {+ constructor(..._args15) {+ super(..._args15);+ this.box_name = "White balance bracketing";+ }+ static {+ this.fourcc = "wbbr";+ }+};+var prgrBox = class extends EntityToGroup {+ constructor(..._args16) {+ super(..._args16);+ this.box_name = "Progressive rendering";+ }+ static {+ this.fourcc = "prgr";+ }+};+var pymdBox = class extends EntityToGroup {+ constructor(..._args17) {+ super(..._args17);+ this.box_name = "Image pyramid";+ }+ static {+ this.fourcc = "pymd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.group_id = stream.readUint32();+ this.num_entities_in_group = stream.readUint32();+ this.entity_ids = [];+ for (let i = 0; i < this.num_entities_in_group; i++) {+ const entity_id = stream.readUint32();+ this.entity_ids.push(entity_id);+ }+ this.tile_size_x = stream.readUint16();+ this.tile_size_y = stream.readUint16();+ this.layer_binning = [];+ this.tiles_in_layer_column_minus1 = [];+ this.tiles_in_layer_row_minus1 = [];+ for (let i = 0; i < this.num_entities_in_group; i++) {+ this.layer_binning[i] = stream.readUint16();+ this.tiles_in_layer_row_minus1[i] = stream.readUint16();+ this.tiles_in_layer_column_minus1[i] = stream.readUint16();+ }+ }+};++//#endregion+//#region src/boxes/fiel.ts+var fielBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "FieldHandlingBox";+ }+ static {+ this.fourcc = "fiel";+ }+ parse(stream) {+ this.fieldCount = stream.readUint8();+ this.fieldOrdering = stream.readUint8();+ }+};++//#endregion+//#region src/boxes/frma.ts+var frmaBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "OriginalFormatBox";+ }+ static {+ this.fourcc = "frma";+ }+ parse(stream) {+ this.data_format = stream.readString(4);+ }+};++//#endregion+//#region src/boxes/imir.ts+var imirBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ImageMirror";+ }+ static {+ this.fourcc = "imir";+ }+ parse(stream) {+ const tmp = stream.readUint8();+ this.reserved = tmp >> 7;+ this.axis = tmp & 1;+ }+};++//#endregion+//#region src/boxes/ipma.ts+var ipmaBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ItemPropertyAssociationBox";+ }+ static {+ this.fourcc = "ipma";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const entry_count = stream.readUint32();+ this.associations = [];+ for (let i = 0; i < entry_count; i++) {+ const id = this.version < 1 ? stream.readUint16() : stream.readUint32();+ const props = [];+ const association_count = stream.readUint8();+ for (let j = 0; j < association_count; j++) {+ const tmp = stream.readUint8();+ props.push({+ essential: (tmp & 128) >> 7 === 1,+ property_index: this.flags & 1 ? (tmp & 127) << 8 | stream.readUint8() : tmp & 127+ });+ }+ this.associations.push({+ id,+ props+ });+ }+ }+};++//#endregion+//#region src/boxes/irot.ts+var irotBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ImageRotation";+ }+ static {+ this.fourcc = "irot";+ }+ parse(stream) {+ this.angle = stream.readUint8() & 3;+ }+};++//#endregion+//#region src/boxes/ispe.ts+var ispeBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ImageSpatialExtentsProperty";+ }+ static {+ this.fourcc = "ispe";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.image_width = stream.readUint32();+ this.image_height = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/itai.ts+var itaiBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TAITimestampBox";+ }+ static {+ this.fourcc = "itai";+ }+ parse(stream) {+ this.TAI_timestamp = stream.readUint64();+ const status_bits = stream.readUint8();+ this.sychronization_state = status_bits >> 7 & 1;+ this.timestamp_generation_failure = status_bits >> 6 & 1;+ this.timestamp_is_modified = status_bits >> 5 & 1;+ }+};++//#endregion+//#region src/boxes/kind.ts+var kindBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "KindBox";+ }+ static {+ this.fourcc = "kind";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.schemeURI = stream.readCString();+ if (!this.isEndOfBox(stream)) this.value = stream.readCString();+ }+ /** @bundle writing/kind.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = this.schemeURI.length + 1 + (this.value ? this.value.length + 1 : 0);+ this.writeHeader(stream);+ stream.writeCString(this.schemeURI);+ if (this.value) stream.writeCString(this.value);+ }+};++//#endregion+//#region src/boxes/leva.ts+var levaBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "LevelAssignmentBox";+ }+ static {+ this.fourcc = "leva";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const count = stream.readUint8();+ this.levels = [];+ for (let i = 0; i < count; i++) {+ const level = {};+ this.levels[i] = level;+ level.track_ID = stream.readUint32();+ const tmp_byte = stream.readUint8();+ level.padding_flag = tmp_byte >> 7;+ level.assignment_type = tmp_byte & 127;+ switch (level.assignment_type) {+ case 0:+ level.grouping_type = stream.readString(4);+ break;+ case 1:+ level.grouping_type = stream.readString(4);+ level.grouping_type_parameter = stream.readUint32();+ break;+ case 2: break;+ case 3: break;+ case 4:+ level.sub_track_id = stream.readUint32();+ break;+ default: Log.warn("BoxParser", `Unknown level assignment type: ${level.assignment_type}`);+ }+ }+ }+};++//#endregion+//#region src/boxes/lhvC.ts+var lhvCBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "LHEVCConfigurationBox";+ }+ static {+ this.fourcc = "lhvC";+ }+ parse(stream) {+ this.configurationVersion = stream.readUint8();+ this.min_spatial_segmentation_idc = stream.readUint16() & 4095;+ this.parallelismType = stream.readUint8() & 3;+ let tmp_byte = stream.readUint8();+ this.numTemporalLayers = (tmp_byte & 13) >> 3;+ this.temporalIdNested = (tmp_byte & 4) >> 2;+ this.lengthSizeMinusOne = tmp_byte & 3;+ this.nalu_arrays = [];+ const numOfArrays = stream.readUint8();+ for (let i = 0; i < numOfArrays; i++) {+ const nalu_array = [];+ this.nalu_arrays.push(nalu_array);+ tmp_byte = stream.readUint8();+ nalu_array.completeness = (tmp_byte & 128) >> 7;+ nalu_array.nalu_type = tmp_byte & 63;+ const numNalus = stream.readUint16();+ for (let j = 0; j < numNalus; j++) {+ const length = stream.readUint16();+ nalu_array.push({ data: stream.readUint8Array(length) });+ }+ }+ }+};++//#endregion+//#region src/boxes/lsel.ts+var lselBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "LayerSelectorProperty";+ }+ static {+ this.fourcc = "lsel";+ }+ parse(stream) {+ this.layer_id = stream.readUint16();+ }+};++//#endregion+//#region src/boxes/maxr.ts+var maxrBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintmaxrate";+ }+ static {+ this.fourcc = "maxr";+ }+ parse(stream) {+ this.period = stream.readUint32();+ this.bytes = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/displays/colorPoint.ts+var ColorPoint = class {+ constructor(x, y) {+ this.x = x;+ this.y = y;+ }+ toString() {+ return "(" + this.x + "," + this.y + ")";+ }+};++//#endregion+//#region src/boxes/mdcv.ts+var mdcvBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "MasteringDisplayColourVolumeBox";+ }+ static {+ this.fourcc = "mdcv";+ }+ parse(stream) {+ this.display_primaries = [];+ this.display_primaries[0] = new ColorPoint(stream.readUint16(), stream.readUint16());+ this.display_primaries[1] = new ColorPoint(stream.readUint16(), stream.readUint16());+ this.display_primaries[2] = new ColorPoint(stream.readUint16(), stream.readUint16());+ this.white_point = new ColorPoint(stream.readUint16(), stream.readUint16());+ this.max_display_mastering_luminance = stream.readUint32();+ this.min_display_mastering_luminance = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/mfro.ts+var mfroBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "MovieFragmentRandomAccessOffsetBox";+ }+ static {+ this.fourcc = "mfro";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this._size = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/mskC.ts+var mskCBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "MaskConfigurationProperty";+ }+ static {+ this.fourcc = "mskC";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.bits_per_pixel = stream.readUint8();+ }+};++//#endregion+//#region src/boxes/npck.ts+var npckBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintPacketsSent";+ }+ static {+ this.fourcc = "npck";+ }+ parse(stream) {+ this.packetssent = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/nump.ts+var numpBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintPacketsSent";+ }+ static {+ this.fourcc = "nump";+ }+ parse(stream) {+ this.packetssent = stream.readUint64();+ }+};++//#endregion+//#region src/boxes/padb.ts+var PaddingBit = class {+ constructor(pad1, pad2) {+ this.pad1 = pad1;+ this.pad2 = pad2;+ }+};+var padbBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "PaddingBitsBox";+ }+ static {+ this.fourcc = "padb";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const sample_count = stream.readUint32();+ this.padbits = [];+ for (let i = 0; i < Math.floor((sample_count + 1) / 2); i++) {+ const bits = stream.readUint8();+ const pad1 = (bits & 112) >> 4;+ const pad2 = bits & 7;+ this.padbits.push(new PaddingBit(pad1, pad2));+ }+ }+};++//#endregion+//#region src/boxes/pasp.ts+var paspBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "PixelAspectRatioBox";+ }+ static {+ this.fourcc = "pasp";+ }+ parse(stream) {+ this.hSpacing = stream.readUint32();+ this.vSpacing = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/payl.ts+var paylBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CuePayloadBox";+ }+ static {+ this.fourcc = "payl";+ }+ parse(stream) {+ this.text = stream.readString(this.size - this.hdr_size);+ }+};++//#endregion+//#region src/boxes/payt.ts+var paytBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintpayloadID";+ }+ static {+ this.fourcc = "payt";+ }+ parse(stream) {+ this.payloadID = stream.readUint32();+ const count = stream.readUint8();+ this.rtpmap_string = stream.readString(count);+ }+};++//#endregion+//#region src/boxes/pdin.ts+var pdinBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ProgressiveDownloadInfoBox";+ this.rate = [];+ this.initial_delay = [];+ }+ static {+ this.fourcc = "pdin";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const count = (this.size - this.hdr_size) / 8;+ for (let i = 0; i < count; i++) {+ this.rate[i] = stream.readUint32();+ this.initial_delay[i] = stream.readUint32();+ }+ }+};++//#endregion+//#region src/boxes/pixi.ts+var pixiBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "PixelInformationProperty";+ }+ static {+ this.fourcc = "pixi";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.num_channels = stream.readUint8();+ this.bits_per_channels = [];+ for (let i = 0; i < this.num_channels; i++) this.bits_per_channels[i] = stream.readUint8();+ }+};++//#endregion+//#region src/boxes/pmax.ts+var pmaxBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintlargestpacket";+ }+ static {+ this.fourcc = "pmax";+ }+ parse(stream) {+ this.bytes = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/prdi.ts+var prdiBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ProgressiveDerivedImageItemInformationProperty";+ }+ static {+ this.fourcc = "prdi";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.step_count = stream.readUint16();+ this.item_count = [];+ if (this.flags & 2) for (let i = 0; i < this.step_count; i++) this.item_count[i] = stream.readUint16();+ }+};++//#endregion+//#region src/boxes/prfr.ts+var prfrBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ProjectionFormatBox";+ }+ static {+ this.fourcc = "prfr";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.projection_type = stream.readUint8() & 31;+ }+};++//#endregion+//#region src/boxes/prft.ts+var prftBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ProducerReferenceTimeBox";+ }+ static {+ this.fourcc = "prft";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.ref_track_id = stream.readUint32();+ this.ntp_timestamp = stream.readUint64();+ if (this.version === 0) this.media_time = stream.readUint32();+ else this.media_time = stream.readUint64();+ }+};++//#endregion+//#region src/boxes/pssh.ts+var psshBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ProtectionSystemSpecificHeaderBox";+ }+ static {+ this.fourcc = "pssh";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.system_id = parseHex16(stream);+ this.kid = [];+ if (this.version > 0) {+ const count = stream.readUint32();+ for (let i = 0; i < count; i++) this.kid[i] = parseHex16(stream);+ }+ const datasize = stream.readUint32();+ if (datasize > 0) this.protection_data = stream.readUint8Array(datasize);+ }+};++//#endregion+//#region src/boxes/qt/clef.ts+var clefBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackCleanApertureDimensionsBox";+ }+ static {+ this.fourcc = "clef";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.width = stream.readUint32();+ this.height = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/qt/data.ts+function parseItifData(type, data) {+ if (type === dataBox.Types.UTF8) return new TextDecoder("utf-8").decode(data);+ const view = new DataView(data.buffer);+ if (type === dataBox.Types.BE_UNSIGNED_INT) if (data.length === 1) return view.getUint8(0);+ else if (data.length === 2) return view.getUint16(0, false);+ else if (data.length === 4) return view.getUint32(0, false);+ else if (data.length === 8) return view.getBigUint64(0, false);+ else throw new Error("Unsupported ITIF_TYPE_BE_UNSIGNED_INT length " + data.length);+ else if (type === dataBox.Types.BE_SIGNED_INT) if (data.length === 1) return view.getInt8(0);+ else if (data.length === 2) return view.getInt16(0, false);+ else if (data.length === 4) return view.getInt32(0, false);+ else if (data.length === 8) return view.getBigInt64(0, false);+ else throw new Error("Unsupported ITIF_TYPE_BE_SIGNED_INT length " + data.length);+ else if (type === dataBox.Types.BE_FLOAT32) return view.getFloat32(0, false);+ Log.warn("DataBox", "Unsupported or unimplemented itif data type: " + type);+}+var dataBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "DataBox";+ }+ static {+ this.fourcc = "data";+ }+ static {+ this.Types = {+ RESERVED: 0,+ UTF8: 1,+ UTF16: 2,+ SJIS: 3,+ UTF8_SORT: 4,+ UTF16_SORT: 5,+ JPEG: 13,+ PNG: 14,+ BE_SIGNED_INT: 21,+ BE_UNSIGNED_INT: 22,+ BE_FLOAT32: 23,+ BE_FLOAT64: 24,+ BMP: 27,+ QT_ATOM: 28,+ BE_SIGNED_INT8: 65,+ BE_SIGNED_INT16: 66,+ BE_SIGNED_INT32: 67,+ BE_FLOAT32_POINT: 70,+ BE_FLOAT32_DIMENSIONS: 71,+ BE_FLOAT32_RECT: 72,+ BE_SIGNED_INT64: 74,+ BE_UNSIGNED_INT8: 75,+ BE_UNSIGNED_INT16: 76,+ BE_UNSIGNED_INT32: 77,+ BE_UNSIGNED_INT64: 78,+ BE_FLOAT64_AFFINE_TRANSFORM: 79+ };+ }+ parse(stream) {+ this.valueType = stream.readUint32();+ this.country = stream.readUint16();+ if (this.country > 255) {+ stream.seek(stream.getPosition() - 2);+ this.countryString = stream.readString(2);+ }+ this.language = stream.readUint16();+ if (this.language > 255) {+ stream.seek(stream.getPosition() - 2);+ this.parseLanguage(stream);+ }+ this.raw = stream.readUint8Array(this.size - this.hdr_size - 8);+ this.value = parseItifData(this.valueType, this.raw);+ }+};++//#endregion+//#region src/boxes/qt/enof.ts+var enofBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackEncodedPixelsDimensionsBox";+ }+ static {+ this.fourcc = "enof";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.width = stream.readUint32();+ this.height = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/qt/ilst.ts+var ilstBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "IlstBox";+ }+ static {+ this.fourcc = "ilst";+ }+ parse(stream) {+ this.list = {};+ let total = this.size - this.hdr_size;+ while (total > 0) {+ const size = stream.readUint32();+ const index = stream.readUint32();+ const res = parseOneBox(stream, false, size - 8);+ if (res.code === 1) this.list[index] = res.box;+ total -= size;+ }+ }+};++//#endregion+//#region src/boxes/qt/keys.ts+var keysBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "KeysBox";+ }+ static {+ this.fourcc = "keys";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.count = stream.readUint32();+ this.keys = {};+ for (let i = 0; i < this.count; i++) {+ const len = stream.readUint32();+ this.keys[i + 1] = stream.readString(len - 4);+ }+ }+};++//#endregion+//#region src/boxes/qt/prof.ts+var profBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackProductionApertureDimensionsBox";+ }+ static {+ this.fourcc = "prof";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.width = stream.readUint32();+ this.height = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/qt/tapt.ts+var taptBox = class extends ContainerBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackApertureModeDimensionsBox";+ this.clefs = [];+ this.profs = [];+ this.enofs = [];+ this.subBoxNames = [+ "clef",+ "prof",+ "enof"+ ];+ }+ static {+ this.fourcc = "tapt";+ }+};++//#endregion+//#region src/boxes/rtp.ts+var rtp_Box = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "rtpmoviehintinformation";+ }+ static {+ this.fourcc = "rtp ";+ }+ parse(stream) {+ this.descriptionformat = stream.readString(4);+ this.sdptext = stream.readString(this.size - this.hdr_size - 4);+ }+};++//#endregion+//#region src/boxes/saio.ts+var saioBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SampleAuxiliaryInformationOffsetsBox";+ }+ static {+ this.fourcc = "saio";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.flags & 1) {+ this.aux_info_type = stream.readString(4);+ this.aux_info_type_parameter = stream.readUint32();+ }+ this.entry_count = stream.readUint32();+ this.offset = [];+ for (let i = 0; i < this.entry_count; i++) if (this.version === 0) this.offset[i] = stream.readUint32();+ else this.offset[i] = stream.readUint64();+ }+};++//#endregion+//#region src/boxes/saiz.ts+var saizBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SampleAuxiliaryInformationSizesBox";+ }+ static {+ this.fourcc = "saiz";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.flags & 1) {+ this.aux_info_type = stream.readString(4);+ this.aux_info_type_parameter = stream.readUint32();+ }+ this.default_sample_info_size = stream.readUint8();+ this.sample_count = stream.readUint32();+ this.sample_info_size = [];+ if (this.default_sample_info_size === 0) for (let i = 0; i < this.sample_count; i++) this.sample_info_size[i] = stream.readUint8();+ }+};++//#endregion+//#region src/boxes/displays/pixel.ts+var Pixel = class {+ constructor(bad_pixel_row, bad_pixel_column) {+ this.bad_pixel_row = bad_pixel_row;+ this.bad_pixel_column = bad_pixel_column;+ }+ toString() {+ return "[row: " + this.bad_pixel_row + ", column: " + this.bad_pixel_column + "]";+ }+};++//#endregion+//#region src/boxes/sbpm.ts+var sbpmBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SensorBadPixelsMapBox";+ }+ static {+ this.fourcc = "sbpm";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.component_count = stream.readUint16();+ this.component_index = [];+ for (let i = 0; i < this.component_count; i++) this.component_index.push(stream.readUint16());+ const flags = stream.readUint8();+ this.correction_applied = 128 === (flags & 128);+ this.num_bad_rows = stream.readUint32();+ this.num_bad_cols = stream.readUint32();+ this.num_bad_pixels = stream.readUint32();+ this.bad_rows = [];+ this.bad_columns = [];+ this.bad_pixels = [];+ for (let i = 0; i < this.num_bad_rows; i++) this.bad_rows.push(stream.readUint32());+ for (let i = 0; i < this.num_bad_cols; i++) this.bad_columns.push(stream.readUint32());+ for (let i = 0; i < this.num_bad_pixels; i++) {+ const row = stream.readUint32();+ const col = stream.readUint32();+ this.bad_pixels.push(new Pixel(row, col));+ }+ }+};++//#endregion+//#region src/boxes/schm.ts+var schmBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SchemeTypeBox";+ }+ static {+ this.fourcc = "schm";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.scheme_type = stream.readString(4);+ this.scheme_version = stream.readUint32();+ if (this.flags & 1) this.scheme_uri = stream.readString(this.size - this.hdr_size - 8);+ }+};++//#endregion+//#region src/boxes/sdp.ts+var sdp_Box = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "rtptracksdphintinformation";+ }+ static {+ this.fourcc = "sdp ";+ }+ parse(stream) {+ this.sdptext = stream.readString(this.size - this.hdr_size);+ }+};++//#endregion+//#region src/boxes/senc.ts+var sencBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SampleEncryptionBox";+ }+ static {+ this.fourcc = "senc";+ }+};++//#endregion+//#region src/boxes/SmDm.ts+var SmDmBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SMPTE2086MasteringDisplayMetadataBox";+ }+ static {+ this.fourcc = "SmDm";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.primaryRChromaticity_x = stream.readUint16();+ this.primaryRChromaticity_y = stream.readUint16();+ this.primaryGChromaticity_x = stream.readUint16();+ this.primaryGChromaticity_y = stream.readUint16();+ this.primaryBChromaticity_x = stream.readUint16();+ this.primaryBChromaticity_y = stream.readUint16();+ this.whitePointChromaticity_x = stream.readUint16();+ this.whitePointChromaticity_y = stream.readUint16();+ this.luminanceMax = stream.readUint32();+ this.luminanceMin = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/srat.ts+var sratBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SamplingRateBox";+ }+ static {+ this.fourcc = "srat";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.sampling_rate = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/stdp.ts+var stdpBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "DegradationPriorityBox";+ }+ static {+ this.fourcc = "stdp";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const count = (this.size - this.hdr_size) / 2;+ this.priority = [];+ for (let i = 0; i < count; i++) this.priority[i] = stream.readUint16();+ }+};++//#endregion+//#region src/boxes/stri.ts+var striBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SubTrackInformationBox";+ }+ static {+ this.fourcc = "stri";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.switch_group = stream.readUint16();+ this.alternate_group = stream.readUint16();+ this.sub_track_id = stream.readUint32();+ const count = (this.size - this.hdr_size - 8) / 4;+ this.attribute_list = [];+ for (let i = 0; i < count; i++) this.attribute_list[i] = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/stsg.ts+var stsgBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SubTrackSampleGroupBox";+ }+ static {+ this.fourcc = "stsg";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.grouping_type = stream.readUint32();+ const count = stream.readUint16();+ this.group_description_index = [];+ for (let i = 0; i < count; i++) this.group_description_index[i] = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/stsh.ts+var stshBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ShadowSyncSampleBox";+ }+ static {+ this.fourcc = "stsh";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const entry_count = stream.readUint32();+ this.shadowed_sample_numbers = [];+ this.sync_sample_numbers = [];+ if (this.version === 0) for (let i = 0; i < entry_count; i++) {+ this.shadowed_sample_numbers.push(stream.readUint32());+ this.sync_sample_numbers.push(stream.readUint32());+ }+ }+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 4 + 8 * this.shadowed_sample_numbers.length;+ this.writeHeader(stream);+ stream.writeUint32(this.shadowed_sample_numbers.length);+ for (let i = 0; i < this.shadowed_sample_numbers.length; i++) {+ stream.writeUint32(this.shadowed_sample_numbers[i]);+ stream.writeUint32(this.sync_sample_numbers[i]);+ }+ }+};++//#endregion+//#region src/boxes/stss.ts+var stssBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SyncSampleBox";+ }+ static {+ this.fourcc = "stss";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const entry_count = stream.readUint32();+ if (this.version === 0) {+ this.sample_numbers = [];+ for (let i = 0; i < entry_count; i++) this.sample_numbers.push(stream.readUint32());+ }+ }+ /** @bundle writing/stss.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 4 + 4 * this.sample_numbers.length;+ this.writeHeader(stream);+ stream.writeUint32(this.sample_numbers.length);+ stream.writeUint32Array(this.sample_numbers);+ }+};++//#endregion+//#region src/boxes/stvi.ts+var stviBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "StereoVideoBox";+ }+ static {+ this.fourcc = "stvi";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const tmp32 = stream.readUint32();+ this.single_view_allowed = tmp32 & 3;+ this.stereo_scheme = stream.readUint32();+ const length = stream.readUint32();+ this.stereo_indication_type = stream.readString(length);+ this.boxes = [];+ while (stream.getPosition() < this.start + this.size) {+ const ret = parseOneBox(stream, false, this.size - (stream.getPosition() - this.start));+ if (ret.code === 1) {+ const box = ret.box;+ this.boxes.push(box);+ this[box.type] = box;+ } else return;+ }+ }+};++//#endregion+//#region src/boxes/stz2.ts+var stz2Box = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CompactSampleSizeBox";+ }+ static {+ this.fourcc = "stz2";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.sample_sizes = [];+ if (this.version === 0) {+ this.reserved = stream.readUint24();+ this.field_size = stream.readUint8();+ const sample_count = stream.readUint32();+ if (this.field_size === 4) for (let i = 0; i < sample_count; i += 2) {+ const tmp = stream.readUint8();+ this.sample_sizes[i] = tmp >> 4 & 15;+ this.sample_sizes[i + 1] = tmp & 15;+ }+ else if (this.field_size === 8) for (let i = 0; i < sample_count; i++) this.sample_sizes[i] = stream.readUint8();+ else if (this.field_size === 16) for (let i = 0; i < sample_count; i++) this.sample_sizes[i] = stream.readUint16();+ else Log.error("BoxParser", "Error in length field in stz2 box", stream.isofile);+ }+ }+};++//#endregion+//#region src/boxes/subs.ts+var subsBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SubSampleInformationBox";+ }+ static {+ this.fourcc = "subs";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const entry_count = stream.readUint32();+ this.entries = [];+ let subsample_count;+ for (let i = 0; i < entry_count; i++) {+ const sampleInfo = {};+ this.entries[i] = sampleInfo;+ sampleInfo.sample_delta = stream.readUint32();+ sampleInfo.subsamples = [];+ subsample_count = stream.readUint16();+ if (subsample_count > 0) for (let j = 0; j < subsample_count; j++) {+ const subsample = {};+ sampleInfo.subsamples.push(subsample);+ if (this.version === 1) subsample.size = stream.readUint32();+ else subsample.size = stream.readUint16();+ subsample.priority = stream.readUint8();+ subsample.discardable = stream.readUint8();+ subsample.codec_specific_parameters = stream.readUint32();+ }+ }+ }+};++//#endregion+//#region src/boxes/taic.ts+var taicBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TAIClockInfoBox";+ }+ static {+ this.fourcc = "taic";+ }+ parse(stream) {+ this.time_uncertainty = stream.readUint64();+ this.clock_resolution = stream.readUint32();+ this.clock_drift_rate = stream.readInt32();+ const reserved_byte = stream.readUint8();+ this.clock_type = (reserved_byte & 192) >> 6;+ }+};++//#endregion+//#region src/boxes/tenc.ts+var tencBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackEncryptionBox";+ }+ static {+ this.fourcc = "tenc";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ stream.readUint8();+ if (this.version === 0) stream.readUint8();+ else {+ const tmp = stream.readUint8();+ this.default_crypt_byte_block = tmp >> 4 & 15;+ this.default_skip_byte_block = tmp & 15;+ }+ this.default_isProtected = stream.readUint8();+ this.default_Per_Sample_IV_Size = stream.readUint8();+ this.default_KID = parseHex16(stream);+ if (this.default_isProtected === 1 && this.default_Per_Sample_IV_Size === 0) {+ this.default_constant_IV_size = stream.readUint8();+ this.default_constant_IV = stream.readUint8Array(this.default_constant_IV_size);+ }+ }+};++//#endregion+//#region src/boxes/tfra.ts+var TfraEntry = class {};+var tfraBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackFragmentRandomAccessBox";+ }+ static {+ this.fourcc = "tfra";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.track_ID = stream.readUint32();+ stream.readUint24();+ const tmp_byte = stream.readUint8();+ this.length_size_of_traf_num = tmp_byte >> 4 & 3;+ this.length_size_of_trun_num = tmp_byte >> 2 & 3;+ this.length_size_of_sample_num = tmp_byte & 3;+ this.entries = [];+ const number_of_entries = stream.readUint32();+ for (let i = 0; i < number_of_entries; i++) {+ const entry = new TfraEntry();+ if (this.version === 1) {+ entry.time = stream.readUint64();+ entry.moof_offset = stream.readUint64();+ } else {+ entry.time = stream.readUint32();+ entry.moof_offset = stream.readUint32();+ }+ entry.traf_number = stream["readUint" + 8 * (this.length_size_of_traf_num + 1)]();+ entry.trun_number = stream["readUint" + 8 * (this.length_size_of_trun_num + 1)]();+ entry.sample_delta = stream["readUint" + 8 * (this.length_size_of_sample_num + 1)]();+ this.entries.push(entry);+ }+ }+};++//#endregion+//#region src/boxes/tmax.ts+var tmaxBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintmaxrelativetime";+ }+ static {+ this.fourcc = "tmax";+ }+ parse(stream) {+ this.time = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/tmin.ts+var tminBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintminrelativetime";+ }+ static {+ this.fourcc = "tmin";+ }+ parse(stream) {+ this.time = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/totl.ts+var totlBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintBytesSent";+ }+ static {+ this.fourcc = "totl";+ }+ parse(stream) {+ this.bytessent = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/tpay.ts+var tpayBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintBytesSent";+ }+ static {+ this.fourcc = "tpay";+ }+ parse(stream) {+ this.bytessent = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/tpyl.ts+var tpylBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintBytesSent";+ }+ static {+ this.fourcc = "tpyl";+ }+ parse(stream) {+ this.bytessent = stream.readUint64();+ }+};++//#endregion+//#region src/boxes/trackgroups/msrc.ts+var msrcTrackGroupTypeBox = class extends TrackGroupTypeBox {+ static {+ this.fourcc = "msrc";+ }+};++//#endregion+//#region src/boxes/tref.ts+var trefBox = class trefBox extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackReferenceBox";+ this.references = [];+ }+ static {+ this.fourcc = "tref";+ }+ static {+ this.allowed_types = [+ "hint",+ "cdsc",+ "font",+ "hind",+ "vdep",+ "vplx",+ "subt",+ "thmb",+ "auxl",+ "cdtg",+ "shsc",+ "aest"+ ];+ }+ parse(stream) {+ while (stream.getPosition() < this.start + this.size) {+ const ret = parseOneBox(stream, true, this.size - (stream.getPosition() - this.start));+ if (ret.code === 1) {+ if (!trefBox.allowed_types.includes(ret.type)) Log.warn("BoxParser", `Unknown track reference type: '${ret.type}'`);+ const box = new TrackReferenceTypeBox(ret.type, ret.size, ret.hdr_size, ret.start);+ if (box.write === Box.prototype.write && box.type !== "mdat") {+ Log.info("BoxParser", "TrackReference " + box.type + " box writing not yet implemented, keeping unparsed data in memory for later write");+ box.parseDataAndRewind(stream);+ }+ box.parse(stream);+ this.references.push(box);+ } else return;+ }+ }+};++//#endregion+//#region src/boxes/trep.ts+var trepBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackExtensionPropertiesBox";+ }+ static {+ this.fourcc = "trep";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.track_ID = stream.readUint32();+ this.boxes = [];+ while (stream.getPosition() < this.start + this.size) {+ const ret = parseOneBox(stream, false, this.size - (stream.getPosition() - this.start));+ if (ret.code === 1) {+ const box = ret.box;+ this.boxes.push(box);+ } else return;+ }+ }+};++//#endregion+//#region src/boxes/trpy.ts+var trpyBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "hintBytesSent";+ }+ static {+ this.fourcc = "trpy";+ }+ parse(stream) {+ this.bytessent = stream.readUint64();+ }+};++//#endregion+//#region src/boxes/tsel.ts+var tselBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackSelectionBox";+ }+ static {+ this.fourcc = "tsel";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.switch_group = stream.readUint32();+ const count = (this.size - this.hdr_size - 4) / 4;+ this.attribute_list = [];+ for (let i = 0; i < count; i++) this.attribute_list[i] = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/txtC.ts+var txtcBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TextConfigBox";+ }+ static {+ this.fourcc = "txtc";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.config = stream.readCString();+ }+};++//#endregion+//#region src/boxes/tyco.ts+var tycoBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TypeCombinationBox";+ }+ static {+ this.fourcc = "tyco";+ }+ parse(stream) {+ const count = (this.size - this.hdr_size) / 4;+ this.compatible_brands = [];+ for (let i = 0; i < count; i++) this.compatible_brands[i] = stream.readString(4);+ }+};++//#endregion+//#region src/boxes/udes.ts+var udesBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "UserDescriptionProperty";+ }+ static {+ this.fourcc = "udes";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.lang = stream.readCString();+ this.name = stream.readCString();+ this.description = stream.readCString();+ this.tags = stream.readCString();+ }+};++//#endregion+//#region src/boxes/uncC.ts+var uncCBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "UncompressedFrameConfigBox";+ }+ static {+ this.fourcc = "uncC";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.profile = stream.readString(4);+ if (this.version === 1) {} else if (this.version === 0) {+ this.component_count = stream.readUint32();+ this.component_index = [];+ this.component_bit_depth_minus_one = [];+ this.component_format = [];+ this.component_align_size = [];+ for (let i = 0; i < this.component_count; i++) {+ this.component_index.push(stream.readUint16());+ this.component_bit_depth_minus_one.push(stream.readUint8());+ this.component_format.push(stream.readUint8());+ this.component_align_size.push(stream.readUint8());+ }+ this.sampling_type = stream.readUint8();+ this.interleave_type = stream.readUint8();+ this.block_size = stream.readUint8();+ const flags = stream.readUint8();+ this.component_little_endian = flags >> 7 & 1;+ this.block_pad_lsb = flags >> 6 & 1;+ this.block_little_endian = flags >> 5 & 1;+ this.block_reversed = flags >> 4 & 1;+ this.pad_unknown = flags >> 3 & 1;+ this.pixel_size = stream.readUint32();+ this.row_align_size = stream.readUint32();+ this.tile_align_size = stream.readUint32();+ this.num_tile_cols_minus_one = stream.readUint32();+ this.num_tile_rows_minus_one = stream.readUint32();+ }+ }+};++//#endregion+//#region src/boxes/urn.ts+var urnBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "DataEntryUrnBox";+ }+ static {+ this.fourcc = "urn ";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.name = stream.readCString();+ if (this.size - this.hdr_size - this.name.length - 1 > 0) this.location = stream.readCString();+ }+ /** @bundle writing/urn.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = this.name.length + 1 + (this.location ? this.location.length + 1 : 0);+ this.writeHeader(stream);+ stream.writeCString(this.name);+ if (this.location) stream.writeCString(this.location);+ }+};++//#endregion+//#region src/boxes/vttC.ts+var vttCBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "WebVTTConfigurationBox";+ }+ static {+ this.fourcc = "vttC";+ }+ parse(stream) {+ this.text = stream.readString(this.size - this.hdr_size);+ }+};++//#endregion+//#region src/boxes/vvnC.ts+var vvnCBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "VvcNALUConfigBox";+ }+ static {+ this.fourcc = "vvnC";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const tmp = stream.readUint8();+ this.lengthSizeMinusOne = tmp & 3;+ }+};++//#endregion+//#region src/boxes/samplegroups/alst.ts+var alstSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "alst";+ }+ parse(stream) {+ const roll_count = stream.readUint16();+ this.first_output_sample = stream.readUint16();+ this.sample_offset = [];+ for (let i = 0; i < roll_count; i++) this.sample_offset[i] = stream.readUint32();+ const remaining = this.description_length - 4 - 4 * roll_count;+ this.num_output_samples = [];+ this.num_total_samples = [];+ for (let i = 0; i < remaining / 4; i++) {+ this.num_output_samples[i] = stream.readUint16();+ this.num_total_samples[i] = stream.readUint16();+ }+ }+};++//#endregion+//#region src/boxes/samplegroups/avll.ts+var avllSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "avll";+ }+ parse(stream) {+ this.layerNumber = stream.readUint8();+ this.accurateStatisticsFlag = stream.readUint8();+ this.avgBitRate = stream.readUint16();+ this.avgFrameRate = stream.readUint16();+ }+};++//#endregion+//#region src/boxes/samplegroups/avss.ts+var avssSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "avss";+ }+ parse(stream) {+ this.subSequenceIdentifier = stream.readUint16();+ this.layerNumber = stream.readUint8();+ const tmp_byte = stream.readUint8();+ this.durationFlag = tmp_byte >> 7;+ this.avgRateFlag = tmp_byte >> 6 & 1;+ if (this.durationFlag) this.duration = stream.readUint32();+ if (this.avgRateFlag) {+ this.accurateStatisticsFlag = stream.readUint8();+ this.avgBitRate = stream.readUint16();+ this.avgFrameRate = stream.readUint16();+ }+ this.dependency = [];+ const numReferences = stream.readUint8();+ for (let i = 0; i < numReferences; i++) this.dependency.push({+ subSeqDirectionFlag: stream.readUint8(),+ layerNumber: stream.readUint8(),+ subSequenceIdentifier: stream.readUint16()+ });+ }+};++//#endregion+//#region src/boxes/samplegroups/dtrt.ts+var dtrtSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "dtrt";+ }+ parse(_stream) {+ Log.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed");+ }+};++//#endregion+//#region src/boxes/samplegroups/mvif.ts+var mvifSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "mvif";+ }+ parse(_stream) {+ Log.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed");+ }+};++//#endregion+//#region src/boxes/samplegroups/prol.ts+var prolSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "prol";+ }+ parse(stream) {+ this.roll_distance = stream.readInt16();+ }+};++//#endregion+//#region src/boxes/samplegroups/rap.ts+var rapSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "rap ";+ }+ parse(stream) {+ const tmp_byte = stream.readUint8();+ this.num_leading_samples_known = tmp_byte >> 7;+ this.num_leading_samples = tmp_byte & 127;+ }+};++//#endregion+//#region src/boxes/samplegroups/rash.ts+var rashSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "rash";+ }+ parse(stream) {+ this.operation_point_count = stream.readUint16();+ if (this.description_length !== 2 + (this.operation_point_count === 1 ? 2 : this.operation_point_count * 6) + 9) {+ Log.warn("BoxParser", "Mismatch in " + this.grouping_type + " sample group length");+ this.data = stream.readUint8Array(this.description_length - 2);+ } else {+ if (this.operation_point_count === 1) this.target_rate_share = stream.readUint16();+ else {+ this.target_rate_share = [];+ this.available_bitrate = [];+ for (let i = 0; i < this.operation_point_count; i++) {+ this.available_bitrate[i] = stream.readUint32();+ this.target_rate_share[i] = stream.readUint16();+ }+ }+ this.maximum_bitrate = stream.readUint32();+ this.minimum_bitrate = stream.readUint32();+ this.discard_priority = stream.readUint8();+ }+ }+};++//#endregion+//#region src/boxes/samplegroups/roll.ts+var rollSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "roll";+ }+ parse(stream) {+ this.roll_distance = stream.readInt16();+ }+};++//#endregion+//#region src/boxes/samplegroups/scif.ts+var scifSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "scif";+ }+ parse(_stream) {+ Log.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed");+ }+};++//#endregion+//#region src/boxes/samplegroups/scnm.ts+var scnmSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "scnm";+ }+ parse(_stream) {+ Log.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed");+ }+};++//#endregion+//#region src/boxes/samplegroups/seig.ts+var seigSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "seig";+ }+ parse(stream) {+ this.reserved = stream.readUint8();+ const tmp = stream.readUint8();+ this.crypt_byte_block = tmp >> 4;+ this.skip_byte_block = tmp & 15;+ this.isProtected = stream.readUint8();+ this.Per_Sample_IV_Size = stream.readUint8();+ this.KID = parseHex16(stream);+ this.constant_IV_size = 0;+ this.constant_IV = 0;+ if (this.isProtected === 1 && this.Per_Sample_IV_Size === 0) {+ this.constant_IV_size = stream.readUint8();+ this.constant_IV = stream.readUint8Array(this.constant_IV_size);+ }+ }+};++//#endregion+//#region src/boxes/samplegroups/stsa.ts+var stsaSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "stsa";+ }+ parse(_stream) {+ Log.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed");+ }+};++//#endregion+//#region src/boxes/samplegroups/sync.ts+var syncSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "sync";+ }+ parse(stream) {+ const tmp_byte = stream.readUint8();+ this.NAL_unit_type = tmp_byte & 63;+ }+};++//#endregion+//#region src/boxes/samplegroups/tele.ts+var teleSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "tele";+ }+ parse(stream) {+ const tmp_byte = stream.readUint8();+ this.level_independently_decodable = tmp_byte >> 7;+ }+};++//#endregion+//#region src/boxes/samplegroups/tsas.ts+var tsasSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "tsas";+ }+ parse(_stream) {+ Log.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed");+ }+};++//#endregion+//#region src/boxes/samplegroups/tscl.ts+var tsclSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "tscl";+ }+ parse(_stream) {+ Log.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed");+ }+};++//#endregion+//#region src/boxes/samplegroups/vipr.ts+var viprSampleGroupEntry = class extends SampleGroupEntry {+ static {+ this.grouping_type = "vipr";+ }+ parse(_stream) {+ Log.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed");+ }+};++//#endregion+//#region src/boxes/uuid/index.ts+var UUIDBox = class extends Box {+ static {+ this.fourcc = "uuid";+ }+};+var UUIDFullBox = class extends FullBox {+ static {+ this.fourcc = "uuid";+ }+};+var piffLsmBox = class extends UUIDFullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "LiveServerManifestBox";+ }+ static {+ this.uuid = "a5d40b30e81411ddba2f0800200c9a66";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.LiveServerManifest = stream.readString(this.size - this.hdr_size).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");+ }+};+var piffPsshBox = class extends UUIDFullBox {+ constructor(..._args2) {+ super(..._args2);+ this.box_name = "PiffProtectionSystemSpecificHeaderBox";+ }+ static {+ this.uuid = "d08a4f1810f34a82b6c832d8aba183d3";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.system_id = parseHex16(stream);+ const datasize = stream.readUint32();+ if (datasize > 0) this.data = stream.readUint8Array(datasize);+ }+};+var piffSencBox = class extends UUIDFullBox {+ constructor(..._args3) {+ super(..._args3);+ this.box_name = "PiffSampleEncryptionBox";+ }+ static {+ this.uuid = "a2394f525a9b4f14a2446c427c648df4";+ }+};+var piffTencBox = class extends UUIDFullBox {+ constructor(..._args4) {+ super(..._args4);+ this.box_name = "PiffTrackEncryptionBox";+ }+ static {+ this.uuid = "8974dbce7be74c5184f97148f9882554";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.default_AlgorithmID = stream.readUint24();+ this.default_IV_size = stream.readUint8();+ this.default_KID = parseHex16(stream);+ }+};+var piffTfrfBox = class extends UUIDFullBox {+ constructor(..._args5) {+ super(..._args5);+ this.box_name = "TfrfBox";+ }+ static {+ this.uuid = "d4807ef2ca3946958e5426cb9e46a79f";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.fragment_count = stream.readUint8();+ this.entries = [];+ for (let i = 0; i < this.fragment_count; i++) {+ let absolute_time = 0;+ let absolute_duration = 0;+ if (this.version === 1) {+ absolute_time = stream.readUint64();+ absolute_duration = stream.readUint64();+ } else {+ absolute_time = stream.readUint32();+ absolute_duration = stream.readUint32();+ }+ this.entries.push({+ absolute_time,+ absolute_duration+ });+ }+ }+};+var piffTfxdBox = class extends UUIDFullBox {+ constructor(..._args6) {+ super(..._args6);+ this.box_name = "TfxdBox";+ }+ static {+ this.uuid = "6d1d9b0542d544e680e2141daff757b2";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 1) {+ this.absolute_time = stream.readUint64();+ this.duration = stream.readUint64();+ } else {+ this.absolute_time = stream.readUint32();+ this.duration = stream.readUint32();+ }+ }+};+var ItemContentIDPropertyBox = class extends UUIDBox {+ constructor(..._args7) {+ super(..._args7);+ this.box_name = "ItemContentIDProperty";+ }+ static {+ this.uuid = "261ef3741d975bbaacbd9d2c8ea73522";+ }+ parse(stream) {+ this.content_id = stream.readCString();+ }+};+var ItemComponentContentIDPropertyBox = class extends UUIDBox {+ constructor(..._args8) {+ super(..._args8);+ this.box_name = "ItemComponentContentIDProperty";+ }+ static {+ this.uuid = "9db9dd6e373c5a4e811021fc83a911fd";+ }+ parse(stream) {+ this.number_of_components = stream.readUint32();+ this.content_ids = [];+ for (let i = 0; i < this.number_of_components; i++) {+ const content_id = stream.readCString();+ this.content_ids.push(content_id);+ }+ }+};++//#endregion+//#region entries/all-boxes.ts+var all_boxes_exports = /* @__PURE__ */ __exportAll({+ CoLLBox: () => CoLLBox,+ ItemComponentContentIDPropertyBox: () => ItemComponentContentIDPropertyBox,+ ItemContentIDPropertyBox: () => ItemContentIDPropertyBox,+ OpusSampleEntry: () => OpusSampleEntry,+ SmDmBox: () => SmDmBox,+ a1lxBox: () => a1lxBox,+ a1opBox: () => a1opBox,+ ac_3SampleEntry: () => ac_3SampleEntry,+ ac_4SampleEntry: () => ac_4SampleEntry,+ aebrBox: () => aebrBox,+ afbrBox: () => afbrBox,+ albcBox: () => albcBox,+ alstSampleGroupEntry: () => alstSampleGroupEntry,+ altrBox: () => altrBox,+ auxCBox: () => auxCBox,+ av01SampleEntry: () => av01SampleEntry,+ av1CBox: () => av1CBox,+ avc1SampleEntry: () => avc1SampleEntry,+ avc2SampleEntry: () => avc2SampleEntry,+ avc3SampleEntry: () => avc3SampleEntry,+ avc4SampleEntry: () => avc4SampleEntry,+ avcCBox: () => avcCBox,+ avllSampleGroupEntry: () => avllSampleGroupEntry,+ avs3SampleEntry: () => avs3SampleEntry,+ avssSampleGroupEntry: () => avssSampleGroupEntry,+ brstBox: () => brstBox,+ btrtBox: () => btrtBox,+ bxmlBox: () => bxmlBox,+ ccstBox: () => ccstBox,+ cdefBox: () => cdefBox,+ clapBox: () => clapBox,+ clefBox: () => clefBox,+ clliBox: () => clliBox,+ cmexBox: () => cmexBox,+ cminBox: () => cminBox,+ cmpCBox: () => cmpCBox,+ cmpdBox: () => cmpdBox,+ co64Box: () => co64Box,+ colrBox: () => colrBox,+ coviBox: () => coviBox,+ cprtBox: () => cprtBox,+ cschBox: () => cschBox,+ cslgBox: () => cslgBox,+ cttsBox: () => cttsBox,+ dOpsBox: () => dOpsBox,+ dac3Box: () => dac3Box,+ dataBox: () => dataBox,+ dav1SampleEntry: () => dav1SampleEntry,+ dec3Box: () => dec3Box,+ dfLaBox: () => dfLaBox,+ dimmBox: () => dimmBox,+ dinfBox: () => dinfBox,+ dmax: () => dmax,+ dmedBox: () => dmedBox,+ dobrBox: () => dobrBox,+ drefBox: () => drefBox,+ drepBox: () => drepBox,+ dtrtSampleGroupEntry: () => dtrtSampleGroupEntry,+ dvh1SampleEntry: () => dvh1SampleEntry,+ dvheSampleEntry: () => dvheSampleEntry,+ ec_3SampleEntry: () => ec_3SampleEntry,+ edtsBox: () => edtsBox,+ elngBox: () => elngBox,+ elstBox: () => elstBox,+ emsgBox: () => emsgBox,+ encaSampleEntry: () => encaSampleEntry,+ encmSampleEntry: () => encmSampleEntry,+ encsSampleEntry: () => encsSampleEntry,+ enctSampleEntry: () => enctSampleEntry,+ encuSampleEntry: () => encuSampleEntry,+ encvSampleEntry: () => encvSampleEntry,+ enofBox: () => enofBox,+ eqivBox: () => eqivBox,+ esdsBox: () => esdsBox,+ etypBox: () => etypBox,+ fLaCSampleEntry: () => fLaCSampleEntry,+ favcBox: () => favcBox,+ fielBox: () => fielBox,+ fobrBox: () => fobrBox,+ freeBox: () => freeBox,+ frmaBox: () => frmaBox,+ ftypBox: () => ftypBox,+ grplBox: () => grplBox,+ hdlrBox: () => hdlrBox,+ hev1SampleEntry: () => hev1SampleEntry,+ hev2SampleEntry: () => hev2SampleEntry,+ hinfBox: () => hinfBox,+ hmhdBox: () => hmhdBox,+ hntiBox: () => hntiBox,+ hvc1SampleEntry: () => hvc1SampleEntry,+ hvc2SampleEntry: () => hvc2SampleEntry,+ hvcCBox: () => hvcCBox,+ hvt1SampleEntry: () => hvt1SampleEntry,+ iaugBox: () => iaugBox,+ idatBox: () => idatBox,+ iinfBox: () => iinfBox,+ ilocBox: () => ilocBox,+ ilstBox: () => ilstBox,+ imirBox: () => imirBox,+ infeBox: () => infeBox,+ iodsBox: () => iodsBox,+ ipcoBox: () => ipcoBox,+ ipmaBox: () => ipmaBox,+ iproBox: () => iproBox,+ iprpBox: () => iprpBox,+ irefBox: () => irefBox,+ irotBox: () => irotBox,+ ispeBox: () => ispeBox,+ itaiBox: () => itaiBox,+ j2kHBox: () => j2kHBox,+ j2kiSampleEntry: () => j2kiSampleEntry,+ keysBox: () => keysBox,+ kindBox: () => kindBox,+ levaBox: () => levaBox,+ lhe1SampleEntry: () => lhe1SampleEntry,+ lhv1SampleEntry: () => lhv1SampleEntry,+ lhvCBox: () => lhvCBox,+ lselBox: () => lselBox,+ lvc1SampleEntry: () => lvc1SampleEntry,+ lvcCBox: () => lvcCBox,+ m4aeSampleEntry: () => m4aeSampleEntry,+ maxrBox: () => maxrBox,+ mdatBox: () => mdatBox,+ mdcvBox: () => mdcvBox,+ mdhdBox: () => mdhdBox,+ mdiaBox: () => mdiaBox,+ mecoBox: () => mecoBox,+ mehdBox: () => mehdBox,+ metaBox: () => metaBox,+ mettSampleEntry: () => mettSampleEntry,+ metxSampleEntry: () => metxSampleEntry,+ mfhdBox: () => mfhdBox,+ mfraBox: () => mfraBox,+ mfroBox: () => mfroBox,+ mha1SampleEntry: () => mha1SampleEntry,+ mha2SampleEntry: () => mha2SampleEntry,+ mhm1SampleEntry: () => mhm1SampleEntry,+ mhm2SampleEntry: () => mhm2SampleEntry,+ minfBox: () => minfBox,+ mjp2SampleEntry: () => mjp2SampleEntry,+ mjpgSampleEntry: () => mjpgSampleEntry,+ moofBox: () => moofBox,+ moovBox: () => moovBox,+ mp4aSampleEntry: () => mp4aSampleEntry,+ mp4sSampleEntry: () => mp4sSampleEntry,+ mp4vSampleEntry: () => mp4vSampleEntry,+ mskCBox: () => mskCBox,+ msrcTrackGroupTypeBox: () => msrcTrackGroupTypeBox,+ mvexBox: () => mvexBox,+ mvhdBox: () => mvhdBox,+ mvifSampleGroupEntry: () => mvifSampleGroupEntry,+ nmhdBox: () => nmhdBox,+ npckBox: () => npckBox,+ numpBox: () => numpBox,+ padbBox: () => padbBox,+ panoBox: () => panoBox,+ paspBox: () => paspBox,+ paylBox: () => paylBox,+ paytBox: () => paytBox,+ pdinBox: () => pdinBox,+ piffLsmBox: () => piffLsmBox,+ piffPsshBox: () => piffPsshBox,+ piffSencBox: () => piffSencBox,+ piffTencBox: () => piffTencBox,+ piffTfrfBox: () => piffTfrfBox,+ piffTfxdBox: () => piffTfxdBox,+ pitmBox: () => pitmBox,+ pixiBox: () => pixiBox,+ pmaxBox: () => pmaxBox,+ povdBox: () => povdBox,+ prdiBox: () => prdiBox,+ prfrBox: () => prfrBox,+ prftBox: () => prftBox,+ prgrBox: () => prgrBox,+ profBox: () => profBox,+ prolSampleGroupEntry: () => prolSampleGroupEntry,+ psshBox: () => psshBox,+ pymdBox: () => pymdBox,+ rapSampleGroupEntry: () => rapSampleGroupEntry,+ rashSampleGroupEntry: () => rashSampleGroupEntry,+ resvSampleEntry: () => resvSampleEntry,+ rinfBox: () => rinfBox,+ rollSampleGroupEntry: () => rollSampleGroupEntry,+ rtp_Box: () => rtp_Box,+ saioBox: () => saioBox,+ saizBox: () => saizBox,+ sbgpBox: () => sbgpBox,+ sbpmBox: () => sbpmBox,+ sbttSampleEntry: () => sbttSampleEntry,+ schiBox: () => schiBox,+ schmBox: () => schmBox,+ scifSampleGroupEntry: () => scifSampleGroupEntry,+ scnmSampleGroupEntry: () => scnmSampleGroupEntry,+ sdp_Box: () => sdp_Box,+ sdtpBox: () => sdtpBox,+ seigSampleGroupEntry: () => seigSampleGroupEntry,+ sencBox: () => sencBox,+ sgpdBox: () => sgpdBox,+ sidxBox: () => sidxBox,+ sinfBox: () => sinfBox,+ skipBox: () => skipBox,+ slidBox: () => slidBox,+ smhdBox: () => smhdBox,+ sratBox: () => sratBox,+ ssixBox: () => ssixBox,+ stblBox: () => stblBox,+ stcoBox: () => stcoBox,+ stdpBox: () => stdpBox,+ sterBox: () => sterBox,+ sthdBox: () => sthdBox,+ stppSampleEntry: () => stppSampleEntry,+ strdBox: () => strdBox,+ striBox: () => striBox,+ strkBox: () => strkBox,+ stsaSampleGroupEntry: () => stsaSampleGroupEntry,+ stscBox: () => stscBox,+ stsdBox: () => stsdBox,+ stsgBox: () => stsgBox,+ stshBox: () => stshBox,+ stssBox: () => stssBox,+ stszBox: () => stszBox,+ sttsBox: () => sttsBox,+ stviBox: () => stviBox,+ stxtSampleEntry: () => stxtSampleEntry,+ stypBox: () => stypBox,+ stz2Box: () => stz2Box,+ subsBox: () => subsBox,+ syncSampleGroupEntry: () => syncSampleGroupEntry,+ taicBox: () => taicBox,+ taptBox: () => taptBox,+ teleSampleGroupEntry: () => teleSampleGroupEntry,+ tencBox: () => tencBox,+ tfdtBox: () => tfdtBox,+ tfhdBox: () => tfhdBox,+ tfraBox: () => tfraBox,+ tkhdBox: () => tkhdBox,+ tmaxBox: () => tmaxBox,+ tminBox: () => tminBox,+ totlBox: () => totlBox,+ tpayBox: () => tpayBox,+ tpylBox: () => tpylBox,+ trafBox: () => trafBox,+ trakBox: () => trakBox,+ trefBox: () => trefBox,+ trepBox: () => trepBox,+ trexBox: () => trexBox,+ trgrBox: () => trgrBox,+ trpyBox: () => trpyBox,+ trunBox: () => trunBox,+ tsasSampleGroupEntry: () => tsasSampleGroupEntry,+ tsclSampleGroupEntry: () => tsclSampleGroupEntry,+ tselBox: () => tselBox,+ tsynBox: () => tsynBox,+ tx3gSampleEntry: () => tx3gSampleEntry,+ txtcBox: () => txtcBox,+ tycoBox: () => tycoBox,+ udesBox: () => udesBox,+ udtaBox: () => udtaBox,+ uncCBox: () => uncCBox,+ uncvSampleEntry: () => uncvSampleEntry,+ urlBox: () => urlBox,+ urnBox: () => urnBox,+ viprSampleGroupEntry: () => viprSampleGroupEntry,+ vmhdBox: () => vmhdBox,+ vp08SampleEntry: () => vp08SampleEntry,+ vp09SampleEntry: () => vp09SampleEntry,+ vpcCBox: () => vpcCBox,+ vttCBox: () => vttCBox,+ vttcBox: () => vttcBox,+ vvc1SampleEntry: () => vvc1SampleEntry,+ vvcCBox: () => vvcCBox,+ vvcNSampleEntry: () => vvcNSampleEntry,+ vvi1SampleEntry: () => vvi1SampleEntry,+ vvnCBox: () => vvnCBox,+ vvs1SampleEntry: () => vvs1SampleEntry,+ waveBox: () => waveBox,+ wbbrBox: () => wbbrBox,+ wvttSampleEntry: () => wvttSampleEntry,+ xmlBox: () => xmlBox+});++//#endregion+//#region entries/all.ts+const BoxParser = registerBoxes(all_boxes_exports);+registerDescriptors(descriptor_exports);++//#endregion+export { AudioSampleEntry, Box, BoxParser, DIFF_BOXES_PROP_NAMES, DIFF_PRIMITIVE_ARRAY_PROP_NAMES, DataStream, Descriptor, ES_Descriptor, Endianness, FullBox, HintSampleEntry, ISOFile, Log, MP4BoxBuffer, MPEG4DescriptorParser, MetadataSampleEntry, MultiBufferStream, SampleEntry, SampleGroupEntry, SampleGroupInfo, SingleItemTypeReferenceBox, SingleItemTypeReferenceBoxLarge, SubtitleSampleEntry, SystemSampleEntry, TX3GParser, TextSampleEntry, Textin4Parser, TrackGroupTypeBox, TrackReferenceTypeBox, VTTin4Parser, VisualSampleEntry, XMLSubtitlein4Parser, boxEqual, boxEqualFields, createFile };+//# sourceMappingURL=mp4box.all.mjs.map\ No newline at end of filediff --git a/src/firefox/vendor/mp4box/rolldown-runtime-w6R9maHv.mjs b/src/firefox/vendor/mp4box/rolldown-runtime-w6R9maHv.mjsnew file mode 100644index 000000000..862d566e4--- /dev/null+++ b/src/firefox/vendor/mp4box/rolldown-runtime-w6R9maHv.mjs@@ -0,0 +1,18 @@+//#region \0rolldown/runtime.js+var __defProp = Object.defineProperty;+var __exportAll = (all, no_symbols) => {+ let target = {};+ for (var name in all) {+ __defProp(target, name, {+ get: all[name],+ enumerable: true+ });+ }+ if (!no_symbols) {+ __defProp(target, Symbol.toStringTag, { value: "Module" });+ }+ return target;+};++//#endregion+export { __exportAll as t };\ No newline at end of filediff --git a/src/firefox/vendor/mp4box/styp-9TIZZDLN.mjs b/src/firefox/vendor/mp4box/styp-9TIZZDLN.mjsnew file mode 100644index 000000000..9fc4171ee--- /dev/null+++ b/src/firefox/vendor/mp4box/styp-9TIZZDLN.mjs@@ -0,0 +1,7225 @@+//#region src/constants.ts+const MAX_SIZE = Math.pow(2, 32);+const MAX_UINT32 = Math.pow(2, 32) - 1;+const TFHD_FLAG_DEFAULT_BASE_IS_MOOF = 131072;+const TRUN_FLAGS_FLAGS = 1024;+const TRUN_FLAGS_CTS_OFFSET = 2048;++//#endregion+//#region src/mp4boxbuffer.ts+var MP4BoxBuffer = class MP4BoxBuffer extends ArrayBuffer {+ constructor(byteLength) {+ super(byteLength);+ this.fileStart = 0;+ this.usedBytes = 0;+ }+ static fromArrayBuffer(buffer, fileStart) {+ const mp4BoxBuffer = new MP4BoxBuffer(buffer.byteLength);+ new Uint8Array(mp4BoxBuffer).set(new Uint8Array(buffer));+ mp4BoxBuffer.fileStart = fileStart;+ return mp4BoxBuffer;+ }+};++//#endregion+//#region src/DataStream.ts+let Endianness = /* @__PURE__ */ function(Endianness) {+ Endianness[Endianness["BIG_ENDIAN"] = 1] = "BIG_ENDIAN";+ Endianness[Endianness["LITTLE_ENDIAN"] = 2] = "LITTLE_ENDIAN";+ return Endianness;+}({});+var DataStream = class DataStream {+ static {+ this.ENDIANNESS = new Int8Array(new Int16Array([1]).buffer)[0] > 0 ? 2 : 1;+ }+ /**+ * DataStream reads scalars, arrays and structs of data from an ArrayBuffer.+ * It's like a file-like DataView on steroids.+ *+ * @param arrayBuffer ArrayBuffer to read from.+ * @param byteOffset Offset from arrayBuffer beginning for the DataStream.+ * @param endianness Endianness of the DataStream (default: BIG_ENDIAN).+ */+ constructor(arrayBuffer, byteOffset, endianness) {+ this._byteLength = 0;+ this.failurePosition = 0;+ this._dynamicSize = 1;+ this._byteOffset = byteOffset || 0;+ if (arrayBuffer instanceof ArrayBuffer) this.buffer = MP4BoxBuffer.fromArrayBuffer(arrayBuffer, 0);+ else if (arrayBuffer instanceof DataView) {+ this.dataView = arrayBuffer;+ if (byteOffset) this._byteOffset += byteOffset;+ } else this.buffer = new MP4BoxBuffer(arrayBuffer || 0);+ this.position = 0;+ this.endianness = endianness ? endianness : 1;+ }+ getPosition() {+ return this.position;+ }+ /**+ * Internal function to resize the DataStream buffer when required.+ * @param extra Number of bytes to add to the buffer allocation.+ */+ _realloc(extra) {+ if (!this._dynamicSize) return;+ const req = this._byteOffset + this.position + extra;+ let blen = this._buffer.byteLength;+ if (req <= blen) {+ if (req > this._byteLength) this._byteLength = req;+ return;+ }+ if (blen < 1) blen = 1;+ while (req > blen) blen *= 2;+ const buf = new MP4BoxBuffer(blen);+ const src = new Uint8Array(this._buffer);+ new Uint8Array(buf, 0, src.length).set(src);+ this.buffer = buf;+ this._byteLength = req;+ }+ /**+ * Internal function to trim the DataStream buffer when required.+ * Used for stripping out the extra bytes from the backing buffer when+ * the virtual byteLength is smaller than the buffer byteLength (happens after+ * growing the buffer with writes and not filling the extra space completely).+ */+ _trimAlloc() {+ if (this._byteLength === this._buffer.byteLength) return;+ const buf = new MP4BoxBuffer(this._byteLength);+ const dst = new Uint8Array(buf);+ const src = new Uint8Array(this._buffer, 0, dst.length);+ dst.set(src);+ this.buffer = buf;+ }+ /**+ * Returns the byte length of the DataStream object.+ * @type {number}+ */+ get byteLength() {+ return this._byteLength - this._byteOffset;+ }+ /**+ * Set/get the backing ArrayBuffer of the DataStream object.+ * The setter updates the DataView to point to the new buffer.+ * @type {Object}+ */+ get buffer() {+ this._trimAlloc();+ return this._buffer;+ }+ set buffer(value) {+ this._buffer = value;+ this._dataView = new DataView(value, this._byteOffset);+ this._byteLength = value.byteLength;+ }+ /**+ * Set/get the byteOffset of the DataStream object.+ * The setter updates the DataView to point to the new byteOffset.+ * @type {number}+ */+ get byteOffset() {+ return this._byteOffset;+ }+ set byteOffset(value) {+ this._byteOffset = value;+ this._dataView = new DataView(this._buffer, this._byteOffset);+ this._byteLength = this._buffer.byteLength;+ }+ /**+ * Set/get the byteOffset of the DataStream object.+ * The setter updates the DataView to point to the new byteOffset.+ * @type {number}+ */+ get dataView() {+ return this._dataView;+ }+ set dataView(value) {+ this._byteOffset = value.byteOffset;+ this._buffer = MP4BoxBuffer.fromArrayBuffer(value.buffer, 0);+ this._dataView = new DataView(this._buffer, this._byteOffset);+ this._byteLength = this._byteOffset + value.byteLength;+ }+ /**+ * Sets the DataStream read/write position to given position.+ * Clamps between 0 and DataStream length.+ *+ * @param pos Position to seek to.+ * @return+ */+ seek(pos) {+ const npos = Math.max(0, Math.min(this.byteLength, pos));+ this.position = isNaN(npos) || !isFinite(npos) ? 0 : npos;+ }+ /**+ * Returns true if the DataStream seek pointer is at the end of buffer and+ * there's no more data to read.+ *+ * @return True if the seek pointer is at the end of the buffer.+ */+ isEof() {+ return this.position >= this._byteLength;+ }+ #isTupleType(type) {+ return Array.isArray(type) && type.length === 3 && type[0] === "[]";+ }+ /**+ * Maps a Uint8Array into the DataStream buffer.+ *+ * Nice for quickly reading in data.+ *+ * @param length Number of elements to map.+ * @param e Endianness of the data to read.+ * @return Uint8Array to the DataStream backing buffer.+ */+ mapUint8Array(length) {+ this._realloc(length * 1);+ const arr = new Uint8Array(this._buffer, this.byteOffset + this.position, length);+ this.position += length * 1;+ return arr;+ }+ /**+ * Reads an Int32Array of desired length and endianness from the DataStream.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return The read Int32Array.+ */+ readInt32Array(length, endianness) {+ length = length === void 0 ? this.byteLength - this.position / 4 : length;+ const arr = new Int32Array(length);+ DataStream.memcpy(arr.buffer, 0, this.buffer, this.byteOffset + this.position, length * arr.BYTES_PER_ELEMENT);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += arr.byteLength;+ return arr;+ }+ /**+ * Reads an Int16Array of desired length and endianness from the DataStream.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return The read Int16Array.+ */+ readInt16Array(length, endianness) {+ length = length === void 0 ? this.byteLength - this.position / 2 : length;+ const arr = new Int16Array(length);+ DataStream.memcpy(arr.buffer, 0, this.buffer, this.byteOffset + this.position, length * arr.BYTES_PER_ELEMENT);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += arr.byteLength;+ return arr;+ }+ /**+ * Reads an Int8Array of desired length from the DataStream.+ *+ * @param length Number of elements to map.+ * @param e Endianness of the data to read.+ * @return The read Int8Array.+ */+ readInt8Array(length) {+ length = length === void 0 ? this.byteLength - this.position : length;+ const arr = new Int8Array(length);+ DataStream.memcpy(arr.buffer, 0, this.buffer, this.byteOffset + this.position, length * arr.BYTES_PER_ELEMENT);+ this.position += arr.byteLength;+ return arr;+ }+ /**+ * Reads a Uint32Array of desired length and endianness from the DataStream.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return The read Uint32Array.+ */+ readUint32Array(length, endianness) {+ length = length === void 0 ? this.byteLength - this.position / 4 : length;+ const arr = new Uint32Array(length);+ DataStream.memcpy(arr.buffer, 0, this.buffer, this.byteOffset + this.position, length * arr.BYTES_PER_ELEMENT);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += arr.byteLength;+ return arr;+ }+ /**+ * Reads a Uint16Array of desired length and endianness from the DataStream.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return The read Uint16Array.+ */+ readUint16Array(length, endianness) {+ length = length === void 0 ? this.byteLength - this.position / 2 : length;+ const arr = new Uint16Array(length);+ DataStream.memcpy(arr.buffer, 0, this.buffer, this.byteOffset + this.position, length * arr.BYTES_PER_ELEMENT);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += arr.byteLength;+ return arr;+ }+ /**+ * Reads a Uint8Array of desired length from the DataStream.+ *+ * @param length Number of elements to map.+ * @param e Endianness of the data to read.+ * @return The read Uint8Array.+ */+ readUint8Array(length) {+ length = length === void 0 ? this.byteLength - this.position : length;+ const arr = new Uint8Array(length);+ DataStream.memcpy(arr.buffer, 0, this.buffer, this.byteOffset + this.position, length * arr.BYTES_PER_ELEMENT);+ this.position += arr.byteLength;+ return arr;+ }+ /**+ * Reads a Float64Array of desired length and endianness from the DataStream.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return The read Float64Array.+ */+ readFloat64Array(length, endianness) {+ length = length === void 0 ? this.byteLength - this.position / 8 : length;+ const arr = new Float64Array(length);+ DataStream.memcpy(arr.buffer, 0, this.buffer, this.byteOffset + this.position, length * arr.BYTES_PER_ELEMENT);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += arr.byteLength;+ return arr;+ }+ /**+ * Reads a Float32Array of desired length and endianness from the DataStream.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return The read Float32Array.+ */+ readFloat32Array(length, endianness) {+ length = length === void 0 ? this.byteLength - this.position / 4 : length;+ const arr = new Float32Array(length);+ DataStream.memcpy(arr.buffer, 0, this.buffer, this.byteOffset + this.position, length * arr.BYTES_PER_ELEMENT);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += arr.byteLength;+ return arr;+ }+ /**+ * Reads a 32-bit int from the DataStream with the desired endianness.+ *+ * @param endianness Endianness of the number.+ * @return The read number.+ */+ readInt32(endianness) {+ const v = this._dataView.getInt32(this.position, (endianness ?? this.endianness) === 2);+ this.position += 4;+ return v;+ }+ /**+ * Reads a 16-bit int from the DataStream with the desired endianness.+ *+ * @param endianness Endianness of the number.+ * @return The read number.+ */+ readInt16(endianness) {+ const v = this._dataView.getInt16(this.position, (endianness ?? this.endianness) === 2);+ this.position += 2;+ return v;+ }+ /**+ * Reads an 8-bit int from the DataStream.+ *+ * @return The read number.+ */+ readInt8() {+ const v = this._dataView.getInt8(this.position);+ this.position += 1;+ return v;+ }+ /**+ * Reads a 32-bit unsigned int from the DataStream with the desired endianness.+ *+ * @param endianness Endianness of the number.+ * @return The read number.+ */+ readUint32(endianness) {+ const v = this._dataView.getUint32(this.position, (endianness ?? this.endianness) === 2);+ this.position += 4;+ return v;+ }+ /**+ * Reads a 16-bit unsigned int from the DataStream with the desired endianness.+ *+ * @param endianness Endianness of the number.+ * @return The read number.+ */+ readUint16(endianness) {+ const v = this._dataView.getUint16(this.position, (endianness ?? this.endianness) === 2);+ this.position += 2;+ return v;+ }+ /**+ * Reads an 8-bit unsigned int from the DataStream.+ *+ * @return The read number.+ */+ readUint8() {+ const v = this._dataView.getUint8(this.position);+ this.position += 1;+ return v;+ }+ /**+ * Reads a 32-bit float from the DataStream with the desired endianness.+ *+ * @param endianness Endianness of the number.+ * @return The read number.+ */+ readFloat32(endianness) {+ const value = this._dataView.getFloat32(this.position, (endianness ?? this.endianness) === 2);+ this.position += 4;+ return value;+ }+ /**+ * Reads a 64-bit float from the DataStream with the desired endianness.+ *+ * @param endianness Endianness of the number.+ * @return The read number.+ */+ readFloat64(endianness) {+ const value = this._dataView.getFloat64(this.position, (endianness ?? this.endianness) === 2);+ this.position += 8;+ return value;+ }+ /**+ * Copies byteLength bytes from the src buffer at srcOffset to the+ * dst buffer at dstOffset.+ *+ * @param dst Destination ArrayBuffer to write to.+ * @param dstOffset Offset to the destination ArrayBuffer.+ * @param src Source ArrayBuffer to read from.+ * @param srcOffset Offset to the source ArrayBuffer.+ * @param byteLength Number of bytes to copy.+ */+ static memcpy(dst, dstOffset, src, srcOffset, byteLength) {+ const dstU8 = new Uint8Array(dst, dstOffset, byteLength);+ const srcU8 = new Uint8Array(src, srcOffset, byteLength);+ dstU8.set(srcU8);+ }+ /**+ * Converts array to native endianness in-place.+ *+ * @param typedArray Typed array to convert.+ * @param endianness True if the data in the array is+ * little-endian. Set false for big-endian.+ * @return The converted typed array.+ */+ static arrayToNative(typedArray, endianness) {+ if (endianness === DataStream.ENDIANNESS) return typedArray;+ else return this.flipArrayEndianness(typedArray);+ }+ /**+ * Converts native endianness array to desired endianness in-place.+ *+ * @param typedArray Typed array to convert.+ * @param littleEndian True if the converted array should be+ * little-endian. Set false for big-endian.+ * @return The converted typed array.+ */+ static nativeToEndian(typedArray, littleEndian) {+ if (littleEndian && DataStream.ENDIANNESS === 2) return typedArray;+ else return this.flipArrayEndianness(typedArray);+ }+ /**+ * Flips typed array endianness in-place.+ *+ * @param typedArray Typed array to flip.+ * @return The converted typed array.+ */+ static flipArrayEndianness(typedArray) {+ const u8 = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);+ for (let i = 0; i < typedArray.byteLength; i += typedArray.BYTES_PER_ELEMENT) for (let j = i + typedArray.BYTES_PER_ELEMENT - 1, k = i; j > k; j--, k++) {+ const tmp = u8[k];+ u8[k] = u8[j];+ u8[j] = tmp;+ }+ return typedArray;+ }+ /**+ * Read a string of desired length and encoding from the DataStream.+ *+ * @param length The length of the string to read in bytes.+ * @param encoding The encoding of the string data in the DataStream.+ * Defaults to ASCII.+ * @return The read string.+ */+ readString(length, encoding) {+ if (encoding === void 0 || encoding === "ASCII") return fromCharCodeUint8(this.mapUint8Array(length === void 0 ? this.byteLength - this.position : length));+ else return new TextDecoder(encoding).decode(this.mapUint8Array(length));+ }+ /**+ * Read null-terminated string of desired length from the DataStream. Truncates+ * the returned string so that the null byte is not a part of it.+ *+ * @param length The length of the string to read.+ * @return The read string.+ */+ readCString(length) {+ let i = 0;+ const blen = this.byteLength - this.position;+ const u8 = new Uint8Array(this._buffer, this._byteOffset + this.position);+ const len = length !== void 0 ? Math.min(length, blen) : blen;+ for (; i < len && u8[i] !== 0; i++);+ const s = fromCharCodeUint8(this.mapUint8Array(i));+ if (length !== void 0) this.position += len - i;+ else if (i !== blen) this.position += 1;+ return s;+ }+ readInt64() {+ return this.readInt32() * MAX_SIZE + this.readUint32();+ }+ readUint64() {+ return this.readUint32() * MAX_SIZE + this.readUint32();+ }+ readUint24() {+ return (this.readUint8() << 16) + (this.readUint8() << 8) + this.readUint8();+ }+ /**+ * Saves the DataStream contents to the given filename.+ * Uses Chrome's anchor download property to initiate download.+ *+ * @param filename Filename to save as.+ * @return+ * @bundle DataStream-write.js+ */+ save(filename) {+ const blob = new Blob([this.buffer]);+ if (typeof window !== "undefined" && typeof document !== "undefined") if (window.URL && URL.createObjectURL) {+ const url = window.URL.createObjectURL(blob);+ const a = document.createElement("a");+ document.body.appendChild(a);+ a.setAttribute("href", url);+ a.setAttribute("download", filename);+ a.setAttribute("target", "_self");+ a.click();+ window.URL.revokeObjectURL(url);+ document.body.removeChild(a);+ } else throw new Error("DataStream.save: Can't create object URL.");+ return blob;+ }+ /** @bundle DataStream-write.js */+ get dynamicSize() {+ return this._dynamicSize;+ }+ /** @bundle DataStream-write.js */+ set dynamicSize(v) {+ if (!v) this._trimAlloc();+ this._dynamicSize = v;+ }+ /**+ * Internal function to trim the DataStream buffer when required.+ * Used for stripping out the first bytes when not needed anymore.+ *+ * @return+ * @bundle DataStream-write.js+ */+ shift(offset) {+ const buf = new MP4BoxBuffer(this._byteLength - offset);+ const dst = new Uint8Array(buf);+ const src = new Uint8Array(this._buffer, offset, dst.length);+ dst.set(src);+ this.buffer = buf;+ this.position -= offset;+ }+ /**+ * Writes an Int32Array of specified endianness to the DataStream.+ *+ * @param array The array to write.+ * @param endianness Endianness of the data to write.+ * @bundle DataStream-write.js+ */+ writeInt32Array(array, endianness) {+ this._realloc(array.length * 4);+ if (array instanceof Int32Array && this.byteOffset + this.position % array.BYTES_PER_ELEMENT === 0) {+ DataStream.memcpy(this._buffer, this.byteOffset + this.position, array.buffer, 0, array.byteLength);+ this.mapInt32Array(array.length, endianness);+ } else for (let i = 0; i < array.length; i++) this.writeInt32(array[i], endianness);+ }+ /**+ * Writes an Int16Array of specified endianness to the DataStream.+ *+ * @param array The array to write.+ * @param endianness Endianness of the data to write.+ * @bundle DataStream-write.js+ */+ writeInt16Array(array, endianness) {+ this._realloc(array.length * 2);+ if (array instanceof Int16Array && this.byteOffset + this.position % array.BYTES_PER_ELEMENT === 0) {+ DataStream.memcpy(this._buffer, this.byteOffset + this.position, array.buffer, 0, array.byteLength);+ this.mapInt16Array(array.length, endianness);+ } else for (let i = 0; i < array.length; i++) this.writeInt16(array[i], endianness);+ }+ /**+ * Writes an Int8Array to the DataStream.+ *+ * @param array The array to write.+ * @bundle DataStream-write.js+ */+ writeInt8Array(array) {+ this._realloc(array.length * 1);+ if (array instanceof Int8Array && this.byteOffset + this.position % array.BYTES_PER_ELEMENT === 0) {+ DataStream.memcpy(this._buffer, this.byteOffset + this.position, array.buffer, 0, array.byteLength);+ this.mapInt8Array(array.length);+ } else for (let i = 0; i < array.length; i++) this.writeInt8(array[i]);+ }+ /**+ * Writes a Uint32Array of specified endianness to the DataStream.+ *+ * @param array The array to write.+ * @param endianness Endianness of the data to write.+ * @bundle DataStream-write.js+ */+ writeUint32Array(array, endianness) {+ this._realloc(array.length * 4);+ if (array instanceof Uint32Array && this.byteOffset + this.position % array.BYTES_PER_ELEMENT === 0) {+ DataStream.memcpy(this._buffer, this.byteOffset + this.position, array.buffer, 0, array.byteLength);+ this.mapUint32Array(array.length, endianness);+ } else for (let i = 0; i < array.length; i++) this.writeUint32(array[i], endianness);+ }+ /**+ * Writes a Uint16Array of specified endianness to the DataStream.+ *+ * @param array The array to write.+ * @param endianness Endianness of the data to write.+ * @bundle DataStream-write.js+ */+ writeUint16Array(array, endianness) {+ this._realloc(array.length * 2);+ if (array instanceof Uint16Array && this.byteOffset + this.position % array.BYTES_PER_ELEMENT === 0) {+ DataStream.memcpy(this._buffer, this.byteOffset + this.position, array.buffer, 0, array.byteLength);+ this.mapUint16Array(array.length, endianness);+ } else for (let i = 0; i < array.length; i++) this.writeUint16(array[i], endianness);+ }+ /**+ * Writes a Uint8Array to the DataStream.+ *+ * @param array The array to write.+ * @bundle DataStream-write.js+ */+ writeUint8Array(array) {+ this._realloc(array.length * 1);+ if (array instanceof Uint8Array && this.byteOffset + this.position % array.BYTES_PER_ELEMENT === 0) {+ DataStream.memcpy(this._buffer, this.byteOffset + this.position, array.buffer, 0, array.byteLength);+ this.mapUint8Array(array.length);+ } else for (let i = 0; i < array.length; i++) this.writeUint8(array[i]);+ }+ /**+ * Writes a Float64Array of specified endianness to the DataStream.+ *+ * @param array The array to write.+ * @param endianness Endianness of the data to write.+ * @bundle DataStream-write.js+ */+ writeFloat64Array(array, endianness) {+ this._realloc(array.length * 8);+ if (array instanceof Float64Array && this.byteOffset + this.position % array.BYTES_PER_ELEMENT === 0) {+ DataStream.memcpy(this._buffer, this.byteOffset + this.position, array.buffer, 0, array.byteLength);+ this.mapFloat64Array(array.length, endianness);+ } else for (let i = 0; i < array.length; i++) this.writeFloat64(array[i], endianness);+ }+ /**+ * Writes a Float32Array of specified endianness to the DataStream.+ *+ * @param array The array to write.+ * @param endianness Endianness of the data to write.+ * @bundle DataStream-write.js+ */+ writeFloat32Array(array, endianness) {+ this._realloc(array.length * 4);+ if (array instanceof Float32Array && this.byteOffset + this.position % array.BYTES_PER_ELEMENT === 0) {+ DataStream.memcpy(this._buffer, this.byteOffset + this.position, array.buffer, 0, array.byteLength);+ this.mapFloat32Array(array.length, endianness);+ } else for (let i = 0; i < array.length; i++) this.writeFloat32(array[i], endianness);+ }+ /**+ * Writes a 64-bit int to the DataStream with the desired endianness.+ *+ * @param value Number to write.+ * @param endianness Endianness of the number.+ * @bundle DataStream-write.js+ */+ writeInt64(value, endianness) {+ this._realloc(8);+ this._dataView.setBigInt64(this.position, BigInt(value), (endianness ?? this.endianness) === 2);+ this.position += 8;+ }+ /**+ * Writes a 32-bit int to the DataStream with the desired endianness.+ *+ * @param value Number to write.+ * @param endianness Endianness of the number.+ * @bundle DataStream-write.js+ */+ writeInt32(value, endianness) {+ this._realloc(4);+ this._dataView.setInt32(this.position, value, (endianness ?? this.endianness) === 2);+ this.position += 4;+ }+ /**+ * Writes a 16-bit int to the DataStream with the desired endianness.+ *+ * @param value Number to write.+ * @param endianness Endianness of the number.+ * @bundle DataStream-write.js+ */+ writeInt16(value, endianness) {+ this._realloc(2);+ this._dataView.setInt16(this.position, value, (endianness ?? this.endianness) === 2);+ this.position += 2;+ }+ /**+ * Writes an 8-bit int to the DataStream.+ *+ * @param value Number to write.+ * @bundle DataStream-write.js+ */+ writeInt8(value) {+ this._realloc(1);+ this._dataView.setInt8(this.position, value);+ this.position += 1;+ }+ /**+ * Writes a 32-bit unsigned int to the DataStream with the desired endianness.+ *+ * @param value Number to write.+ * @param endianness Endianness of the number.+ * @bundle DataStream-write.js+ */+ writeUint32(value, endianness) {+ this._realloc(4);+ this._dataView.setUint32(this.position, value, (endianness ?? this.endianness) === 2);+ this.position += 4;+ }+ /**+ * Writes a 16-bit unsigned int to the DataStream with the desired endianness.+ *+ * @param value Number to write.+ * @param endianness Endianness of the number.+ * @bundle DataStream-write.js+ */+ writeUint16(value, endianness) {+ this._realloc(2);+ this._dataView.setUint16(this.position, value, (endianness ?? this.endianness) === 2);+ this.position += 2;+ }+ /**+ * Writes an 8-bit unsigned int to the DataStream.+ *+ * @param value Number to write.+ * @bundle DataStream-write.js+ */+ writeUint8(value) {+ this._realloc(1);+ this._dataView.setUint8(this.position, value);+ this.position += 1;+ }+ /**+ * Writes a 32-bit float to the DataStream with the desired endianness.+ *+ * @param value Number to write.+ * @param endianness Endianness of the number.+ * @bundle DataStream-write.js+ */+ writeFloat32(value, endianness) {+ this._realloc(4);+ this._dataView.setFloat32(this.position, value, (endianness ?? this.endianness) === 2);+ this.position += 4;+ }+ /**+ * Writes a 64-bit float to the DataStream with the desired endianness.+ *+ * @param value Number to write.+ * @param endianness Endianness of the number.+ * @bundle DataStream-write.js+ */+ writeFloat64(value, endianness) {+ this._realloc(8);+ this._dataView.setFloat64(this.position, value, (endianness ?? this.endianness) === 2);+ this.position += 8;+ }+ /**+ * Write a UCS-2 string of desired endianness to the DataStream. The+ * lengthOverride argument lets you define the number of characters to write.+ * If the string is shorter than lengthOverride, the extra space is padded with+ * zeroes.+ *+ * @param value The string to write.+ * @param endianness The endianness to use for the written string data.+ * @param lengthOverride The number of characters to write.+ * @bundle DataStream-write.js+ */+ writeUCS2String(value, endianness, lengthOverride) {+ if (lengthOverride === void 0) lengthOverride = value.length;+ let i;+ for (i = 0; i < value.length && i < lengthOverride; i++) this.writeUint16(value.charCodeAt(i), endianness);+ for (; i < lengthOverride; i++) this.writeUint16(0);+ }+ /**+ * Writes a string of desired length and encoding to the DataStream.+ *+ * @param value The string to write.+ * @param encoding The encoding for the written string data.+ * Defaults to ASCII.+ * @param length The number of characters to write.+ * @bundle DataStream-write.js+ */+ writeString(value, encoding, length) {+ let i = 0;+ if (encoding === void 0 || encoding === "ASCII") if (length !== void 0) {+ const len = Math.min(value.length, length);+ for (i = 0; i < len; i++) this.writeUint8(value.charCodeAt(i));+ for (; i < length; i++) this.writeUint8(0);+ } else for (i = 0; i < value.length; i++) this.writeUint8(value.charCodeAt(i));+ else this.writeUint8Array(new TextEncoder(encoding).encode(value.substring(0, length)));+ }+ /**+ * Writes a null-terminated string to DataStream and zero-pads it to length+ * bytes. If length is not given, writes the string followed by a zero.+ * If string is longer than length, the written part of the string does not have+ * a trailing zero.+ *+ * @param value The string to write.+ * @param length The number of characters to write.+ * @bundle DataStream-write.js+ */+ writeCString(value, length) {+ let i = 0;+ if (length !== void 0) {+ const len = Math.min(value.length, length);+ for (i = 0; i < len; i++) this.writeUint8(value.charCodeAt(i));+ for (; i < length; i++) this.writeUint8(0);+ } else {+ for (i = 0; i < value.length; i++) this.writeUint8(value.charCodeAt(i));+ this.writeUint8(0);+ }+ }+ /**+ * Writes a struct to the DataStream. Takes a structDefinition that gives the+ * types and a struct object that gives the values. Refer to readStruct for the+ * structure of structDefinition.+ *+ * @param structDefinition Type definition of the struct.+ * @param struct The struct data object.+ * @bundle DataStream-write.js+ */+ writeStruct(structDefinition, struct) {+ for (let i = 0; i < structDefinition.length; i++) {+ const [structName, structType] = structDefinition[i];+ const structValue = struct[structName];+ this.writeType(structType, structValue, struct);+ }+ }+ /**+ * Writes object v of type t to the DataStream.+ *+ * @param type Type of data to write.+ * @param value Value of data to write.+ * @param struct Struct to pass to write callback functions.+ * @bundle DataStream-write.js+ */+ writeType(type, value, struct) {+ if (typeof type === "function") return type(this, value);+ else if (typeof type === "object" && !(type instanceof Array)) return type.set(this, value, struct);+ let lengthOverride;+ let charset = "ASCII";+ const pos = this.position;+ let parsedType = type;+ if (typeof type === "string" && /:/.test(type)) {+ const tp = type.split(":");+ parsedType = tp[0];+ lengthOverride = parseInt(tp[1]);+ }+ if (typeof parsedType === "string" && /,/.test(parsedType)) {+ const tp = parsedType.split(",");+ parsedType = tp[0];+ charset = tp[1];+ }+ switch (parsedType) {+ case "uint8":+ this.writeUint8(value);+ break;+ case "int8":+ this.writeInt8(value);+ break;+ case "uint16":+ this.writeUint16(value, this.endianness);+ break;+ case "int16":+ this.writeInt16(value, this.endianness);+ break;+ case "uint32":+ this.writeUint32(value, this.endianness);+ break;+ case "int32":+ this.writeInt32(value, this.endianness);+ break;+ case "float32":+ this.writeFloat32(value, this.endianness);+ break;+ case "float64":+ this.writeFloat64(value, this.endianness);+ break;+ case "uint16be":+ this.writeUint16(value, 1);+ break;+ case "int16be":+ this.writeInt16(value, 1);+ break;+ case "uint32be":+ this.writeUint32(value, 1);+ break;+ case "int32be":+ this.writeInt32(value, 1);+ break;+ case "float32be":+ this.writeFloat32(value, 1);+ break;+ case "float64be":+ this.writeFloat64(value, 1);+ break;+ case "uint16le":+ this.writeUint16(value, 2);+ break;+ case "int16le":+ this.writeInt16(value, 2);+ break;+ case "uint32le":+ this.writeUint32(value, 2);+ break;+ case "int32le":+ this.writeInt32(value, 2);+ break;+ case "float32le":+ this.writeFloat32(value, 2);+ break;+ case "float64le":+ this.writeFloat64(value, 2);+ break;+ case "cstring":+ this.writeCString(value, lengthOverride);+ break;+ case "string":+ this.writeString(value, charset, lengthOverride);+ break;+ case "u16string":+ this.writeUCS2String(value, this.endianness, lengthOverride);+ break;+ case "u16stringle":+ this.writeUCS2String(value, 2, lengthOverride);+ break;+ case "u16stringbe":+ this.writeUCS2String(value, 1, lengthOverride);+ break;+ default: if (this.#isTupleType(parsedType)) {+ const [, ta] = parsedType;+ for (let i = 0; i < value.length; i++) this.writeType(ta, value[i]);+ break;+ } else {+ this.writeStruct(parsedType, value);+ break;+ }+ }+ if (lengthOverride) {+ this.position = pos;+ this._realloc(lengthOverride);+ this.position = pos + lengthOverride;+ }+ }+ /** @bundle DataStream-write.js */+ writeUint64(value) {+ const h = Math.floor(value / MAX_SIZE);+ this.writeUint32(h);+ this.writeUint32(value & 4294967295);+ }+ /** @bundle DataStream-write.js */+ writeUint24(value) {+ this.writeUint8((value & 16711680) >> 16);+ this.writeUint8((value & 65280) >> 8);+ this.writeUint8(value & 255);+ }+ /** @bundle DataStream-write.js */+ adjustUint32(position, value) {+ const pos = this.position;+ this.seek(position);+ this.writeUint32(value);+ this.seek(pos);+ }+ /**+ * Reads a struct of data from the DataStream. The struct is defined as+ * an array of [name, type]-pairs. See the example below:+ *+ * ```ts+ * ds.readStruct([+ * ['headerTag', 'uint32'], // Uint32 in DataStream endianness.+ * ['headerTag2', 'uint32be'], // Big-endian Uint32.+ * ['headerTag3', 'uint32le'], // Little-endian Uint32.+ * ['array', ['[]', 'uint32', 16]], // Uint32Array of length 16.+ * ['array2', ['[]', 'uint32', 'array2Length']] // Uint32Array of length array2Length+ * ]);+ * ```+ *+ * The possible values for the type are as follows:+ *+ * ## Number types+ *+ * Unsuffixed number types use DataStream endianness.+ * To explicitly specify endianness, suffix the type with+ * 'le' for little-endian or 'be' for big-endian,+ * e.g. 'int32be' for big-endian int32.+ *+ * - `uint8` -- 8-bit unsigned int+ * - `uint16` -- 16-bit unsigned int+ * - `uint32` -- 32-bit unsigned int+ * - `int8` -- 8-bit int+ * - `int16` -- 16-bit int+ * - `int32` -- 32-bit int+ * - `float32` -- 32-bit float+ * - `float64` -- 64-bit float+ *+ * ## String types+ *+ * - `cstring` -- ASCII string terminated by a zero byte.+ * - `string:N` -- ASCII string of length N.+ * - `string,CHARSET:N` -- String of byteLength N encoded with given CHARSET.+ * - `u16string:N` -- UCS-2 string of length N in DataStream endianness.+ * - `u16stringle:N` -- UCS-2 string of length N in little-endian.+ * - `u16stringbe:N` -- UCS-2 string of length N in big-endian.+ *+ * ## Complex types+ *+ * ### Struct+ * ```ts+ * [[name, type], [name_2, type_2], ..., [name_N, type_N]]+ * ```+ *+ * ### Callback function to read and return data+ * ```ts+ * function(dataStream, struct) {}+ * ```+ *+ * ### Getter/setter functions+ * to read and return data, handy for using the same struct definition+ * for reading and writing structs.+ * ```ts+ * {+ * get: function(dataStream, struct) {},+ * set: function(dataStream, struct) {}+ * }+ * ```+ *+ * ### Array+ * Array of given type and length. The length can be either+ * - a number+ * - a string that references a previously-read field+ * - `*`+ * - a callback: `function(struct, dataStream, type){}`+ *+ * If length is `*`, reads in as many elements as it can.+ * ```ts+ * ['[]', type, length]+ * ```+ *+ * @param structDefinition Struct definition object.+ * @return The read struct. Null if failed to read struct.+ * @bundle DataStream-read-struct.js+ */+ readStruct(structDefinition) {+ const struct = {};+ const p = this.position;+ for (let i = 0; i < structDefinition.length; i += 1) {+ const t = structDefinition[i][1];+ const v = this.readType(t, struct);+ if (!v) {+ if (this.failurePosition === 0) this.failurePosition = this.position;+ this.position = p;+ return;+ }+ struct[structDefinition[i][0]] = v;+ }+ return struct;+ }+ /**+ * Read UCS-2 string of desired length and endianness from the DataStream.+ *+ * @param length The length of the string to read.+ * @param endianness The endianness of the string data in the DataStream.+ * @return The read string.+ * @bundle DataStream-read-struct.js+ */+ readUCS2String(length, endianness) {+ return String.fromCharCode.apply(void 0, this.readUint16Array(length, endianness));+ }+ /**+ * Reads an object of type t from the DataStream, passing struct as the thus-far+ * read struct to possible callbacks that refer to it. Used by readStruct for+ * reading in the values, so the type is one of the readStruct types.+ *+ * @param type Type of the object to read.+ * @param struct Struct to refer to when resolving length references+ * and for calling callbacks.+ * @return Returns the object on successful read, null on unsuccessful.+ * @bundle DataStream-read-struct.js+ */+ readType(type, struct) {+ if (typeof type === "function") return type(this, struct);+ if (typeof type === "object" && !(type instanceof Array)) return type.get(this, struct);+ if (type instanceof Array && type.length !== 3) return this.readStruct(type);+ let value;+ let lengthOverride;+ let charset = "ASCII";+ const pos = this.position;+ let parsedType = type;+ if (typeof parsedType === "string" && /:/.test(parsedType)) {+ const tp = parsedType.split(":");+ parsedType = tp[0];+ lengthOverride = parseInt(tp[1]);+ }+ if (typeof parsedType === "string" && /,/.test(parsedType)) {+ const tp = parsedType.split(",");+ parsedType = tp[0];+ charset = tp[1];+ }+ switch (parsedType) {+ case "uint8":+ value = this.readUint8();+ break;+ case "int8":+ value = this.readInt8();+ break;+ case "uint16":+ value = this.readUint16(this.endianness);+ break;+ case "int16":+ value = this.readInt16(this.endianness);+ break;+ case "uint32":+ value = this.readUint32(this.endianness);+ break;+ case "int32":+ value = this.readInt32(this.endianness);+ break;+ case "float32":+ value = this.readFloat32(this.endianness);+ break;+ case "float64":+ value = this.readFloat64(this.endianness);+ break;+ case "uint16be":+ value = this.readUint16(1);+ break;+ case "int16be":+ value = this.readInt16(1);+ break;+ case "uint32be":+ value = this.readUint32(1);+ break;+ case "int32be":+ value = this.readInt32(1);+ break;+ case "float32be":+ value = this.readFloat32(1);+ break;+ case "float64be":+ value = this.readFloat64(1);+ break;+ case "uint16le":+ value = this.readUint16(2);+ break;+ case "int16le":+ value = this.readInt16(2);+ break;+ case "uint32le":+ value = this.readUint32(2);+ break;+ case "int32le":+ value = this.readInt32(2);+ break;+ case "float32le":+ value = this.readFloat32(2);+ break;+ case "float64le":+ value = this.readFloat64(2);+ break;+ case "cstring":+ value = this.readCString(lengthOverride);+ break;+ case "string":+ value = this.readString(lengthOverride, charset);+ break;+ case "u16string":+ value = this.readUCS2String(lengthOverride, this.endianness);+ break;+ case "u16stringle":+ value = this.readUCS2String(lengthOverride, 2);+ break;+ case "u16stringbe":+ value = this.readUCS2String(lengthOverride, 1);+ break;+ default: if (this.#isTupleType(parsedType)) {+ const [, ta, len] = parsedType;+ const length = typeof len === "function" ? len(struct, this, parsedType) : typeof len === "string" && struct[len] !== void 0 ? parseInt(struct[len]) : typeof len === "number" ? len : len === "*" ? void 0 : parseInt(len);+ if (typeof ta === "string") {+ const tap = ta.replace(/(le|be)$/, "");+ let endianness;+ if (/le$/.test(ta)) endianness = 2;+ else if (/be$/.test(ta)) endianness = 1;+ switch (tap) {+ case "uint8":+ value = this.readUint8Array(length);+ break;+ case "uint16":+ value = this.readUint16Array(length, endianness);+ break;+ case "uint32":+ value = this.readUint32Array(length, endianness);+ break;+ case "int8":+ value = this.readInt8Array(length);+ break;+ case "int16":+ value = this.readInt16Array(length, endianness);+ break;+ case "int32":+ value = this.readInt32Array(length, endianness);+ break;+ case "float32":+ value = this.readFloat32Array(length, endianness);+ break;+ case "float64":+ value = this.readFloat64Array(length, endianness);+ break;+ case "cstring":+ case "utf16string":+ case "string":+ if (!length) {+ value = [];+ while (!this.isEof()) {+ const u = this.readType(ta, struct);+ if (!u) break;+ value.push(u);+ }+ } else {+ value = new Array(length);+ for (let i = 0; i < length; i++) value[i] = this.readType(ta, struct);+ }+ break;+ }+ } else if (!length) {+ value = [];+ while (true) {+ const pos = this.position;+ try {+ const type = this.readType(ta, struct);+ if (!type) {+ this.position = pos;+ break;+ }+ value.push(type);+ } catch {+ this.position = pos;+ break;+ }+ }+ } else {+ value = new Array(length);+ for (let i = 0; i < length; i++) {+ const type = this.readType(ta, struct);+ if (!type) return;+ value[i] = type;+ }+ }+ break;+ }+ }+ if (lengthOverride) this.position = pos + lengthOverride;+ return value;+ }+ /**+ * Maps an Int32Array into the DataStream buffer, swizzling it to native+ * endianness in-place. The current offset from the start of the buffer needs to+ * be a multiple of element size, just like with typed array views.+ *+ * Nice for quickly reading in data. Warning: potentially modifies the buffer+ * contents.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return Int32Array to the DataStream backing buffer.+ * @bundle DataStream-map.js+ */+ mapInt32Array(length, endianness) {+ this._realloc(length * 4);+ const arr = new Int32Array(this._buffer, this.byteOffset + this.position, length);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += length * 4;+ return arr;+ }+ /**+ * Maps an Int16Array into the DataStream buffer, swizzling it to native+ * endianness in-place. The current offset from the start of the buffer needs to+ * be a multiple of element size, just like with typed array views.+ *+ * Nice for quickly reading in data. Warning: potentially modifies the buffer+ * contents.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return Int16Array to the DataStream backing buffer.+ * @bundle DataStream-map.js+ */+ mapInt16Array(length, endianness) {+ this._realloc(length * 2);+ const arr = new Int16Array(this._buffer, this.byteOffset + this.position, length);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += length * 2;+ return arr;+ }+ /**+ * Maps an Int8Array into the DataStream buffer.+ *+ * Nice for quickly reading in data.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return Int8Array to the DataStream backing buffer.+ * @bundle DataStream-map.js+ */+ mapInt8Array(length, _endianness) {+ this._realloc(length * 1);+ const arr = new Int8Array(this._buffer, this.byteOffset + this.position, length);+ this.position += length * 1;+ return arr;+ }+ /**+ * Maps a Uint32Array into the DataStream buffer, swizzling it to native+ * endianness in-place. The current offset from the start of the buffer needs to+ * be a multiple of element size, just like with typed array views.+ *+ * Nice for quickly reading in data. Warning: potentially modifies the buffer+ * contents.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return Uint32Array to the DataStream backing buffer.+ * @bundle DataStream-map.js+ */+ mapUint32Array(length, endianness) {+ this._realloc(length * 4);+ const arr = new Uint32Array(this._buffer, this.byteOffset + this.position, length);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += length * 4;+ return arr;+ }+ /**+ * Maps a Uint16Array into the DataStream buffer, swizzling it to native+ * endianness in-place. The current offset from the start of the buffer needs to+ * be a multiple of element size, just like with typed array views.+ *+ * Nice for quickly reading in data. Warning: potentially modifies the buffer+ * contents.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return Uint16Array to the DataStream backing buffer.+ * @bundle DataStream-map.js+ */+ mapUint16Array(length, endianness) {+ this._realloc(length * 2);+ const arr = new Uint16Array(this._buffer, this.byteOffset + this.position, length);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += length * 2;+ return arr;+ }+ /**+ * Maps a Float64Array into the DataStream buffer, swizzling it to native+ * endianness in-place. The current offset from the start of the buffer needs to+ * be a multiple of element size, just like with typed array views.+ *+ * Nice for quickly reading in data. Warning: potentially modifies the buffer+ * contents.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return Float64Array to the DataStream backing buffer.+ * @bundle DataStream-map.js+ */+ mapFloat64Array(length, endianness) {+ this._realloc(length * 8);+ const arr = new Float64Array(this._buffer, this.byteOffset + this.position, length);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += length * 8;+ return arr;+ }+ /**+ * Maps a Float32Array into the DataStream buffer, swizzling it to native+ * endianness in-place. The current offset from the start of the buffer needs to+ * be a multiple of element size, just like with typed array views.+ *+ * Nice for quickly reading in data. Warning: potentially modifies the buffer+ * contents.+ *+ * @param length Number of elements to map.+ * @param endianness Endianness of the data to read.+ * @return Float32Array to the DataStream backing buffer.+ * @bundle DataStream-map.js+ */+ mapFloat32Array(length, endianness) {+ this._realloc(length * 4);+ const arr = new Float32Array(this._buffer, this.byteOffset + this.position, length);+ DataStream.arrayToNative(arr, endianness ?? this.endianness);+ this.position += length * 4;+ return arr;+ }+};+function fromCharCodeUint8(uint8arr) {+ const arr = [];+ for (let i = 0; i < uint8arr.length; i++) arr[i] = uint8arr[i];+ return String.fromCharCode.apply(void 0, arr);+}++//#endregion+//#region src/log.ts+const start = /* @__PURE__ */ new Date();+const LOG_LEVEL_ERROR = 4;+const LOG_LEVEL_WARNING = 3;+const LOG_LEVEL_INFO = 2;+const LOG_LEVEL_DEBUG = 1;+let log_level = LOG_LEVEL_ERROR;+const Log = {+ setLogLevel(level) {+ if (level === this.debug) log_level = LOG_LEVEL_DEBUG;+ else if (level === this.info) log_level = LOG_LEVEL_INFO;+ else if (level === this.warn) log_level = LOG_LEVEL_WARNING;+ else if (level === this.error) log_level = LOG_LEVEL_ERROR;+ else log_level = LOG_LEVEL_ERROR;+ },+ debug(module, msg) {+ if (console.debug === void 0) console.debug = console.log;+ if (LOG_LEVEL_DEBUG >= log_level) console.debug("[" + Log.getDurationString((/* @__PURE__ */ new Date()).getTime() - start.getTime(), 1e3) + "]", "[" + module + "]", msg);+ },+ log(module, _msg) {+ this.debug(module.msg);+ },+ info(module, msg) {+ if (LOG_LEVEL_INFO >= log_level) console.info("[" + Log.getDurationString((/* @__PURE__ */ new Date()).getTime() - start.getTime(), 1e3) + "]", "[" + module + "]", msg);+ },+ warn(module, msg) {+ if (LOG_LEVEL_WARNING >= log_level) console.warn("[" + Log.getDurationString((/* @__PURE__ */ new Date()).getTime() - start.getTime(), 1e3) + "]", "[" + module + "]", msg);+ },+ error(module, msg, isofile) {+ if (isofile?.onError) isofile.onError(module, msg);+ else if (LOG_LEVEL_ERROR >= log_level) console.error("[" + Log.getDurationString((/* @__PURE__ */ new Date()).getTime() - start.getTime(), 1e3) + "]", "[" + module + "]", msg);+ },+ getDurationString(duration, _timescale) {+ let neg;+ function pad(number, length) {+ const a = ("" + number).split(".");+ while (a[0].length < length) a[0] = "0" + a[0];+ return a.join(".");+ }+ if (duration < 0) {+ neg = true;+ duration = -duration;+ } else neg = false;+ let duration_sec = duration / (_timescale || 1);+ const hours = Math.floor(duration_sec / 3600);+ duration_sec -= hours * 3600;+ const minutes = Math.floor(duration_sec / 60);+ duration_sec -= minutes * 60;+ let msec = duration_sec * 1e3;+ duration_sec = Math.floor(duration_sec);+ msec -= duration_sec * 1e3;+ msec = Math.floor(msec);+ return (neg ? "-" : "") + hours + ":" + pad(minutes, 2) + ":" + pad(duration_sec, 2) + "." + pad(msec, 3);+ },+ printRanges(ranges) {+ const length = ranges.length;+ if (length > 0) {+ let str = "";+ for (let i = 0; i < length; i++) {+ if (i > 0) str += ",";+ str += "[" + Log.getDurationString(ranges.start(i)) + "," + Log.getDurationString(ranges.end(i)) + "]";+ }+ return str;+ } else return "(empty)";+ }+};++//#endregion+//#region src/buffer.ts+/**+* helper functions to concatenate two ArrayBuffer objects+* @param buffer1+* @param buffer2+* @return the concatenation of buffer1 and buffer2 in that order+*/+function concatBuffers(buffer1, buffer2) {+ Log.debug("ArrayBuffer", "Trying to create a new buffer of size: " + (buffer1.byteLength + buffer2.byteLength));+ const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);+ tmp.set(new Uint8Array(buffer1), 0);+ tmp.set(new Uint8Array(buffer2), buffer1.byteLength);+ return tmp.buffer;+}+/**+* MultiBufferStream is a class that acts as a SimpleStream for parsing+* It holds several, possibly non-contiguous ArrayBuffer objects, each with a fileStart property+* containing the offset for the buffer data in an original/virtual file+*+* It inherits also from DataStream for all read/write/alloc operations+*/+var MultiBufferStream = class extends DataStream {+ constructor(buffer) {+ super(/* @__PURE__ */ new ArrayBuffer(), 0);+ this.buffers = [];+ this.bufferIndex = -1;+ if (buffer) {+ this.insertBuffer(buffer);+ this.bufferIndex = 0;+ }+ }+ /***********************************************************************************+ * Methods for the managnement of the buffers *+ * (insertion, removal, concatenation, ...) *+ ***********************************************************************************/+ initialized() {+ if (this.bufferIndex > -1) return true;+ else if (this.buffers.length > 0) {+ const firstBuffer = this.buffers[0];+ if (firstBuffer.fileStart === 0) {+ this.buffer = firstBuffer;+ this.bufferIndex = 0;+ Log.debug("MultiBufferStream", "Stream ready for parsing");+ return true;+ } else {+ Log.warn("MultiBufferStream", "The first buffer should have a fileStart of 0");+ this.logBufferLevel();+ return false;+ }+ } else {+ Log.warn("MultiBufferStream", "No buffer to start parsing from");+ this.logBufferLevel();+ return false;+ }+ }+ /**+ * Reduces the size of a given buffer, but taking the part between offset and offset+newlength+ * @param {ArrayBuffer} buffer+ * @param {Number} offset the start of new buffer+ * @param {Number} newLength the length of the new buffer+ * @return {ArrayBuffer} the new buffer+ */+ reduceBuffer(buffer, offset, newLength) {+ const smallB = new Uint8Array(newLength);+ smallB.set(new Uint8Array(buffer, offset, newLength));+ smallB.buffer.fileStart = buffer.fileStart + offset;+ smallB.buffer.usedBytes = 0;+ return smallB.buffer;+ }+ /**+ * Inserts the new buffer in the sorted list of buffers,+ * making sure, it is not overlapping with existing ones (possibly reducing its size).+ * if the new buffer overrides/replaces the 0-th buffer (for instance because it is bigger),+ * updates the DataStream buffer for parsing+ */+ insertBuffer(ab) {+ let to_add = true;+ let i = 0;+ for (; i < this.buffers.length; i++) {+ const b = this.buffers[i];+ if (ab.fileStart <= b.fileStart) {+ if (ab.fileStart === b.fileStart) if (ab.byteLength > b.byteLength) {+ this.buffers.splice(i, 1);+ i--;+ continue;+ } else Log.warn("MultiBufferStream", "Buffer (fileStart: " + ab.fileStart + " - Length: " + ab.byteLength + ") already appended, ignoring");+ else {+ if (ab.fileStart + ab.byteLength <= b.fileStart) {} else ab = this.reduceBuffer(ab, 0, b.fileStart - ab.fileStart);+ Log.debug("MultiBufferStream", "Appending new buffer (fileStart: " + ab.fileStart + " - Length: " + ab.byteLength + ")");+ this.buffers.splice(i, 0, ab);+ if (i === 0) this.buffer = ab;+ }+ to_add = false;+ break;+ } else if (ab.fileStart < b.fileStart + b.byteLength) {+ const offset = b.fileStart + b.byteLength - ab.fileStart;+ const newLength = ab.byteLength - offset;+ if (newLength > 0) ab = this.reduceBuffer(ab, offset, newLength);+ else {+ to_add = false;+ break;+ }+ }+ }+ if (to_add) {+ Log.debug("MultiBufferStream", "Appending new buffer (fileStart: " + ab.fileStart + " - Length: " + ab.byteLength + ")");+ this.buffers.push(ab);+ if (i === 0) this.buffer = ab;+ }+ }+ /**+ * Displays the status of the buffers (number and used bytes)+ * @param {Object} info callback method for display+ */+ logBufferLevel(info) {+ const ranges = [];+ let bufferedString = "";+ let range;+ let used = 0;+ let total = 0;+ for (let i = 0; i < this.buffers.length; i++) {+ const buffer = this.buffers[i];+ if (i === 0) {+ range = {+ start: buffer.fileStart,+ end: buffer.fileStart + buffer.byteLength+ };+ ranges.push(range);+ bufferedString += "[" + range.start + "-";+ } else if (range.end === buffer.fileStart) range.end = buffer.fileStart + buffer.byteLength;+ else {+ range = {+ start: buffer.fileStart,+ end: buffer.fileStart + buffer.byteLength+ };+ bufferedString += ranges[ranges.length - 1].end - 1 + "], [" + range.start + "-";+ ranges.push(range);+ }+ used += buffer.usedBytes;+ total += buffer.byteLength;+ }+ if (ranges.length > 0) bufferedString += range.end - 1 + "]";+ const log = info ? Log.info : Log.debug;+ if (this.buffers.length === 0) log("MultiBufferStream", "No more buffer in memory");+ else log("MultiBufferStream", "" + this.buffers.length + " stored buffer(s) (" + used + "/" + total + " bytes), continuous ranges: " + bufferedString);+ }+ cleanBuffers() {+ for (let i = 0; i < this.buffers.length; i++) {+ const buffer = this.buffers[i];+ if (buffer.usedBytes === buffer.byteLength) {+ Log.debug("MultiBufferStream", "Removing buffer #" + i);+ this.buffers.splice(i, 1);+ i--;+ }+ }+ }+ mergeNextBuffer() {+ if (this.bufferIndex + 1 < this.buffers.length) {+ const next_buffer = this.buffers[this.bufferIndex + 1];+ if (next_buffer.fileStart === this.buffer.fileStart + this.buffer.byteLength) {+ const oldLength = this.buffer.byteLength;+ const oldUsedBytes = this.buffer.usedBytes;+ const oldFileStart = this.buffer.fileStart;+ this.buffers[this.bufferIndex] = concatBuffers(this.buffer, next_buffer);+ this.buffer = this.buffers[this.bufferIndex];+ this.buffers.splice(this.bufferIndex + 1, 1);+ this.buffer.usedBytes = oldUsedBytes;+ this.buffer.fileStart = oldFileStart;+ Log.debug("ISOFile", "Concatenating buffer for box parsing (length: " + oldLength + "->" + this.buffer.byteLength + ")");+ return true;+ } else return false;+ } else return false;+ }+ /*************************************************************************+ * Seek-related functions *+ *************************************************************************/+ /**+ * Finds the buffer that holds the given file position+ * @param {Boolean} fromStart indicates if the search should start from the current buffer (false)+ * or from the first buffer (true)+ * @param {Number} filePosition position in the file to seek to+ * @param {Boolean} markAsUsed indicates if the bytes in between the current position and the seek position+ * should be marked as used for garbage collection+ * @return {Number} the index of the buffer holding the seeked file position, -1 if not found.+ */+ findPosition(fromStart, filePosition, markAsUsed) {+ let index = -1;+ let i = fromStart === true ? 0 : this.bufferIndex;+ while (i < this.buffers.length) {+ const abuffer = this.buffers[i];+ if (abuffer && abuffer.fileStart <= filePosition) {+ index = i;+ if (markAsUsed) {+ if (abuffer.fileStart + abuffer.byteLength <= filePosition) abuffer.usedBytes = abuffer.byteLength;+ else abuffer.usedBytes = filePosition - abuffer.fileStart;+ this.logBufferLevel();+ }+ } else break;+ i++;+ }+ if (index === -1) return -1;+ const abuffer = this.buffers[index];+ if (abuffer.fileStart + abuffer.byteLength >= filePosition) {+ Log.debug("MultiBufferStream", "Found position in existing buffer #" + index);+ return index;+ } else return -1;+ }+ /**+ * Finds the largest file position contained in a buffer or in the next buffers if they are contiguous (no gap)+ * starting from the given buffer index or from the current buffer if the index is not given+ *+ * @param {Number} inputindex Index of the buffer to start from+ * @return {Number} The largest file position found in the buffers+ */+ findEndContiguousBuf(inputindex) {+ const index = inputindex !== void 0 ? inputindex : this.bufferIndex;+ let currentBuf = this.buffers[index];+ if (this.buffers.length > index + 1) for (let i = index + 1; i < this.buffers.length; i++) {+ const nextBuf = this.buffers[i];+ if (nextBuf.fileStart === currentBuf.fileStart + currentBuf.byteLength) currentBuf = nextBuf;+ else break;+ }+ return currentBuf.fileStart + currentBuf.byteLength;+ }+ /**+ * Returns the largest file position contained in the buffers, larger than the given position+ * @param {Number} pos the file position to start from+ * @return {Number} the largest position in the current buffer or in the buffer and the next contiguous+ * buffer that holds the given position+ */+ getEndFilePositionAfter(pos) {+ const index = this.findPosition(true, pos, false);+ if (index !== -1) return this.findEndContiguousBuf(index);+ else return pos;+ }+ /*************************************************************************+ * Garbage collection related functions *+ *************************************************************************/+ /**+ * Marks a given number of bytes as used in the current buffer for garbage collection+ * @param {Number} nbBytes+ */+ addUsedBytes(nbBytes) {+ this.buffer.usedBytes += nbBytes;+ this.logBufferLevel();+ }+ /**+ * Marks the entire current buffer as used, ready for garbage collection+ */+ setAllUsedBytes() {+ this.buffer.usedBytes = this.buffer.byteLength;+ this.logBufferLevel();+ }+ /*************************************************************************+ * Common API between MultiBufferStream and SimpleStream *+ *************************************************************************/+ /**+ * Tries to seek to a given file position+ * if possible, repositions the parsing from there and returns true+ * if not possible, does not change anything and returns false+ * @param {Number} filePosition position in the file to seek to+ * @param {Boolean} fromStart indicates if the search should start from the current buffer (false)+ * or from the first buffer (true)+ * @param {Boolean} markAsUsed indicates if the bytes in between the current position and the seek position+ * should be marked as used for garbage collection+ * @return {Boolean} true if the seek succeeded, false otherwise+ */+ seek(filePosition, fromStart, markAsUsed) {+ const index = this.findPosition(fromStart, filePosition, markAsUsed);+ if (index !== -1) {+ this.buffer = this.buffers[index];+ this.bufferIndex = index;+ this.position = filePosition - this.buffer.fileStart;+ Log.debug("MultiBufferStream", "Repositioning parser at buffer position: " + this.position);+ return true;+ } else {+ Log.debug("MultiBufferStream", "Position " + filePosition + " not found in buffered data");+ return false;+ }+ }+ /**+ * Returns the current position in the file+ * @return {Number} the position in the file+ */+ getPosition() {+ if (this.bufferIndex === -1 || this.buffers[this.bufferIndex] === void 0) return 0;+ return this.buffers[this.bufferIndex].fileStart + this.position;+ }+ /**+ * Returns the length of the current buffer+ * @return {Number} the length of the current buffer+ */+ getLength() {+ return this.byteLength;+ }+ getEndPosition() {+ if (this.bufferIndex === -1 || this.buffers[this.bufferIndex] === void 0) return 0;+ return this.buffers[this.bufferIndex].fileStart + this.byteLength;+ }+ getAbsoluteEndPosition() {+ if (this.buffers.length === 0) return 0;+ const lastBuffer = this.buffers[this.buffers.length - 1];+ return lastBuffer.fileStart + lastBuffer.byteLength;+ }+};++//#endregion+//#region src/box.ts+var Box = class {+ static {+ this.registryId = Symbol.for("BoxIdentifier");+ }+ #type;+ get type() {+ return this.constructor.fourcc ?? this.#type;+ }+ set type(value) {+ this.#type = value;+ }+ constructor(size = 0) {+ this.size = size;+ }+ addBox(box) {+ if (!this.boxes) this.boxes = [];+ this.boxes.push(box);+ if (this[box.type + "s"]) this[box.type + "s"].push(box);+ else this[box.type] = box;+ return box;+ }+ set(prop, value) {+ this[prop] = value;+ return this;+ }+ addEntry(value, _prop) {+ const prop = _prop || "entries";+ if (!this[prop]) this[prop] = [];+ this[prop].push(value);+ return this;+ }+ /** @bundle box-write.js */+ writeHeader(stream, msg) {+ this.size += 8;+ if (this.size > MAX_UINT32 || this.original_size === 1) this.size += 8;+ if (this.type === "uuid") this.size += 16;+ Log.debug("BoxWriter", "Writing box " + this.type + " of size: " + this.size + " at position " + stream.getPosition() + (msg || ""));+ if (this.original_size === 0) stream.writeUint32(0);+ else if (this.size > MAX_UINT32 || this.original_size === 1) stream.writeUint32(1);+ else {+ this.sizePosition = stream.getPosition();+ stream.writeUint32(this.size);+ }+ stream.writeString(this.type, void 0, 4);+ if (this.type === "uuid") {+ const uuidBytes = /* @__PURE__ */ new Uint8Array(16);+ for (let i = 0; i < 16; i++) uuidBytes[i] = parseInt(this.uuid.substring(i * 2, i * 2 + 2), 16);+ stream.writeUint8Array(uuidBytes);+ }+ if (this.size > MAX_UINT32 || this.original_size === 1) {+ this.sizePosition = stream.getPosition();+ stream.writeUint64(this.size);+ }+ }+ /** @bundle box-write.js */+ write(stream) {+ if (this.type === "mdat") {+ const box = this;+ if (box.stream) {+ this.size = box.stream.getAbsoluteEndPosition();+ this.writeHeader(stream);+ for (const buffer of box.stream.buffers) {+ const u8 = new Uint8Array(buffer);+ stream.writeUint8Array(u8);+ }+ } else if (box.data) {+ this.size = box.data.length;+ this.writeHeader(stream);+ stream.writeUint8Array(box.data);+ }+ } else {+ this.size = this.data ? this.data.length : 0;+ this.writeHeader(stream);+ if (this.data) stream.writeUint8Array(this.data);+ }+ }+ /** @bundle box-print.js */+ printHeader(output) {+ this.size += 8;+ if (this.size > MAX_UINT32) this.size += 8;+ if (this.type === "uuid") this.size += 16;+ output.log(output.indent + "size:" + this.size);+ output.log(output.indent + "type:" + this.type);+ }+ /** @bundle box-print.js */+ print(output) {+ this.printHeader(output);+ }+ /** @bundle box-parse.js */+ parse(stream) {+ if (this.type !== "mdat") this.data = stream.readUint8Array(this.size - this.hdr_size);+ else if (this.size === 0) stream.seek(stream.getEndPosition());+ else stream.seek(this.start + this.size);+ }+ /** @bundle box-parse.js */+ parseDataAndRewind(stream) {+ this.data = stream.readUint8Array(this.size - this.hdr_size);+ stream.seek(this.start + this.hdr_size);+ }+ /** @bundle box-parse.js */+ parseLanguage(stream) {+ this.language = stream.readUint16();+ const chars = [];+ chars[0] = this.language >> 10 & 31;+ chars[1] = this.language >> 5 & 31;+ chars[2] = this.language & 31;+ this.languageString = String.fromCharCode(chars[0] + 96, chars[1] + 96, chars[2] + 96);+ }+ /** @bundle isofile-advanced-creation.js */+ computeSize(stream_) {+ const stream = stream_ || new MultiBufferStream();+ this.write(stream);+ }+ isEndOfBox(stream) {+ return stream.getPosition() === this.start + this.size;+ }+};+var FullBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.flags = 0;+ this.version = 0;+ }+ /** @bundle box-write.js */+ writeHeader(stream) {+ this.size += 4;+ super.writeHeader(stream, " v=" + this.version + " f=" + this.flags);+ stream.writeUint8(this.version);+ stream.writeUint24(this.flags);+ }+ /** @bundle box-print.js */+ printHeader(output) {+ this.size += 4;+ super.printHeader(output);+ output.log(output.indent + "version:" + this.version);+ output.log(output.indent + "flags:" + this.flags);+ }+ /** @bundle box-parse.js */+ parseDataAndRewind(stream) {+ this.parseFullHeader(stream);+ this.data = stream.readUint8Array(this.size - this.hdr_size);+ this.hdr_size -= 4;+ stream.seek(this.start + this.hdr_size);+ }+ /** @bundle box-parse.js */+ parseFullHeader(stream) {+ this.version = stream.readUint8();+ this.flags = stream.readUint24();+ this.hdr_size += 4;+ }+ /** @bundle box-parse.js */+ parse(stream) {+ this.parseFullHeader(stream);+ this.data = stream.readUint8Array(this.size - this.hdr_size);+ }+};+var SampleGroupEntry = class {+ static {+ this.registryId = Symbol.for("SampleGroupEntryIdentifier");+ }+ constructor(grouping_type) {+ this.grouping_type = grouping_type;+ }+ /** @bundle writing/samplegroups/samplegroup.js */+ write(stream) {+ stream.writeUint8Array(this.data);+ }+ /** @bundle parsing/samplegroups/samplegroup.js */+ parse(stream) {+ Log.warn("BoxParser", `Unknown sample group type: '${this.grouping_type}'`);+ this.data = stream.readUint8Array(this.description_length);+ }+};+var TrackGroupTypeBox = class extends FullBox {+ /** @bundle parsing/TrackGroup.js */+ parse(stream) {+ this.parseFullHeader(stream);+ this.track_group_id = stream.readUint32();+ }+};+/** @bundle parsing/singleitemtypereference.js */+var SingleItemTypeReferenceBox = class extends Box {+ constructor(fourcc, size, box_name, hdr_size, start) {+ super(size);+ this.box_name = box_name;+ this.hdr_size = hdr_size;+ this.start = start;+ this.type = fourcc;+ }+ parse(stream) {+ this.from_item_ID = stream.readUint16();+ const count = stream.readUint16();+ this.references = [];+ for (let i = 0; i < count; i++) this.references[i] = { to_item_ID: stream.readUint16() };+ }+};+/** @bundle parsing/singleitemtypereferencelarge.js */+var SingleItemTypeReferenceBoxLarge = class extends Box {+ constructor(fourcc, size, box_name, hdr_size, start) {+ super(size);+ this.box_name = box_name;+ this.hdr_size = hdr_size;+ this.start = start;+ this.type = fourcc;+ }+ parse(stream) {+ this.from_item_ID = stream.readUint32();+ const count = stream.readUint16();+ this.references = [];+ for (let i = 0; i < count; i++) this.references[i] = { to_item_ID: stream.readUint32() };+ }+};+/** @bundle parsing/TrakReference.js */+var TrackReferenceTypeBox = class extends Box {+ constructor(fourcc, size, hdr_size, start) {+ super(size);+ this.hdr_size = hdr_size;+ this.start = start;+ this.type = fourcc;+ }+ parse(stream) {+ this.track_ids = stream.readUint32Array((this.size - this.hdr_size) / 4);+ }+ /** @bundle box-write.js */+ write(stream) {+ this.size = this.track_ids.length * 4;+ this.writeHeader(stream);+ stream.writeUint32Array(this.track_ids);+ }+};++//#endregion+//#region src/box-diff.ts+const DIFF_BOXES_PROP_NAMES = [+ "boxes",+ "entries",+ "references",+ "subsamples",+ "items",+ "item_infos",+ "extents",+ "associations",+ "subsegments",+ "ranges",+ "seekLists",+ "seekPoints",+ "esd",+ "levels"+];+const DIFF_PRIMITIVE_ARRAY_PROP_NAMES = [+ "compatible_brands",+ "matrix",+ "opcolor",+ "sample_counts",+ "sample_deltas",+ "first_chunk",+ "samples_per_chunk",+ "sample_sizes",+ "chunk_offsets",+ "sample_offsets",+ "sample_description_index",+ "sample_duration"+];+/** @bundle box-diff.js */+function boxEqualFields(box_a, box_b) {+ if (box_a && !box_b) return false;+ let prop;+ for (prop in box_a) if (DIFF_BOXES_PROP_NAMES.find((name) => name === prop)) continue;+ else if (box_a[prop] instanceof Box || box_b[prop] instanceof Box) continue;+ else if (typeof box_a[prop] === "undefined" || typeof box_b[prop] === "undefined") continue;+ else if (typeof box_a[prop] === "function" || typeof box_b[prop] === "function") continue;+ else if ("subBoxNames" in box_a && box_a.subBoxNames.indexOf(prop.slice(0, 4)) > -1 || "subBoxNames" in box_b && box_b.subBoxNames.indexOf(prop.slice(0, 4)) > -1) continue;+ else if (prop === "data" || prop === "start" || prop === "size" || prop === "creation_time" || prop === "modification_time") continue;+ else if (DIFF_PRIMITIVE_ARRAY_PROP_NAMES.find((name) => name === prop)) continue;+ else if (box_a[prop] !== box_b[prop]) return false;+ return true;+}+function boxEqual(box_a, box_b) {+ if (!boxEqualFields(box_a, box_b)) return false;+ for (let j = 0; j < DIFF_BOXES_PROP_NAMES.length; j++) {+ const name = DIFF_BOXES_PROP_NAMES[j];+ if (box_a[name] && box_b[name]) {+ if (!boxEqual(box_a[name], box_b[name])) return false;+ }+ }+ return true;+}++//#endregion+//#region src/registry.ts+function getRegistryId(boxClass) {+ let current = boxClass;+ while (current) {+ if ("registryId" in current) return current["registryId"];+ current = Object.getPrototypeOf(current);+ }+}+const isSampleGroupEntry = (value) => {+ const symbol = Symbol.for("SampleGroupEntryIdentifier");+ return getRegistryId(value) === symbol;+};+const isSampleEntry = (value) => {+ const symbol = Symbol.for("SampleEntryIdentifier");+ return getRegistryId(value) === symbol;+};+const isBox = (value) => {+ const symbol = Symbol.for("BoxIdentifier");+ return getRegistryId(value) === symbol;+};+const BoxRegistry = {+ uuid: {},+ sampleEntry: {},+ sampleGroupEntry: {},+ box: {}+};+function registerBoxes(registry) {+ const localRegistry = {+ uuid: {},+ sampleEntry: {},+ sampleGroupEntry: {},+ box: {}+ };+ for (const [key, value] of Object.entries(registry)) {+ if (isSampleGroupEntry(value)) {+ const groupingType = "grouping_type" in value ? value.grouping_type : void 0;+ if (!groupingType) throw new Error(`SampleGroupEntry class ${key} does not have a valid static grouping_type. Please ensure it is defined correctly.`);+ if (groupingType in localRegistry.sampleGroupEntry) throw new Error(`SampleGroupEntry class ${key} has a grouping_type that is already registered. Please ensure it is unique.`);+ localRegistry.sampleGroupEntry[groupingType] = value;+ continue;+ }+ if (isSampleEntry(value)) {+ const fourcc = "fourcc" in value ? value.fourcc : void 0;+ if (!fourcc) throw new Error(`SampleEntry class ${key} does not have a valid static fourcc. Please ensure it is defined correctly.`);+ if (fourcc in localRegistry.sampleEntry) throw new Error(`SampleEntry class ${key} has a fourcc that is already registered. Please ensure it is unique.`);+ localRegistry.sampleEntry[fourcc] = value;+ continue;+ }+ if (isBox(value)) {+ const fourcc = "fourcc" in value ? value.fourcc : void 0;+ const uuid = "uuid" in value ? value.uuid : void 0;+ if (fourcc === "uuid") {+ if (!uuid) throw new Error(`Box class ${key} has a fourcc of 'uuid' but does not have a valid uuid. Please ensure it is defined correctly.`);+ if (uuid in localRegistry.uuid) throw new Error(`Box class ${key} has a uuid that is already registered. Please ensure it is unique.`);+ localRegistry.uuid[uuid] = value;+ continue;+ }+ localRegistry.box[fourcc] = value;+ continue;+ }+ throw new Error(`Box class ${key} does not have a valid static fourcc, uuid, or grouping_type. Please ensure it is defined correctly.`);+ }+ BoxRegistry.uuid = { ...localRegistry.uuid };+ BoxRegistry.sampleEntry = { ...localRegistry.sampleEntry };+ BoxRegistry.sampleGroupEntry = { ...localRegistry.sampleGroupEntry };+ BoxRegistry.box = { ...localRegistry.box };+ return BoxRegistry;+}+const DescriptorRegistry = {};+function registerDescriptors(registry) {+ Object.entries(registry).forEach(([key, value]) => DescriptorRegistry[key] = value);+ return DescriptorRegistry;+}++//#endregion+//#region src/parser.ts+function parseUUID(stream) {+ return parseHex16(stream);+}+function parseHex16(stream) {+ let hex16 = "";+ for (let i = 0; i < 16; i++) {+ const hex = stream.readUint8().toString(16);+ hex16 += hex.length === 1 ? "0" + hex : hex;+ }+ return hex16;+}+function parseOneBox(stream, headerOnly, parentSize) {+ let box;+ let originalSize;+ const start = stream.getPosition();+ let hdr_size = 0;+ let uuid;+ if (stream.getEndPosition() - start < 8) {+ Log.debug("BoxParser", "Not enough data in stream to parse the type and size of the box");+ return { code: 0 };+ }+ if (parentSize && parentSize < 8) {+ Log.debug("BoxParser", "Not enough bytes left in the parent box to parse a new box");+ return { code: 0 };+ }+ let size = stream.readUint32();+ const type = stream.readString(4);+ if (type.length !== 4 || !/^[\x20-\x7E]{4}$/.test(type)) {+ Log.error("BoxParser", `Invalid box type: '${type}'`);+ return {+ code: -1,+ start,+ type+ };+ }+ let box_type = type;+ Log.debug("BoxParser", "Found box of type '" + type + "' and size " + size + " at position " + start);+ hdr_size = 8;+ if (type === "uuid") {+ if (stream.getEndPosition() - stream.getPosition() < 16 || parentSize - hdr_size < 16) {+ stream.seek(start);+ Log.debug("BoxParser", "Not enough bytes left in the parent box to parse a UUID box");+ return { code: 0 };+ }+ uuid = parseUUID(stream);+ hdr_size += 16;+ box_type = uuid;+ }+ if (size === 1) {+ if (stream.getEndPosition() - stream.getPosition() < 8 || parentSize && parentSize - hdr_size < 8) {+ stream.seek(start);+ Log.warn("BoxParser", "Not enough data in stream to parse the extended size of the \"" + type + "\" box");+ return { code: 0 };+ }+ originalSize = size;+ size = stream.readUint64();+ hdr_size += 8;+ } else if (size === 0) if (parentSize) size = parentSize;+ else if (type !== "mdat") {+ Log.error("BoxParser", "Unlimited box size not supported for type: '" + type + "'");+ box = new Box(size);+ box.type = type;+ return {+ code: 1,+ box,+ size: box.size+ };+ } else size = stream.getEndPosition() - start;+ if (size !== 0 && size < hdr_size) {+ Log.error("BoxParser", "Box of type " + type + " has an invalid size " + size + " (too small to be a box)");+ return {+ code: 0,+ type,+ size,+ hdr_size,+ start+ };+ }+ if (size !== 0 && parentSize && size > parentSize) {+ Log.error("BoxParser", "Box of type '" + type + "' has a size " + size + " greater than its container size " + parentSize);+ return {+ code: 0,+ type,+ size,+ hdr_size,+ start+ };+ }+ if (size !== 0 && start + size > stream.getEndPosition()) {+ stream.seek(start);+ Log.info("BoxParser", "Not enough data in stream to parse the entire '" + type + "' box");+ return {+ code: 0,+ type,+ size,+ hdr_size,+ start,+ original_size: originalSize+ };+ }+ if (headerOnly) return {+ code: 1,+ type,+ size,+ hdr_size,+ start+ };+ else if (type in BoxRegistry.box) box = new BoxRegistry.box[type](size);+ else if (type !== "uuid") {+ Log.warn("BoxParser", `Unknown box type: '${type}'`);+ box = new Box(size);+ box.type = type;+ box.has_unparsed_data = true;+ } else if (uuid in BoxRegistry.uuid) box = new BoxRegistry.uuid[uuid](size);+ else {+ Log.warn("BoxParser", `Unknown UUID box type: '${uuid}'`);+ box = new Box(size);+ box.type = type;+ box.uuid = uuid;+ box.has_unparsed_data = true;+ }+ box.original_size = originalSize;+ box.hdr_size = hdr_size;+ box.start = start;+ if (box.write === Box.prototype.write && box.type !== "mdat") {+ Log.info("BoxParser", "'" + box_type + "' box writing not yet implemented, keeping unparsed data in memory for later write");+ box.parseDataAndRewind(stream);+ }+ box.parse(stream);+ const diff = stream.getPosition() - (box.start + box.size);+ if (diff < 0) {+ Log.warn("BoxParser", "Parsing of box '" + box_type + "' did not read the entire indicated box data size (missing " + -diff + " bytes), seeking forward");+ stream.seek(box.start + box.size);+ } else if (diff > 0 && box.size !== 0) {+ Log.error("BoxParser", "Parsing of box '" + box_type + "' read " + diff + " more bytes than the indicated box data size, seeking backwards");+ stream.seek(box.start + box.size);+ }+ return {+ code: 1,+ box,+ size: box.size+ };+}++//#endregion+//#region src/containerBox.ts+var ContainerBox = class extends Box {+ /** @bundle box-write.js */+ write(stream) {+ this.size = 0;+ this.writeHeader(stream);+ if (this.boxes) {+ for (let i = 0; i < this.boxes.length; i++) if (this.boxes[i]) {+ this.boxes[i].write(stream);+ this.size += this.boxes[i].size;+ }+ }+ Log.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size);+ stream.adjustUint32(this.sizePosition, this.size);+ }+ /** @bundle box-print.js */+ print(output) {+ this.printHeader(output);+ for (let i = 0; i < this.boxes.length; i++) if (this.boxes[i]) {+ const prev_indent = output.indent;+ output.indent += " ";+ this.boxes[i].print(output);+ output.indent = prev_indent;+ }+ }+ /** @bundle box-parse.js */+ parse(stream) {+ let ret;+ while (stream.getPosition() < this.start + this.size) {+ ret = parseOneBox(stream, false, this.size - (stream.getPosition() - this.start));+ if (ret.code === 1) {+ const box = ret.box;+ if (!this.boxes) this.boxes = [];+ this.boxes.push(box);+ if (this.subBoxNames && this.subBoxNames.indexOf(box.type) !== -1) {+ const fourcc = this.subBoxNames[this.subBoxNames.indexOf(box.type)] + "s";+ if (!this[fourcc]) this[fourcc] = [];+ this[fourcc].push(box);+ } else {+ const box_type = box.type !== "uuid" ? box.type : box.uuid;+ if (this[box_type]) Log.warn("ContainerBox", `Box of type ${box_type} already exists in container box ${this.type}.`);+ else this[box_type] = box;+ }+ } else return;+ }+ }+};++//#endregion+//#region src/boxes/sampleentries/base.ts+var SampleEntry = class extends ContainerBox {+ static {+ this.registryId = Symbol.for("SampleEntryIdentifier");+ }+ constructor(size, hdr_size, start) {+ super(size);+ this.hdr_size = hdr_size;+ this.start = start;+ }+ /** @bundle box-codecs.js */+ isVideo() {+ return false;+ }+ /** @bundle box-codecs.js */+ isAudio() {+ return false;+ }+ /** @bundle box-codecs.js */+ isSubtitle() {+ return false;+ }+ /** @bundle box-codecs.js */+ isMetadata() {+ return false;+ }+ /** @bundle box-codecs.js */+ isHint() {+ return false;+ }+ /** @bundle box-codecs.js */+ getCodec() {+ return this.type.replace(".", "");+ }+ /** @bundle box-codecs.js */+ getWidth() {+ return "";+ }+ /** @bundle box-codecs.js */+ getHeight() {+ return "";+ }+ /** @bundle box-codecs.js */+ getChannelCount() {+ return "";+ }+ /** @bundle box-codecs.js */+ getSampleRate() {+ return "";+ }+ /** @bundle box-codecs.js */+ getSampleSize() {+ return "";+ }+ /** @bundle parsing/sampleentries/sampleentry.js */+ parseHeader(stream) {+ stream.readUint8Array(6);+ this.data_reference_index = stream.readUint16();+ this.hdr_size += 8;+ }+ /** @bundle parsing/sampleentries/sampleentry.js */+ parse(stream) {+ this.parseHeader(stream);+ this.data = stream.readUint8Array(this.size - this.hdr_size);+ }+ /** @bundle parsing/sampleentries/sampleentry.js */+ parseDataAndRewind(stream) {+ this.parseHeader(stream);+ this.data = stream.readUint8Array(this.size - this.hdr_size);+ this.hdr_size -= 8;+ stream.seek(this.start + this.hdr_size);+ }+ /** @bundle parsing/sampleentries/sampleentry.js */+ parseFooter(stream) {+ super.parse(stream);+ }+ /** @bundle writing/sampleentry.js */+ writeHeader(stream) {+ this.size = 8;+ super.writeHeader(stream);+ stream.writeUint8(0);+ stream.writeUint8(0);+ stream.writeUint8(0);+ stream.writeUint8(0);+ stream.writeUint8(0);+ stream.writeUint8(0);+ stream.writeUint16(this.data_reference_index);+ }+ /** @bundle writing/sampleentry.js */+ writeFooter(stream) {+ if (this.boxes) for (let i = 0; i < this.boxes.length; i++) {+ this.boxes[i].write(stream);+ this.size += this.boxes[i].size;+ }+ Log.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size);+ stream.adjustUint32(this.sizePosition, this.size);+ }+ /** @bundle writing/sampleentry.js */+ write(stream) {+ this.writeHeader(stream);+ stream.writeUint8Array(this.data);+ this.size += this.data.length;+ Log.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size);+ stream.adjustUint32(this.sizePosition, this.size);+ }+};+var HintSampleEntry = class extends SampleEntry {};+var MetadataSampleEntry = class extends SampleEntry {+ /** @bundle box-codecs.js */+ isMetadata() {+ return true;+ }+};+var SubtitleSampleEntry = class extends SampleEntry {+ /** @bundle box-codecs.js */+ isSubtitle() {+ return true;+ }+};+var TextSampleEntry = class extends SampleEntry {};+var VisualSampleEntry = class extends SampleEntry {+ parse(stream) {+ this.parseHeader(stream);+ stream.readUint16();+ stream.readUint16();+ stream.readUint32Array(3);+ this.width = stream.readUint16();+ this.height = stream.readUint16();+ this.horizresolution = stream.readUint32();+ this.vertresolution = stream.readUint32();+ stream.readUint32();+ this.frame_count = stream.readUint16();+ const compressorname_length = Math.min(31, stream.readUint8());+ this.compressorname = stream.readString(compressorname_length);+ if (compressorname_length < 31) stream.readString(31 - compressorname_length);+ this.depth = stream.readUint16();+ stream.readUint16();+ this.parseFooter(stream);+ }+ /** @bundle box-codecs.js */+ isVideo() {+ return true;+ }+ /** @bundle box-codecs.js */+ getWidth() {+ return this.width;+ }+ /** @bundle box-codecs.js */+ getHeight() {+ return this.height;+ }+ /** @bundle writing/sampleentries/sampleentry.js */+ write(stream) {+ this.writeHeader(stream);+ this.size += 70;+ stream.writeUint16(0);+ stream.writeUint16(0);+ stream.writeUint32(0);+ stream.writeUint32(0);+ stream.writeUint32(0);+ stream.writeUint16(this.width);+ stream.writeUint16(this.height);+ stream.writeUint32(this.horizresolution);+ stream.writeUint32(this.vertresolution);+ stream.writeUint32(0);+ stream.writeUint16(this.frame_count);+ stream.writeUint8(Math.min(31, this.compressorname.length));+ stream.writeString(this.compressorname, void 0, 31);+ stream.writeUint16(this.depth);+ stream.writeInt16(-1);+ this.writeFooter(stream);+ }+};+var AudioSampleEntry = class extends SampleEntry {+ parse(stream) {+ this.parseHeader(stream);+ this.version = stream.readUint16();+ stream.readUint16();+ stream.readUint32();+ this.channel_count = stream.readUint16();+ this.samplesize = stream.readUint16();+ stream.readUint16();+ stream.readUint16();+ this.samplerate = stream.readUint32() / 65536;+ if (stream.isofile?.ftyp?.major_brand.includes("qt")) {+ if (this.version === 1) this.extensions = stream.readUint8Array(16);+ else if (this.version === 2) this.extensions = stream.readUint8Array(36);+ }+ this.parseFooter(stream);+ }+ /** @bundle box-codecs.js */+ isAudio() {+ return true;+ }+ /** @bundle box-codecs.js */+ getChannelCount() {+ return this.channel_count;+ }+ /** @bundle box-codecs.js */+ getSampleRate() {+ return this.samplerate;+ }+ /** @bundle box-codecs.js */+ getSampleSize() {+ return this.samplesize;+ }+ /** @bundle writing/sampleentry.js */+ write(stream) {+ this.writeHeader(stream);+ this.size += 20;+ stream.writeUint32(0);+ stream.writeUint32(0);+ stream.writeUint16(this.channel_count);+ stream.writeUint16(this.samplesize);+ stream.writeUint16(0);+ stream.writeUint16(0);+ stream.writeUint32(this.samplerate << 16);+ this.writeFooter(stream);+ }+};+var SystemSampleEntry = class extends SampleEntry {+ parse(stream) {+ this.parseHeader(stream);+ this.parseFooter(stream);+ }+ /** @bundle writing/sampleentry.js */+ write(stream) {+ this.writeHeader(stream);+ this.writeFooter(stream);+ }+};++//#endregion+//#region src/boxes/displays/parameterSetArray.ts+var ParameterSetArray = class extends Array {+ toString() {+ let str = "<table class='inner-table'>";+ str += "<thead><tr><th>length</th><th>nalu_data</th></tr></thead>";+ str += "<tbody>";+ for (let i = 0; i < this.length; i++) {+ const nalu = this[i];+ str += "<tr>";+ str += "<td>" + nalu.length + "</td>";+ str += "<td>";+ str += nalu.data.reduce(function(str, byte) {+ return str + byte.toString(16).padStart(2, "0");+ }, "0x");+ str += "</td></tr>";+ }+ str += "</tbody></table>";+ return str;+ }+};++//#endregion+//#region src/boxes/avcC.ts+var avcCBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "AVCConfigurationBox";+ }+ static {+ this.fourcc = "avcC";+ }+ parse(stream) {+ this.configurationVersion = stream.readUint8();+ this.AVCProfileIndication = stream.readUint8();+ this.profile_compatibility = stream.readUint8();+ this.AVCLevelIndication = stream.readUint8();+ this.lengthSizeMinusOne = stream.readUint8() & 3;+ this.nb_SPS_nalus = stream.readUint8() & 31;+ let toparse = this.size - this.hdr_size - 6;+ this.SPS = new ParameterSetArray();+ for (let i = 0; i < this.nb_SPS_nalus; i++) {+ const length = stream.readUint16();+ this.SPS.push({+ length,+ data: stream.readUint8Array(length)+ });+ toparse -= 2 + length;+ }+ this.nb_PPS_nalus = stream.readUint8();+ toparse--;+ this.PPS = new ParameterSetArray();+ for (let i = 0; i < this.nb_PPS_nalus; i++) {+ const length = stream.readUint16();+ this.PPS.push({+ length,+ data: stream.readUint8Array(length)+ });+ toparse -= 2 + length;+ }+ if (toparse > 0) this.ext = stream.readUint8Array(toparse);+ }+ /** @bundle writing/avcC.js */+ write(stream) {+ this.size = 7;+ for (let i = 0; i < this.SPS.length; i++) this.size += 2 + this.SPS[i].length;+ for (let i = 0; i < this.PPS.length; i++) this.size += 2 + this.PPS[i].length;+ if (this.ext) this.size += this.ext.length;+ this.writeHeader(stream);+ stream.writeUint8(this.configurationVersion);+ stream.writeUint8(this.AVCProfileIndication);+ stream.writeUint8(this.profile_compatibility);+ stream.writeUint8(this.AVCLevelIndication);+ stream.writeUint8(this.lengthSizeMinusOne + 252);+ stream.writeUint8(this.SPS.length + 224);+ for (let i = 0; i < this.SPS.length; i++) {+ stream.writeUint16(this.SPS[i].length);+ stream.writeUint8Array(this.SPS[i].data);+ }+ stream.writeUint8(this.PPS.length);+ for (let i = 0; i < this.PPS.length; i++) {+ stream.writeUint16(this.PPS[i].length);+ stream.writeUint8Array(this.PPS[i].data);+ }+ if (this.ext) stream.writeUint8Array(this.ext);+ }+};++//#endregion+//#region src/boxes/defaults.ts+var mdatBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "MediaDataBox";+ }+ static {+ this.fourcc = "mdat";+ }+};+var idatBox = class extends Box {+ constructor(..._args2) {+ super(..._args2);+ this.box_name = "ItemDataBox";+ }+ static {+ this.fourcc = "idat";+ }+};+var freeBox = class extends Box {+ constructor(..._args3) {+ super(..._args3);+ this.box_name = "FreeSpaceBox";+ }+ static {+ this.fourcc = "free";+ }+};+var skipBox = class extends Box {+ constructor(..._args4) {+ super(..._args4);+ this.box_name = "FreeSpaceBox";+ }+ static {+ this.fourcc = "skip";+ }+};+var hmhdBox = class extends FullBox {+ constructor(..._args5) {+ super(..._args5);+ this.box_name = "HintMediaHeaderBox";+ }+ static {+ this.fourcc = "hmhd";+ }+};+var nmhdBox = class extends FullBox {+ constructor(..._args6) {+ super(..._args6);+ this.box_name = "NullMediaHeaderBox";+ }+ static {+ this.fourcc = "nmhd";+ }+};+var iodsBox = class extends FullBox {+ constructor(..._args7) {+ super(..._args7);+ this.box_name = "ObjectDescriptorBox";+ }+ static {+ this.fourcc = "iods";+ }+};+var xmlBox = class extends FullBox {+ constructor(..._args8) {+ super(..._args8);+ this.box_name = "XMLBox";+ }+ static {+ this.fourcc = "xml ";+ }+};+var bxmlBox = class extends FullBox {+ constructor(..._args9) {+ super(..._args9);+ this.box_name = "BinaryXMLBox";+ }+ static {+ this.fourcc = "bxml";+ }+};+var iproBox = class extends FullBox {+ constructor(..._args10) {+ super(..._args10);+ this.box_name = "ItemProtectionBox";+ this.sinfs = [];+ }+ static {+ this.fourcc = "ipro";+ }+ get protections() {+ return this.sinfs;+ }+};+var moovBox = class extends ContainerBox {+ constructor(..._args11) {+ super(..._args11);+ this.box_name = "MovieBox";+ this.traks = [];+ this.psshs = [];+ this.subBoxNames = ["trak", "pssh"];+ }+ static {+ this.fourcc = "moov";+ }+};+var trakBox = class extends ContainerBox {+ constructor(..._args12) {+ super(..._args12);+ this.box_name = "TrackBox";+ this.samples = [];+ }+ static {+ this.fourcc = "trak";+ }+};+var edtsBox = class extends ContainerBox {+ constructor(..._args13) {+ super(..._args13);+ this.box_name = "EditBox";+ }+ static {+ this.fourcc = "edts";+ }+};+var mdiaBox = class extends ContainerBox {+ constructor(..._args14) {+ super(..._args14);+ this.box_name = "MediaBox";+ }+ static {+ this.fourcc = "mdia";+ }+};+var minfBox = class extends ContainerBox {+ constructor(..._args15) {+ super(..._args15);+ this.box_name = "MediaInformationBox";+ }+ static {+ this.fourcc = "minf";+ }+};+var dinfBox = class extends ContainerBox {+ constructor(..._args16) {+ super(..._args16);+ this.box_name = "DataInformationBox";+ }+ static {+ this.fourcc = "dinf";+ }+};+var stblBox = class extends ContainerBox {+ constructor(..._args17) {+ super(..._args17);+ this.box_name = "SampleTableBox";+ this.sgpds = [];+ this.sbgps = [];+ this.subBoxNames = ["sgpd", "sbgp"];+ }+ static {+ this.fourcc = "stbl";+ }+};+var mvexBox = class extends ContainerBox {+ constructor(..._args18) {+ super(..._args18);+ this.box_name = "MovieExtendsBox";+ this.trexs = [];+ this.subBoxNames = ["trex"];+ }+ static {+ this.fourcc = "mvex";+ }+};+var moofBox = class extends ContainerBox {+ constructor(..._args19) {+ super(..._args19);+ this.box_name = "MovieFragmentBox";+ this.trafs = [];+ this.subBoxNames = ["traf"];+ }+ static {+ this.fourcc = "moof";+ }+};+var trafBox = class extends ContainerBox {+ constructor(..._args20) {+ super(..._args20);+ this.box_name = "TrackFragmentBox";+ this.truns = [];+ this.sgpds = [];+ this.sbgps = [];+ this.subBoxNames = [+ "trun",+ "sgpd",+ "sbgp"+ ];+ }+ static {+ this.fourcc = "traf";+ }+};+var vttcBox = class extends ContainerBox {+ constructor(..._args21) {+ super(..._args21);+ this.box_name = "VTTCueBox";+ }+ static {+ this.fourcc = "vttc";+ }+};+var mfraBox = class extends ContainerBox {+ constructor(..._args22) {+ super(..._args22);+ this.box_name = "MovieFragmentRandomAccessBox";+ this.tfras = [];+ this.subBoxNames = ["tfra"];+ }+ static {+ this.fourcc = "mfra";+ }+};+var mecoBox = class extends ContainerBox {+ constructor(..._args23) {+ super(..._args23);+ this.box_name = "AdditionalMetadataContainerBox";+ }+ static {+ this.fourcc = "meco";+ }+};+var hntiBox = class extends ContainerBox {+ constructor(..._args24) {+ super(..._args24);+ this.box_name = "trackhintinformation";+ this.subBoxNames = ["sdp ", "rtp "];+ }+ static {+ this.fourcc = "hnti";+ }+};+var hinfBox = class extends ContainerBox {+ constructor(..._args25) {+ super(..._args25);+ this.box_name = "hintstatisticsbox";+ this.maxrs = [];+ this.subBoxNames = ["maxr"];+ }+ static {+ this.fourcc = "hinf";+ }+};+var strkBox = class extends ContainerBox {+ constructor(..._args26) {+ super(..._args26);+ this.box_name = "SubTrackBox";+ }+ static {+ this.fourcc = "strk";+ }+};+var strdBox = class extends ContainerBox {+ constructor(..._args27) {+ super(..._args27);+ this.box_name = "SubTrackDefinitionBox";+ }+ static {+ this.fourcc = "strd";+ }+};+var sinfBox = class extends ContainerBox {+ constructor(..._args28) {+ super(..._args28);+ this.box_name = "ProtectionSchemeInfoBox";+ }+ static {+ this.fourcc = "sinf";+ }+};+var rinfBox = class extends ContainerBox {+ constructor(..._args29) {+ super(..._args29);+ this.box_name = "RestrictedSchemeInfoBox";+ }+ static {+ this.fourcc = "rinf";+ }+};+var schiBox = class extends ContainerBox {+ constructor(..._args30) {+ super(..._args30);+ this.box_name = "SchemeInformationBox";+ }+ static {+ this.fourcc = "schi";+ }+};+var trgrBox = class extends ContainerBox {+ constructor(..._args31) {+ super(..._args31);+ this.box_name = "TrackGroupBox";+ }+ static {+ this.fourcc = "trgr";+ }+};+var udtaBox = class extends ContainerBox {+ constructor(..._args32) {+ super(..._args32);+ this.box_name = "UserDataBox";+ this.kinds = [];+ this.strks = [];+ this.subBoxNames = ["kind", "strk"];+ }+ static {+ this.fourcc = "udta";+ }+};+var iprpBox = class extends ContainerBox {+ constructor(..._args33) {+ super(..._args33);+ this.box_name = "ItemPropertiesBox";+ this.ipmas = [];+ this.subBoxNames = ["ipma"];+ }+ static {+ this.fourcc = "iprp";+ }+};+var ipcoBox = class extends ContainerBox {+ constructor(..._args34) {+ super(..._args34);+ this.box_name = "ItemPropertyContainerBox";+ this.hvcCs = [];+ this.ispes = [];+ this.claps = [];+ this.irots = [];+ this.subBoxNames = [+ "hvcC",+ "ispe",+ "clap",+ "irot"+ ];+ }+ static {+ this.fourcc = "ipco";+ }+};+var grplBox = class extends ContainerBox {+ constructor(..._args35) {+ super(..._args35);+ this.box_name = "GroupsListBox";+ }+ static {+ this.fourcc = "grpl";+ }+};+var j2kHBox = class extends ContainerBox {+ constructor(..._args36) {+ super(..._args36);+ this.box_name = "J2KHeaderInfoBox";+ }+ static {+ this.fourcc = "j2kH";+ }+};+var etypBox = class extends ContainerBox {+ constructor(..._args37) {+ super(..._args37);+ this.box_name = "ExtendedTypeBox";+ this.tycos = [];+ this.subBoxNames = ["tyco"];+ }+ static {+ this.fourcc = "etyp";+ }+};+var povdBox = class extends ContainerBox {+ constructor(..._args38) {+ super(..._args38);+ this.box_name = "ProjectedOmniVideoBox";+ this.subBoxNames = ["prfr"];+ }+ static {+ this.fourcc = "povd";+ }+};++//#endregion+//#region src/boxes/dref.ts+var drefBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "DataReferenceBox";+ }+ static {+ this.fourcc = "dref";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.entries = [];+ const entry_count = stream.readUint32();+ for (let i = 0; i < entry_count; i++) {+ const ret = parseOneBox(stream, false, this.size - (stream.getPosition() - this.start));+ if (ret.code === 1) {+ const box = ret.box;+ this.entries.push(box);+ } else return;+ }+ }+ /** @bundle writing/dref.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 4;+ this.writeHeader(stream);+ stream.writeUint32(this.entries.length);+ for (let i = 0; i < this.entries.length; i++) {+ this.entries[i].write(stream);+ this.size += this.entries[i].size;+ }+ Log.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size);+ stream.adjustUint32(this.sizePosition, this.size);+ }+};++//#endregion+//#region src/boxes/elng.ts+var elngBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ExtendedLanguageBox";+ }+ static {+ this.fourcc = "elng";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.extended_language = stream.readString(this.size - this.hdr_size);+ }+ /** @bundle writing/elng.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = this.extended_language.length;+ this.writeHeader(stream);+ stream.writeString(this.extended_language);+ }+};++//#endregion+//#region src/boxes/ftyp.ts+var ftypBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "FileTypeBox";+ }+ static {+ this.fourcc = "ftyp";+ }+ parse(stream) {+ let toparse = this.size - this.hdr_size;+ this.major_brand = stream.readString(4);+ this.minor_version = stream.readUint32();+ const minor_version_str = String.fromCharCode(this.minor_version >> 24, this.minor_version >> 16 & 255, this.minor_version >> 8 & 255, this.minor_version & 255);+ if (minor_version_str.match("[a-zA-Z0-9]{4}")) this.minor_version = minor_version_str;+ toparse -= 8;+ this.compatible_brands = [];+ let i = 0;+ while (toparse >= 4) {+ this.compatible_brands[i] = stream.readString(4);+ toparse -= 4;+ i++;+ }+ }+ /** @bundle writing/ftyp.js */+ write(stream) {+ this.size = 8 + 4 * this.compatible_brands.length;+ this.writeHeader(stream);+ stream.writeString(this.major_brand, void 0, 4);+ if (typeof this.minor_version === "number") stream.writeUint32(this.minor_version);+ else stream.writeString(this.minor_version, void 0, 4);+ for (let i = 0; i < this.compatible_brands.length; i++) stream.writeString(this.compatible_brands[i], void 0, 4);+ }+};++//#endregion+//#region src/boxes/hdlr.ts+var hdlrBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "HandlerBox";+ }+ static {+ this.fourcc = "hdlr";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 0) {+ stream.readUint32();+ this.handler = stream.readString(4);+ stream.readUint32Array(3);+ if (!this.isEndOfBox(stream)) {+ const name_size = this.start + this.size - stream.getPosition();+ this.name = stream.readCString();+ const end = this.start + this.size - 1;+ stream.seek(end);+ if (stream.readUint8() !== 0 && name_size > 1) {+ Log.info("BoxParser", "Warning: hdlr name is not null-terminated, possibly length-prefixed string. Trimming first byte.");+ this.name = this.name.slice(1);+ }+ }+ }+ }+ /** @bundle writing/hldr.js */+ write(stream) {+ this.size = 20 + this.name.length + 1;+ this.version = 0;+ this.flags = 0;+ this.writeHeader(stream);+ stream.writeUint32(0);+ stream.writeString(this.handler, void 0, 4);+ stream.writeUint32Array([+ 0,+ 0,+ 0+ ]);+ stream.writeCString(this.name);+ }+};++//#endregion+//#region src/boxes/hvcC.ts+var hvcCBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "HEVCConfigurationBox";+ }+ static {+ this.fourcc = "hvcC";+ }+ parse(stream) {+ this.configurationVersion = stream.readUint8();+ let tmp_byte = stream.readUint8();+ this.general_profile_space = tmp_byte >> 6;+ this.general_tier_flag = (tmp_byte & 32) >> 5;+ this.general_profile_idc = tmp_byte & 31;+ this.general_profile_compatibility = stream.readUint32();+ this.general_constraint_indicator = stream.readUint8Array(6);+ this.general_level_idc = stream.readUint8();+ this.min_spatial_segmentation_idc = stream.readUint16() & 4095;+ this.parallelismType = stream.readUint8() & 3;+ this.chroma_format_idc = stream.readUint8() & 3;+ this.bit_depth_luma_minus8 = stream.readUint8() & 7;+ this.bit_depth_chroma_minus8 = stream.readUint8() & 7;+ this.avgFrameRate = stream.readUint16();+ tmp_byte = stream.readUint8();+ this.constantFrameRate = tmp_byte >> 6;+ this.numTemporalLayers = (tmp_byte & 13) >> 3;+ this.temporalIdNested = (tmp_byte & 4) >> 2;+ this.lengthSizeMinusOne = tmp_byte & 3;+ this.nalu_arrays = [];+ const numOfArrays = stream.readUint8();+ for (let i = 0; i < numOfArrays; i++) {+ const nalu_array = [];+ this.nalu_arrays.push(nalu_array);+ tmp_byte = stream.readUint8();+ nalu_array.completeness = (tmp_byte & 128) >> 7;+ nalu_array.nalu_type = tmp_byte & 63;+ const numNalus = stream.readUint16();+ for (let j = 0; j < numNalus; j++) {+ const length = stream.readUint16();+ nalu_array.push({ data: stream.readUint8Array(length) });+ }+ }+ }+ /** @bundle writing/write.js */+ write(stream) {+ this.size = 23;+ for (let i = 0; i < this.nalu_arrays.length; i++) {+ this.size += 3;+ for (let j = 0; j < this.nalu_arrays[i].length; j++) this.size += 2 + this.nalu_arrays[i][j].data.length;+ }+ this.writeHeader(stream);+ stream.writeUint8(this.configurationVersion);+ stream.writeUint8((this.general_profile_space << 6) + (this.general_tier_flag << 5) + this.general_profile_idc);+ stream.writeUint32(this.general_profile_compatibility);+ stream.writeUint8Array(this.general_constraint_indicator);+ stream.writeUint8(this.general_level_idc);+ stream.writeUint16(this.min_spatial_segmentation_idc + (15 << 24));+ stream.writeUint8(this.parallelismType + 252);+ stream.writeUint8(this.chroma_format_idc + 252);+ stream.writeUint8(this.bit_depth_luma_minus8 + 248);+ stream.writeUint8(this.bit_depth_chroma_minus8 + 248);+ stream.writeUint16(this.avgFrameRate);+ stream.writeUint8((this.constantFrameRate << 6) + (this.numTemporalLayers << 3) + (this.temporalIdNested << 2) + this.lengthSizeMinusOne);+ stream.writeUint8(this.nalu_arrays.length);+ for (let i = 0; i < this.nalu_arrays.length; i++) {+ stream.writeUint8((this.nalu_arrays[i].completeness << 7) + this.nalu_arrays[i].nalu_type);+ stream.writeUint16(this.nalu_arrays[i].length);+ for (let j = 0; j < this.nalu_arrays[i].length; j++) {+ stream.writeUint16(this.nalu_arrays[i][j].data.length);+ stream.writeUint8Array(this.nalu_arrays[i][j].data);+ }+ }+ }+};++//#endregion+//#region src/boxes/mdhd.ts+var mdhdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "MediaHeaderBox";+ }+ static {+ this.fourcc = "mdhd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 1) {+ this.creation_time = stream.readUint64();+ this.modification_time = stream.readUint64();+ this.timescale = stream.readUint32();+ this.duration = stream.readUint64();+ } else {+ this.creation_time = stream.readUint32();+ this.modification_time = stream.readUint32();+ this.timescale = stream.readUint32();+ this.duration = stream.readUint32();+ }+ this.parseLanguage(stream);+ stream.readUint16();+ }+ /** @bundle writing/mdhd.js */+ write(stream) {+ const useVersion1 = this.modification_time > MAX_UINT32 || this.creation_time > MAX_UINT32 || this.duration > MAX_UINT32 || this.version === 1;+ this.version = useVersion1 ? 1 : 0;+ this.size = 20;+ this.size += useVersion1 ? 12 : 0;+ this.flags = 0;+ this.writeHeader(stream);+ if (useVersion1) {+ stream.writeUint64(this.creation_time);+ stream.writeUint64(this.modification_time);+ stream.writeUint32(this.timescale);+ stream.writeUint64(this.duration);+ } else {+ stream.writeUint32(this.creation_time);+ stream.writeUint32(this.modification_time);+ stream.writeUint32(this.timescale);+ stream.writeUint32(this.duration);+ }+ stream.writeUint16(this.language);+ stream.writeUint16(0);+ }+};++//#endregion+//#region src/boxes/mehd.ts+var mehdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "MovieExtendsHeaderBox";+ }+ static {+ this.fourcc = "mehd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.flags & 1) {+ Log.warn("BoxParser", "mehd box incorrectly uses flags set to 1, converting version to 1");+ this.version = 1;+ }+ if (this.version === 1) this.fragment_duration = stream.readUint64();+ else this.fragment_duration = stream.readUint32();+ }+ /** @bundle writing/mehd.js */+ write(stream) {+ const useVersion1 = this.fragment_duration > MAX_UINT32 || this.version === 1;+ this.version = useVersion1 ? 1 : 0;+ this.size = 4;+ this.size += useVersion1 ? 4 : 0;+ this.flags = 0;+ this.writeHeader(stream);+ if (useVersion1) stream.writeUint64(this.fragment_duration);+ else stream.writeUint32(this.fragment_duration);+ }+};++//#endregion+//#region src/boxes/infe.ts+var infeBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ItemInfoEntry";+ }+ static {+ this.fourcc = "infe";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 0 || this.version === 1) {+ this.item_ID = stream.readUint16();+ this.item_protection_index = stream.readUint16();+ this.item_name = stream.readCString();+ this.content_type = stream.readCString();+ if (!this.isEndOfBox(stream)) this.content_encoding = stream.readCString();+ }+ if (this.version === 1) {+ this.extension_type = stream.readString(4);+ Log.warn("BoxParser", "Cannot parse extension type");+ stream.seek(this.start + this.size);+ return;+ }+ if (this.version >= 2) {+ if (this.version === 2) this.item_ID = stream.readUint16();+ else if (this.version === 3) this.item_ID = stream.readUint32();+ this.item_protection_index = stream.readUint16();+ this.item_type = stream.readString(4);+ this.item_name = stream.readCString();+ if (this.item_type === "mime") {+ this.content_type = stream.readCString();+ this.content_encoding = stream.readCString();+ } else if (this.item_type === "uri ") this.item_uri_type = stream.readCString();+ }+ }+};++//#endregion+//#region src/boxes/iinf.ts+var iinfBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ItemInfoBox";+ }+ static {+ this.fourcc = "iinf";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 0) this.entry_count = stream.readUint16();+ else this.entry_count = stream.readUint32();+ this.item_infos = [];+ for (let i = 0; i < this.entry_count; i++) {+ const ret = parseOneBox(stream, false, this.size - (stream.getPosition() - this.start));+ if (ret.code === 1) {+ const box = ret.box;+ if (box.type === "infe") this.item_infos[i] = box;+ else Log.error("BoxParser", "Expected 'infe' box, got " + ret.box.type, stream.isofile);+ } else return;+ }+ }+};++//#endregion+//#region src/boxes/iloc.ts+var ilocBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ItemLocationBox";+ }+ static {+ this.fourcc = "iloc";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ let byte;+ byte = stream.readUint8();+ this.offset_size = byte >> 4 & 15;+ this.length_size = byte & 15;+ byte = stream.readUint8();+ this.base_offset_size = byte >> 4 & 15;+ if (this.version === 1 || this.version === 2) this.index_size = byte & 15;+ else this.index_size = 0;+ this.items = [];+ let item_count = 0;+ if (this.version < 2) item_count = stream.readUint16();+ else if (this.version === 2) item_count = stream.readUint32();+ else throw new Error("version of iloc box not supported");+ for (let i = 0; i < item_count; i++) {+ let item_ID = 0;+ let construction_method = 0;+ let base_offset = 0;+ if (this.version < 2) item_ID = stream.readUint16();+ else if (this.version === 2) item_ID = stream.readUint32();+ else throw new Error("version of iloc box not supported");+ if (this.version === 1 || this.version === 2) construction_method = stream.readUint16() & 15;+ else construction_method = 0;+ const data_reference_index = stream.readUint16();+ switch (this.base_offset_size) {+ case 0:+ base_offset = 0;+ break;+ case 4:+ base_offset = stream.readUint32();+ break;+ case 8:+ base_offset = stream.readUint64();+ break;+ default: throw new Error("Error reading base offset size");+ }+ const extents = [];+ const extent_count = stream.readUint16();+ for (let j = 0; j < extent_count; j++) {+ let extent_index = 0;+ let extent_offset = 0;+ let extent_length = 0;+ if (this.version === 1 || this.version === 2) switch (this.index_size) {+ case 0:+ extent_index = 0;+ break;+ case 4:+ extent_index = stream.readUint32();+ break;+ case 8:+ extent_index = stream.readUint64();+ break;+ default: throw new Error("Error reading extent index");+ }+ switch (this.offset_size) {+ case 0:+ extent_offset = 0;+ break;+ case 4:+ extent_offset = stream.readUint32();+ break;+ case 8:+ extent_offset = stream.readUint64();+ break;+ default: throw new Error("Error reading extent index");+ }+ switch (this.length_size) {+ case 0:+ extent_length = 0;+ break;+ case 4:+ extent_length = stream.readUint32();+ break;+ case 8:+ extent_length = stream.readUint64();+ break;+ default: throw new Error("Error reading extent index");+ }+ extents.push({+ extent_index,+ extent_length,+ extent_offset+ });+ }+ this.items.push({+ base_offset,+ construction_method,+ item_ID,+ data_reference_index,+ extents+ });+ }+ }+};++//#endregion+//#region src/boxes/iref.ts+const REFERENCE_TYPE_NAMES = {+ auxl: "Auxiliary image item",+ base: "Pre-derived image item base",+ cdsc: "Item describes referenced item",+ dimg: "Derived image item",+ dpnd: "Item coding dependency",+ eroi: "Region",+ evir: "EVC slice",+ exbl: "Scalable image item",+ "fdl ": "File delivery",+ font: "Font item",+ iloc: "Item data location",+ mask: "Region mask",+ mint: "Data integrity",+ pred: "Predictively coded item",+ prem: "Pre-multiplied item",+ tbas: "HEVC tile track base item",+ text: "Text item",+ thmb: "Thumbnail image item"+};+var irefBox = class irefBox extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ItemReferenceBox";+ this.references = [];+ }+ static {+ this.fourcc = "iref";+ }+ static {+ this.allowed_types = [+ "auxl",+ "base",+ "cdsc",+ "dimg",+ "dpnd",+ "eroi",+ "evir",+ "exbl",+ "fdl ",+ "font",+ "iloc",+ "mask",+ "mint",+ "pred",+ "prem",+ "tbas",+ "text",+ "thmb"+ ];+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.references = [];+ while (stream.getPosition() < this.start + this.size) {+ const ret = parseOneBox(stream, true, this.size - (stream.getPosition() - this.start));+ if (ret.code === 1) {+ let name = "Unknown item reference";+ if (!irefBox.allowed_types.includes(ret.type)) Log.warn("BoxParser", `Unknown item reference type: '${ret.type}'`);+ else name = REFERENCE_TYPE_NAMES[ret.type];+ const box = this.version === 0 ? new SingleItemTypeReferenceBox(ret.type, ret.size, name, ret.hdr_size, ret.start) : new SingleItemTypeReferenceBoxLarge(ret.type, ret.size, name, ret.hdr_size, ret.start);+ if (box.write === Box.prototype.write && box.type !== "mdat") {+ Log.warn("BoxParser", box.type + " box writing not yet implemented, keeping unparsed data in memory for later write");+ box.parseDataAndRewind(stream);+ }+ box.parse(stream);+ this.references.push(box);+ } else return;+ }+ }+};++//#endregion+//#region src/boxes/pitm.ts+var pitmBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "PrimaryItemBox";+ }+ static {+ this.fourcc = "pitm";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 0) this.item_id = stream.readUint16();+ else this.item_id = stream.readUint32();+ }+};++//#endregion+//#region src/boxes/meta.ts+var metaBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "MetaBox";+ this.isQT = false;+ }+ static {+ this.fourcc = "meta";+ }+ parse(stream) {+ const pos = stream.getPosition();+ if (this.size > 8) {+ stream.readUint32();+ switch (stream.readString(4)) {+ case "hdlr":+ case "mhdr":+ case "keys":+ case "ilst":+ case "ctry":+ case "lang":+ this.isQT = true;+ break;+ default: break;+ }+ stream.seek(pos);+ }+ if (!this.isQT) this.parseFullHeader(stream);+ ContainerBox.prototype.parse.call(this, stream);+ }+};++//#endregion+//#region src/boxes/mfhd.ts+var mfhdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "MovieFragmentHeaderBox";+ }+ static {+ this.fourcc = "mfhd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.sequence_number = stream.readUint32();+ }+ /** @bundle writing/mfhd.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 4;+ this.writeHeader(stream);+ stream.writeUint32(this.sequence_number);+ }+};++//#endregion+//#region src/boxes/mvhd.ts+var mvhdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "MovieHeaderBox";+ }+ static {+ this.fourcc = "mvhd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 1) {+ this.creation_time = stream.readUint64();+ this.modification_time = stream.readUint64();+ this.timescale = stream.readUint32();+ this.duration = stream.readUint64();+ } else {+ this.creation_time = stream.readUint32();+ this.modification_time = stream.readUint32();+ this.timescale = stream.readUint32();+ this.duration = stream.readUint32();+ }+ this.rate = stream.readUint32();+ this.volume = stream.readUint16() >> 8;+ stream.readUint16();+ stream.readUint32Array(2);+ this.matrix = stream.readInt32Array(9);+ stream.readUint32Array(6);+ this.next_track_id = stream.readUint32();+ }+ /** @bundle writing/mvhd.js */+ write(stream) {+ const useVersion1 = this.modification_time > MAX_UINT32 || this.creation_time > MAX_UINT32 || this.duration > MAX_UINT32 || this.version === 1;+ this.version = useVersion1 ? 1 : 0;+ this.size = 96;+ this.size += useVersion1 ? 12 : 0;+ this.flags = 0;+ this.writeHeader(stream);+ if (useVersion1) {+ stream.writeUint64(this.creation_time);+ stream.writeUint64(this.modification_time);+ stream.writeUint32(this.timescale);+ stream.writeUint64(this.duration);+ } else {+ stream.writeUint32(this.creation_time);+ stream.writeUint32(this.modification_time);+ stream.writeUint32(this.timescale);+ stream.writeUint32(this.duration);+ }+ stream.writeUint32(this.rate);+ stream.writeUint16(this.volume << 8);+ stream.writeUint16(0);+ stream.writeUint32(0);+ stream.writeUint32(0);+ stream.writeInt32Array(this.matrix);+ stream.writeUint32(0);+ stream.writeUint32(0);+ stream.writeUint32(0);+ stream.writeUint32(0);+ stream.writeUint32(0);+ stream.writeUint32(0);+ stream.writeUint32(this.next_track_id);+ }+ /** @bundle box-print.js */+ print(output) {+ super.printHeader(output);+ output.log(output.indent + "creation_time: " + this.creation_time);+ output.log(output.indent + "modification_time: " + this.modification_time);+ output.log(output.indent + "timescale: " + this.timescale);+ output.log(output.indent + "duration: " + this.duration);+ output.log(output.indent + "rate: " + this.rate);+ output.log(output.indent + "volume: " + (this.volume >> 8));+ output.log(output.indent + "matrix: " + this.matrix.join(", "));+ output.log(output.indent + "next_track_id: " + this.next_track_id);+ }+};++//#endregion+//#region src/boxes/sampleentries/mett.ts+var mettSampleEntry = class extends MetadataSampleEntry {+ static {+ this.fourcc = "mett";+ }+ parse(stream) {+ this.parseHeader(stream);+ this.content_encoding = stream.readCString();+ this.mime_format = stream.readCString();+ this.parseFooter(stream);+ }+};++//#endregion+//#region src/boxes/sampleentries/metx.ts+var metxSampleEntry = class extends MetadataSampleEntry {+ static {+ this.fourcc = "metx";+ }+ parse(stream) {+ this.parseHeader(stream);+ this.content_encoding = stream.readCString();+ this.namespace = stream.readCString();+ this.schema_location = stream.readCString();+ this.parseFooter(stream);+ }+};++//#endregion+//#region src/boxes/av1C.ts+var av1CBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "AV1CodecConfigurationBox";+ }+ static {+ this.fourcc = "av1C";+ }+ parse(stream) {+ let tmp = stream.readUint8();+ if ((tmp >> 7 & 1) !== 1) {+ Log.error("BoxParser", "av1C marker problem", stream.isofile);+ return;+ }+ this.version = tmp & 127;+ if (this.version !== 1) {+ Log.error("BoxParser", "av1C version " + this.version + " not supported", stream.isofile);+ return;+ }+ tmp = stream.readUint8();+ this.seq_profile = tmp >> 5 & 7;+ this.seq_level_idx_0 = tmp & 31;+ tmp = stream.readUint8();+ this.seq_tier_0 = tmp >> 7 & 1;+ this.high_bitdepth = tmp >> 6 & 1;+ this.twelve_bit = tmp >> 5 & 1;+ this.monochrome = tmp >> 4 & 1;+ this.chroma_subsampling_x = tmp >> 3 & 1;+ this.chroma_subsampling_y = tmp >> 2 & 1;+ this.chroma_sample_position = tmp & 3;+ tmp = stream.readUint8();+ this.reserved_1 = tmp >> 5 & 7;+ if (this.reserved_1 !== 0) {+ Log.error("BoxParser", "av1C reserved_1 parsing problem", stream.isofile);+ return;+ }+ this.initial_presentation_delay_present = tmp >> 4 & 1;+ if (this.initial_presentation_delay_present === 1) this.initial_presentation_delay_minus_one = tmp & 15;+ else {+ this.reserved_2 = tmp & 15;+ if (this.reserved_2 !== 0) {+ Log.error("BoxParser", "av1C reserved_2 parsing problem", stream.isofile);+ return;+ }+ }+ const configOBUs_length = this.size - this.hdr_size - 4;+ this.configOBUs = stream.readUint8Array(configOBUs_length);+ }+};++//#endregion+//#region src/boxes/esds.ts+var esdsBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ElementaryStreamDescriptorBox";+ }+ static {+ this.fourcc = "esds";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const esd_data = stream.readUint8Array(this.size - this.hdr_size);+ if ("MPEG4DescriptorParser" in DescriptorRegistry) {+ const esd_parser = new DescriptorRegistry.MPEG4DescriptorParser();+ this.esd = esd_parser.parseOneDescriptor(new DataStream(esd_data.buffer, 0));+ }+ }+};++//#endregion+//#region src/boxes/qt/wave.ts+var waveBox = class extends ContainerBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "siDecompressionParamBox";+ }+ static {+ this.fourcc = "wave";+ }+};++//#endregion+//#region src/boxes/lvcC.ts+var lvcCBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "LCEVCConfigurationBox";+ }+ static {+ this.fourcc = "lvcC";+ }+ parse(stream) {+ this.configurationVersion = stream.readUint8();+ if (this.configurationVersion !== 1) {+ Log.error("BoxParser", "lvcC version " + this.configurationVersion + " not supported", stream.isofile);+ return;+ }+ this.LCEVCProfileIndication = stream.readUint8();+ this.LCEVCLevelIndication = stream.readUint8();+ let tmp_byte = stream.readUint8();+ this.chroma_format_idc = tmp_byte >> 6 & 3;+ this.bit_depth_luma_minus8 = tmp_byte >> 3 & 7;+ this.bit_depth_chroma_minus8 = tmp_byte & 7;+ tmp_byte = stream.readUint8();+ this.lengthSizeMinusOne = tmp_byte >> 6 & 3;+ let reserved = tmp_byte & 63;+ if (reserved !== 63) {+ Log.error("BoxParser", "lvcC reserved parsing problem", stream.isofile);+ return;+ }+ this.pic_width_in_luma_samples = stream.readUint32();+ this.pic_height_in_luma_samples = stream.readUint32();+ tmp_byte = stream.readUint8();+ this.sc_in_stream = tmp_byte >> 7 & 1;+ this.gc_in_stream = tmp_byte >> 6 & 1;+ this.ai_in_stream = tmp_byte >> 5 & 1;+ reserved = tmp_byte & 31;+ if (reserved !== 31) {+ Log.error("BoxParser", "lvcC reserved parsing problem", stream.isofile);+ return;+ }+ this.nalu_arrays = [];+ const numOfArrays = stream.readUint8();+ for (let i = 0; i < numOfArrays; i++) {+ const nalu_array = [];+ this.nalu_arrays.push(nalu_array);+ tmp_byte = stream.readUint8();+ reserved = tmp_byte >> 6 & 3;+ if (reserved !== 0) {+ Log.error("BoxParser", "lvcC reserved parsing problem", stream.isofile);+ return;+ }+ nalu_array.nalu_type = tmp_byte & 63;+ const numOfNalus = stream.readUint16();+ for (let j = 0; j < numOfNalus; j++) {+ const length = stream.readUint16();+ nalu_array.push({ data: stream.readUint8Array(length) });+ }+ }+ }+};++//#endregion+//#region src/boxes/vpcC.ts+var vpcCBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "VPCodecConfigurationRecord";+ }+ static {+ this.fourcc = "vpcC";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 1) {+ this.profile = stream.readUint8();+ this.level = stream.readUint8();+ const tmp = stream.readUint8();+ this.bitDepth = tmp >> 4;+ this.chromaSubsampling = tmp >> 1 & 7;+ this.videoFullRangeFlag = tmp & 1;+ this.colourPrimaries = stream.readUint8();+ this.transferCharacteristics = stream.readUint8();+ this.matrixCoefficients = stream.readUint8();+ this.codecIntializationDataSize = stream.readUint16();+ this.codecIntializationData = stream.readUint8Array(this.codecIntializationDataSize);+ } else {+ this.profile = stream.readUint8();+ this.level = stream.readUint8();+ let tmp = stream.readUint8();+ this.bitDepth = tmp >> 4 & 15;+ this.colorSpace = tmp & 15;+ tmp = stream.readUint8();+ this.chromaSubsampling = tmp >> 4 & 15;+ this.transferFunction = tmp >> 1 & 7;+ this.videoFullRangeFlag = tmp & 1;+ this.codecIntializationDataSize = stream.readUint16();+ this.codecIntializationData = stream.readUint8Array(this.codecIntializationDataSize);+ }+ }+};++//#endregion+//#region src/boxes/vvcC.ts+var vvcCBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "VvcConfigurationBox";+ }+ static {+ this.fourcc = "vvcC";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const bitReader = {+ held_bits: void 0,+ num_held_bits: 0,+ stream_read_1_bytes: function(strm) {+ this.held_bits = strm.readUint8();+ this.num_held_bits = 8;+ },+ stream_read_2_bytes: function(strm) {+ this.held_bits = strm.readUint16();+ this.num_held_bits = 16;+ },+ extract_bits: function(num_bits) {+ const ret = this.held_bits >> this.num_held_bits - num_bits & (1 << num_bits) - 1;+ this.num_held_bits -= num_bits;+ return ret;+ }+ };+ bitReader.stream_read_1_bytes(stream);+ bitReader.extract_bits(5);+ this.lengthSizeMinusOne = bitReader.extract_bits(2);+ this.ptl_present_flag = bitReader.extract_bits(1);+ if (this.ptl_present_flag) {+ bitReader.stream_read_2_bytes(stream);+ this.ols_idx = bitReader.extract_bits(9);+ this.num_sublayers = bitReader.extract_bits(3);+ this.constant_frame_rate = bitReader.extract_bits(2);+ this.chroma_format_idc = bitReader.extract_bits(2);+ bitReader.stream_read_1_bytes(stream);+ this.bit_depth_minus8 = bitReader.extract_bits(3);+ bitReader.extract_bits(5);+ bitReader.stream_read_2_bytes(stream);+ bitReader.extract_bits(2);+ this.num_bytes_constraint_info = bitReader.extract_bits(6);+ this.general_profile_idc = bitReader.extract_bits(7);+ this.general_tier_flag = bitReader.extract_bits(1);+ this.general_level_idc = stream.readUint8();+ bitReader.stream_read_1_bytes(stream);+ this.ptl_frame_only_constraint_flag = bitReader.extract_bits(1);+ this.ptl_multilayer_enabled_flag = bitReader.extract_bits(1);+ this.general_constraint_info = new Uint8Array(this.num_bytes_constraint_info);+ if (this.num_bytes_constraint_info) {+ for (let i = 0; i < this.num_bytes_constraint_info - 1; i++) {+ const cnstr1 = bitReader.extract_bits(6);+ bitReader.stream_read_1_bytes(stream);+ const cnstr2 = bitReader.extract_bits(2);+ this.general_constraint_info[i] = cnstr1 << 2 | cnstr2;+ }+ this.general_constraint_info[this.num_bytes_constraint_info - 1] = bitReader.extract_bits(6);+ } else bitReader.extract_bits(6);+ if (this.num_sublayers > 1) {+ bitReader.stream_read_1_bytes(stream);+ this.ptl_sublayer_present_mask = 0;+ for (let j = this.num_sublayers - 2; j >= 0; --j) {+ const val = bitReader.extract_bits(1);+ this.ptl_sublayer_present_mask |= val << j;+ }+ for (let j = this.num_sublayers; j <= 8 && this.num_sublayers > 1; ++j) bitReader.extract_bits(1);+ this.sublayer_level_idc = [];+ for (let j = this.num_sublayers - 2; j >= 0; --j) if (this.ptl_sublayer_present_mask & 1 << j) this.sublayer_level_idc[j] = stream.readUint8();+ }+ this.ptl_num_sub_profiles = stream.readUint8();+ this.general_sub_profile_idc = [];+ if (this.ptl_num_sub_profiles) for (let i = 0; i < this.ptl_num_sub_profiles; i++) this.general_sub_profile_idc.push(stream.readUint32());+ this.max_picture_width = stream.readUint16();+ this.max_picture_height = stream.readUint16();+ this.avg_frame_rate = stream.readUint16();+ }+ const VVC_NALU_OPI = 12;+ const VVC_NALU_DEC_PARAM = 13;+ this.nalu_arrays = [];+ const num_of_arrays = stream.readUint8();+ for (let i = 0; i < num_of_arrays; i++) {+ const nalu_array = [];+ this.nalu_arrays.push(nalu_array);+ bitReader.stream_read_1_bytes(stream);+ nalu_array.completeness = bitReader.extract_bits(1);+ bitReader.extract_bits(2);+ nalu_array.nalu_type = bitReader.extract_bits(5);+ let numNalus = 1;+ if (nalu_array.nalu_type !== VVC_NALU_DEC_PARAM && nalu_array.nalu_type !== VVC_NALU_OPI) numNalus = stream.readUint16();+ for (let j = 0; j < numNalus; j++) {+ const len = stream.readUint16();+ nalu_array.push({+ data: stream.readUint8Array(len),+ length: len+ });+ }+ }+ }+};++//#endregion+//#region src/boxes/colr.ts+var colrBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ColourInformationBox";+ }+ static {+ this.fourcc = "colr";+ }+ parse(stream) {+ this.colour_type = stream.readString(4);+ if (this.colour_type === "nclx") {+ this.colour_primaries = stream.readUint16();+ this.transfer_characteristics = stream.readUint16();+ this.matrix_coefficients = stream.readUint16();+ const tmp = stream.readUint8();+ this.full_range_flag = tmp >> 7;+ } else if (this.colour_type === "rICC") this.ICC_profile = stream.readUint8Array(this.size - 4);+ else if (this.colour_type === "prof") this.ICC_profile = stream.readUint8Array(this.size - 4);+ }+};++//#endregion+//#region src/boxes/sampleentries/sampleentry.ts+/** @bundle box-codecs.js */+function decimalToHex(d, padding) {+ let hex = Number(d).toString(16);+ padding = typeof padding === "undefined" ? 2 : padding;+ while (hex.length < padding) hex = "0" + hex;+ return hex;+}+var avcCSampleEntryBase = class extends VisualSampleEntry {+ /** @bundle box-codecs.js */+ getCodec() {+ const baseCodec = super.getCodec();+ if (this.avcC) return `${baseCodec}.${decimalToHex(this.avcC.AVCProfileIndication)}${decimalToHex(this.avcC.profile_compatibility)}${decimalToHex(this.avcC.AVCLevelIndication)}`;+ else return baseCodec;+ }+};+var avc1SampleEntry = class extends avcCSampleEntryBase {+ constructor(..._args) {+ super(..._args);+ this.box_name = "AVCSampleEntry";+ }+ static {+ this.fourcc = "avc1";+ }+};+var avc2SampleEntry = class extends avcCSampleEntryBase {+ constructor(..._args2) {+ super(..._args2);+ this.box_name = "AVC2SampleEntry";+ }+ static {+ this.fourcc = "avc2";+ }+};+var avc3SampleEntry = class extends avcCSampleEntryBase {+ constructor(..._args3) {+ super(..._args3);+ this.box_name = "AVCSampleEntry";+ }+ static {+ this.fourcc = "avc3";+ }+};+var avc4SampleEntry = class extends avcCSampleEntryBase {+ constructor(..._args4) {+ super(..._args4);+ this.box_name = "AVC2SampleEntry";+ }+ static {+ this.fourcc = "avc4";+ }+};+var av01SampleEntry = class extends VisualSampleEntry {+ constructor(..._args5) {+ super(..._args5);+ this.box_name = "AV1SampleEntry";+ }+ static {+ this.fourcc = "av01";+ }+ /** @bundle box-codecs.js */+ getCodec() {+ const baseCodec = super.getCodec();+ const level_idx_0 = this.av1C.seq_level_idx_0;+ const level = level_idx_0 < 10 ? "0" + level_idx_0 : level_idx_0;+ let bitdepth;+ if (this.av1C.seq_profile === 2 && this.av1C.high_bitdepth === 1) bitdepth = this.av1C.twelve_bit === 1 ? "12" : "10";+ else if (this.av1C.seq_profile <= 2) bitdepth = this.av1C.high_bitdepth === 1 ? "10" : "08";+ return baseCodec + "." + this.av1C.seq_profile + "." + level + (this.av1C.seq_tier_0 ? "H" : "M") + "." + bitdepth;+ }+};+var dav1SampleEntry = class extends VisualSampleEntry {+ static {+ this.fourcc = "dav1";+ }+};+var hvcCSampleEntryBase = class extends VisualSampleEntry {+ /** @bundle box-codecs.js */+ getCodec() {+ let baseCodec = super.getCodec();+ if (this.hvcC) {+ baseCodec += ".";+ switch (this.hvcC.general_profile_space) {+ case 0:+ baseCodec += "";+ break;+ case 1:+ baseCodec += "A";+ break;+ case 2:+ baseCodec += "B";+ break;+ case 3:+ baseCodec += "C";+ break;+ }+ baseCodec += this.hvcC.general_profile_idc;+ baseCodec += ".";+ let val = this.hvcC.general_profile_compatibility;+ let reversed = 0;+ for (let i = 0; i < 32; i++) {+ reversed |= val & 1;+ if (i === 31) break;+ reversed <<= 1;+ val >>= 1;+ }+ baseCodec += decimalToHex(reversed, 0);+ baseCodec += ".";+ if (this.hvcC.general_tier_flag === 0) baseCodec += "L";+ else baseCodec += "H";+ baseCodec += this.hvcC.general_level_idc;+ let hasByte = false;+ let constraint_string = "";+ for (let i = 5; i >= 0; i--) if (this.hvcC.general_constraint_indicator[i] || hasByte) {+ constraint_string = "." + decimalToHex(this.hvcC.general_constraint_indicator[i], 0) + constraint_string;+ hasByte = true;+ }+ baseCodec += constraint_string;+ }+ return baseCodec;+ }+};+var hvc1SampleEntry = class extends hvcCSampleEntryBase {+ constructor(..._args6) {+ super(..._args6);+ this.box_name = "HEVCSampleEntry";+ }+ static {+ this.fourcc = "hvc1";+ }+};+var hvc2SampleEntry = class extends hvcCSampleEntryBase {+ static {+ this.fourcc = "hvc2";+ }+};+var hev1SampleEntry = class extends hvcCSampleEntryBase {+ constructor(..._args7) {+ super(..._args7);+ this.box_name = "HEVCSampleEntry";+ this.colrs = [];+ this.subBoxNames = ["colr"];+ }+ static {+ this.fourcc = "hev1";+ }+};+var hev2SampleEntry = class extends hvcCSampleEntryBase {+ static {+ this.fourcc = "hev2";+ }+};+var hvt1SampleEntry = class extends VisualSampleEntry {+ constructor(..._args8) {+ super(..._args8);+ this.box_name = "HEVCTileSampleSampleEntry";+ }+ static {+ this.fourcc = "hvt1";+ }+};+var lhe1SampleEntry = class extends VisualSampleEntry {+ constructor(..._args9) {+ super(..._args9);+ this.box_name = "LHEVCSampleEntry";+ }+ static {+ this.fourcc = "lhe1";+ }+};+var lhv1SampleEntry = class extends VisualSampleEntry {+ constructor(..._args10) {+ super(..._args10);+ this.box_name = "LHEVCSampleEntry";+ }+ static {+ this.fourcc = "lhv1";+ }+};+var lvc1SampleEntry = class extends VisualSampleEntry {+ constructor(..._args11) {+ super(..._args11);+ this.box_name = "LCEVCSampleEntry";+ }+ static {+ this.fourcc = "lvc1";+ }+ /** @bundle box-codecs.js */+ getCodec() {+ let baseCodec = super.getCodec();+ if (this.lvcC) {+ baseCodec += ".";+ baseCodec += "vprf";+ baseCodec += this.lvcC.LCEVCProfileIndication;+ baseCodec += ".";+ baseCodec += "vlev";+ baseCodec += this.lvcC.LCEVCLevelIndication;+ }+ return baseCodec;+ }+};+var dvh1SampleEntry = class extends VisualSampleEntry {+ static {+ this.fourcc = "dvh1";+ }+};+var dvheSampleEntry = class extends VisualSampleEntry {+ static {+ this.fourcc = "dvhe";+ }+};+/** @babel box-codecs.js */+var vvcCSampleEntryBase = class extends VisualSampleEntry {+ getCodec() {+ let baseCodec = super.getCodec();+ if (this.vvcC) {+ baseCodec += "." + this.vvcC.general_profile_idc;+ if (this.vvcC.general_tier_flag) baseCodec += ".H";+ else baseCodec += ".L";+ baseCodec += this.vvcC.general_level_idc;+ let constraint_string = "";+ if (this.vvcC.general_constraint_info) {+ const bytes = [];+ let byte = 0;+ byte |= this.vvcC.ptl_frame_only_constraint_flag << 7;+ byte |= this.vvcC.ptl_multilayer_enabled_flag << 6;+ let last_nonzero;+ for (let i = 0; i < this.vvcC.general_constraint_info.length; ++i) {+ byte |= this.vvcC.general_constraint_info[i] >> 2 & 63;+ bytes.push(byte);+ if (byte) last_nonzero = i;+ byte = this.vvcC.general_constraint_info[i] >> 2 & 3;+ }+ if (last_nonzero === void 0) constraint_string = ".CA";+ else {+ constraint_string = ".C";+ const base32_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";+ let held_bits = 0;+ let num_held_bits = 0;+ for (let i = 0; i <= last_nonzero; ++i) {+ held_bits = held_bits << 8 | bytes[i];+ num_held_bits += 8;+ while (num_held_bits >= 5) {+ const val = held_bits >> num_held_bits - 5 & 31;+ constraint_string += base32_chars[val];+ num_held_bits -= 5;+ held_bits &= (1 << num_held_bits) - 1;+ }+ }+ if (num_held_bits) {+ held_bits <<= 5 - num_held_bits;+ constraint_string += base32_chars[held_bits & 31];+ }+ }+ }+ baseCodec += constraint_string;+ }+ return baseCodec;+ }+};+var vvc1SampleEntry = class extends vvcCSampleEntryBase {+ constructor(..._args12) {+ super(..._args12);+ this.box_name = "VvcSampleEntry";+ }+ static {+ this.fourcc = "vvc1";+ }+};+var vvi1SampleEntry = class extends vvcCSampleEntryBase {+ constructor(..._args13) {+ super(..._args13);+ this.box_name = "VvcSampleEntry";+ }+ static {+ this.fourcc = "vvi1";+ }+};+var vvs1SampleEntry = class extends VisualSampleEntry {+ constructor(..._args14) {+ super(..._args14);+ this.box_name = "VvcSampleEntry";+ }+ static {+ this.fourcc = "vvs1";+ }+};+var vvcNSampleEntry = class extends VisualSampleEntry {+ constructor(..._args15) {+ super(..._args15);+ this.box_name = "VvcNonVCLSampleEntry";+ }+ static {+ this.fourcc = "vvcN";+ }+};+var vpcCSampleEntryBase = class extends VisualSampleEntry {+ getCodec() {+ const baseCodec = super.getCodec();+ let level = this.vpcC.level;+ if (level === 0) level = "00";+ let bitDepth = this.vpcC.bitDepth;+ if (bitDepth === 8) bitDepth = "08";+ return `${baseCodec}.0${this.vpcC.profile}.${level}.${bitDepth}`;+ }+};+var vp08SampleEntry = class extends vpcCSampleEntryBase {+ static {+ this.fourcc = "vp08";+ }+};+var vp09SampleEntry = class extends vpcCSampleEntryBase {+ static {+ this.fourcc = "vp09";+ }+};+var avs3SampleEntry = class extends VisualSampleEntry {+ static {+ this.fourcc = "avs3";+ }+};+var j2kiSampleEntry = class extends VisualSampleEntry {+ constructor(..._args16) {+ super(..._args16);+ this.box_name = "J2KSampleEntry";+ }+ static {+ this.fourcc = "j2ki";+ }+};+var mjp2SampleEntry = class extends VisualSampleEntry {+ static {+ this.fourcc = "mjp2";+ }+};+var mjpgSampleEntry = class extends VisualSampleEntry {+ static {+ this.fourcc = "mjpg";+ }+};+var uncvSampleEntry = class extends VisualSampleEntry {+ constructor(..._args17) {+ super(..._args17);+ this.box_name = "UncompressedVideoSampleEntry";+ }+ static {+ this.fourcc = "uncv";+ }+};+var mp4vSampleEntry = class extends VisualSampleEntry {+ constructor(..._args18) {+ super(..._args18);+ this.box_name = "MP4VisualSampleEntry";+ }+ static {+ this.fourcc = "mp4v";+ }+};+var mp4aSampleEntry = class extends AudioSampleEntry {+ constructor(..._args19) {+ super(..._args19);+ this.box_name = "MP4AudioSampleEntry";+ }+ static {+ this.fourcc = "mp4a";+ }+ getCodec() {+ const baseCodec = super.getCodec();+ const esds = this.esds ?? this.wave?.esds;+ if (esds && esds.esd) {+ const oti = esds.esd.getOTI();+ const dsi = esds.esd.getAudioConfig();+ return baseCodec + "." + decimalToHex(oti) + (dsi ? "." + dsi : "");+ } else return baseCodec;+ }+};+var m4aeSampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "m4ae";+ }+};+var ac_3SampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "ac-3";+ }+};+var ac_4SampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "ac-4";+ }+};+var ec_3SampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "ec-3";+ }+};+var OpusSampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "Opus";+ }+};+var mha1SampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "mha1";+ }+};+var mha2SampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "mha2";+ }+};+var mhm1SampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "mhm1";+ }+};+var mhm2SampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "mhm2";+ }+};+var fLaCSampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "fLaC";+ }+};+var encvSampleEntry = class extends VisualSampleEntry {+ static {+ this.fourcc = "encv";+ }+};+var encaSampleEntry = class extends AudioSampleEntry {+ static {+ this.fourcc = "enca";+ }+};+var encuSampleEntry = class extends SubtitleSampleEntry {+ constructor(..._args20) {+ super(..._args20);+ this.subBoxNames = ["sinf"];+ this.sinfs = [];+ }+ static {+ this.fourcc = "encu";+ }+};+var encsSampleEntry = class extends SystemSampleEntry {+ constructor(..._args21) {+ super(..._args21);+ this.subBoxNames = ["sinf"];+ this.sinfs = [];+ }+ static {+ this.fourcc = "encs";+ }+};+var mp4sSampleEntry = class extends SystemSampleEntry {+ static {+ this.fourcc = "mp4s";+ }+};+var enctSampleEntry = class extends TextSampleEntry {+ constructor(..._args22) {+ super(..._args22);+ this.subBoxNames = ["sinf"];+ this.sinfs = [];+ }+ static {+ this.fourcc = "enct";+ }+};+var encmSampleEntry = class extends MetadataSampleEntry {+ constructor(..._args23) {+ super(..._args23);+ this.subBoxNames = ["sinf"];+ this.sinfs = [];+ }+ static {+ this.fourcc = "encm";+ }+};+var resvSampleEntry = class extends VisualSampleEntry {+ constructor(..._args24) {+ super(..._args24);+ this.box_name = "RestrictedVideoSampleEntry";+ }+ static {+ this.fourcc = "resv";+ }+};++//#endregion+//#region src/boxes/sampleentries/sbtt.ts+var sbttSampleEntry = class extends SubtitleSampleEntry {+ static {+ this.fourcc = "sbtt";+ }+ parse(stream) {+ this.parseHeader(stream);+ this.content_encoding = stream.readCString();+ this.mime_format = stream.readCString();+ this.parseFooter(stream);+ }+};++//#endregion+//#region src/boxes/sampleentries/stpp.ts+var stppSampleEntry = class extends SubtitleSampleEntry {+ static {+ this.fourcc = "stpp";+ }+ parse(stream) {+ this.parseHeader(stream);+ this.namespace = stream.readCString();+ this.schema_location = stream.readCString();+ this.auxiliary_mime_types = stream.readCString();+ this.parseFooter(stream);+ }+ /** @bundle writing/sampleentry.js */+ write(stream) {+ this.writeHeader(stream);+ this.size += this.namespace.length + 1 + this.schema_location.length + 1 + this.auxiliary_mime_types.length + 1;+ stream.writeCString(this.namespace);+ stream.writeCString(this.schema_location);+ stream.writeCString(this.auxiliary_mime_types);+ this.writeFooter(stream);+ }+};++//#endregion+//#region src/boxes/sampleentries/stxt.ts+var stxtSampleEntry = class extends SubtitleSampleEntry {+ static {+ this.fourcc = "stxt";+ }+ parse(stream) {+ this.parseHeader(stream);+ this.content_encoding = stream.readCString();+ this.mime_format = stream.readCString();+ this.parseFooter(stream);+ }+ getCodec() {+ const baseCodec = super.getCodec();+ if (this.mime_format) return baseCodec + "." + this.mime_format;+ else return baseCodec;+ }+};++//#endregion+//#region src/boxes/sampleentries/tx3g.ts+var tx3gSampleEntry = class extends SubtitleSampleEntry {+ static {+ this.fourcc = "tx3g";+ }+ parse(stream) {+ this.parseHeader(stream);+ this.displayFlags = stream.readUint32();+ this.horizontal_justification = stream.readInt8();+ this.vertical_justification = stream.readInt8();+ this.bg_color_rgba = stream.readUint8Array(4);+ this.box_record = stream.readInt16Array(4);+ this.style_record = stream.readUint8Array(12);+ this.parseFooter(stream);+ }+};++//#endregion+//#region src/boxes/sampleentries/wvtt.ts+var wvttSampleEntry = class extends MetadataSampleEntry {+ static {+ this.fourcc = "wvtt";+ }+ parse(stream) {+ this.parseHeader(stream);+ this.parseFooter(stream);+ }+};++//#endregion+//#region src/boxes/sbgp.ts+var sbgpBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SampleToGroupBox";+ }+ static {+ this.fourcc = "sbgp";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.grouping_type = stream.readString(4);+ if (this.version === 1) this.grouping_type_parameter = stream.readUint32();+ else this.grouping_type_parameter = 0;+ this.entries = [];+ const entry_count = stream.readUint32();+ for (let i = 0; i < entry_count; i++) this.entries.push({+ sample_count: stream.readInt32(),+ group_description_index: stream.readInt32()+ });+ }+ /** @bundle writing/sbgp.js */+ write(stream) {+ if (this.grouping_type_parameter) this.version = 1;+ else this.version = 0;+ this.flags = 0;+ this.size = 8 + 8 * this.entries.length + (this.version === 1 ? 4 : 0);+ this.writeHeader(stream);+ stream.writeString(this.grouping_type, void 0, 4);+ if (this.version === 1) stream.writeUint32(this.grouping_type_parameter);+ stream.writeUint32(this.entries.length);+ for (let i = 0; i < this.entries.length; i++) {+ const entry = this.entries[i];+ stream.writeInt32(entry.sample_count);+ stream.writeInt32(entry.group_description_index);+ }+ }+};++//#endregion+//#region src/boxes/sdtp.ts+var sdtpBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SampleDependencyTypeBox";+ }+ static {+ this.fourcc = "sdtp";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const count = this.size - this.hdr_size;+ this.is_leading = [];+ this.sample_depends_on = [];+ this.sample_is_depended_on = [];+ this.sample_has_redundancy = [];+ for (let i = 0; i < count; i++) {+ const tmp_byte = stream.readUint8();+ this.is_leading[i] = tmp_byte >> 6;+ this.sample_depends_on[i] = tmp_byte >> 4 & 3;+ this.sample_is_depended_on[i] = tmp_byte >> 2 & 3;+ this.sample_has_redundancy[i] = tmp_byte & 3;+ }+ }+};++//#endregion+//#region src/boxes/sgpd.ts+var sgpdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SampleGroupDescriptionBox";+ }+ static {+ this.fourcc = "sgpd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.grouping_type = stream.readString(4);+ Log.debug("BoxParser", "Found Sample Groups of type " + this.grouping_type);+ if (this.version === 1) this.default_length = stream.readUint32();+ else this.default_length = 0;+ if (this.version >= 2) this.default_group_description_index = stream.readUint32();+ this.entries = [];+ const entry_count = stream.readUint32();+ for (let i = 0; i < entry_count; i++) {+ let entry;+ if (this.grouping_type in BoxRegistry.sampleGroupEntry) entry = new BoxRegistry.sampleGroupEntry[this.grouping_type](this.grouping_type);+ else entry = new SampleGroupEntry(this.grouping_type);+ this.entries.push(entry);+ if (this.version === 1) if (this.default_length === 0) entry.description_length = stream.readUint32();+ else entry.description_length = this.default_length;+ else entry.description_length = this.default_length;+ if (entry.write === SampleGroupEntry.prototype.write) {+ Log.info("BoxParser", "SampleGroup for type " + this.grouping_type + " writing not yet implemented, keeping unparsed data in memory for later write");+ entry.data = stream.readUint8Array(entry.description_length);+ stream.seek(stream.getPosition() - entry.description_length);+ }+ entry.parse(stream);+ }+ }+ /** @bundle writing/sgpd.js */+ write(stream) {+ this.flags = 0;+ this.size = 12;+ for (let i = 0; i < this.entries.length; i++) {+ const entry = this.entries[i];+ if (this.version === 1) {+ if (this.default_length === 0) this.size += 4;+ this.size += entry.data.length;+ }+ }+ this.writeHeader(stream);+ stream.writeString(this.grouping_type, void 0, 4);+ if (this.version === 1) stream.writeUint32(this.default_length);+ if (this.version >= 2) stream.writeUint32(this.default_sample_description_index);+ stream.writeUint32(this.entries.length);+ for (let i = 0; i < this.entries.length; i++) {+ const entry = this.entries[i];+ if (this.version === 1) {+ if (this.default_length === 0) stream.writeUint32(entry.description_length);+ }+ entry.write(stream);+ }+ }+};++//#endregion+//#region src/boxes/sidx.ts+var sidxBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CompressedSegmentIndexBox";+ }+ static {+ this.fourcc = "sidx";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.reference_ID = stream.readUint32();+ this.timescale = stream.readUint32();+ if (this.version === 0) {+ this.earliest_presentation_time = stream.readUint32();+ this.first_offset = stream.readUint32();+ } else {+ this.earliest_presentation_time = stream.readUint64();+ this.first_offset = stream.readUint64();+ }+ stream.readUint16();+ this.references = [];+ const count = stream.readUint16();+ for (let i = 0; i < count; i++) {+ const type = stream.readUint32();+ const subsegment_duration = stream.readUint32();+ const sap = stream.readUint32();+ this.references.push({+ reference_type: type >> 31 & 1,+ referenced_size: type & 2147483647,+ subsegment_duration,+ starts_with_SAP: sap >> 31 & 1,+ SAP_type: sap >> 28 & 7,+ SAP_delta_time: sap & 268435455+ });+ }+ }+ /** @bundle writing/sidx.js */+ write(stream) {+ const useVersion1 = this.earliest_presentation_time > MAX_UINT32 || this.first_offset > MAX_UINT32 || this.version === 1;+ this.version = useVersion1 ? 1 : 0;+ this.size = 12 + 12 * this.references.length;+ this.size += useVersion1 ? 16 : 8;+ this.flags = 0;+ this.writeHeader(stream);+ stream.writeUint32(this.reference_ID);+ stream.writeUint32(this.timescale);+ if (useVersion1) {+ stream.writeUint64(this.earliest_presentation_time);+ stream.writeUint64(this.first_offset);+ } else {+ stream.writeUint32(this.earliest_presentation_time);+ stream.writeUint32(this.first_offset);+ }+ stream.writeUint16(0);+ stream.writeUint16(this.references.length);+ for (let i = 0; i < this.references.length; i++) {+ const ref = this.references[i];+ stream.writeUint32(ref.reference_type << 31 | ref.referenced_size);+ stream.writeUint32(ref.subsegment_duration);+ stream.writeUint32(ref.starts_with_SAP << 31 | ref.SAP_type << 28 | ref.SAP_delta_time);+ }+ }+};++//#endregion+//#region src/boxes/smhd.ts+var smhdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SoundMediaHeaderBox";+ }+ static {+ this.fourcc = "smhd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.balance = stream.readUint16();+ stream.readUint16();+ }+ /** @bundle writing/smhd.js */+ write(stream) {+ this.version = 0;+ this.size = 4;+ this.writeHeader(stream);+ stream.writeUint16(this.balance);+ stream.writeUint16(0);+ }+};++//#endregion+//#region src/boxes/stco.ts+var stcoBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "ChunkOffsetBox";+ }+ static {+ this.fourcc = "stco";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const entry_count = stream.readUint32();+ this.chunk_offsets = [];+ if (this.version === 0) for (let i = 0; i < entry_count; i++) this.chunk_offsets.push(stream.readUint32());+ }+ /** @bundle writings/stco.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 4 + 4 * this.chunk_offsets.length;+ this.writeHeader(stream);+ stream.writeUint32(this.chunk_offsets.length);+ stream.writeUint32Array(this.chunk_offsets);+ }+ /** @bundle box-unpack.js */+ unpack(samples) {+ for (let i = 0; i < this.chunk_offsets.length; i++) samples[i].offset = this.chunk_offsets[i];+ }+};++//#endregion+//#region src/boxes/sthd.ts+var sthdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SubtitleMediaHeaderBox";+ }+ static {+ this.fourcc = "sthd";+ }+};++//#endregion+//#region src/boxes/stsc.ts+var stscBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SampleToChunkBox";+ }+ static {+ this.fourcc = "stsc";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const entry_count = stream.readUint32();+ this.first_chunk = [];+ this.samples_per_chunk = [];+ this.sample_description_index = [];+ if (this.version === 0) for (let i = 0; i < entry_count; i++) {+ this.first_chunk.push(stream.readUint32());+ this.samples_per_chunk.push(stream.readUint32());+ this.sample_description_index.push(stream.readUint32());+ }+ }+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 4 + 12 * this.first_chunk.length;+ this.writeHeader(stream);+ stream.writeUint32(this.first_chunk.length);+ for (let i = 0; i < this.first_chunk.length; i++) {+ stream.writeUint32(this.first_chunk[i]);+ stream.writeUint32(this.samples_per_chunk[i]);+ stream.writeUint32(this.sample_description_index[i]);+ }+ }+ unpack(samples) {+ let l = 0;+ let m = 0;+ for (let i = 0; i < this.first_chunk.length; i++) for (let j = 0; j < (i + 1 < this.first_chunk.length ? this.first_chunk[i + 1] : Infinity); j++) {+ m++;+ for (let k = 0; k < this.samples_per_chunk[i]; k++) {+ if (samples[l]) {+ samples[l].description_index = this.sample_description_index[i];+ samples[l].chunk_index = m;+ } else return;+ l++;+ }+ }+ }+};++//#endregion+//#region src/boxes/stsd.ts+var stsdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SampleDescriptionBox";+ }+ static {+ this.fourcc = "stsd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.entries = [];+ const entryCount = stream.readUint32();+ for (let i = 1; i <= entryCount; i++) {+ const ret = parseOneBox(stream, true, this.size - (stream.getPosition() - this.start));+ if (ret.code === 1) {+ let box;+ if (ret.type in BoxRegistry.sampleEntry) {+ box = new BoxRegistry.sampleEntry[ret.type](ret.size);+ box.hdr_size = ret.hdr_size;+ box.start = ret.start;+ } else {+ Log.warn("BoxParser", `Unknown sample entry type: '${ret.type}'`);+ box = new SampleEntry(ret.size, ret.hdr_size, ret.start);+ box.type = ret.type;+ }+ if (box.write === SampleEntry.prototype.write) {+ Log.info("BoxParser", "SampleEntry " + box.type + " box writing not yet implemented, keeping unparsed data in memory for later write");+ box.parseDataAndRewind(stream);+ }+ box.parse(stream);+ this.entries.push(box);+ } else return;+ }+ }+ /** @bundle writing/stsd.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 0;+ this.writeHeader(stream);+ stream.writeUint32(this.entries.length);+ this.size += 4;+ for (let i = 0; i < this.entries.length; i++) {+ this.entries[i].write(stream);+ this.size += this.entries[i].size;+ }+ Log.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size);+ stream.adjustUint32(this.sizePosition, this.size);+ }+};++//#endregion+//#region src/boxes/stsz.ts+var stszBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SampleSizeBox";+ }+ static {+ this.fourcc = "stsz";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.sample_sizes = [];+ if (this.version === 0) {+ this.sample_size = stream.readUint32();+ this.sample_count = stream.readUint32();+ for (let i = 0; i < this.sample_count; i++) if (this.sample_size === 0) this.sample_sizes.push(stream.readUint32());+ else this.sample_sizes[i] = this.sample_size;+ }+ }+ /** @bundle writing/stsz.js */+ write(stream) {+ let constant = true;+ this.version = 0;+ this.flags = 0;+ if (this.sample_sizes.length > 0 && this.sample_size === 0) constant = false;+ this.size = 8;+ if (!constant) this.size += 4 * this.sample_sizes.length;+ this.writeHeader(stream);+ stream.writeUint32(this.sample_size);+ stream.writeUint32(this.sample_sizes.length);+ if (!constant) stream.writeUint32Array(this.sample_sizes);+ }+ /** @bundle box-unpack.js */+ unpack(samples) {+ for (let i = 0; i < this.sample_sizes.length; i++) samples[i].size = this.sample_sizes[i];+ }+};++//#endregion+//#region src/boxes/stts.ts+var sttsBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TimeToSampleBox";+ this.sample_counts = [];+ this.sample_deltas = [];+ }+ static {+ this.fourcc = "stts";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ const entry_count = stream.readUint32();+ this.sample_counts.length = 0;+ this.sample_deltas.length = 0;+ if (this.version === 0) for (let i = 0; i < entry_count; i++) {+ this.sample_counts.push(stream.readUint32());+ let delta = stream.readInt32();+ if (delta < 0) {+ Log.warn("BoxParser", "File uses negative stts sample delta, using value 1 instead, sync may be lost!");+ delta = 1;+ }+ this.sample_deltas.push(delta);+ }+ }+ /** @bundle writing/stts.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 4 + 8 * this.sample_counts.length;+ this.writeHeader(stream);+ stream.writeUint32(this.sample_counts.length);+ for (let i = 0; i < this.sample_counts.length; i++) {+ stream.writeUint32(this.sample_counts[i]);+ stream.writeUint32(this.sample_deltas[i]);+ }+ }+ /** @bundle box-unpack.js */+ unpack(samples) {+ let k = 0;+ for (let i = 0; i < this.sample_counts.length; i++) for (let j = 0; j < this.sample_counts[i]; j++) {+ if (k === 0) samples[k].dts = 0;+ else samples[k].dts = samples[k - 1].dts + this.sample_deltas[i];+ k++;+ }+ }+};++//#endregion+//#region src/boxes/tfdt.ts+var tfdtBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackFragmentBaseMediaDecodeTimeBox";+ }+ static {+ this.fourcc = "tfdt";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 1) this.baseMediaDecodeTime = stream.readUint64();+ else this.baseMediaDecodeTime = stream.readUint32();+ }+ /** @bundle writing/tdft.js */+ write(stream) {+ const useVersion1 = this.baseMediaDecodeTime > MAX_UINT32 || this.version === 1;+ this.version = useVersion1 ? 1 : 0;+ this.size = 4;+ this.size += useVersion1 ? 4 : 0;+ this.flags = 0;+ this.writeHeader(stream);+ if (useVersion1) stream.writeUint64(this.baseMediaDecodeTime);+ else stream.writeUint32(this.baseMediaDecodeTime);+ }+};++//#endregion+//#region src/boxes/tfhd.ts+var tfhdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackFragmentHeaderBox";+ }+ static {+ this.fourcc = "tfhd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ let readBytes = 0;+ this.track_id = stream.readUint32();+ if (this.size - this.hdr_size > readBytes && this.flags & 1) {+ this.base_data_offset = stream.readUint64();+ readBytes += 8;+ } else this.base_data_offset = 0;+ if (this.size - this.hdr_size > readBytes && this.flags & 2) {+ this.default_sample_description_index = stream.readUint32();+ readBytes += 4;+ } else this.default_sample_description_index = 0;+ if (this.size - this.hdr_size > readBytes && this.flags & 8) {+ this.default_sample_duration = stream.readUint32();+ readBytes += 4;+ } else this.default_sample_duration = 0;+ if (this.size - this.hdr_size > readBytes && this.flags & 16) {+ this.default_sample_size = stream.readUint32();+ readBytes += 4;+ } else this.default_sample_size = 0;+ if (this.size - this.hdr_size > readBytes && this.flags & 32) {+ this.default_sample_flags = stream.readUint32();+ readBytes += 4;+ } else this.default_sample_flags = 0;+ }+ /** @bundle writing/tfhd.js */+ write(stream) {+ this.version = 0;+ this.size = 4;+ if (this.flags & 1) this.size += 8;+ if (this.flags & 2) this.size += 4;+ if (this.flags & 8) this.size += 4;+ if (this.flags & 16) this.size += 4;+ if (this.flags & 32) this.size += 4;+ this.writeHeader(stream);+ stream.writeUint32(this.track_id);+ if (this.flags & 1) stream.writeUint64(this.base_data_offset);+ if (this.flags & 2) stream.writeUint32(this.default_sample_description_index);+ if (this.flags & 8) stream.writeUint32(this.default_sample_duration);+ if (this.flags & 16) stream.writeUint32(this.default_sample_size);+ if (this.flags & 32) stream.writeUint32(this.default_sample_flags);+ }+};++//#endregion+//#region src/boxes/tkhd.ts+var tkhdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackHeaderBox";+ this.layer = 0;+ this.alternate_group = 0;+ }+ static {+ this.fourcc = "tkhd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 1) {+ this.creation_time = stream.readUint64();+ this.modification_time = stream.readUint64();+ this.track_id = stream.readUint32();+ stream.readUint32();+ this.duration = stream.readUint64();+ } else {+ this.creation_time = stream.readUint32();+ this.modification_time = stream.readUint32();+ this.track_id = stream.readUint32();+ stream.readUint32();+ this.duration = stream.readUint32();+ }+ stream.readUint32Array(2);+ this.layer = stream.readInt16();+ this.alternate_group = stream.readInt16();+ this.volume = stream.readInt16() >> 8;+ stream.readUint16();+ this.matrix = stream.readInt32Array(9);+ this.width = stream.readUint32();+ this.height = stream.readUint32();+ }+ write(stream) {+ const useVersion1 = this.modification_time > MAX_UINT32 || this.creation_time > MAX_UINT32 || this.duration > MAX_UINT32 || this.version === 1;+ this.version = useVersion1 ? 1 : 0;+ this.size = 80;+ this.size += useVersion1 ? 12 : 0;+ this.flags = this.flags ?? 3;+ this.writeHeader(stream);+ if (useVersion1) {+ stream.writeUint64(this.creation_time);+ stream.writeUint64(this.modification_time);+ stream.writeUint32(this.track_id);+ stream.writeUint32(0);+ stream.writeUint64(this.duration);+ } else {+ stream.writeUint32(this.creation_time);+ stream.writeUint32(this.modification_time);+ stream.writeUint32(this.track_id);+ stream.writeUint32(0);+ stream.writeUint32(this.duration);+ }+ stream.writeUint32Array([0, 0]);+ stream.writeInt16(this.layer);+ stream.writeInt16(this.alternate_group);+ stream.writeInt16(this.volume << 8);+ stream.writeInt16(0);+ stream.writeInt32Array(this.matrix);+ stream.writeUint32(this.width);+ stream.writeUint32(this.height);+ }+ /** @bundle box-print.js */+ print(output) {+ super.printHeader(output);+ output.log(output.indent + "creation_time: " + this.creation_time);+ output.log(output.indent + "modification_time: " + this.modification_time);+ output.log(output.indent + "track_id: " + this.track_id);+ output.log(output.indent + "duration: " + this.duration);+ output.log(output.indent + "volume: " + (this.volume >> 8));+ output.log(output.indent + "matrix: " + this.matrix.join(", "));+ output.log(output.indent + "layer: " + this.layer);+ output.log(output.indent + "alternate_group: " + this.alternate_group);+ output.log(output.indent + "width: " + this.width);+ output.log(output.indent + "height: " + this.height);+ }+};++//#endregion+//#region src/boxes/trex.ts+var trexBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackExtendsBox";+ }+ static {+ this.fourcc = "trex";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.track_id = stream.readUint32();+ this.default_sample_description_index = stream.readUint32();+ this.default_sample_duration = stream.readUint32();+ this.default_sample_size = stream.readUint32();+ this.default_sample_flags = stream.readUint32();+ }+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 20;+ this.writeHeader(stream);+ stream.writeUint32(this.track_id);+ stream.writeUint32(this.default_sample_description_index);+ stream.writeUint32(this.default_sample_duration);+ stream.writeUint32(this.default_sample_size);+ stream.writeUint32(this.default_sample_flags);+ }+};++//#endregion+//#region src/boxes/trun.ts+var trunBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "TrackRunBox";+ this.sample_duration = [];+ this.sample_size = [];+ this.sample_flags = [];+ this.sample_composition_time_offset = [];+ }+ static {+ this.fourcc = "trun";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ let readBytes = 0;+ this.sample_count = stream.readUint32();+ readBytes += 4;+ if (this.size - this.hdr_size > readBytes && this.flags & 1) {+ this.data_offset = stream.readInt32();+ readBytes += 4;+ } else this.data_offset = 0;+ if (this.size - this.hdr_size > readBytes && this.flags & 4) {+ this.first_sample_flags = stream.readUint32();+ readBytes += 4;+ } else this.first_sample_flags = 0;+ this.sample_duration = [];+ this.sample_size = [];+ this.sample_flags = [];+ this.sample_composition_time_offset = [];+ if (this.size - this.hdr_size > readBytes) for (let i = 0; i < this.sample_count; i++) {+ if (this.flags & 256) this.sample_duration[i] = stream.readUint32();+ if (this.flags & 512) this.sample_size[i] = stream.readUint32();+ if (this.flags & 1024) this.sample_flags[i] = stream.readUint32();+ if (this.flags & 2048) if (this.version === 0) this.sample_composition_time_offset[i] = stream.readUint32();+ else this.sample_composition_time_offset[i] = stream.readInt32();+ }+ }+ /** @bundle writing/trun.js */+ write(stream) {+ this.size = 4;+ if (this.flags & 1) this.size += 4;+ if (this.flags & 4) this.size += 4;+ if (this.flags & 256) this.size += 4 * this.sample_duration.length;+ if (this.flags & 512) this.size += 4 * this.sample_size.length;+ if (this.flags & 1024) this.size += 4 * this.sample_flags.length;+ if (this.flags & 2048) this.size += 4 * this.sample_composition_time_offset.length;+ this.writeHeader(stream);+ stream.writeUint32(this.sample_count);+ if (this.flags & 1) {+ this.data_offset_position = stream.getPosition();+ stream.writeInt32(this.data_offset);+ }+ if (this.flags & 4) stream.writeUint32(this.first_sample_flags);+ for (let i = 0; i < this.sample_count; i++) {+ if (this.flags & 256) stream.writeUint32(this.sample_duration[i]);+ if (this.flags & 512) stream.writeUint32(this.sample_size[i]);+ if (this.flags & 1024) stream.writeUint32(this.sample_flags[i]);+ if (this.flags & 2048) if (this.version === 0) stream.writeUint32(this.sample_composition_time_offset[i]);+ else stream.writeInt32(this.sample_composition_time_offset[i]);+ }+ }+};++//#endregion+//#region src/boxes/url.ts+var urlBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "DataEntryUrlBox";+ }+ static {+ this.fourcc = "url ";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.flags !== 1) this.location = stream.readCString();+ }+ /** @bundle writing/url.js */+ write(stream) {+ this.version = 0;+ if (this.location) {+ this.flags = 0;+ this.size = this.location.length + 1;+ } else {+ this.flags = 1;+ this.size = 0;+ }+ this.writeHeader(stream);+ if (this.location) stream.writeCString(this.location);+ }+};++//#endregion+//#region src/boxes/vmhd.ts+var vmhdBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "VideoMediaHeaderBox";+ }+ static {+ this.fourcc = "vmhd";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.graphicsmode = stream.readUint16();+ this.opcolor = stream.readUint16Array(3);+ }+ /** @bundle writing/vmhd.js */+ write(stream) {+ this.version = 0;+ this.size = 8;+ this.writeHeader(stream);+ stream.writeUint16(this.graphicsmode);+ stream.writeUint16Array(this.opcolor);+ }+};++//#endregion+//#region src/isofile.ts+var SampleGroupInfo = class {+ constructor(grouping_type, grouping_type_parameter, sbgp) {+ this.grouping_type = grouping_type;+ this.grouping_type_parameter = grouping_type_parameter;+ this.sbgp = sbgp;+ this.last_sample_in_run = -1;+ this.entry_index = -1;+ }+};+var ISOFile = class ISOFile {+ constructor(stream, discardMdatData = true) {+ this.boxes = [];+ this.mdats = [];+ this.moofs = [];+ this.isProgressive = false;+ this.moovStartFound = false;+ this.moovStartSent = false;+ this.readySent = false;+ this.sampleListBuilt = false;+ this.fragmentedTracks = [];+ this.extractedTracks = [];+ this.isFragmentationInitialized = false;+ this.sampleProcessingStarted = false;+ this.nextMoofNumber = 0;+ this.itemListBuilt = false;+ this.sidxSent = false;+ this.items = [];+ this.entity_groups = [];+ this.itemsDataSize = 0;+ this.lastMoofIndex = 0;+ this.samplesDataSize = 0;+ this.lastBoxStartPosition = 0;+ this.nextParsePosition = 0;+ this.discardMdatData = true;+ this.discardMdatData = discardMdatData;+ if (stream) {+ this.stream = stream;+ this.parse();+ } else this.stream = new MultiBufferStream();+ this.stream.isofile = this;+ }+ setSegmentOptions(id, user, opts) {+ const { sizePerSegment = Number.MAX_SAFE_INTEGER, rapAlignement = true, normalizeAudioSampleEntriesForMSE = true } = opts;+ let nbSamples = opts.nbSamples ?? opts.nbSamplesPerFragment ?? 1e3;+ const nbSamplesPerFragment = opts.nbSamplesPerFragment ?? nbSamples;+ if (nbSamples <= 0 || nbSamplesPerFragment <= 0 || sizePerSegment <= 0) {+ Log.error("ISOFile", `Invalid segment options: nbSamples=${nbSamples}, nbSamplesPerFragment=${nbSamplesPerFragment}, sizePerSegment=${sizePerSegment}`);+ return;+ }+ if (nbSamples < nbSamplesPerFragment) {+ Log.warn("ISOFile", `nbSamples (${nbSamples}) is less than nbSamplesPerFragment (${nbSamplesPerFragment}), setting nbSamples to nbSamplesPerFragment`);+ nbSamples = nbSamplesPerFragment;+ }+ if (this.fragmentedTracks.some((track) => track.nb_samples !== nbSamples)) {+ Log.error("ISOFile", `Cannot set segment options for track ${id}: nbSamples (${nbSamples}) does not match existing tracks`);+ return;+ }+ const trak = this.getTrackById(id);+ if (trak) {+ const fragTrack = {+ id,+ user,+ trak,+ segmentStream: void 0,+ nb_samples: nbSamples,+ nb_samples_per_fragment: nbSamplesPerFragment,+ size_per_segment: sizePerSegment,+ rapAlignement,+ normalizeAudioSampleEntriesForMSE,+ state: {+ lastFragmentSampleNumber: 0,+ lastSegmentSampleNumber: 0,+ accumulatedSize: 0+ }+ };+ this.fragmentedTracks.push(fragTrack);+ trak.nextSample = 0;+ }+ if (this.discardMdatData) Log.warn("ISOFile", "Segmentation options set but discardMdatData is true, samples will not be segmented");+ }+ unsetSegmentOptions(id) {+ let index = -1;+ for (let i = 0; i < this.fragmentedTracks.length; i++) if (this.fragmentedTracks[i].id === id) index = i;+ if (index > -1) this.fragmentedTracks.splice(index, 1);+ }+ setExtractionOptions(id, user, { nbSamples: nb_samples = 1e3 } = {}) {+ const trak = this.getTrackById(id);+ if (trak) {+ this.extractedTracks.push({+ id,+ user,+ trak,+ nb_samples,+ samples: []+ });+ trak.nextSample = 0;+ }+ if (this.discardMdatData) Log.warn("ISOFile", "Extraction options set but discardMdatData is true, samples will not be extracted");+ }+ unsetExtractionOptions(id) {+ let index = -1;+ for (let i = 0; i < this.extractedTracks.length; i++) if (this.extractedTracks[i].id === id) index = i;+ if (index > -1) this.extractedTracks.splice(index, 1);+ }+ parse() {+ const parseBoxHeadersOnly = false;+ if (this.restoreParsePosition) {+ if (!this.restoreParsePosition()) return;+ }+ while (true) if (this.hasIncompleteMdat && this.hasIncompleteMdat()) if (this.processIncompleteMdat()) continue;+ else return;+ else {+ if (this.saveParsePosition) this.saveParsePosition();+ const ret = parseOneBox(this.stream, parseBoxHeadersOnly);+ if (ret.code === 0) if (this.processIncompleteBox) if (this.processIncompleteBox(ret)) continue;+ else return;+ else return;+ else if (ret.code === 1) {+ const box = ret.box;+ this.boxes.push(box);+ if (box.type === "uuid") {+ if (this[box.uuid] !== void 0) Log.warn("ISOFile", "Duplicate Box of uuid: " + box.uuid + ", overriding previous occurrence");+ this[box.uuid] = box;+ } else switch (box.type) {+ case "mdat":+ this.mdats.push(box);+ this.transferMdatData(box);+ break;+ case "moof":+ this.moofs.push(box);+ break;+ case "free":+ case "skip": break;+ case "moov":+ this.moovStartFound = true;+ if (this.mdats.length === 0) this.isProgressive = true;+ default:+ if (this[box.type] !== void 0) if (Array.isArray(this[box.type + "s"])) {+ Log.info("ISOFile", `Found multiple boxes of type ${box.type} in ISOFile, adding to array`);+ this[box.type + "s"].push(box);+ } else {+ Log.warn("ISOFile", `Found multiple boxes of type ${box.type} but no array exists. Creating array dynamically.`);+ this[box.type + "s"] = [this[box.type], box];+ }+ else {+ this[box.type] = box;+ if (Array.isArray(this[box.type + "s"])) this[box.type + "s"].push(box);+ }+ break;+ }+ if (this.updateUsedBytes) this.updateUsedBytes(box, ret);+ } else if (ret.code === -1) {+ Log.error("ISOFile", `Invalid data found while parsing box of type '${ret.type}' at position ${ret.start}. Aborting parsing.`, this);+ break;+ }+ }+ }+ checkBuffer(ab) {+ if (!ab) throw new Error("Buffer must be defined and non empty");+ if (ab.byteLength === 0) {+ Log.warn("ISOFile", "Ignoring empty buffer (fileStart: " + ab.fileStart + ")");+ this.stream.logBufferLevel();+ return false;+ }+ Log.info("ISOFile", "Processing buffer (fileStart: " + ab.fileStart + ")");+ ab.usedBytes = 0;+ this.stream.insertBuffer(ab);+ this.stream.logBufferLevel();+ if (!this.stream.initialized()) {+ Log.warn("ISOFile", "Not ready to start parsing");+ return false;+ }+ return true;+ }+ /**+ * Processes a new ArrayBuffer (with a fileStart property)+ * Returns the next expected file position, or undefined if not ready to parse+ */+ appendBuffer(ab, last) {+ let nextFileStart;+ if (!this.checkBuffer(ab)) return;+ this.parse();+ if (this.moovStartFound && !this.moovStartSent) {+ this.moovStartSent = true;+ if (this.onMoovStart) this.onMoovStart();+ }+ if (this.moov) {+ if (!this.sampleListBuilt) {+ this.buildSampleLists();+ this.sampleListBuilt = true;+ }+ this.updateSampleLists();+ if (this.onReady && !this.readySent) {+ this.readySent = true;+ this.onReady(this.getInfo());+ }+ this.processSamples(last);+ if (this.nextSeekPosition) {+ nextFileStart = this.nextSeekPosition;+ this.nextSeekPosition = void 0;+ } else nextFileStart = this.nextParsePosition;+ if (this.stream.getEndFilePositionAfter) nextFileStart = this.stream.getEndFilePositionAfter(nextFileStart);+ } else if (this.nextParsePosition) nextFileStart = this.nextParsePosition;+ else nextFileStart = 0;+ if (this.sidx) {+ if (this.onSidx && !this.sidxSent) {+ this.onSidx(this.sidx);+ this.sidxSent = true;+ }+ }+ if (this.meta) {+ if (this.flattenItemInfo && !this.itemListBuilt) {+ this.flattenItemInfo();+ this.itemListBuilt = true;+ }+ if (this.processItems) this.processItems(this.onItem);+ }+ if (this.stream.cleanBuffers) {+ Log.info("ISOFile", "Done processing buffer (fileStart: " + ab.fileStart + ") - next buffer to fetch should have a fileStart position of " + nextFileStart);+ this.stream.logBufferLevel();+ this.stream.cleanBuffers();+ this.stream.logBufferLevel(true);+ Log.info("ISOFile", "Sample data size in memory: " + this.getAllocatedSampleDataSize());+ }+ return nextFileStart;+ }+ getFragmentDuration() {+ const mvex = this.getBox("mvex");+ if (!mvex) return;+ if (mvex.mehd) return {+ num: mvex.mehd.fragment_duration,+ den: this.moov.mvhd.timescale+ };+ const traks = this.getBoxes("trak", false);+ let maximum = {+ num: 0,+ den: 1+ };+ for (const trak of traks) {+ const duration = trak.samples_duration;+ const timescale = trak.mdia.mdhd.timescale;+ if (duration && timescale) {+ if (duration / timescale > maximum.num / maximum.den) maximum = {+ num: duration,+ den: timescale+ };+ }+ }+ return maximum;+ }+ getInfo() {+ if (!this.moov) return {+ hasMoov: false,+ mime: ""+ };+ const _1904 = (/* @__PURE__ */ new Date("1904-01-01T00:00:00Z")).getTime();+ const isFragmented = this.getBox("mvex") !== void 0;+ const movie = {+ hasMoov: true,+ duration: this.moov.mvhd.duration,+ timescale: this.moov.mvhd.timescale,+ isFragmented,+ fragment_duration: this.getFragmentDuration(),+ isProgressive: this.isProgressive,+ hasIOD: this.moov.iods !== void 0,+ brands: [this.ftyp.major_brand].concat(this.ftyp.compatible_brands),+ created: new Date(_1904 + this.moov.mvhd.creation_time * 1e3),+ modified: new Date(_1904 + this.moov.mvhd.modification_time * 1e3),+ tracks: [],+ audioTracks: [],+ videoTracks: [],+ subtitleTracks: [],+ metadataTracks: [],+ hintTracks: [],+ otherTracks: [],+ mime: ""+ };+ for (let i = 0; i < this.moov.traks.length; i++) {+ const trak = this.moov.traks[i];+ const sample_desc = trak.mdia.minf.stbl.stsd.entries[0];+ const size = trak.samples_size;+ const track_timescale = trak.mdia.mdhd.timescale;+ const samples_duration = trak.samples_duration;+ const track = {+ samples_duration,+ bitrate: size * 8 * track_timescale / samples_duration,+ size,+ timescale: track_timescale,+ alternate_group: trak.tkhd.alternate_group,+ codec: sample_desc.getCodec(),+ created: new Date(_1904 + trak.tkhd.creation_time * 1e3),+ cts_shift: trak.mdia.minf.stbl.cslg,+ duration: trak.mdia.mdhd.duration,+ id: trak.tkhd.track_id,+ kind: trak.udta && trak.udta.kinds.length ? trak.udta.kinds[0] : {+ schemeURI: "",+ value: ""+ },+ language: trak.mdia.elng ? trak.mdia.elng.extended_language : trak.mdia.mdhd.languageString,+ layer: trak.tkhd.layer,+ matrix: trak.tkhd.matrix,+ modified: new Date(_1904 + trak.tkhd.modification_time * 1e3),+ movie_duration: trak.tkhd.duration,+ movie_timescale: movie.timescale,+ name: trak.mdia.hdlr.name,+ nb_samples: trak.samples.length,+ references: [],+ track_height: trak.tkhd.height / 65536,+ track_width: trak.tkhd.width / 65536,+ volume: trak.tkhd.volume+ };+ movie.tracks.push(track);+ if (trak.tref) for (let j = 0; j < trak.tref.references.length; j++) track.references.push({+ type: trak.tref.references[j].type,+ track_ids: trak.tref.references[j].track_ids+ });+ if (trak.edts !== void 0 && trak.edts.elst !== void 0) track.edits = trak.edts.elst.entries;+ if (sample_desc instanceof AudioSampleEntry) {+ track.type = "audio";+ movie.audioTracks.push(track);+ track.audio = {+ sample_rate: sample_desc.getSampleRate(),+ channel_count: sample_desc.getChannelCount(),+ sample_size: sample_desc.getSampleSize()+ };+ } else if (sample_desc instanceof VisualSampleEntry) {+ track.type = "video";+ movie.videoTracks.push(track);+ track.video = {+ width: sample_desc.getWidth(),+ height: sample_desc.getHeight()+ };+ } else if (sample_desc instanceof SubtitleSampleEntry) {+ track.type = "subtitles";+ movie.subtitleTracks.push(track);+ } else if (sample_desc instanceof HintSampleEntry) {+ track.type = "metadata";+ movie.hintTracks.push(track);+ } else if (sample_desc instanceof MetadataSampleEntry) {+ track.type = "metadata";+ movie.metadataTracks.push(track);+ } else {+ track.type = "metadata";+ movie.otherTracks.push(track);+ }+ }+ if (movie.videoTracks && movie.videoTracks.length > 0) movie.mime += "video/mp4; codecs=\"";+ else if (movie.audioTracks && movie.audioTracks.length > 0) movie.mime += "audio/mp4; codecs=\"";+ else movie.mime += "application/mp4; codecs=\"";+ for (let i = 0; i < movie.tracks.length; i++) {+ if (i !== 0) movie.mime += ",";+ movie.mime += movie.tracks[i].codec;+ }+ movie.mime += "\"; profiles=\"";+ movie.mime += this.ftyp.compatible_brands.join();+ movie.mime += "\"";+ return movie;+ }+ setNextSeekPositionFromSample(sample) {+ if (!sample) return;+ if (this.nextSeekPosition) this.nextSeekPosition = Math.min(sample.offset + sample.alreadyRead, this.nextSeekPosition);+ else this.nextSeekPosition = sample.offset + sample.alreadyRead;+ }+ processSamples(last) {+ if (!this.sampleProcessingStarted) return;+ if (this.isFragmentationInitialized && this.onSegment !== void 0) {+ const consumedTracks = /* @__PURE__ */ new Set();+ while (consumedTracks.size < this.fragmentedTracks.length && this.fragmentedTracks.some((track) => track.trak.nextSample < track.trak.samples.length) && this.sampleProcessingStarted) for (const fragTrak of this.fragmentedTracks) {+ const trak = fragTrak.trak;+ if (!consumedTracks.has(fragTrak.id)) {+ const sample = trak.nextSample < trak.samples.length ? this.getSample(trak, trak.nextSample) : void 0;+ if (!sample) {+ this.setNextSeekPositionFromSample(trak.samples[trak.nextSample]);+ consumedTracks.add(fragTrak.id);+ continue;+ }+ fragTrak.state.accumulatedSize += sample.size;+ const sampleNum = trak.nextSample + 1;+ const isFragmentOverdue = sampleNum - fragTrak.state.lastFragmentSampleNumber > fragTrak.nb_samples_per_fragment;+ const isSegmentOverdue = sampleNum - fragTrak.state.lastSegmentSampleNumber > fragTrak.nb_samples;+ let isFragmentBoundary = isFragmentOverdue || sampleNum % fragTrak.nb_samples_per_fragment === 0;+ let isSegmentBoundary = isSegmentOverdue || sampleNum % fragTrak.nb_samples === 0;+ let isSizeBoundary = fragTrak.state.accumulatedSize >= fragTrak.size_per_segment;+ const isRAP = !fragTrak.rapAlignement || sample.is_sync;+ const isFlush = last || trak.nextSample + 1 >= trak.samples.length;+ if (isFlush && !isRAP) Log.warn("ISOFile", "Flushing track #" + fragTrak.id + " at sample #" + trak.nextSample + " which is not a RAP, this may lead to playback issues");+ isFragmentBoundary = isFragmentBoundary && isRAP;+ isSegmentBoundary = isSegmentBoundary && isRAP;+ isSizeBoundary = isSizeBoundary && isRAP;+ if (isFragmentBoundary || isSizeBoundary || isFlush) {+ if (isFragmentOverdue) Log.warn("ISOFile", "Fragment on track #" + fragTrak.id + " is overdue, creating it with samples [" + fragTrak.state.lastFragmentSampleNumber + ", " + trak.nextSample + "]");+ else Log.debug("ISOFile", "Creating media fragment on track #" + fragTrak.id + " for samples [" + fragTrak.state.lastFragmentSampleNumber + ", " + trak.nextSample + "]");+ const result = this.createFragment(fragTrak.id, fragTrak.state.lastFragmentSampleNumber, trak.nextSample, fragTrak.segmentStream);+ if (result) {+ fragTrak.segmentStream = result;+ fragTrak.state.lastFragmentSampleNumber = trak.nextSample + 1;+ } else {+ consumedTracks.add(fragTrak.id);+ continue;+ }+ }+ if (isSegmentBoundary || isSizeBoundary || isFlush) {+ if (isSegmentOverdue) Log.warn("ISOFile", "Segment on track #" + fragTrak.id + " is overdue, sending it with samples [" + Math.max(0, trak.nextSample - fragTrak.nb_samples) + ", " + (trak.nextSample - 1) + "]");+ else Log.info("ISOFile", "Sending fragmented data on track #" + fragTrak.id + " for samples [" + Math.max(0, trak.nextSample - fragTrak.nb_samples) + ", " + (trak.nextSample - 1) + "]");+ Log.info("ISOFile", "Sample data size in memory: " + this.getAllocatedSampleDataSize());+ if (this.onSegment) this.onSegment(fragTrak.id, fragTrak.user, fragTrak.segmentStream.buffer, trak.nextSample + 1, last || trak.nextSample + 1 >= trak.samples.length);+ fragTrak.segmentStream = void 0;+ fragTrak.state.accumulatedSize = 0;+ fragTrak.state.lastSegmentSampleNumber = trak.nextSample + 1;+ }+ trak.nextSample++;+ }+ }+ }+ if (this.onSamples !== void 0) for (let i = 0; i < this.extractedTracks.length; i++) {+ const extractTrak = this.extractedTracks[i];+ const trak = extractTrak.trak;+ while (trak.nextSample < trak.samples.length && this.sampleProcessingStarted) {+ Log.debug("ISOFile", "Exporting on track #" + extractTrak.id + " sample #" + trak.nextSample);+ const sample = this.getSample(trak, trak.nextSample);+ if (sample) {+ trak.nextSample++;+ extractTrak.samples.push(sample);+ } else {+ this.setNextSeekPositionFromSample(trak.samples[trak.nextSample]);+ break;+ }+ if (trak.nextSample % extractTrak.nb_samples === 0 || trak.nextSample >= trak.samples.length) {+ Log.debug("ISOFile", "Sending samples on track #" + extractTrak.id + " for sample " + trak.nextSample);+ if (this.onSamples) this.onSamples(extractTrak.id, extractTrak.user, extractTrak.samples);+ extractTrak.samples = [];+ if (extractTrak !== this.extractedTracks[i]) break;+ }+ }+ }+ }+ getBox(type) {+ const result = this.getBoxes(type, true);+ return result.length ? result[0] : void 0;+ }+ getBoxes(type, returnEarly) {+ const result = [];+ const sweep = (root) => {+ if (root instanceof Box && root.type && root.type === type) result.push(root);+ const inner = [];+ if (root["boxes"]) inner.push(...root.boxes);+ if (root["entries"]) inner.push(...root["entries"]);+ if (root["item_infos"]) inner.push(...root["item_infos"]);+ if (root["references"]) inner.push(...root["references"]);+ for (const box of inner) {+ if (result.length && returnEarly) return;+ sweep(box);+ }+ };+ sweep(this);+ return result;+ }+ getTrackSamplesInfo(track_id) {+ const track = this.getTrackById(track_id);+ if (track) return track.samples;+ }+ getTrackSample(track_id, number) {+ const track = this.getTrackById(track_id);+ return this.getSample(track, number);+ }+ releaseUsedSamples(id, sampleNum) {+ let size = 0;+ const trak = this.getTrackById(id);+ if (!trak.lastValidSample) trak.lastValidSample = 0;+ for (let i = trak.lastValidSample; i < sampleNum; i++) size += this.releaseSample(trak, i);+ Log.info("ISOFile", "Track #" + id + " released samples up to " + sampleNum + " (released size: " + size + ", remaining: " + this.samplesDataSize + ")");+ trak.lastValidSample = sampleNum;+ }+ start() {+ this.sampleProcessingStarted = true;+ this.processSamples(false);+ }+ stop() {+ this.sampleProcessingStarted = false;+ }+ flush() {+ Log.info("ISOFile", "Flushing remaining samples");+ this.updateSampleLists();+ this.processSamples(true);+ this.stream.cleanBuffers();+ this.stream.logBufferLevel(true);+ }+ seekTrack(time, useRap, trak) {+ let rap_seek_sample_num = 0;+ let seek_sample_num = 0;+ let timescale;+ if (trak.samples.length === 0) {+ Log.info("ISOFile", "No sample in track, cannot seek! Using time " + Log.getDurationString(0, 1) + " and offset: 0");+ return {+ offset: 0,+ time: 0+ };+ }+ for (let j = 0; j < trak.samples.length; j++) {+ const sample = trak.samples[j];+ if (j === 0) {+ seek_sample_num = 0;+ timescale = sample.timescale;+ } else if (sample.cts > time * sample.timescale) {+ seek_sample_num = j - 1;+ break;+ }+ if (useRap && sample.is_sync) rap_seek_sample_num = j;+ }+ if (useRap) seek_sample_num = rap_seek_sample_num;+ time = trak.samples[seek_sample_num].cts;+ trak.nextSample = seek_sample_num;+ this.resetFragmentedTrackStateAfterSeek(trak, seek_sample_num);+ this.resetExtractedTrackStateAfterSeek(trak);+ while (trak.samples[seek_sample_num].alreadyRead === trak.samples[seek_sample_num].size) {+ if (!trak.samples[seek_sample_num + 1]) break;+ seek_sample_num++;+ }+ const seek_offset = trak.samples[seek_sample_num].offset + trak.samples[seek_sample_num].alreadyRead;+ Log.info("ISOFile", "Seeking to " + (useRap ? "RAP" : "") + " sample #" + trak.nextSample + " on track " + trak.tkhd.track_id + ", time " + Log.getDurationString(time, timescale) + " and offset: " + seek_offset);+ return {+ offset: seek_offset,+ time: time / timescale+ };+ }+ resetFragmentedTrackStateAfterSeek(trak, seekSampleNumber) {+ const fragTrack = this.fragmentedTracks.find((t) => t.trak === trak);+ if (!fragTrack) return;+ fragTrack.state.lastFragmentSampleNumber = seekSampleNumber;+ fragTrack.state.lastSegmentSampleNumber = seekSampleNumber;+ fragTrack.state.accumulatedSize = 0;+ fragTrack.segmentStream = void 0;+ }+ resetExtractedTrackStateAfterSeek(trak) {+ const extractTrack = this.extractedTracks.find((t) => t.trak === trak);+ if (!extractTrack) return;+ extractTrack.samples = [];+ }+ getTrackDuration(trak) {+ if (!trak.samples) return Infinity;+ const sample = trak.samples[trak.samples.length - 1];+ return (sample.cts + sample.duration) / sample.timescale;+ }+ seek(time, useRap) {+ const moov = this.moov;+ let seek_info = {+ offset: Infinity,+ time: Infinity+ };+ if (!this.moov) throw new Error("Cannot seek: moov not received!");+ else {+ for (let i = 0; i < moov.traks.length; i++) {+ const trak = moov.traks[i];+ if (time > this.getTrackDuration(trak)) continue;+ const trak_seek_info = this.seekTrack(time, useRap, trak);+ if (trak_seek_info.offset < seek_info.offset) seek_info.offset = trak_seek_info.offset;+ if (trak_seek_info.time < seek_info.time) seek_info.time = trak_seek_info.time;+ }+ Log.info("ISOFile", "Seeking at time " + Log.getDurationString(seek_info.time, 1) + " needs a buffer with a fileStart position of " + seek_info.offset);+ if (seek_info.offset === Infinity) seek_info = {+ offset: this.nextParsePosition,+ time: 0+ };+ else seek_info.offset = this.stream.getEndFilePositionAfter(seek_info.offset);+ Log.info("ISOFile", "Adjusted seek position (after checking data already in buffer): " + seek_info.offset);+ return seek_info;+ }+ }+ equal(b) {+ let box_index = 0;+ while (box_index < this.boxes.length && box_index < b.boxes.length) {+ const a_box = this.boxes[box_index];+ const b_box = b.boxes[box_index];+ if (!boxEqual(a_box, b_box)) return false;+ box_index++;+ }+ return true;+ }+ /**+ * Rewrite the entire file+ * @bundle isofile-write.js+ */+ write(outstream) {+ for (let i = 0; i < this.boxes.length; i++) this.boxes[i].write(outstream);+ }+ /** @bundle isofile-write.js */+ createFragment(track_id, sampleStart, sampleEnd, existingStream) {+ if (sampleEnd < sampleStart) {+ Log.warn("ISOFile", `Skipping fragment creation on track #${track_id}: invalid sample range [${sampleStart}, ${sampleEnd}]`);+ return existingStream || new DataStream();+ }+ const samples = [];+ for (let i = sampleStart; i <= sampleEnd; i++) {+ const trak = this.getTrackById(track_id);+ const sample = this.getSample(trak, i);+ if (!sample) {+ this.setNextSeekPositionFromSample(trak.samples[i]);+ return;+ }+ samples.push(sample);+ }+ const stream = existingStream || new DataStream();+ const moof = this.createMoof(samples);+ moof.write(stream);+ moof.trafs[0].truns[0].data_offset = moof.size + 8;+ Log.debug("MP4Box", "Adjusting data_offset with new value " + moof.trafs[0].truns[0].data_offset);+ stream.adjustUint32(moof.trafs[0].truns[0].data_offset_position, moof.trafs[0].truns[0].data_offset);+ const mdat = new mdatBox();+ mdat.stream = new MultiBufferStream();+ let offset = 0;+ for (const sample of samples) if (sample.data) {+ const mp4Buffer = MP4BoxBuffer.fromArrayBuffer(sample.data.buffer, offset);+ mdat.stream.insertBuffer(mp4Buffer);+ offset += sample.data.byteLength;+ }+ mdat.write(stream);+ return stream;+ }+ /**+ * Modify the file and create the initialization segment+ * @bundle isofile-write.js+ */+ static writeInitializationSegment(ftyp, moov, total_duration, normalizeAudioSampleEntryTrackIds) {+ Log.debug("ISOFile", "Generating initialization segment");+ const stream = new DataStream();+ ftyp.write(stream);+ const restoreCallbacks = ISOFile.normalizeAudioSampleEntriesForMSEFragmentedInit(moov.traks, normalizeAudioSampleEntryTrackIds);+ try {+ const mvex = moov.addBox(new mvexBox());+ if (total_duration) {+ const mehd = mvex.addBox(new mehdBox());+ mehd.fragment_duration = total_duration;+ }+ for (let i = 0; i < moov.traks.length; i++) {+ const trex = mvex.addBox(new trexBox());+ trex.track_id = moov.traks[i].tkhd.track_id;+ trex.default_sample_description_index = 1;+ trex.default_sample_duration = moov.traks[i].samples[0]?.duration ?? 0;+ trex.default_sample_size = 0;+ trex.default_sample_flags = 65536;+ }+ moov.write(stream);+ } finally {+ for (let i = restoreCallbacks.length - 1; i >= 0; i--) restoreCallbacks[i]();+ }+ return stream.buffer;+ }+ /** @bundle isofile-write.js */+ save(name) {+ const stream = new DataStream();+ stream.isofile = this;+ this.write(stream);+ return stream.save(name);+ }+ /** @bundle isofile-write.js */+ getBuffer() {+ const stream = new DataStream();+ stream.isofile = this;+ this.write(stream);+ return stream;+ }+ /** @bundle isofile-write.js */+ static normalizeAudioSampleEntriesForMSEFragmentedInit(traks, normalizeAudioSampleEntryTrackIds) {+ const restoreCallbacks = [];+ for (const trak of traks) {+ if (!normalizeAudioSampleEntryTrackIds?.has(trak.tkhd.track_id)) continue;+ for (const sampleEntry of trak.mdia.minf.stbl.stsd?.entries ?? []) {+ if (!(sampleEntry instanceof mp4aSampleEntry)) continue;+ const esds = sampleEntry.wave?.esds;+ if (sampleEntry.esds || !esds) continue;+ const previousEsds = sampleEntry.esds;+ const previousWave = sampleEntry.wave;+ const previousBoxes = sampleEntry.boxes;+ restoreCallbacks.push(() => {+ sampleEntry.esds = previousEsds;+ sampleEntry.wave = previousWave;+ sampleEntry.boxes = previousBoxes;+ });+ const boxesWithoutWave = Array.isArray(sampleEntry.boxes) ? sampleEntry.boxes.filter((box) => box?.type !== "wave" && box?.type !== "esds") : [];+ sampleEntry.esds = esds;+ sampleEntry.boxes = [...boxesWithoutWave, esds];+ sampleEntry.wave = void 0;+ }+ }+ return restoreCallbacks;+ }+ initializeSegmentation(mode) {+ if (!this.onSegment) Log.warn("MP4Box", "No segmentation callback set!");+ if (mode !== void 0 && mode !== "combined" && mode !== "per-track") throw new Error(`Invalid segmentation mode: ${mode}`);+ if (!this.isFragmentationInitialized) {+ this.isFragmentationInitialized = true;+ this.resetTables();+ }+ const tracksToInitialize = [];+ for (const fragmentedTrack of this.fragmentedTracks) {+ const trak = this.getTrackById(fragmentedTrack.id);+ if (!trak) {+ Log.warn("ISOFile", `Track with id ${fragmentedTrack.id} not found, skipping fragmentation initialization`);+ continue;+ }+ tracksToInitialize.push({+ id: fragmentedTrack.id,+ user: fragmentedTrack.user,+ trak+ });+ }+ const fragmentDuration = this.moov?.mvex?.mehd?.fragment_duration;+ const normalizeAudioSampleEntryTrackIds = new Set(this.fragmentedTracks.filter((track) => track.normalizeAudioSampleEntriesForMSE !== false).map((track) => track.id));+ if (mode === "per-track") return tracksToInitialize.map(({ id, user, trak }) => {+ const moov = new moovBox();+ moov.addBox(this.moov.mvhd);+ moov.addBox(trak);+ return {+ id,+ user,+ buffer: ISOFile.writeInitializationSegment(this.ftyp, moov, fragmentDuration, normalizeAudioSampleEntryTrackIds)+ };+ });+ const moov = new moovBox();+ moov.addBox(this.moov.mvhd);+ for (const track of tracksToInitialize) moov.addBox(track.trak);+ return {+ tracks: tracksToInitialize.map(({ id, user }) => ({+ id,+ user+ })),+ buffer: ISOFile.writeInitializationSegment(this.ftyp, moov, fragmentDuration, normalizeAudioSampleEntryTrackIds)+ };+ }+ /**+ * Resets all sample tables+ * @bundle isofile-sample-processing.js+ */+ resetTables() {+ this.initial_duration = this.moov.mvhd.duration;+ this.moov.mvhd.duration = 0;+ for (let i = 0; i < this.moov.traks.length; i++) {+ const trak = this.moov.traks[i];+ trak.tkhd.duration = 0;+ trak.mdia.mdhd.duration = 0;+ const stco = trak.mdia.minf.stbl.stco || trak.mdia.minf.stbl.co64;+ stco.chunk_offsets = [];+ const stsc = trak.mdia.minf.stbl.stsc;+ stsc.first_chunk = [];+ stsc.samples_per_chunk = [];+ stsc.sample_description_index = [];+ const stsz = trak.mdia.minf.stbl.stsz || trak.mdia.minf.stbl.stz2;+ stsz.sample_sizes = [];+ const stts = trak.mdia.minf.stbl.stts;+ stts.sample_counts = [];+ stts.sample_deltas = [];+ const ctts = trak.mdia.minf.stbl.ctts;+ if (ctts) {+ ctts.sample_counts = [];+ ctts.sample_offsets = [];+ }+ const stss = trak.mdia.minf.stbl.stss;+ const k = trak.mdia.minf.stbl.boxes.indexOf(stss);+ if (k !== -1) trak.mdia.minf.stbl.boxes[k] = void 0;+ }+ }+ /** @bundle isofile-sample-processing.js */+ static initSampleGroups(trak, traf, sbgps, trak_sgpds, traf_sgpds) {+ if (traf) traf.sample_groups_info = [];+ if (!trak.sample_groups_info) trak.sample_groups_info = [];+ for (let k = 0; k < sbgps.length; k++) {+ const sample_group_key = sbgps[k].grouping_type + "/" + sbgps[k].grouping_type_parameter;+ const sample_group_info = new SampleGroupInfo(sbgps[k].grouping_type, sbgps[k].grouping_type_parameter, sbgps[k]);+ if (traf) traf.sample_groups_info[sample_group_key] = sample_group_info;+ if (!trak.sample_groups_info[sample_group_key]) trak.sample_groups_info[sample_group_key] = sample_group_info;+ for (let l = 0; l < trak_sgpds.length; l++) if (trak_sgpds[l].grouping_type === sbgps[k].grouping_type) {+ sample_group_info.description = trak_sgpds[l];+ sample_group_info.description.used = true;+ }+ if (traf_sgpds) {+ for (let l = 0; l < traf_sgpds.length; l++) if (traf_sgpds[l].grouping_type === sbgps[k].grouping_type) {+ sample_group_info.fragment_description = traf_sgpds[l];+ sample_group_info.fragment_description.used = true;+ sample_group_info.is_fragment = true;+ }+ }+ }+ if (!traf) {+ for (let k = 0; k < trak_sgpds.length; k++) if (!trak_sgpds[k].used && trak_sgpds[k].version >= 2) {+ const sample_group_key = trak_sgpds[k].grouping_type + "/0";+ const sample_group_info = new SampleGroupInfo(trak_sgpds[k].grouping_type, 0);+ if (!trak.sample_groups_info[sample_group_key]) trak.sample_groups_info[sample_group_key] = sample_group_info;+ }+ } else if (traf_sgpds) {+ for (let k = 0; k < traf_sgpds.length; k++) if (!traf_sgpds[k].used && traf_sgpds[k].version >= 2) {+ const sample_group_key = traf_sgpds[k].grouping_type + "/0";+ const sample_group_info = new SampleGroupInfo(traf_sgpds[k].grouping_type, 0);+ sample_group_info.is_fragment = true;+ if (!traf.sample_groups_info[sample_group_key]) traf.sample_groups_info[sample_group_key] = sample_group_info;+ }+ }+ }+ /** @bundle isofile-sample-processing.js */+ static setSampleGroupProperties(trak, sample, sample_number, sample_groups_info) {+ sample.sample_groups = [];+ for (const k in sample_groups_info) {+ sample.sample_groups[k] = {+ grouping_type: sample_groups_info[k].grouping_type,+ grouping_type_parameter: sample_groups_info[k].grouping_type_parameter+ };+ if (sample_number >= sample_groups_info[k].last_sample_in_run) {+ if (sample_groups_info[k].last_sample_in_run < 0) sample_groups_info[k].last_sample_in_run = 0;+ sample_groups_info[k].entry_index++;+ if (sample_groups_info[k].entry_index <= sample_groups_info[k].sbgp.entries.length - 1) sample_groups_info[k].last_sample_in_run += sample_groups_info[k].sbgp.entries[sample_groups_info[k].entry_index].sample_count;+ }+ if (sample_groups_info[k].entry_index <= sample_groups_info[k].sbgp.entries.length - 1) sample.sample_groups[k].group_description_index = sample_groups_info[k].sbgp.entries[sample_groups_info[k].entry_index].group_description_index;+ else sample.sample_groups[k].group_description_index = -1;+ if (sample.sample_groups[k].group_description_index !== 0) {+ let description;+ if (sample_groups_info[k].fragment_description) description = sample_groups_info[k].fragment_description;+ else description = sample_groups_info[k].description;+ if (sample.sample_groups[k].group_description_index > 0) {+ let index;+ if (sample.sample_groups[k].group_description_index > 65535) index = (sample.sample_groups[k].group_description_index >> 16) - 1;+ else index = sample.sample_groups[k].group_description_index - 1;+ if (description && index >= 0) sample.sample_groups[k].description = description.entries[index];+ } else if (description && description.version >= 2) {+ if (description.default_group_description_index > 0) sample.sample_groups[k].description = description.entries[description.default_group_description_index - 1];+ }+ }+ }+ }+ /** @bundle isofile-sample-processing.js */+ static process_sdtp(sdtp, sample, number) {+ if (!sample) return;+ if (sdtp) {+ sample.is_leading = sdtp.is_leading[number];+ sample.depends_on = sdtp.sample_depends_on[number];+ sample.is_depended_on = sdtp.sample_is_depended_on[number];+ sample.has_redundancy = sdtp.sample_has_redundancy[number];+ } else {+ sample.is_leading = 0;+ sample.depends_on = 0;+ sample.is_depended_on = 0;+ sample.has_redundancy = 0;+ }+ }+ buildSampleLists() {+ for (let i = 0; i < this.moov.traks.length; i++) this.buildTrakSampleLists(this.moov.traks[i]);+ }+ buildTrakSampleLists(trak) {+ let j;+ let chunk_run_index;+ let chunk_index;+ let last_chunk_in_run;+ let offset_in_chunk;+ let last_sample_in_chunk;+ trak.samples = [];+ trak.samples_duration = 0;+ trak.samples_size = 0;+ const stco = trak.mdia.minf.stbl.stco || trak.mdia.minf.stbl.co64;+ const stsc = trak.mdia.minf.stbl.stsc;+ const stsz = trak.mdia.minf.stbl.stsz || trak.mdia.minf.stbl.stz2;+ const stts = trak.mdia.minf.stbl.stts;+ const ctts = trak.mdia.minf.stbl.ctts;+ const stss = trak.mdia.minf.stbl.stss;+ const stsd = trak.mdia.minf.stbl.stsd;+ const subs = trak.mdia.minf.stbl.subs;+ const stdp = trak.mdia.minf.stbl.stdp;+ const sbgps = trak.mdia.minf.stbl.sbgps;+ const sgpds = trak.mdia.minf.stbl.sgpds;+ let last_sample_in_stts_run = -1;+ let stts_run_index = -1;+ let last_sample_in_ctts_run = -1;+ let ctts_run_index = -1;+ let last_stss_index = 0;+ let subs_entry_index = 0;+ let last_subs_sample_index = 0;+ ISOFile.initSampleGroups(trak, void 0, sbgps, sgpds);+ if (typeof stsz === "undefined") return;+ for (j = 0; j < stsz.sample_sizes.length; j++) {+ const sample = {+ number: j,+ track_id: trak.tkhd.track_id,+ timescale: trak.mdia.mdhd.timescale,+ alreadyRead: 0,+ size: stsz.sample_sizes[j]+ };+ trak.samples[j] = sample;+ trak.samples_size += sample.size;+ if (j === 0) {+ chunk_index = 1;+ chunk_run_index = 0;+ sample.chunk_index = chunk_index;+ sample.chunk_run_index = chunk_run_index;+ last_sample_in_chunk = stsc.samples_per_chunk[chunk_run_index];+ offset_in_chunk = 0;+ if (chunk_run_index + 1 < stsc.first_chunk.length) last_chunk_in_run = stsc.first_chunk[chunk_run_index + 1] - 1;+ else last_chunk_in_run = Infinity;+ } else if (j < last_sample_in_chunk) {+ sample.chunk_index = chunk_index;+ sample.chunk_run_index = chunk_run_index;+ } else {+ chunk_index++;+ sample.chunk_index = chunk_index;+ offset_in_chunk = 0;+ if (chunk_index <= last_chunk_in_run) {} else {+ chunk_run_index++;+ if (chunk_run_index + 1 < stsc.first_chunk.length) last_chunk_in_run = stsc.first_chunk[chunk_run_index + 1] - 1;+ else last_chunk_in_run = Infinity;+ }+ sample.chunk_run_index = chunk_run_index;+ last_sample_in_chunk += stsc.samples_per_chunk[chunk_run_index];+ }+ sample.description_index = stsc.sample_description_index[sample.chunk_run_index] - 1;+ sample.description = stsd.entries[sample.description_index];+ sample.offset = stco.chunk_offsets[sample.chunk_index - 1] + offset_in_chunk;+ offset_in_chunk += sample.size;+ if (j > last_sample_in_stts_run) {+ stts_run_index++;+ if (last_sample_in_stts_run < 0) last_sample_in_stts_run = 0;+ last_sample_in_stts_run += stts.sample_counts[stts_run_index];+ }+ if (j > 0) {+ trak.samples[j - 1].duration = stts.sample_deltas[stts_run_index];+ trak.samples_duration += trak.samples[j - 1].duration;+ sample.dts = trak.samples[j - 1].dts + trak.samples[j - 1].duration;+ } else sample.dts = 0;+ if (ctts) {+ if (j >= last_sample_in_ctts_run) {+ ctts_run_index++;+ if (last_sample_in_ctts_run < 0) last_sample_in_ctts_run = 0;+ last_sample_in_ctts_run += ctts.sample_counts[ctts_run_index];+ }+ sample.cts = trak.samples[j].dts + ctts.sample_offsets[ctts_run_index];+ } else sample.cts = sample.dts;+ if (stss) {+ if (j === stss.sample_numbers[last_stss_index] - 1) {+ sample.is_sync = true;+ last_stss_index++;+ } else {+ sample.is_sync = false;+ sample.degradation_priority = 0;+ }+ if (subs) {+ if (subs.entries[subs_entry_index].sample_delta + last_subs_sample_index === j + 1) {+ sample.subsamples = subs.entries[subs_entry_index].subsamples;+ last_subs_sample_index += subs.entries[subs_entry_index].sample_delta;+ subs_entry_index++;+ }+ }+ } else sample.is_sync = true;+ ISOFile.process_sdtp(trak.mdia.minf.stbl.sdtp, sample, sample.number);+ if (stdp) sample.degradation_priority = stdp.priority[j];+ else sample.degradation_priority = 0;+ if (subs) {+ if (subs.entries[subs_entry_index].sample_delta + last_subs_sample_index === j) {+ sample.subsamples = subs.entries[subs_entry_index].subsamples;+ last_subs_sample_index += subs.entries[subs_entry_index].sample_delta;+ }+ }+ if (sbgps.length > 0 || sgpds.length > 0) ISOFile.setSampleGroupProperties(trak, sample, j, trak.sample_groups_info);+ }+ if (j > 0) {+ trak.samples[j - 1].duration = Math.max(trak.mdia.mdhd.duration - trak.samples[j - 1].dts, 0);+ trak.samples_duration += trak.samples[j - 1].duration;+ }+ }+ /**+ * Update sample list when new 'moof' boxes are received+ * @bundle isofile-sample-processing.js+ */+ updateSampleLists() {+ let default_sample_description_index;+ let default_sample_duration;+ let default_sample_size;+ let default_sample_flags;+ let last_run_position;+ if (this.moov === void 0) return;+ while (this.lastMoofIndex < this.moofs.length) {+ const box = this.moofs[this.lastMoofIndex];+ this.lastMoofIndex++;+ if (box.type === "moof") {+ const moof = box;+ for (let i = 0; i < moof.trafs.length; i++) {+ const traf = moof.trafs[i];+ const trak = this.getTrackById(traf.tfhd.track_id);+ const trex = this.getTrexById(traf.tfhd.track_id);+ if (traf.tfhd.flags & 2) default_sample_description_index = traf.tfhd.default_sample_description_index;+ else default_sample_description_index = trex ? trex.default_sample_description_index : 1;+ if (traf.tfhd.flags & 8) default_sample_duration = traf.tfhd.default_sample_duration;+ else default_sample_duration = trex ? trex.default_sample_duration : 0;+ if (traf.tfhd.flags & 16) default_sample_size = traf.tfhd.default_sample_size;+ else default_sample_size = trex ? trex.default_sample_size : 0;+ if (traf.tfhd.flags & 32) default_sample_flags = traf.tfhd.default_sample_flags;+ else default_sample_flags = trex ? trex.default_sample_flags : 0;+ traf.sample_number = 0;+ if (traf.sbgps.length > 0) ISOFile.initSampleGroups(trak, traf, traf.sbgps, trak.mdia.minf.stbl.sgpds, traf.sgpds);+ for (let j = 0; j < traf.truns.length; j++) {+ const trun = traf.truns[j];+ for (let k = 0; k < trun.sample_count; k++) {+ const description_index = default_sample_description_index - 1;+ let sample_flags = default_sample_flags;+ if (trun.flags & 1024) sample_flags = trun.sample_flags[k];+ else if (k === 0 && trun.flags & 4) sample_flags = trun.first_sample_flags;+ let size = default_sample_size;+ if (trun.flags & 512) size = trun.sample_size[k];+ trak.samples_size += size;+ let duration = default_sample_duration;+ if (trun.flags & 256) duration = trun.sample_duration[k];+ trak.samples_duration += duration;+ let dts;+ if (trak.first_traf_merged || k > 0) dts = trak.samples[trak.samples.length - 1].dts + trak.samples[trak.samples.length - 1].duration;+ else {+ if (traf.tfdt) dts = traf.tfdt.baseMediaDecodeTime;+ else dts = 0;+ trak.first_traf_merged = true;+ }+ let cts = dts;+ if (trun.flags & 2048) cts = dts + trun.sample_composition_time_offset[k];+ const bdop = traf.tfhd.flags & 1 ? true : false;+ const dbim = traf.tfhd.flags & 131072 ? true : false;+ const dop = trun.flags & 1 ? true : false;+ let bdo = 0;+ if (!bdop) if (!dbim) if (j === 0) bdo = moof.start;+ else bdo = last_run_position;+ else bdo = moof.start;+ else bdo = traf.tfhd.base_data_offset;+ let offset;+ if (j === 0 && k === 0) if (dop) offset = bdo + trun.data_offset;+ else offset = bdo;+ else offset = last_run_position;+ last_run_position = offset + size;+ const number_in_traf = traf.sample_number;+ traf.sample_number++;+ const sample = {+ cts,+ description_index,+ description: trak.mdia.minf.stbl.stsd.entries[description_index],+ dts,+ duration,+ moof_number: this.lastMoofIndex,+ number_in_traf,+ number: trak.samples.length,+ offset,+ size,+ timescale: trak.mdia.mdhd.timescale,+ track_id: trak.tkhd.track_id,+ is_sync: sample_flags >> 16 & 1 ? false : true,+ is_leading: sample_flags >> 26 & 3,+ depends_on: sample_flags >> 24 & 3,+ is_depended_on: sample_flags >> 22 & 3,+ has_redundancy: sample_flags >> 20 & 3,+ degradation_priority: sample_flags & 65535+ };+ traf.first_sample_index = trak.samples.length;+ trak.samples.push(sample);+ if (traf.sbgps.length > 0 || traf.sgpds.length > 0 || trak.mdia.minf.stbl.sbgps.length > 0 || trak.mdia.minf.stbl.sgpds.length > 0) ISOFile.setSampleGroupProperties(trak, sample, sample.number_in_traf, traf.sample_groups_info);+ }+ }+ if (traf.subs) {+ trak.has_fragment_subsamples = true;+ let sample_index = traf.first_sample_index;+ for (let j = 0; j < traf.subs.entries.length; j++) {+ sample_index += traf.subs.entries[j].sample_delta;+ const sample = trak.samples[sample_index - 1];+ sample.subsamples = traf.subs.entries[j].subsamples;+ }+ }+ }+ }+ }+ }+ /**+ * Try to get sample data for a given sample:+ * returns null if not found+ * returns the same sample if already requested+ *+ * @bundle isofile-sample-processing.js+ */+ getSample(trak, sampleNum) {+ const sample = trak.samples[sampleNum];+ if (!this.moov) return;+ if (!sample.data) {+ sample.data = new Uint8Array(sample.size);+ sample.alreadyRead = 0;+ this.samplesDataSize += sample.size;+ Log.debug("ISOFile", "Allocating sample #" + sampleNum + " on track #" + trak.tkhd.track_id + " of size " + sample.size + " (total: " + this.samplesDataSize + ")");+ } else if (sample.alreadyRead === sample.size) return sample;+ while (true) {+ let stream = this.stream;+ let index = stream.findPosition(true, sample.offset + sample.alreadyRead, false);+ let buffer;+ let fileStart;+ if (index > -1) {+ buffer = stream.buffers[index];+ fileStart = buffer.fileStart;+ } else for (const mdat of this.mdats) {+ if (!mdat.stream) {+ Log.debug("ISOFile", "mdat stream not yet fully read for #" + this.mdats.indexOf(mdat) + " mdat");+ continue;+ }+ index = mdat.stream.findPosition(true, sample.offset + sample.alreadyRead - mdat.start - mdat.hdr_size, false);+ if (index > -1) {+ stream = mdat.stream;+ buffer = mdat.stream.buffers[index];+ fileStart = mdat.start + mdat.hdr_size + buffer.fileStart;+ break;+ }+ }+ if (buffer) {+ const lengthAfterStart = buffer.byteLength - (sample.offset + sample.alreadyRead - fileStart);+ if (sample.size - sample.alreadyRead <= lengthAfterStart) {+ Log.debug("ISOFile", "Getting sample #" + sampleNum + " data (alreadyRead: " + sample.alreadyRead + " offset: " + (sample.offset + sample.alreadyRead - fileStart) + " read size: " + (sample.size - sample.alreadyRead) + " full size: " + sample.size + ")");+ DataStream.memcpy(sample.data.buffer, sample.alreadyRead, buffer, sample.offset + sample.alreadyRead - fileStart, sample.size - sample.alreadyRead);+ buffer.usedBytes += sample.size - sample.alreadyRead;+ stream.logBufferLevel();+ sample.alreadyRead = sample.size;+ return sample;+ } else {+ if (lengthAfterStart === 0) return;+ Log.debug("ISOFile", "Getting sample #" + sampleNum + " partial data (alreadyRead: " + sample.alreadyRead + " offset: " + (sample.offset + sample.alreadyRead - fileStart) + " read size: " + lengthAfterStart + " full size: " + sample.size + ")");+ DataStream.memcpy(sample.data.buffer, sample.alreadyRead, buffer, sample.offset + sample.alreadyRead - fileStart, lengthAfterStart);+ sample.alreadyRead += lengthAfterStart;+ buffer.usedBytes += lengthAfterStart;+ stream.logBufferLevel();+ }+ } else return;+ }+ }+ /**+ * Release the memory used to store the data of the sample+ *+ * @bundle isofile-sample-processing.js+ */+ releaseSample(trak, sampleNum) {+ const sample = trak.samples[sampleNum];+ if (sample.data) {+ this.samplesDataSize -= sample.size;+ sample.data = void 0;+ sample.alreadyRead = 0;+ return sample.size;+ } else return 0;+ }+ /** @bundle isofile-sample-processing.js */+ getAllocatedSampleDataSize() {+ return this.samplesDataSize;+ }+ /**+ * Builds the MIME Type 'codecs' sub-parameters for the whole file+ *+ * @bundle isofile-sample-processing.js+ */+ getCodecs() {+ let codecs = "";+ for (let i = 0; i < this.moov.traks.length; i++) {+ const trak = this.moov.traks[i];+ if (i > 0) codecs += ",";+ codecs += trak.mdia.minf.stbl.stsd.entries[0].getCodec();+ }+ return codecs;+ }+ /**+ * Helper function+ *+ * @bundle isofile-sample-processing.js+ */+ getTrexById(id) {+ if (!this.moov || !this.moov.mvex) return;+ for (let i = 0; i < this.moov.mvex.trexs.length; i++) {+ const trex = this.moov.mvex.trexs[i];+ if (trex.track_id === id) return trex;+ }+ }+ /**+ * Helper function+ *+ * @bundle isofile-sample-processing.js+ */+ getTrackById(id) {+ if (!this.moov) return;+ for (let j = 0; j < this.moov.traks.length; j++) {+ const trak = this.moov.traks[j];+ if (trak.tkhd.track_id === id) return trak;+ }+ }+ /** @bundle isofile-item-processing.js */+ flattenItemInfo() {+ const items = this.items;+ const entity_groups = this.entity_groups;+ const meta = this.meta;+ if (!meta || !meta.hdlr || !meta.iinf) return;+ for (let i = 0; i < meta.iinf.item_infos.length; i++) {+ const id = meta.iinf.item_infos[i].item_ID;+ items[id] = {+ id,+ name: meta.iinf.item_infos[i].item_name,+ ref_to: [],+ content_type: meta.iinf.item_infos[i].content_type,+ content_encoding: meta.iinf.item_infos[i].content_encoding,+ item_uri_type: meta.iinf.item_infos[i].item_uri_type,+ type: meta.iinf.item_infos[i].item_type ? meta.iinf.item_infos[i].item_type : "mime",+ protection: meta.iinf.item_infos[i].item_protection_index > 0 ? meta.ipro.protections[meta.iinf.item_infos[i].item_protection_index - 1] : void 0+ };+ }+ if (meta.grpl) for (let i = 0; i < meta.grpl.boxes.length; i++) {+ const entityGroup = meta.grpl.boxes[i];+ entity_groups[entityGroup.group_id] = {+ id: entityGroup.group_id,+ entity_ids: entityGroup.entity_ids,+ type: entityGroup.type+ };+ }+ if (meta.iloc) for (let i = 0; i < meta.iloc.items.length; i++) {+ const itemloc = meta.iloc.items[i];+ const item = items[itemloc.item_ID];+ if (itemloc.data_reference_index !== 0) {+ Log.warn("Item storage with reference to other files: not supported");+ item.source = meta.dinf.boxes[itemloc.data_reference_index - 1];+ }+ item.extents = [];+ item.size = 0;+ for (let j = 0; j < itemloc.extents.length; j++) {+ item.extents[j] = {+ offset: itemloc.extents[j].extent_offset + itemloc.base_offset,+ length: itemloc.extents[j].extent_length,+ alreadyRead: 0+ };+ if (itemloc.construction_method === 1) item.extents[j].offset += meta.idat.start + meta.idat.hdr_size;+ item.size += item.extents[j].length;+ }+ }+ if (meta.pitm) {+ const id = meta.pitm.item_id;+ if (!items[id]) Log.warn("ISOFile", "Primary item_id #" + id + " does not exist in items");+ else items[id].primary = true;+ }+ if (meta.iref) for (let i = 0; i < meta.iref.references.length; i++) {+ const ref = meta.iref.references[i];+ for (let j = 0; j < ref.references.length; j++) items[ref.from_item_ID].ref_to.push({+ type: ref.type,+ id: ref.references[j]+ });+ }+ if (meta.iprp) for (let k = 0; k < meta.iprp.ipmas.length; k++) {+ const ipma = meta.iprp.ipmas[k];+ for (let i = 0; i < ipma.associations.length; i++) {+ const association = ipma.associations[i];+ const item = items[association.id] ?? entity_groups[association.id];+ if (item) {+ if (item.properties === void 0) item.properties = { boxes: [] };+ for (let j = 0; j < association.props.length; j++) {+ const propEntry = association.props[j];+ if (propEntry.property_index > 0 && propEntry.property_index - 1 < meta.iprp.ipco.boxes.length) {+ const propbox = meta.iprp.ipco.boxes[propEntry.property_index - 1];+ item.properties[propbox.type] = propbox;+ item.properties.boxes.push(propbox);+ }+ }+ }+ }+ }+ }+ /** @bundle isofile-item-processing.js */+ getItem(item_id) {+ if (!this.meta) return;+ const item = this.items[item_id];+ if (!item.data && item.size) {+ item.data = new Uint8Array(item.size);+ item.alreadyRead = 0;+ this.itemsDataSize += item.size;+ Log.debug("ISOFile", "Allocating item #" + item_id + " of size " + item.size + " (total: " + this.itemsDataSize + ")");+ } else if (item.alreadyRead === item.size) return item;+ for (let i = 0; i < item.extents.length; i++) {+ const extent = item.extents[i];+ if (extent.alreadyRead === extent.length) continue;+ else {+ const index = this.stream.findPosition(true, extent.offset + extent.alreadyRead, false);+ if (index > -1) {+ const buffer = this.stream.buffers[index];+ const lengthAfterStart = buffer.byteLength - (extent.offset + extent.alreadyRead - buffer.fileStart);+ if (extent.length - extent.alreadyRead <= lengthAfterStart) {+ Log.debug("ISOFile", "Getting item #" + item_id + " extent #" + i + " data (alreadyRead: " + extent.alreadyRead + " offset: " + (extent.offset + extent.alreadyRead - buffer.fileStart) + " read size: " + (extent.length - extent.alreadyRead) + " full extent size: " + extent.length + " full item size: " + item.size + ")");+ DataStream.memcpy(item.data.buffer, item.alreadyRead, buffer, extent.offset + extent.alreadyRead - buffer.fileStart, extent.length - extent.alreadyRead);+ if (!this.parsingMdat || this.discardMdatData) buffer.usedBytes += extent.length - extent.alreadyRead;+ this.stream.logBufferLevel();+ item.alreadyRead += extent.length - extent.alreadyRead;+ extent.alreadyRead = extent.length;+ } else {+ Log.debug("ISOFile", "Getting item #" + item_id + " extent #" + i + " partial data (alreadyRead: " + extent.alreadyRead + " offset: " + (extent.offset + extent.alreadyRead - buffer.fileStart) + " read size: " + lengthAfterStart + " full extent size: " + extent.length + " full item size: " + item.size + ")");+ DataStream.memcpy(item.data.buffer, item.alreadyRead, buffer, extent.offset + extent.alreadyRead - buffer.fileStart, lengthAfterStart);+ extent.alreadyRead += lengthAfterStart;+ item.alreadyRead += lengthAfterStart;+ if (!this.parsingMdat || this.discardMdatData) buffer.usedBytes += lengthAfterStart;+ this.stream.logBufferLevel();+ return;+ }+ } else return;+ }+ }+ if (item.alreadyRead === item.size) return item;+ }+ /**+ * Release the memory used to store the data of the item+ *+ * @bundle isofile-item-processing.js+ */+ releaseItem(item_id) {+ const item = this.items[item_id];+ if (item.data) {+ this.itemsDataSize -= item.size;+ item.data = void 0;+ item.alreadyRead = 0;+ for (let i = 0; i < item.extents.length; i++) {+ const extent = item.extents[i];+ extent.alreadyRead = 0;+ }+ return item.size;+ } else return 0;+ }+ /** @bundle isofile-item-processing.js */+ processItems(callback) {+ for (const i in this.items) {+ const item = this.items[i];+ this.getItem(item.id);+ if (callback && !item.sent) {+ callback(item);+ item.sent = true;+ item.data = void 0;+ }+ }+ }+ /** @bundle isofile-item-processing.js */+ hasItem(name) {+ for (const i in this.items) {+ const item = this.items[i];+ if (item.name === name) return item.id;+ }+ return -1;+ }+ /** @bundle isofile-item-processing.js */+ getMetaHandler() {+ if (this.meta) return this.meta.hdlr.handler;+ }+ /** @bundle isofile-item-processing.js */+ getPrimaryItem() {+ if (this.meta && this.meta.pitm) return this.getItem(this.meta.pitm.item_id);+ }+ /** @bundle isofile-item-processing.js */+ itemToFragmentedTrackFile({ itemId } = {}) {+ let item;+ if (itemId) item = this.getItem(itemId);+ else item = this.getPrimaryItem();+ if (!item) return;+ const file = new ISOFile();+ file.discardMdatData = false;+ const trackOptions = {+ type: item.type,+ description_boxes: item.properties.boxes+ };+ if (item.properties.ispe) {+ trackOptions.width = item.properties.ispe.image_width;+ trackOptions.height = item.properties.ispe.image_height;+ }+ const trackId = file.addTrack(trackOptions);+ if (trackId) {+ file.addSample(trackId, item.data);+ return file;+ }+ }+ /** @bundle isofile-advanced-parsing.js */+ processIncompleteBox(ret) {+ if (ret.type === "mdat") {+ const box = new mdatBox(ret.size);+ this.parsingMdat = box;+ this.boxes.push(box);+ this.mdats.push(box);+ box.start = ret.start;+ box.hdr_size = ret.hdr_size;+ box.original_size = ret.original_size;+ this.stream.addUsedBytes(box.hdr_size);+ this.lastBoxStartPosition = box.start + box.size;+ if (this.stream.seek(box.start + box.size, false, this.discardMdatData)) {+ this.transferMdatData();+ this.parsingMdat = void 0;+ return true;+ } else {+ if (!this.moovStartFound) this.nextParsePosition = box.start + box.size;+ else this.nextParsePosition = this.stream.findEndContiguousBuf();+ return false;+ }+ } else {+ if (ret.type === "moov") {+ this.moovStartFound = true;+ if (this.mdats.length === 0) this.isProgressive = true;+ }+ if (this.stream.mergeNextBuffer ? this.stream.mergeNextBuffer() : false) {+ this.nextParsePosition = this.stream.getEndPosition();+ return true;+ } else {+ if (!ret.type) this.nextParsePosition = this.stream.getEndPosition();+ else if (this.moovStartFound) this.nextParsePosition = this.stream.getEndPosition();+ else this.nextParsePosition = this.stream.getPosition() + ret.size;+ return false;+ }+ }+ }+ /** @bundle isofile-advanced-parsing.js */+ hasIncompleteMdat() {+ return this.parsingMdat !== void 0;+ }+ /**+ * Transfer the data of the mdat box to its stream+ * @param mdat the mdat box to use+ */+ transferMdatData(inMdat) {+ const mdat = inMdat ?? this.parsingMdat;+ if (this.discardMdatData) {+ Log.debug("ISOFile", "Discarding 'mdat' data, not transferring it to the mdat box stream");+ return;+ }+ if (!mdat) {+ Log.warn("ISOFile", "Cannot transfer 'mdat' data, no mdat box is being parsed");+ return;+ }+ const startBufferIndex = this.stream.findPosition(true, mdat.start + mdat.hdr_size, false);+ const endBufferIndex = this.stream.findPosition(true, mdat.start + mdat.size, false);+ if (startBufferIndex === -1 || endBufferIndex === -1) {+ Log.warn("ISOFile", "Cannot transfer 'mdat' data, start or end buffer not found");+ return;+ }+ mdat.stream = new MultiBufferStream();+ for (let i = startBufferIndex; i <= endBufferIndex; i++) {+ const buffer = this.stream.buffers[i];+ const startOffset = i === startBufferIndex ? mdat.start + mdat.hdr_size - buffer.fileStart : 0;+ const endOffset = i === endBufferIndex ? mdat.start + mdat.size - buffer.fileStart : buffer.byteLength;+ if (endOffset > startOffset) {+ Log.debug("ISOFile", "Transferring 'mdat' data from buffer #" + i + " (" + startOffset + " to " + endOffset + ")");+ const transferSize = endOffset - startOffset;+ const newBuffer = new MP4BoxBuffer(transferSize);+ const lastPosition = mdat.stream.getAbsoluteEndPosition();+ DataStream.memcpy(newBuffer, 0, buffer, startOffset, transferSize);+ newBuffer.fileStart = lastPosition;+ mdat.stream.insertBuffer(newBuffer);+ buffer.usedBytes += transferSize;+ }+ }+ }+ /** @bundle isofile-advanced-parsing.js */+ processIncompleteMdat() {+ const box = this.parsingMdat;+ if (this.stream.seek(box.start + box.size, false, this.discardMdatData)) {+ Log.debug("ISOFile", "Found 'mdat' end in buffered data");+ this.transferMdatData();+ this.parsingMdat = void 0;+ return true;+ } else {+ this.nextParsePosition = this.stream.findEndContiguousBuf();+ return false;+ }+ }+ /** @bundle isofile-advanced-parsing.js */+ restoreParsePosition() {+ return this.stream.seek(this.lastBoxStartPosition, true, this.discardMdatData);+ }+ /** @bundle isofile-advanced-parsing.js */+ saveParsePosition() {+ this.lastBoxStartPosition = this.stream.getPosition();+ }+ /** @bundle isofile-advanced-parsing.js */+ updateUsedBytes(box, _ret) {+ if (this.stream.addUsedBytes) if (box.type === "mdat") {+ this.stream.addUsedBytes(box.hdr_size);+ if (this.discardMdatData) this.stream.addUsedBytes(box.size - box.hdr_size);+ } else this.stream.addUsedBytes(box.size);+ }+ /** @bundle isofile-advanced-creation.js */+ addBox(box) {+ return Box.prototype.addBox.call(this, box);+ }+ /** @bundle isofile-advanced-creation.js */+ init(options = {}) {+ const ftyp = this.addBox(new ftypBox());+ ftyp.major_brand = options.brands && options.brands[0] || "iso4";+ ftyp.minor_version = 0;+ ftyp.compatible_brands = options.brands || ["iso4"];+ const moov = this.addBox(new moovBox());+ moov.addBox(new mvexBox());+ const mvhd = moov.addBox(new mvhdBox());+ mvhd.timescale = options.timescale || 600;+ mvhd.rate = options.rate || 65536;+ mvhd.creation_time = 0;+ mvhd.modification_time = 0;+ mvhd.duration = options.duration || 0;+ mvhd.volume = options.width ? 0 : 256;+ mvhd.matrix = [+ 65536,+ 0,+ 0,+ 0,+ 65536,+ 0,+ 0,+ 0,+ 1073741824+ ];+ mvhd.next_track_id = 1;+ return this;+ }+ /** @bundle isofile-advanced-creation.js */+ addTrack(_options = {}) {+ if (!this.moov) this.init(_options);+ const options = _options || {};+ options.width = options.width || 320;+ options.height = options.height || 320;+ options.id = options.id || this.moov.mvhd.next_track_id;+ options.type = options.type || "avc1";+ const trak = this.moov.addBox(new trakBox());+ this.moov.mvhd.next_track_id = options.id + 1;+ const tkhd = trak.addBox(new tkhdBox());+ tkhd.flags = 1 | 2 | 4;+ tkhd.creation_time = 0;+ tkhd.modification_time = 0;+ tkhd.track_id = options.id;+ tkhd.duration = options.duration || 0;+ tkhd.layer = options.layer || 0;+ tkhd.alternate_group = 0;+ tkhd.volume = 1;+ tkhd.matrix = [+ 65536,+ 0,+ 0,+ 0,+ 65536,+ 0,+ 0,+ 0,+ 1073741824+ ];+ tkhd.width = options.width << 16;+ tkhd.height = options.height << 16;+ const mdia = trak.addBox(new mdiaBox());+ const mdhd = mdia.addBox(new mdhdBox());+ mdhd.creation_time = 0;+ mdhd.modification_time = 0;+ mdhd.timescale = options.timescale || 1;+ mdhd.duration = options.media_duration || 0;+ mdhd.language = options.language || "und";+ const hdlr = mdia.addBox(new hdlrBox());+ hdlr.handler = options.hdlr || "vide";+ hdlr.name = options.name || "Track created with MP4Box.js";+ const elng = mdia.addBox(new elngBox());+ elng.extended_language = options.language || "fr-FR";+ const minf = mdia.addBox(new minfBox());+ const sampleEntry = BoxRegistry.sampleEntry[options.type];+ if (!sampleEntry) return;+ const sample_description_entry = new sampleEntry();+ sample_description_entry.data_reference_index = 1;+ if (sample_description_entry instanceof VisualSampleEntry) {+ const sde = sample_description_entry;+ const vmhd = minf.addBox(new vmhdBox());+ vmhd.graphicsmode = 0;+ vmhd.opcolor = [+ 0,+ 0,+ 0+ ];+ sde.width = options.width;+ sde.height = options.height;+ sde.horizresolution = 72 << 16;+ sde.vertresolution = 72 << 16;+ sde.frame_count = 1;+ sde.compressorname = options.type + " Compressor";+ sde.depth = 24;+ if (options.avcDecoderConfigRecord) sde.addBox(new avcCBox(options.avcDecoderConfigRecord.byteLength)).parse(new DataStream(options.avcDecoderConfigRecord));+ else if (options.hevcDecoderConfigRecord) sde.addBox(new hvcCBox(options.hevcDecoderConfigRecord.byteLength)).parse(new DataStream(options.hevcDecoderConfigRecord));+ } else if (sample_description_entry instanceof AudioSampleEntry) {+ const sde = sample_description_entry;+ const smhd = minf.addBox(new smhdBox());+ smhd.balance = options.balance || 0;+ sde.channel_count = options.channel_count || 2;+ sde.samplesize = options.samplesize || 16;+ sde.samplerate = options.samplerate || 65536;+ } else if (sample_description_entry instanceof HintSampleEntry) minf.addBox(new hmhdBox());+ else if (sample_description_entry instanceof SubtitleSampleEntry) {+ minf.addBox(new sthdBox());+ if (sample_description_entry instanceof stppSampleEntry) {+ sample_description_entry.namespace = options.namespace || "nonamespace";+ sample_description_entry.schema_location = options.schema_location || "";+ sample_description_entry.auxiliary_mime_types = options.auxiliary_mime_types || "";+ }+ } else if (sample_description_entry instanceof MetadataSampleEntry) minf.addBox(new nmhdBox());+ else if (sample_description_entry instanceof SystemSampleEntry) minf.addBox(new nmhdBox());+ else minf.addBox(new nmhdBox());+ if (options.description) sample_description_entry.addBox.call(sample_description_entry, options.description);+ if (options.description_boxes) options.description_boxes.forEach(function(b) {+ sample_description_entry.addBox.call(sample_description_entry, b);+ });+ const dref = minf.addBox(new dinfBox()).addBox(new drefBox());+ const url = new urlBox();+ url.flags = 1;+ dref.addEntry(url);+ const stbl = minf.addBox(new stblBox());+ stbl.addBox(new stsdBox()).addEntry(sample_description_entry);+ const stts = stbl.addBox(new sttsBox());+ stts.sample_counts = [];+ stts.sample_deltas = [];+ const stsc = stbl.addBox(new stscBox());+ stsc.first_chunk = [];+ stsc.samples_per_chunk = [];+ stsc.sample_description_index = [];+ const stco = stbl.addBox(new stcoBox());+ stco.chunk_offsets = [];+ const stsz = stbl.addBox(new stszBox());+ stsz.sample_sizes = [];+ const trex = this.moov.mvex.addBox(new trexBox());+ trex.track_id = options.id;+ trex.default_sample_description_index = options.default_sample_description_index || 1;+ trex.default_sample_duration = options.default_sample_duration || 0;+ trex.default_sample_size = options.default_sample_size || 0;+ trex.default_sample_flags = options.default_sample_flags || 0;+ this.buildTrakSampleLists(trak);+ return options.id;+ }+ /** @bundle isofile-advanced-creation.js */+ addSample(track_id, data, { sample_description_index, duration = 1, cts = 0, dts = 0, is_sync = false, is_leading = 0, depends_on = 0, is_depended_on = 0, has_redundancy = 0, degradation_priority = 0, subsamples, offset = 0 } = {}) {+ const trak = this.getTrackById(track_id);+ if (trak === void 0) return;+ const descriptionIndex = sample_description_index ? sample_description_index - 1 : 0;+ const sample = {+ number: trak.samples.length,+ track_id: trak.tkhd.track_id,+ timescale: trak.mdia.mdhd.timescale,+ description_index: descriptionIndex,+ description: trak.mdia.minf.stbl.stsd.entries[descriptionIndex],+ data,+ size: data.byteLength,+ alreadyRead: data.byteLength,+ duration,+ cts,+ dts,+ is_sync,+ is_leading,+ depends_on,+ is_depended_on,+ has_redundancy,+ degradation_priority,+ offset,+ subsamples+ };+ trak.samples.push(sample);+ trak.samples_size += sample.size;+ trak.samples_duration += sample.duration;+ if (trak.first_dts === void 0) trak.first_dts = dts;+ this.processSamples();+ const moof = this.addBox(this.createMoof([sample]));+ moof.computeSize();+ moof.trafs[0].truns[0].data_offset = moof.size + 8;+ const mdat = this.addBox(new mdatBox());+ mdat.data = new Uint8Array(data);+ return sample;+ }+ /** @bundle isofile-advanced-creation.js */+ createMoof(samples) {+ if (samples.length === 0) return;+ if (samples.some((s) => s.track_id !== samples[0].track_id)) throw new Error("Cannot create moof for samples from different tracks: " + samples.map((s) => s.track_id).join(", "));+ const trackId = samples[0].track_id;+ const trak = this.getTrackById(trackId);+ if (!trak) throw new Error("Cannot create moof for non-existing track: " + trackId);+ const moof = new moofBox();+ const mfhd = moof.addBox(new mfhdBox());+ mfhd.sequence_number = ++this.nextMoofNumber;+ const traf = moof.addBox(new trafBox());+ const tfhd = traf.addBox(new tfhdBox());+ tfhd.track_id = trackId;+ tfhd.flags = TFHD_FLAG_DEFAULT_BASE_IS_MOOF;+ const tfdt = traf.addBox(new tfdtBox());+ tfdt.baseMediaDecodeTime = samples[0].dts - (trak.first_dts || 0);+ const trun = traf.addBox(new trunBox());+ trun.flags = 1 | 256 | 512 | TRUN_FLAGS_FLAGS | TRUN_FLAGS_CTS_OFFSET;+ trun.data_offset = 0;+ trun.first_sample_flags = 0;+ trun.sample_count = samples.length;+ for (const sample of samples) {+ let sample_flags = 0;+ if (sample.is_sync) sample_flags = 1 << 25;+ else sample_flags = 65536;+ trun.sample_duration.push(sample.duration);+ trun.sample_size.push(sample.size);+ trun.sample_flags.push(sample_flags);+ trun.sample_composition_time_offset.push(sample.cts - sample.dts);+ }+ return moof;+ }+ /** @bundle box-print.js */+ print(output) {+ output.indent = "";+ for (let i = 0; i < this.boxes.length; i++) if (this.boxes[i]) this.boxes[i].print(output);+ }+};++//#endregion+//#region src/create-file.ts+function createFile(keepMdatData = false, stream) {+ return new ISOFile(stream, !keepMdatData);+}++//#endregion+//#region src/boxes/emsg.ts+var emsgBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "EventMessageBox";+ }+ static {+ this.fourcc = "emsg";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ if (this.version === 1) {+ this.timescale = stream.readUint32();+ this.presentation_time = stream.readUint64();+ this.event_duration = stream.readUint32();+ this.id = stream.readUint32();+ this.scheme_id_uri = stream.readCString();+ this.value = stream.readCString();+ } else {+ this.scheme_id_uri = stream.readCString();+ this.value = stream.readCString();+ this.timescale = stream.readUint32();+ this.presentation_time_delta = stream.readUint32();+ this.event_duration = stream.readUint32();+ this.id = stream.readUint32();+ }+ let message_size = this.size - this.hdr_size - (16 + (this.scheme_id_uri.length + 1) + (this.value.length + 1));+ if (this.version === 1) message_size -= 4;+ this.message_data = stream.readUint8Array(message_size);+ }+ /** @bundle writing/emsg.js */+ write(stream) {+ this.version = 0;+ this.flags = 0;+ this.size = 16 + this.message_data.length + (this.scheme_id_uri.length + 1) + (this.value.length + 1);+ this.writeHeader(stream);+ stream.writeCString(this.scheme_id_uri);+ stream.writeCString(this.value);+ stream.writeUint32(this.timescale);+ stream.writeUint32(this.presentation_time_delta);+ stream.writeUint32(this.event_duration);+ stream.writeUint32(this.id);+ stream.writeUint8Array(this.message_data);+ }+};++//#endregion+//#region src/boxes/ssix.ts+var ssixBox = class extends FullBox {+ constructor(..._args) {+ super(..._args);+ this.box_name = "CompressedSubsegmentIndexBox";+ }+ static {+ this.fourcc = "ssix";+ }+ parse(stream) {+ this.parseFullHeader(stream);+ this.subsegments = [];+ const subsegment_count = stream.readUint32();+ for (let i = 0; i < subsegment_count; i++) {+ const subsegment = {};+ this.subsegments.push(subsegment);+ subsegment.ranges = [];+ const range_count = stream.readUint32();+ for (let j = 0; j < range_count; j++) {+ const range = {};+ subsegment.ranges.push(range);+ range.level = stream.readUint8();+ range.range_size = stream.readUint24();+ }+ }+ }+};++//#endregion+//#region src/boxes/styp.ts+var stypBox = class extends Box {+ constructor(..._args) {+ super(..._args);+ this.box_name = "SegmentTypeBox";+ }+ static {+ this.fourcc = "styp";+ }+ parse(stream) {+ let toparse = this.size - this.hdr_size;+ this.major_brand = stream.readString(4);+ this.minor_version = stream.readUint32();+ toparse -= 8;+ this.compatible_brands = [];+ let i = 0;+ while (toparse >= 4) {+ this.compatible_brands[i] = stream.readString(4);+ toparse -= 4;+ i++;+ }+ }+ write(stream) {+ this.size = 8 + 4 * this.compatible_brands.length;+ this.writeHeader(stream);+ stream.writeString(this.major_brand, void 0, 4);+ stream.writeUint32(this.minor_version);+ for (let i = 0; i < this.compatible_brands.length; i++) stream.writeString(this.compatible_brands[i], void 0, 4);+ }+};++//#endregion+export { hvc2SampleEntry as $, SingleItemTypeReferenceBoxLarge as $n, hinfBox as $t, OpusSampleEntry as A, xmlBox as An, metxSampleEntry as At, dvh1SampleEntry as B, ContainerBox as Bn, mehdBox as Bt, sdtpBox as C, strdBox as Cn, colrBox as Ct, stxtSampleEntry as D, trgrBox as Dn, waveBox as Dt, tx3gSampleEntry as E, trakBox as En, lvcCBox as Et, avc2SampleEntry as F, SampleEntry as Fn, pitmBox as Ft, encsSampleEntry as G, DIFF_BOXES_PROP_NAMES as Gn, elngBox as Gt, ec_3SampleEntry as H, parseOneBox as Hn, hvcCBox as Ht, avc3SampleEntry as I, SubtitleSampleEntry as In, irefBox as It, encvSampleEntry as J, boxEqualFields as Jn, dinfBox as Jt, enctSampleEntry as K, DIFF_PRIMITIVE_ARRAY_PROP_NAMES as Kn, drefBox as Kt, avc4SampleEntry as L, SystemSampleEntry as Ln, ilocBox as Lt, ac_4SampleEntry as M, AudioSampleEntry as Mn, mvhdBox as Mt, av01SampleEntry as N, HintSampleEntry as Nn, mfhdBox as Nt, stppSampleEntry as O, udtaBox as On, esdsBox as Ot, avc1SampleEntry as P, MetadataSampleEntry as Pn, metaBox as Pt, hvc1SampleEntry as Q, SingleItemTypeReferenceBox as Qn, grplBox as Qt, avs3SampleEntry as R, TextSampleEntry as Rn, iinfBox as Rt, sgpdBox as S, stblBox as Sn, vvs1SampleEntry as St, wvttSampleEntry as T, trafBox as Tn, vpcCBox as Tt, encaSampleEntry as U, registerBoxes as Un, hdlrBox as Ut, dvheSampleEntry as V, parseHex16 as Vn, mdhdBox as Vt, encmSampleEntry as W, registerDescriptors as Wn, ftypBox as Wt, hev1SampleEntry as X, FullBox as Xn, etypBox as Xt, fLaCSampleEntry as Y, Box as Yn, edtsBox as Yt, hev2SampleEntry as Z, SampleGroupEntry as Zn, freeBox as Zt, stscBox as _, povdBox as _n, vp08SampleEntry as _t, ISOFile as a, iproBox as an, Endianness as ar, m4aeSampleEntry as at, smhdBox as b, sinfBox as bn, vvcNSampleEntry as bt, urlBox as c, mdatBox as cn, mhm1SampleEntry as ct, tkhdBox as d, mfraBox as dn, mjpgSampleEntry as dt, hmhdBox as en, TrackGroupTypeBox as er, hvt1SampleEntry as et, tfhdBox as f, minfBox as fn, mp4aSampleEntry as ft, stsdBox as g, nmhdBox as gn, uncvSampleEntry as gt, stszBox as h, mvexBox as hn, resvSampleEntry as ht, createFile as i, ipcoBox as in, DataStream as ir, lvc1SampleEntry as it, ac_3SampleEntry as j, avcCBox as jn, mettSampleEntry as jt, sbttSampleEntry as k, vttcBox as kn, av1CBox as kt, trunBox as l, mdiaBox as ln, mhm2SampleEntry as lt, sttsBox as m, moovBox as mn, mp4vSampleEntry as mt, ssixBox as n, idatBox as nn, MultiBufferStream as nr, lhe1SampleEntry as nt, SampleGroupInfo as o, iprpBox as on, MP4BoxBuffer as or, mha1SampleEntry as ot, tfdtBox as p, moofBox as pn, mp4sSampleEntry as pt, encuSampleEntry as q, boxEqual as qn, bxmlBox as qt, emsgBox as r, iodsBox as rn, Log as rr, lhv1SampleEntry as rt, vmhdBox as s, j2kHBox as sn, MAX_UINT32 as sr, mha2SampleEntry as st, stypBox as t, hntiBox as tn, TrackReferenceTypeBox as tr, j2kiSampleEntry as tt, trexBox as u, mecoBox as un, mjp2SampleEntry as ut, sthdBox as v, rinfBox as vn, vp09SampleEntry as vt, sbgpBox as w, strkBox as wn, vvcCBox as wt, sidxBox as x, skipBox as xn, vvi1SampleEntry as xt, stcoBox as y, schiBox as yn, vvc1SampleEntry as yt, dav1SampleEntry as z, VisualSampleEntry as zn, infeBox as zt };+//# sourceMappingURL=styp-9TIZZDLN.mjs.map\ No newline at end of filediff --git a/test/fixtures/video/README.md b/test/fixtures/video/README.mdnew file mode 100644index 000000000..c72773162--- /dev/null+++ b/test/fixtures/video/README.md@@ -0,0 +1,27 @@+# Video fixtures++One-second 64×64 test clips for `test/generative-media-video.mjs`, made with+FFmpeg 6.1 from its built-in test sources:++| Files | Video | Audio | Container |+| --- | --- | --- | --- |+| `h264-aac-1.mp4`, `h264-aac-2.mp4` | H.264, 12 fps, 2 B-frames | AAC, 16 kHz mono | MP4, faststart, edit lists |+| `h264-aac-fragmented-1.mp4`, `h264-aac-fragmented-2.mp4` | H.264, 12 fps, 2 B-frames | AAC, 16 kHz mono | Fragmented MP4, no edit lists |+| `h264-aac-48px.mp4` | H.264 at 48×48 | AAC | MP4 (codec setup differs from the others) |+| `vp9-opus-1.mp4`, `vp9-opus-2.mp4` | VP9, 12 fps | Opus, 48 kHz mono | MP4 (royalty-free codecs, playable in Playwright's Chromium) |++```sh+H="-c:v libx264 -preset veryfast -pix_fmt yuv420p -g 12 -bf 2 -c:a aac -b:a 24k -ac 1 -shortest"+ffmpeg -f lavfi -i "testsrc=size=64x64:rate=12:duration=1" -f lavfi -i "sine=frequency=300:sample_rate=16000:duration=1" \+ $H -movflags +faststart -fflags +bitexact -map_metadata -1 h264-aac-1.mp4+ffmpeg -f lavfi -i "testsrc=size=64x64:rate=12:duration=1" -f lavfi -i "sine=frequency=500:sample_rate=16000:duration=1" \+ $H -movflags frag_keyframe+empty_moov+default_base_moof -fflags +bitexact -map_metadata -1 h264-aac-fragmented-1.mp4+ffmpeg -f lavfi -i "testsrc2=size=64x64:rate=12:duration=1" -f lavfi -i "sine=frequency=400:sample_rate=48000:duration=1" \+ -c:v libvpx-vp9 -b:v 60k -g 12 -deadline realtime -cpu-used 8 -c:a libopus -b:a 16k -ac 1 -shortest \+ -fflags +bitexact -map_metadata -1 vp9-opus-1.mp4+ffmpeg -f lavfi -i "testsrc=size=48x48:rate=12:duration=1" -f lavfi -i "sine=frequency=300:sample_rate=16000:duration=1" \+ $H -movflags +faststart -fflags +bitexact -map_metadata -1 h264-aac-48px.mp4+```++The second clip of each pair uses a different tone (600, 1000 and 800 Hz), so its+bytes and bitrate fields differ while the codec setup matches.diff --git a/test/fixtures/video/h264-aac-1.mp4 b/test/fixtures/video/h264-aac-1.mp4new file mode 100644index 000000000..3230cd36eBinary files /dev/null and b/test/fixtures/video/h264-aac-1.mp4 differdiff --git a/test/fixtures/video/h264-aac-2.mp4 b/test/fixtures/video/h264-aac-2.mp4new file mode 100644index 000000000..af31c37c1Binary files /dev/null and b/test/fixtures/video/h264-aac-2.mp4 differdiff --git a/test/fixtures/video/h264-aac-48px.mp4 b/test/fixtures/video/h264-aac-48px.mp4new file mode 100644index 000000000..acf7e3b74Binary files /dev/null and b/test/fixtures/video/h264-aac-48px.mp4 differdiff --git a/test/fixtures/video/h264-aac-fragmented-1.mp4 b/test/fixtures/video/h264-aac-fragmented-1.mp4new file mode 100644index 000000000..2313722caBinary files /dev/null and b/test/fixtures/video/h264-aac-fragmented-1.mp4 differdiff --git a/test/fixtures/video/h264-aac-fragmented-2.mp4 b/test/fixtures/video/h264-aac-fragmented-2.mp4new file mode 100644index 000000000..0f813f1c8Binary files /dev/null and b/test/fixtures/video/h264-aac-fragmented-2.mp4 differdiff --git a/test/fixtures/video/vp9-opus-1.mp4 b/test/fixtures/video/vp9-opus-1.mp4new file mode 100644index 000000000..1482e5dd3Binary files /dev/null and b/test/fixtures/video/vp9-opus-1.mp4 differdiff --git a/test/fixtures/video/vp9-opus-2.mp4 b/test/fixtures/video/vp9-opus-2.mp4new file mode 100644index 000000000..92436c688Binary files /dev/null and b/test/fixtures/video/vp9-opus-2.mp4 differdiff --git a/test/generative-media-video.mjs b/test/generative-media-video.mjsnew file mode 100644index 000000000..87e54d0c7--- /dev/null+++ b/test/generative-media-video.mjs@@ -0,0 +1,601 @@+import assert from 'node:assert/strict';+import test, { after, before } from 'node:test';+import fs from 'node:fs/promises';+import { createServer } from 'node:http';+import { extname, resolve, sep } from 'node:path';+import { chromium } from 'playwright';+import { makeSchedulerHarness } from './lib/scheduler-harness.mjs';++// Videos longer than one clip: generate_image fits scenes to the model's clip+// lengths, generates the clips, and joins them into one MP4 without+// re-encoding. Over two minutes it asks the user first (video-length-cap).++const area = { get: async () => ({}), set: async () => {}, remove: async () => {} };+globalThis.chrome = globalThis.browser = { storage: { local: area, session: area }, runtime: { getURL: x => x, sendMessage: async () => ({}) } };++// The generated media store's IndexedDB calls, kept in memory: Node has no+// IndexedDB. Other databases never open.+const assets = new Map();+globalThis.indexedDB = {+ open(name) {+ const request = {};+ if (name !== 'webbrain_generated_media') return request;+ request.result = {+ close() {},+ transaction() {+ const transaction = {+ objectStore: () => ({+ put(record) { assets.set(record.id, record); setTimeout(() => transaction.oncomplete?.()); },+ get(id) { const read = {}; setTimeout(() => { read.result = assets.get(id); read.onsuccess?.(); }); return read; },+ }),+ };+ return transaction;+ },+ };+ setTimeout(() => request.onsuccess?.());+ return request;+ },+};+const storedBytes = async mediaId => new Uint8Array(await assets.get(mediaId).blob.arrayBuffer());++const json = (body, status = 200, headers = {}) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json', ...headers } });+// The mock jobs ask to be polled again at once.+const soon = { 'Retry-After': '0.001' };+const fixtures = Object.fromEntries(await Promise.all([+ 'h264-aac-1', 'h264-aac-2', 'h264-aac-48px', 'h264-aac-fragmented-1', 'h264-aac-fragmented-2', 'vp9-opus-1', 'vp9-opus-2',+].map(async name => [name, new Uint8Array(await fs.readFile(new URL(`./fixtures/video/${name}.mp4`, import.meta.url)))])));+const { createFile, MP4BoxBuffer } = await import('../src/chrome/vendor/mp4box/mp4box.all.mjs');++function parse(bytes) {+ const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);+ const file = createFile();+ file.appendBuffer(MP4BoxBuffer.fromArrayBuffer(buffer, 0));+ file.flush();+ return file;+}++const sampleBytes = (bytes, trak) => trak.samples.map(sample => bytes.subarray(sample.offset, sample.offset + sample.size));++// OpenRouter's video API: a catalog entry, jobs that complete on the first+// poll, and clip bytes chosen per job.+function videoApi({ entry, clip = () => fixtures['h264-aac-1'], fail = () => false }) {+ const calls = { submits: [], inFlight: 0, maxInFlight: 0 };+ const jobs = new Map();+ const fetchImpl = async (url, init = {}) => {+ assert.equal(init.redirect, 'error');+ if (url.endsWith('/images/models')) return json({ data: [] });+ if (url.endsWith('/videos/models')) return json({ data: [entry] });+ if (init.method === 'POST') {+ const body = JSON.parse(init.body);+ const index = calls.submits.push(body) - 1;+ if (fail(index, body)) return json({ error: { message: 'Provider overloaded' } }, 503);+ const id = `job-${index}`;+ jobs.set(id, { body, index });+ calls.inFlight += 1;+ calls.maxInFlight = Math.max(calls.maxInFlight, calls.inFlight);+ return json({ id }, 202, soon);+ }+ const match = /\/videos\/(job-\d+)(\/content)?/.exec(url);+ assert.ok(match, url);+ if (!match[2]) return json({ status: 'completed' }, 200, soon);+ await new Promise(done => setTimeout(done, 5));+ calls.inFlight -= 1;+ return new Response(clip(jobs.get(match[1])), { headers: { 'Content-Type': 'video/mp4' } });+ };+ return { fetchImpl, calls };+}++const grok = { id: 'x-ai/grok-imagine-video-1.5-lite', supported_durations: Array.from({ length: 15 }, (_, i) => i + 1),+ supported_resolutions: ['480p', '720p', '1080p'], supported_aspect_ratios: ['16:9', '9:16', '1:1'] };+const config = { provider: 'openrouter', apiKey: 'or-key', model: grok.id };+// The agent's chat provider, one object so clarification authority matches.+const chatProvider = { name: 'owned', model: 'owned', config: {} };+const scenes = (count, duration) => Array.from({ length: count }, (_, i) => ({ prompt: `Scene idea ${i + 1}`, duration }));+// A card that is still waiting fails the assertion instead of hanging the suite.+const settled = promise => Promise.race([promise, new Promise(done => setTimeout(() => done('still waiting'), 1000))]);++const root = resolve('.');+const server = createServer(async (req, res) => {+ try {+ const path = new URL(req.url, 'http://localhost').pathname;+ if (path === '/__media.html') {+ res.setHeader('Content-Type', 'text/html');+ res.end('<!doctype html><meta charset="utf-8"><div id="chat"></div>');+ return;+ }+ const file = resolve(root, `.${path}`);+ if (!file.startsWith(root + sep)) throw new Error('outside root');+ res.setHeader('Content-Type', ({ '.js': 'text/javascript', '.mjs': 'text/javascript', '.mp4': 'video/mp4' })[extname(file)] || 'text/plain');+ res.end(await fs.readFile(file));+ } catch { res.statusCode = 404; res.end(); }+});+let browser, origin;+before(async () => {+ browser = await chromium.launch({ headless: true });+ await new Promise(done => server.listen(0, '127.0.0.1', done));+ origin = `http://127.0.0.1:${server.address().port}`;+});+after(async () => {+ await browser?.close();+ await new Promise(done => server.close(done));+});++for (const build of ['chrome', 'firefox']) {+ const join = await import(`../src/${build}/src/agent/video-join.js`);+ const media = await import(`../src/${build}/src/agent/generative-media.js`);+ const journal = await import(`../src/${build}/src/run-ui-journal.js`);+ const { Agent } = await import(`../src/${build}/src/agent/agent.js`);+ const Scheduler = await import(`../src/${build}/src/agent/scheduler.js`);+ // generate_image as the agent calls it, with the selected OpenRouter model.+ const generate = (args, options) => media.generateImage(args, { config, ...options });++ test(`${build}: clips with one codec setup join into one MP4 without re-encoding`, () => {+ const sources = [fixtures['h264-aac-1'], fixtures['h264-aac-2']];+ const { bytes, durationSeconds } = join.joinMp4Clips(sources);+ assert.equal(durationSeconds, 2);+ assert.equal(join.mp4DurationSeconds(bytes), 2);+ const output = parse(bytes);+ assert.deepEqual(output.boxes.map(box => box.type), ['ftyp', 'moov', 'mdat'], 'moov comes before mdat');+ const [video, audio] = output.moov.traks;+ assert.equal(video.mdia.hdlr.handler, 'vide');+ assert.equal(audio.mdia.hdlr.handler, 'soun');+ // Every video frame is the source's frame, byte for byte, in order.+ const sourceFrames = sources.flatMap(source => sampleBytes(source, parse(source).moov.traks[0]));+ const joinedFrames = sampleBytes(bytes, video);+ assert.equal(joinedFrames.length, 24);+ joinedFrames.forEach((frame, index) => assert.deepEqual(frame, sourceFrames[index], `frame ${index}`));+ // The second clip's frames are shown right after the first clip's.+ const shown = video.samples.map(sample => sample.cts - video.edts.elst.entries[0].media_time).sort((a, b) => a - b);+ assert.deepEqual(shown.map(value => value / 1024), Array.from({ length: 24 }, (_, i) => i));+ // Audio: the first clip's frames are all kept; the second clip's start-up+ // frame is dropped, the rest is copied as is, and its first real frame+ // plays exactly one second in, with its picture.+ const [firstAudio, secondAudio] = sources.map(source => sampleBytes(source, parse(source).moov.traks[1]));+ assert.deepEqual(sampleBytes(bytes, audio).slice(0, 17), firstAudio);+ assert.deepEqual(sampleBytes(bytes, audio).slice(17), secondAudio.slice(1));+ assert.equal(audio.samples[17].cts - audio.edts.elst.entries[0].media_time, 16000);+ });++ test(`${build}: fragmented and VP9/Opus clips join too`, () => {+ // [clips, codecs, audio frames kept from the first clip, where the second clip's audio starts]+ for (const [names, codecs, seam, seamTime] of [+ // No edit lists: the first clip's last kept frame is lengthened to meet the second.+ [['h264-aac-fragmented-1', 'h264-aac-fragmented-2'], ['avc1', 'mp4a'], 14, 16000],+ // Opus: the first clip's short final frame would play over the second+ // clip's first frame, so it is dropped rather than squeezed.+ [['vp9-opus-1', 'vp9-opus-2'], ['vp09', 'Opus'], 50, 48000],+ ]) {+ const label = names.join('+');+ const { bytes, durationSeconds } = join.joinMp4Clips(names.map(name => fixtures[name]));+ assert.equal(durationSeconds, 2, label);+ const output = parse(bytes);+ const [video, audio] = output.moov.traks;+ assert.deepEqual(output.moov.traks.map(trak => trak.mdia.minf.stbl.stsd.entries[0].type), codecs, label);+ assert.equal(video.samples.length, 24, label);+ const firstAudio = sampleBytes(fixtures[names[0]], parse(fixtures[names[0]]).moov.traks[1]);+ const secondAudio = parse(fixtures[names[1]]).moov.traks[1];+ assert.deepEqual(sampleBytes(bytes, audio).slice(0, seam), firstAudio.slice(0, seam), `${label}: the first clip's audio up to the seam`);+ assert.deepEqual(sampleBytes(bytes, audio).slice(seam), sampleBytes(fixtures[names[1]], secondAudio), `${label}: the second clip's audio, whole`);+ assert.equal(audio.samples[seam].cts, seamTime, `${label}: the second clip's audio starts one second in`);+ const shortest = Math.min(...secondAudio.samples.map(sample => sample.duration));+ assert.ok(audio.samples.every(sample => sample.duration >= shortest), `${label}: no frame is squeezed`);+ }+ });++ test(`${build}: clips with different codec settings or tracks are not joined`, () => {+ for (const pair of [['h264-aac-1', 'h264-aac-48px'], ['h264-aac-1', 'vp9-opus-1']]) {+ assert.throws(() => join.joinMp4Clips(pair.map(name => fixtures[name])), error => error.code === 'clips_incompatible', pair.join('+'));+ }+ assert.throws(() => join.joinMp4Clips([fixtures['h264-aac-1'], new Uint8Array([0, 0, 0, 8, 102, 114, 101, 101])]), error => error.code === 'not_mp4');+ assert.throws(() => join.joinMp4Clips([fixtures['h264-aac-1'], fixtures['h264-aac-2']], { maxBytes: 1000 }), error => error.code === 'too_large');+ assert.equal(join.mp4DurationSeconds(new Uint8Array([1, 2, 3])), null);+ });++ test(`${build}: scenes fit the model's clip lengths and stay within two minutes`, () => {+ const { clips, total } = media.planVideoClips([{ prompt: 'Opening', duration: 12 }, { prompt: 'Long walk', duration: 20 }], [5, 10, 15]);+ assert.deepEqual(clips, [+ { prompt: 'Opening', duration: 15 },+ { prompt: 'Long walk (part 1 of 2)', duration: 10 },+ { prompt: 'Long walk (part 2 of 2)', duration: 10 },+ ]);+ assert.equal(total, 35);+ assert.equal(media.planVideoClips(scenes(8, 15), grok.supported_durations).total, 120);+ assert.throws(() => media.planVideoClips(scenes(9, 15), grok.supported_durations), /up to 120 s/);+ assert.throws(() => media.planVideoClips(scenes(25, 4), grok.supported_durations), /at most 24/);+ assert.throws(() => media.planVideoClips(scenes(2, 5), null), /does not list the clip lengths/);+ assert.throws(() => media.planVideoClips([{ prompt: ' ', duration: 5 }], [5]), /Scene 1 needs a prompt/);+ });++ test(`${build}: one clip sends only the duration, aspect ratio and resolution the model supports`, async () => {+ const api = videoApi({ entry: grok });+ const result = await generate({ prompt: 'A red apple', duration: 8, aspect_ratio: '9:16', resolution: '720p' }, { fetchImpl: api.fetchImpl });+ assert.equal(result.success, true, result.error);+ assert.deepEqual(api.calls.submits, [{ model: grok.id, prompt: 'A red apple', duration: 8, aspect_ratio: '9:16', resolution: '720p' }]);+ assert.equal(result.mimeType, 'video/mp4');+ assert.equal(result.durationSeconds, 1, "the clip's real length");+ assert.deepEqual(await storedBytes(result.mediaId), fixtures['h264-aac-1']);+ const estimated = videoApi({ entry: { ...grok, supported_durations: [4, 8, 12] } });+ await media.runMediaGeneration({ prompt: 'A red apple', video: { estimated_duration: 7 }, config, fetchImpl: estimated.fetchImpl });+ assert.equal(estimated.calls.submits[0].duration, 8, 'an estimate rounds up to a clip length the model makes');+ for (const [video, pattern] of [+ [{ duration: 16 }, /needs more than one clip/],+ [{ estimated_duration: 40 }, /Describe it as scenes/],+ [{ aspect_ratio: '4:5' }, /does not support aspect_ratio "4:5"\. Supported: 16:9, 9:16, 1:1/],+ [{ resolution: '4K' }, /does not support resolution/],+ [{ scenes: scenes(2, 5) }, /estimated_duration/],+ [{ scenes: scenes(2, 5), estimated_duration: 10, duration: 5 }, /each scene its duration/],+ ]) {+ const rejected = videoApi({ entry: grok });+ await assert.rejects(media.runMediaGeneration({ prompt: 'A red apple', video, config, fetchImpl: rejected.fetchImpl }), pattern, JSON.stringify(video));+ assert.equal(rejected.calls.submits.length, 0, 'nothing is submitted');+ }+ await assert.rejects(media.runMediaGeneration({ prompt: 'x', video: { duration: 5 }, config,+ fetchImpl: async url => (url.endsWith('/images/models') ? json({ data: [{ id: grok.id }] }) : assert.fail(url)) }), /need a video model/);+ await assert.rejects(media.runMediaGeneration({ prompt: 'x', video: { duration: 5 }, config: { apiKey: 'k', model: 'fal-ai/flux/schnell' },+ fetchImpl: async url => assert.fail(url) }), /OpenRouter video models/);+ });++ test(`${build}: a video of two minutes or less generates without asking`, async () => {+ const api = videoApi({ entry: grok });+ const progress = [];+ let asked = 0;+ const result = await generate({ prompt: 'Flat motion graphics, navy background', scenes: scenes(4, 15), estimated_duration: 60 }, {+ fetchImpl: api.fetchImpl, onProgress: message => progress.push(message),+ confirmVideoLength: async () => { asked += 1; return 'once'; },+ });+ assert.equal(result.success, true, result.error);+ assert.equal(asked, 0, 'no card within the cap');+ assert.equal(api.calls.submits.length, 4);+ assert.ok(api.calls.maxInFlight <= 3, `at most three clips at a time (saw ${api.calls.maxInFlight})`);+ api.calls.submits.forEach((body, index) => {+ assert.equal(body.duration, 15);+ assert.equal(body.prompt, `Flat motion graphics, navy background\n\nScene ${index + 1} of 4: Scene idea ${index + 1}`);+ });+ assert.equal(result.clipCount, 4);+ assert.equal(result.durationSeconds, 4, 'the real length of the joined clips');+ assert.equal(result.mimeType, 'video/mp4');+ assert.equal(join.mp4DurationSeconds(await storedBytes(result.mediaId)), 4, 'one joined asset');+ assert.deepEqual(progress, ['Generating 4 video clips…', 'Video clips: 1 of 4 ready', 'Video clips: 2 of 4 ready',+ 'Video clips: 3 of 4 ready', 'Video clips: 4 of 4 ready', 'Joining 4 clips…']);+ });++ test(`${build}: a longer estimate asks first and generates nothing unless the user agrees`, async () => {+ for (const [answer, pattern] of [['deny', /chose not to generate the 2:00 version/], ['unavailable', /could not ask the user/], [null, /withdrawn/]]) {+ const api = videoApi({ entry: grok });+ const asked = [];+ const result = await generate({ prompt: 'Explainer', scenes: scenes(8, 15), estimated_duration: 330 }, {+ fetchImpl: api.fetchImpl, confirmVideoLength: async details => { asked.push(details); return answer; },+ });+ assert.deepEqual(asked, [{ estimatedSeconds: 330, totalSeconds: 120, clipCount: 8, maxSeconds: 120 }]);+ assert.equal(result.success, false);+ assert.equal(result.declined, true);+ assert.match(result.error, /needs about 5:30/);+ assert.match(result.error, pattern);+ assert.equal(api.calls.submits.length, 0, `${answer}: nothing is submitted`);+ }+ const api = videoApi({ entry: grok });+ const approved = await generate({ prompt: 'Explainer', scenes: scenes(8, 15), estimated_duration: 330 }, {+ fetchImpl: api.fetchImpl, confirmVideoLength: async () => 'once',+ });+ assert.equal(approved.success, true, approved.error);+ assert.equal(api.calls.submits.length, 8);+ assert.equal(approved.clipCount, 8);+ const withoutCard = videoApi({ entry: grok });+ const unasked = await generate({ prompt: 'Explainer', scenes: scenes(8, 15), estimated_duration: 330 }, { fetchImpl: withoutCard.fetchImpl });+ assert.equal(unasked.declined, true, 'without a card nothing is generated');+ assert.equal(withoutCard.calls.submits.length, 0);+ });++ test(`${build}: a clip is retried once and a second failure ends the video`, async () => {+ const retried = videoApi({ entry: grok, fail: index => index === 1 });+ const recovered = await generate({ prompt: 'Story', scenes: scenes(3, 10), estimated_duration: 30 }, { fetchImpl: retried.fetchImpl });+ assert.equal(recovered.success, true, recovered.error);+ assert.equal(retried.calls.submits.length, 4, 'three clips and one retry');+ const failing = videoApi({ entry: grok, fail: (_index, body) => body.prompt.includes('Scene 2 of 3') });+ const stored = assets.size;+ const failed = await generate({ prompt: 'Story', scenes: scenes(3, 10), estimated_duration: 30 }, { fetchImpl: failing.fetchImpl });+ assert.equal(failed.success, false);+ assert.match(failed.error, /^Clip 2 of 3 failed: OpenRouter video submit failed \(HTTP 503\).*Provider overloaded/);+ assert.equal(assets.size, stored, 'no partial video is kept');+ });++ test(`${build}: Stop ends every clip of a video`, async () => {+ const controller = new AbortController();+ const api = videoApi({ entry: grok });+ const stored = assets.size;+ const result = await generate({ prompt: 'Story', scenes: scenes(5, 10), estimated_duration: 50 }, {+ signal: controller.signal,+ // The user presses Stop while the first clip downloads.+ fetchImpl: async (url, init) => {+ if (url.includes('/content')) {+ controller.abort(new Error('Stopped by user.'));+ init.signal.throwIfAborted();+ }+ return api.fetchImpl(url, init);+ },+ });+ assert.equal(result.success, false);+ assert.equal(result.error, 'Stopped by user.');+ assert.equal(api.calls.submits.length, 3, 'clips 4 and 5 never start');+ assert.equal(assets.size, stored);+ });++ test(`${build}: clips that cannot be joined are kept and shown in order`, async () => {+ const api = videoApi({ entry: grok, clip: job => (job.index === 1 ? fixtures['h264-aac-48px'] : fixtures['h264-aac-1']) });+ const result = await generate({ prompt: 'Story', scenes: scenes(2, 10), estimated_duration: 20 }, { fetchImpl: api.fetchImpl });+ assert.equal(result.success, true, result.error);+ assert.equal(result.joined, false);+ assert.equal(result.clipCount, 2);+ assert.equal(result.durationSeconds, 2);+ assert.equal(result.mediaId, undefined);+ assert.deepEqual(result.clips.map(clip => clip.mimeType), ['video/mp4', 'video/mp4']);+ assert.deepEqual(await storedBytes(result.clips[1].mediaId), fixtures['h264-aac-48px']);+ const compacted = journal.compactRunUiData('tool_result', { name: 'generate_image', result });+ assert.deepEqual(compacted.result.clips, result.clips, 'the journal keeps the clips for replay');+ assert.equal(compacted.result.joined, false);+ assert.equal(compacted.result.clipCount, 2);+ const agent = new Agent({ getActive: () => chatProvider });+ const forModel = JSON.parse(agent._limitToolResult(result));+ assert.ok(forModel.clips.every(clip => !('mediaId' in clip)), 'asset handles stay out of model context');+ assert.match(forModel.note, /shows them one after another/);+ assert.match(forModel.note, /You have not seen it/);+ assert.match(forModel.note, /do not invent a hosted URL/);+ });++ test(`${build}: the chat shows a joined video as one video that plays to the end`, async () => {+ const page = await browser.newPage();+ try {+ await page.goto(`${origin}/__media.html`);+ const shown = await page.evaluate(async ({ build, entry }) => {+ const { generateImage } = await import(`/src/${build}/src/agent/generative-media.js`);+ const { appendGeneratedMedia } = await import(`/src/${build}/src/ui/generated-media-view.js`);+ const { compactRunUiData } = await import(`/src/${build}/src/run-ui-journal.js`);+ const fixture = async name => (await fetch(`/test/fixtures/video/${name}.mp4`)).arrayBuffer();+ const reply = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json', 'Retry-After': '0.001' } });+ const run = clips => {+ let submitted = 0;+ return generateImage({ prompt: 'Test pattern', scenes: clips.map((_, i) => ({ prompt: `Part ${i + 1}`, duration: 1 })), estimated_duration: clips.length }, {+ config: { provider: 'openrouter', apiKey: 'synthetic-key', model: entry.id },+ fetchImpl: async (url, init = {}) => {+ if (url.endsWith('/images/models')) return reply({ data: [] });+ if (url.endsWith('/videos/models')) return reply({ data: [entry] });+ if (init.method === 'POST') return reply({ id: `job-${submitted++}` }, 202);+ const [, index, content] = /job-(\d+)(\/content)?/.exec(url);+ return content ? new Response(await fixture(clips[index]), { headers: { 'Content-Type': 'video/mp4' } }) : reply({ status: 'completed' });+ },+ });+ };+ // What the side panel renders: the run journal's copy of the tool result.+ const show = async result => {+ if (!result.success) throw new Error(result.error);+ const container = document.createElement('div');+ document.querySelector('#chat').append(container);+ await appendGeneratedMedia(container, compactRunUiData('tool_result', { name: 'generate_image', result }).result, key => key);+ return container;+ };+ const joined = await run(['vp9-opus-1', 'vp9-opus-2']);+ const single = await show(joined);+ const video = single.querySelector('video');+ await new Promise((resolve, reject) => {+ if (video.readyState >= 1) resolve();+ video.onloadedmetadata = resolve;+ video.onerror = () => reject(new Error(`media error ${video.error?.code}`));+ });+ video.muted = true;+ video.playbackRate = 4;+ const ended = new Promise(resolve => { video.onended = () => resolve(true); setTimeout(() => resolve(false), 8000); });+ await video.play();+ const playedToEnd = await ended;+ const separate = await run(['vp9-opus-1', 'h264-aac-48px']);+ const several = await show(separate);+ return {+ joined: { clipCount: joined.clipCount, durationSeconds: joined.durationSeconds, videos: single.querySelectorAll('video').length,+ duration: video.duration, playedToEnd, frames: video.getVideoPlaybackQuality().totalVideoFrames,+ download: single.querySelector('a[download]')?.getAttribute('download') },+ separate: { joined: separate.joined, clips: separate.clips.map(clip => clip.mediaId),+ shown: [...several.querySelectorAll('.generated-media')].map(wrapper => wrapper.dataset.mediaId),+ playable: [...several.querySelectorAll('video')].map(element => element.src.startsWith('blob:')) },+ };+ }, { build, entry: grok });+ assert.deepEqual(shown.joined, { clipCount: 2, durationSeconds: 2, videos: 1, duration: 2, playedToEnd: true,+ frames: shown.joined.frames, download: 'webbrain-media.mp4' });+ assert.ok(shown.joined.frames >= 20, `rendered ${shown.joined.frames} frames`);+ assert.equal(shown.separate.joined, false);+ assert.deepEqual(shown.separate.shown, shown.separate.clips, 'unjoinable clips appear in order');+ assert.deepEqual(shown.separate.playable, [true, true]);+ } finally { await page.close(); }+ });++ test(`${build}: the agent asks on WebBrain's card, and an unattended run cannot`, async () => {+ const tab = 41, request = 'video-request', runId = 'video-run';+ const agent = new Agent({ getActive: () => chatProvider });+ agent._persist = () => {};+ agent._runningTabs.add(tab);+ agent.currentRunId.set(tab, runId);+ agent.conversations.set(tab, [{ role: 'system', content: 'Owned fixture.' }, { role: 'user', content: 'Turn this page into a video.' }]);+ agent._beginSteeringRun(tab, () => {}, { detachedRequestId: request });+ const details = { estimatedSeconds: 330, totalSeconds: 120, clipCount: 8, maxSeconds: 120 };+ const updates = [];+ const onUpdate = (type, data) => {+ updates.push({ type, data });+ if (type === 'clarify') agent._capturePendingClarificationForUi(tab, request, data, { seq: 1, runId });+ };+ const answer = agent._promptVideoLengthConfirmation(tab, details, onUpdate);+ const card = updates.find(update => update.type === 'clarify').data;+ assert.equal(card.promptKind, 'video_length');+ assert.deepEqual(card.videoLengthConfirmation, details);+ assert.deepEqual(card.options, ['once', 'deny']);+ assert.equal(card.timeoutSec, undefined, 'the card never times out');+ assert.match(card.question, /needs about 5:30.*up to 2:00.*2:00 version from 8 clips/);+ assert.deepEqual(agent.activeRunState(tab).pendingCurrentClarification.data.videoLengthConfirmation, details, 'a reopened panel can show the card');+ agent.submitClarifyResponse(tab, card.clarifyId, 'once', 'user');+ assert.equal(await settled(answer), 'once');+ const cancelled = agent._promptVideoLengthConfirmation(tab, details, onUpdate);+ agent._cancelClarifications(tab, 'Stopped');+ assert.equal(await settled(cancelled), null);+ updates.length = 0;+ agent.scheduledRunPolicies.set(tab, { requireConsequentialConfirmation: false });+ assert.equal(await settled(agent._promptVideoLengthConfirmation(tab, details, onUpdate)), 'unavailable');+ assert.equal(updates.length, 0, 'an unattended run shows no card');+ agent.scheduledRunPolicies.delete(tab);+ assert.equal(await settled(agent._promptVideoLengthConfirmation(tab, details, null)), 'unavailable');+ agent._cancelClarifications(tab, 'cleanup');+ });++ test(`${build}: a scheduled run keeps the video length card for a reopened panel`, async () => {+ let finish;+ const details = { estimatedSeconds: 330, totalSeconds: 120, clipCount: 8, maxSeconds: 120 };+ const h = makeSchedulerHarness(Scheduler, {+ processMessage: async (_tab, _message, onUpdate) => {+ onUpdate('clarify', { promptKind: 'video_length', clarifyId: 'video_length_1', options: ['once', 'deny'],+ question: 'This video needs about 5:30, but WebBrain makes videos up to 2:00. Generate a 2:00 version from 8 clips instead?',+ videoLengthConfirmation: details });+ await new Promise(resolve => { finish = resolve; });+ return 'done';+ },+ });+ const created = await h.manager.createResumeJob({ tabId: 77, conversationId: 'conv-1',+ args: { after_seconds: 60, reason: 'wait', resume_instruction: 'make the video' } });+ const running = h.manager.handleAlarm(h.alarmName(created.jobId));+ await new Promise(resolve => setTimeout(resolve, 0));+ const pending = h.jobs()[0].pendingClarify;+ assert.equal(h.jobs()[0].status, 'needs_user_input');+ assert.equal(pending.promptKind, 'video_length');+ assert.deepEqual(pending.options, ['once', 'deny']);+ assert.deepEqual(pending.videoLengthConfirmation, details);+ assert.equal(pending.timeoutSec, undefined, 'no countdown');+ finish();+ await running;+ });++ test(`${build}: generate_image in a run reports clip progress and asks before a long video`, async () => {+ const tab = 43;+ const agent = new Agent({ getActive: () => chatProvider });+ agent._persist = () => {};+ const updates = [];+ let answer = 'deny';+ const onUpdate = (type, data) => {+ updates.push({ type, data });+ if (type === 'clarify') agent.submitClarifyResponse(tab, data.clarifyId, answer, 'user');+ };+ const originalFetch = globalThis.fetch;+ try {+ const short = videoApi({ entry: grok });+ globalThis.fetch = short.fetchImpl;+ const result = await agent._executeToolImpl(tab, 'generate_image', { prompt: 'Explainer', scenes: scenes(2, 10), estimated_duration: 20 }, onUpdate, { imageGenConfig: config });+ assert.equal(result.success, true, result.error);+ assert.equal(result.clipCount, 2);+ assert.ok(assets.has(result.mediaId));+ assert.deepEqual(updates.map(({ type, data }) => [type, data.name, data.message]), [+ ['tool_progress', 'generate_image', 'Generating 2 video clips…'],+ ['tool_progress', 'generate_image', 'Video clips: 1 of 2 ready'],+ ['tool_progress', 'generate_image', 'Video clips: 2 of 2 ready'],+ ['tool_progress', 'generate_image', 'Joining 2 clips…'],+ ]);+ updates.length = 0;+ const long = videoApi({ entry: grok });+ globalThis.fetch = long.fetchImpl;+ const declined = await agent._executeToolImpl(tab, 'generate_image', { prompt: 'Explainer', scenes: scenes(8, 15), estimated_duration: 330 }, onUpdate, { imageGenConfig: config });+ assert.deepEqual(updates.map(update => [update.type, update.data.promptKind]), [['clarify', 'video_length']]);+ assert.equal(declined.success, false);+ assert.match(declined.error, /The user chose not to generate the 2:00 version/);+ assert.equal(long.calls.submits.length, 0);+ answer = 'once';+ const approved = await agent._executeToolImpl(tab, 'generate_image', { prompt: 'Explainer', scenes: scenes(8, 15), estimated_duration: 330 }, onUpdate, { imageGenConfig: config });+ assert.equal(approved.success, true, approved.error);+ assert.equal(approved.clipCount, 8);+ assert.equal(long.calls.submits.length, 8);+ } finally { globalThis.fetch = originalFetch; }+ });++ test(`${build}: the generate_image schema takes scenes and nothing else`, async () => {+ const originalChrome = globalThis.chrome, originalBrowser = globalThis.browser;+ const local = { get: async () => ({ imageGenModel: config }), set: async () => {}, remove: async () => {} };+ globalThis.chrome = globalThis.browser = {+ storage: { local, session: local }, runtime: { getURL: value => `chrome-extension://test/${value}`, sendMessage: async () => ({}) },+ tabs: { get: async id => ({ id, url: 'https://example.com', title: 'Example' }), sendMessage: async () => ({}) },+ scripting: { executeScript: async () => [{ result: null }] },+ };+ try {+ const provider = { supportsVision: false, promptTier: 'full' };+ const agent = new Agent({ getActive: () => provider, getVisionProvider: async () => null });+ agent._ensureGateSetting = async () => {};+ agent._persist = () => {};+ agent.permissions.check = () => ({ allowed: true });+ const dispatched = [], messages = [];+ agent.executeTool = async (_tab, _name, args) => { dispatched.push(args); return { success: false, error: 'Not generated in this test.' }; };+ const call = args => agent._executeToolBatch(12, [{ id: 'media-call', function: { name: 'generate_image', arguments: JSON.stringify(args) } }],+ messages, () => {}, provider, '', new Set(['generate_image']), 1);+ const valid = { prompt: 'Flat motion graphics', scenes: [{ prompt: 'Title card', duration: 6 }, { prompt: 'The idea', duration: 15 }],+ estimated_duration: 21, aspect_ratio: '16:9', resolution: '720p' };+ await call(valid);+ assert.deepEqual(dispatched, [valid]);+ for (const [invalid, path] of [+ [{ ...valid, scenes: [{ prompt: 'Title card', duration: 6, camera: 'drone' }] }, '$.scenes[0].camera'],+ [{ ...valid, scenes: [{ prompt: 'Title card' }] }, '$.scenes[0].duration'],+ [{ ...valid, estimated_duration: 0 }, '$.estimated_duration'],+ [{ ...valid, duration: '8s' }, '$.duration'],+ ]) {+ messages.length = 0;+ await call(invalid);+ assert.match(messages[0].content, /invalid_tool_arguments/, path);+ assert.ok(messages[0].content.includes(path), `${path}: ${messages[0].content}`);+ }+ assert.equal(dispatched.length, 1, 'invalid calls are not dispatched');+ } finally { globalThis.chrome = originalChrome; globalThis.browser = originalBrowser; }+ });++ test(`${build}: the side panel card states the length in the user's language`, async () => {+ const source = (await fs.readFile(new URL(`../src/${build}/src/ui/sidepanel.js`, import.meta.url), 'utf8')).replace(/\r\n/g, '\n');+ const extract = name => {+ const start = source.search(new RegExp(`^(?:async )?function ${name}\\(`, 'm'));+ assert.ok(start >= 0, name);+ return source.slice(start, source.indexOf('\n}', start) + 2);+ };+ const dictionary = (await import(`../src/${build}/src/ui/locales/tr.js`)).default;+ const english = (await import(`../src/${build}/src/ui/locales/en.js`)).default;+ for (const key of ['question', 'offer', 'generate', 'dont', 'seconds']) {+ assert.equal(typeof english[`sp.video_length.${key}`], 'string', key);+ assert.notEqual(dictionary[`sp.video_length.${key}`], english[`sp.video_length.${key}`], `tr ${key} is translated`);+ }+ const page = await browser.newPage();+ try {+ await page.setContent('<div id="messages"><div class="message assistant" data-run-request-id="video-request"><div class="message-content"><div class="message-text"></div></div></div></div>');+ await page.evaluate(({ functions, dictionary }) => {+ const noop = () => {};+ Object.assign(window, {+ messagesEl: document.querySelector('#messages'), currentAssistantEl: document.querySelector('.assistant'), currentTabId: 7,+ submittedClarificationIds: new Set(), answers: [],+ t: (key, params) => String(dictionary[key] ?? key).replace(/\{(\w+)\}/g, (_, name) => (params?.[name] != null ? String(params[name]) : `{${name}}`)),+ submitClarify: (_card, _tab, clarifyId, value, source) => window.answers.push({ clarifyId, value, source }),+ hideRecommendedActions: noop, resetChatNavigation: noop, hideActivity: noop, scrollToBottom: noop, applyClarifyTimeoutExtension: noop,+ addMessage: () => { throw new Error('no new message'); },+ });+ (0, eval)(functions);+ window.renderClarifyCard({ clarifyId: 'video_length_1', promptKind: 'video_length', question: 'English fallback',+ videoLengthConfirmation: { estimatedSeconds: 330, totalSeconds: 120, clipCount: 8, maxSeconds: 120 }, options: ['once', 'deny'] });+ }, { functions: ['renderClarifyCard', 'clarificationSubmissionKey'].map(extract).join('\n'), dictionary });+ const card = page.locator('.clarify-card[data-video-length-confirmation="1"]');+ assert.equal(await card.locator('.clarify-question').innerText(), 'Bu video yaklaşık 5:30 gerektiriyor, ancak WebBrain en fazla 2:00 uzunluğunda video üretiyor.');+ assert.equal(await card.locator('.clarify-reason').innerText(), 'Bunun yerine 8 klipten 2:00 uzunluğunda bir sürüm üretilsin mi?');+ assert.deepEqual(await card.locator('.clarify-option').allInnerTexts(), ['2:00 sürümünü üret', 'Üretme']);+ assert.equal(await card.locator('.clarify-input').count(), 0, 'fixed choices, no free text');+ await card.locator('.clarify-option[data-value="deny"]').click();+ assert.deepEqual(await page.evaluate(() => window.answers), [{ clarifyId: 'video_length_1', value: 'deny', source: 'option' }]);+ } finally { await page.close(); }+ });++ test(`${build}: the model reports a joined video's length, never its contents`, () => {+ const agent = new Agent({ getActive: () => chatProvider });+ const forModel = JSON.parse(agent._limitToolResult({ success: true, provider: 'openrouter', model: grok.id,+ mediaId: 'private-asset-id', mimeType: 'video/mp4', inlineMedia: true, durationSeconds: 112.5, clipCount: 8 }));+ assert.equal(forModel.mediaId, undefined);+ assert.equal(forModel.durationSeconds, 112.5);+ assert.equal(forModel.clipCount, 8);+ assert.match(forModel.note, /describe it only by what you asked for and by its durationSeconds and clipCount/);+ assert.doesNotMatch(forModel.note, /one after another/);+ const compacted = journal.compactRunUiData('tool_result', { name: 'generate_image', result: { success: true, mediaId: 'a', mimeType: 'video/mp4', durationSeconds: 112.5, clipCount: 8 } });+ assert.equal(compacted.result.durationSeconds, 112.5);+ assert.equal(compacted.result.clipCount, 8);+ });+}diff --git a/test/run.js b/test/run.jsindex fdf4d64b1..67e181866 100644--- a/test/run.js+++ b/test/run.js@@ -57733,8 +57733,8 @@ test('sidepanel long replies use reading-first turn navigation', () => {);assert.equal((clarifySource.match(/scrollToBottom\(\{ force: true \}\);/g) || []).length,- 7,- `${label}: workflow healing, submit, recipient, deletion, unverified-step, permission, and clarify prompts should override reading-first scroll suppression`,+ 8,+ `${label}: workflow healing, submit, recipient, deletion, video-length, unverified-step, permission, and clarify prompts should override reading-first scroll suppression`,);assert.match(panel,@@ -134200,7 +134200,7 @@ test('generate_image tool exists in both builds, full tier only, and settings UIconst agentJs = fs.readFileSync(path.join(ROOT, `src/${build}/src/agent/agent.js`), 'utf8');assert.ok(agentJs.includes("name === 'generate_image'"), `${build}: agent.js should dispatch generate_image`);- assert.match(agentJs, /generateImage\(args, \{ signal: executionContext\?\._contentActionAbortSignal, \.\.\.\(executionContext\?\.imageGenConfig \? \{ config: executionContext\.imageGenConfig \} : \{\}\) \}\)/,+ assert.match(agentJs, /generateImage\(args, \{\s*signal: executionContext\?\._contentActionAbortSignal,\s*\.\.\.\(executionContext\?\.imageGenConfig \? \{ config: executionContext\.imageGenConfig \} : \{\}\),/,`${build}: agent.js should pass the linked run signal into fal generation`);assert.equal(untrustedTools.has('generate_image'), true, `${build}: fal.ai output must be untrusted`);