@grundyjs/canvas-take 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ import type { AudioEncoderFactory } from './video.js';
2
+ export interface AacEncoderOptions {
3
+ readonly workerUrl?: string | URL;
4
+ /** Per-command startup/encode/flush timeout. Default 30000 ms. */
5
+ readonly timeoutMs?: number;
6
+ }
7
+ /** Dedicated Worker running the pinned libavcodec AAC-LC WASM backend; no native AAC assumption. */
8
+ export declare function createAacAudioEncoder(options?: AacEncoderOptions): AudioEncoderFactory;
@@ -0,0 +1,174 @@
1
+ function invalid(config) {
2
+ if (config.codec !== 'mp4a.40.2' || config.bitstreamFormat !== 'aac')
3
+ return 'AAC adapter requires mp4a.40.2 with raw aac framing';
4
+ if (![44100, 48000].includes(config.sampleRate) || ![1, 2].includes(config.numberOfChannels))
5
+ return 'AAC adapter supports 44.1/48 kHz mono/stereo';
6
+ if (!Number.isSafeInteger(config.bitrate) || config.bitrate < 8000 || config.bitrate > 512000)
7
+ return 'AAC bitrate must be an integer in 8000..512000';
8
+ return undefined;
9
+ }
10
+ const us = (samples, rate) => Math.sign(samples) * Number((BigInt(Math.abs(samples)) * 1000000n + BigInt(rate / 2)) / BigInt(rate));
11
+ /** Dedicated Worker running the pinned libavcodec AAC-LC WASM backend; no native AAC assumption. */
12
+ export function createAacAudioEncoder(options = {}) {
13
+ const workerUrl = options.workerUrl, timeoutMs = options.timeoutMs === undefined ? 30000 : options.timeoutMs;
14
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647)
15
+ throw new RangeError('AAC timeoutMs must be 1..2147483647');
16
+ return {
17
+ async checkSupport(config) {
18
+ const reason = invalid(config) ?? (typeof Worker === 'undefined' || typeof WebAssembly === 'undefined' ? 'AAC requires Worker and WebAssembly' : undefined);
19
+ return reason ? { supported: false, reason } : { supported: true };
20
+ },
21
+ async create(config, context) {
22
+ const reason = invalid(config);
23
+ if (reason)
24
+ throw new DOMException(reason, 'NotSupportedError');
25
+ if (context.signal.aborted)
26
+ throw context.signal.reason;
27
+ const channels = config.numberOfChannels, rate = config.sampleRate;
28
+ if (1024 * channels * 4 > context.maxPendingBytes)
29
+ throw new RangeError('AAC maxPendingBytes cannot hold one codec frame');
30
+ let worker = workerUrl === undefined ? new Worker(new URL('./video-aac-worker.js', import.meta.url), { type: 'module' }) : new Worker(workerUrl, { type: 'module' });
31
+ let id = 0, failure, disposed = false, ended = false, accepted = 0, filled = 0, encoded = 0;
32
+ let first, last, pcm = new Float32Array(1024 * channels);
33
+ let pending;
34
+ let cancel;
35
+ const cancelled = new Promise((_, reject) => { cancel = reject; });
36
+ void cancelled.catch(() => { });
37
+ const guard = () => { if (disposed)
38
+ throw failure ?? new DOMException('AAC encoder disposed', 'AbortError'); };
39
+ const wait = async (work) => { const value = await Promise.race([work, cancelled]); guard(); return value; };
40
+ function dispose() {
41
+ if (disposed)
42
+ return;
43
+ disposed = true;
44
+ failure ??= context.signal.reason ?? new DOMException('AAC encoder disposed', 'AbortError');
45
+ context.signal.removeEventListener('abort', dispose);
46
+ worker?.removeEventListener('message', onMessage);
47
+ worker?.removeEventListener('error', onError);
48
+ worker?.removeEventListener('messageerror', onMessageError);
49
+ worker?.terminate();
50
+ worker = undefined;
51
+ pcm = undefined;
52
+ cancel(failure);
53
+ if (pending) {
54
+ clearTimeout(pending.timer);
55
+ pending.reject(failure);
56
+ pending = undefined;
57
+ }
58
+ }
59
+ function fail(error) { if (disposed)
60
+ return; failure = error; dispose(); context.output.fail(error); }
61
+ function onError(event) { fail(new Error(event.message || 'AAC worker failed')); }
62
+ function onMessageError() { fail(new Error('AAC worker message could not be decoded')); }
63
+ function onMessage(event) {
64
+ if (disposed || !pending)
65
+ return;
66
+ const message = event.data;
67
+ if (!message || message.id !== pending.id || (!message.result && typeof message.error !== 'string')) {
68
+ fail(new Error('Invalid AAC worker response'));
69
+ return;
70
+ }
71
+ if (message.error) {
72
+ fail(new Error(message.error));
73
+ return;
74
+ }
75
+ const request = pending;
76
+ pending = undefined;
77
+ clearTimeout(request.timer);
78
+ request.resolve(message.result);
79
+ }
80
+ function send(type, data, transfer = []) {
81
+ guard();
82
+ if (pending)
83
+ throw new Error('AAC worker command overlap');
84
+ return new Promise((resolve, reject) => {
85
+ const requestId = id++;
86
+ pending = { id: requestId, resolve, reject, timer: setTimeout(() => fail(new Error(`AAC worker ${type} timed out`)), timeoutMs) };
87
+ try {
88
+ worker.postMessage({ id: requestId, type, data }, transfer);
89
+ }
90
+ catch (error) {
91
+ fail(error);
92
+ }
93
+ });
94
+ }
95
+ async function packets(result) {
96
+ if (!Array.isArray(result.packets) || result.packets.length > 4)
97
+ throw new Error('Invalid AAC packet response');
98
+ for (const p of result.packets) {
99
+ guard();
100
+ if (!Number.isSafeInteger(p.sampleOffset) || p.samples !== 1024 || !(p.data instanceof Uint8Array) || !p.data.byteLength || p.data.byteLength + 64 > context.maxPendingBytes)
101
+ throw new Error('Invalid AAC packet');
102
+ if (first === undefined) {
103
+ if (p.sampleOffset >= 0 || p.sampleOffset < -8192)
104
+ throw new Error('AAC backend did not expose valid encoder delay');
105
+ first = p.sampleOffset;
106
+ }
107
+ if (last !== undefined && last !== p.sampleOffset)
108
+ throw new Error('Noncontiguous AAC sample positions');
109
+ const next = p.sampleOffset + p.samples;
110
+ await wait(context.output.write({ type: 'packet', packet: { track: 'audio', timestampUs: us(p.sampleOffset, rate), decodeTimestampUs: us(p.sampleOffset, rate),
111
+ durationUs: us(next, rate) - us(p.sampleOffset, rate), type: 'key', data: p.data } }));
112
+ guard();
113
+ last = next;
114
+ }
115
+ }
116
+ async function encodeFrame() {
117
+ const data = pcm;
118
+ pcm = new Float32Array(1024 * channels);
119
+ filled = 0;
120
+ await packets(await send('frame', { pcm: data, sampleOffset: encoded }, [data.buffer]));
121
+ encoded += 1024;
122
+ }
123
+ worker.addEventListener('message', onMessage);
124
+ worker.addEventListener('error', onError);
125
+ worker.addEventListener('messageerror', onMessageError);
126
+ context.signal.addEventListener('abort', dispose, { once: true });
127
+ try {
128
+ if (context.signal.aborted)
129
+ dispose();
130
+ const init = await send('init', { channels, sampleRate: rate, bitrate: config.bitrate, maxBytes: context.maxPendingBytes });
131
+ if (init.frameSize !== 1024 || !(init.description instanceof Uint8Array) || init.description.length < 2 || init.description.byteLength + 64 > context.maxPendingBytes)
132
+ throw new Error('Invalid AAC initialization response');
133
+ await wait(context.output.write({ type: 'config', track: 'audio', config: { codec: config.codec, bitstreamFormat: 'aac', sampleRate: rate, numberOfChannels: channels, description: init.description } }));
134
+ guard();
135
+ }
136
+ catch (error) {
137
+ dispose();
138
+ throw error;
139
+ }
140
+ return {
141
+ async encodeAudio(block) {
142
+ guard();
143
+ if (ended || block.sampleOffset !== accepted || block.sampleRate !== rate || block.channels.length !== channels || block.channels.some(c => c.length !== block.channels[0].length))
144
+ throw new Error('Invalid AAC input timeline/configuration');
145
+ for (let offset = 0; offset < block.channels[0].length;) {
146
+ const count = Math.min(1024 - filled, block.channels[0].length - offset);
147
+ for (let i = 0; i < count; i++)
148
+ for (let c = 0; c < channels; c++)
149
+ pcm[(filled + i) * channels + c] = block.channels[c][offset + i];
150
+ filled += count;
151
+ offset += count;
152
+ accepted += count;
153
+ if (filled === 1024)
154
+ await encodeFrame();
155
+ }
156
+ },
157
+ async flush() {
158
+ guard();
159
+ if (ended)
160
+ throw new Error('AAC track already ended');
161
+ ended = true;
162
+ if (filled)
163
+ await encodeFrame();
164
+ await packets(await send('flush'));
165
+ if (first === undefined || last === undefined || last < accepted)
166
+ throw new Error('AAC backend returned incomplete audio');
167
+ await wait(context.output.write({ type: 'end', track: 'audio', presentationSamples: accepted, leadingDiscardSamples: -first, trailingDiscardSamples: last - accepted }));
168
+ guard();
169
+ },
170
+ dispose
171
+ };
172
+ }
173
+ };
174
+ }
@@ -0,0 +1,3 @@
1
+ import type { MuxerFactory } from './video.js';
2
+ /** Optional, bundled Mediabunny MP4 writer. No encoding or implicit format selection. */
3
+ export declare function createMp4Muxer(): MuxerFactory;
@@ -0,0 +1,38 @@
1
+ /*! Includes Mediabunny 1.65.0 (MPL-2.0). Source in video-mp4.js.map; see mediabunny-LICENSE.txt. */
2
+ function f(t){if(!t)throw new Error("Assertion failed.")}var Ai=Math.PI/180,ms=180/Math.PI;var yt=[1,0,0,0,1,0,0,0,1],$t=(t,e,r)=>{let[i,n,,s,o]=t,a=Math.abs(i)*e+Math.abs(s)*r,c=Math.abs(n)*e+Math.abs(o)*r;return rt(rt(jt(-e/2,-r/2),t),jt(a/2,c/2))};var Gt=t=>{let e=t*Ai,r=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[r,i,0,-i,r,0,0,0,1]},jt=(t,e)=>[1,0,0,0,1,0,t,e,1],Kt=(t,e)=>[t,0,0,0,e,0,0,0,1],rt=(t,e)=>{let r=new Array(9);for(let i=0;i<3;i++)for(let n=0;n<3;n++)r[3*i+n]=t[3*i]*e[n]+t[3*i+1]*e[3+n]+t[3*i+2]*e[6+n];return r};var te=t=>t&&t[t.length-1],re=t=>t>=0&&t<2**32,Xt=t=>t>=-(2**31)&&t<2**31,m=t=>{let e=0;for(;t.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return 2**e-1+t.readBits(e)};var ie=t=>{let e=m(t);return e%2===0?-(e/2):(e+1)/2};var me=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),ne=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),gi=typeof globalThis.TextEncoder<"u"?globalThis.TextEncoder:class{constructor(){this.encoding="utf-8"}encode(e=""){let r=new Uint8Array(3*e.length),i=0;for(let n=0;n<e.length;n++){let s=e.charCodeAt(n);if(s<128)r[i++]=s;else if(s<2048)r[i++]=192|s>>6,r[i++]=128|s&63;else if(s<55296||s>57343)r[i++]=224|s>>12,r[i++]=128|s>>6&63,r[i++]=128|s&63;else{let o=n+1<e.length?e.charCodeAt(n+1):0;s<56320&&o>=56320&&o<=57343?(s=65536+(s-55296<<10)+(o-56320),n++,r[i++]=240|s>>18,r[i++]=128|s>>12&63,r[i++]=128|s>>6&63,r[i++]=128|s&63):(r[i++]=239,r[i++]=191,r[i++]=189)}}return r.slice(0,i)}},hs=typeof globalThis.TextDecoder<"u"?globalThis.TextDecoder:class{constructor(e="utf-8"){let r=e.trim().toLowerCase();if(r==="utf-8"||r==="utf8"||r==="unicode-1-1-utf-8")this.encoding="utf-8";else if(r==="utf-16le"||r==="utf-16")this.encoding="utf-16le";else if(r==="utf-16be")this.encoding="utf-16be";else throw new RangeError(`The encoding label provided ('${e}') is invalid.`)}decode(e){let r=e?me(e):new Uint8Array(0),i=[];if(this.encoding==="utf-8"){let s=r.length>=3&&r[0]===239&&r[1]===187&&r[2]===191?3:0;for(;s<r.length;){let o=r[s];if(o<128){i.push(o),s++;continue}let a,c;if(o>=194&&o<224)a=1,c=o&31;else if(o>=224&&o<240)a=2,c=o&15;else if(o>=240&&o<245)a=3,c=o&7;else{i.push(65533),s++;continue}let l=o===224?160:o===240?144:128,d=o===237?159:o===244?143:191,p=1;for(;p<=a;p++){let b=s+p<r.length?r[s+p]:0;if(b<l||b>d)break;c=c<<6|b&63,l=128,d=191}s+=p,p<=a?i.push(65533):c>=65536?(c-=65536,i.push(55296|c>>10,56320|c&1023)):i.push(c)}}else{let s=this.encoding==="utf-16le",o=s?255:254,a=s?254:255,c=r.length>=2&&r[0]===o&&r[1]===a?2:0;for(;c+1<r.length;){let l=s?r[c]|r[c+1]<<8:r[c]<<8|r[c+1];if(c+=2,l>=55296&&l<=56319){let d=c+1<r.length?s?r[c]|r[c+1]<<8:r[c]<<8|r[c+1]:-1;d>=56320&&d<=57343?(i.push(l,d),c+=2):i.push(65533)}else l>=56320&&l<=57343?i.push(65533):i.push(l)}c<r.length&&i.push(65533)}let n="";for(let s=0;s<i.length;s+=8192)n+=String.fromCharCode(...i.slice(s,s+8192));return n}};var j=new gi;var We={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12};var De={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18};var Ne={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9};var Zt=t=>!t||t.primaries==null&&t.transfer==null&&t.matrix==null&&t.fullRange==null;var xt=t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t),_e=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,r=new Promise(n=>{let s=!1;e=()=>{s||(n(),this.pending--,s=!0)}}),i=this.currentPromise;return this.currentPromise=r,this.pending++,await i,e}};var Yt=()=>{let t,e;return{promise:new Promise((i,n)=>{t=i,e=n}),resolve:t,reject:e}};var Be=t=>{throw new Error(`Unexpected value: ${t}`)};var Jt=(t,e,r,i)=>{r=r>>>0,r=r&16777215,i?(t.setUint8(e,r&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r>>>16&255)):(t.setUint8(e,r>>>16&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r&255))};var er="und";var tr=t=>{let e=0;for(;t!==0;)t&=t-1,e++;return e},wi=/^[a-z]{3}$/,rr=t=>wi.test(t),Tt=1e6*(1+Number.EPSILON);var ir=(t,e)=>{let r=t<0?-1:1;t=Math.abs(t);let i=0,n=1,s=1,o=0,a=t;for(;;){let c=Math.floor(a),l=c*s+i,d=c*o+n;if(d>e)return{num:r*s,den:o};if(i=s,n=o,s=l,o=d,a=1/(a-c),!isFinite(a))break}return{num:r*s,den:o}};var bt=null,Ct=()=>bt!==null?bt:bt=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));var bi=(async()=>{})().constructor,He=t=>t instanceof bi||t instanceof Promise?!0:typeof t?.then=="function";var it=function*(t){for(let e in t){let r=t[e];r!==void 0&&(yield{key:e,value:r})}};var nr=t=>typeof t=="number"&&!Number.isNaN(t);var sr=t=>{f(Number.isInteger(t.num)),f(Number.isInteger(t.den)),f(t.den!==0);let e=Math.abs(t.num),r=Math.abs(t.den);for(;r!==0;){let n=e%r;e=r,r=n}let i=e||1;return{num:t.num/i,den:t.den/i}};var nt=t=>Array.isArray(t)?t:[t],Ae=class{constructor(){this._listeners=new Map}on(e,r,i){this._listeners.has(e)||this._listeners.set(e,new Set);let n={fn:r,once:i?.once??!1};return this._listeners.get(e).add(n),()=>{this._listeners.get(e)?.delete(n)}}_emit(...e){let[r,i]=e,n=this._listeners.get(r);if(n)for(let s of n){try{s.fn(i)}catch(o){console.error(o)}s.once&&n.delete(s)}}};var or=t=>t!==null&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype&&Object.values(t).every(e=>typeof e=="string");var se;(function(t){t[t.Silent=0]="Silent",t[t.Errors=1]="Errors",t[t.Warnings=2]="Warnings",t[t.Info=3]="Info"})(se||(se={}));var W=class t{constructor(){}static get level(){return t._level}static set level(e){if(e!==se.Silent&&e!==se.Errors&&e!==se.Warnings&&e!==se.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");t._level=e}static get _emitter(){return t._emitterInstance??=new Ae}static on(e,r,i){return t._emitter.on(e,r,i)}static _error(...e){t._emitter._emit("error",e),t._level>=se.Errors&&console.error(...e)}static _warn(...e){t._emitter._emit("warn",e),t._level>=se.Warnings&&console.warn(...e)}static _info(...e){t._emitter._emit("info",e),t._level>=se.Info&&console.info(...e)}};W._level=se.Info;W._emitterInstance=null;var qe=class{constructor(e,r){if(this.data=e,this.mimeType=r,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof r!="string")throw new TypeError("mimeType must be a string.")}},Et=class{constructor(e,r,i,n){if(this.data=e,this.mimeType=r,this.name=i,this.description=n,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!==void 0&&typeof r!="string")throw new TypeError("mimeType, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("name, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("description, when provided, must be a string.")}},ar=t=>{if(!t||typeof t!="object")throw new TypeError("tags must be an object.");if(t.title!==void 0&&typeof t.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(t.description!==void 0&&typeof t.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(t.artist!==void 0&&typeof t.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(t.album!==void 0&&typeof t.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(t.albumArtist!==void 0&&typeof t.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(t.trackNumber!==void 0&&(!Number.isInteger(t.trackNumber)||t.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(t.tracksTotal!==void 0&&(!Number.isInteger(t.tracksTotal)||t.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(t.discNumber!==void 0&&(!Number.isInteger(t.discNumber)||t.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(t.discsTotal!==void 0&&(!Number.isInteger(t.discsTotal)||t.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(t.genre!==void 0&&typeof t.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(t.date!==void 0&&(!(t.date instanceof Date)||Number.isNaN(t.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(t.creationTime!==void 0&&t.creationTime!==null&&(!(t.creationTime instanceof Date)||Number.isNaN(t.creationTime.getTime())))throw new TypeError("tags.creationTime, when provided, must be a valid Date or null.");if(t.beatsPerMinute!==void 0&&(!Number.isInteger(t.beatsPerMinute)||t.beatsPerMinute<=0))throw new TypeError("tags.beatsPerMinute, when provided, must be a positive integer.");if(t.lyrics!==void 0&&typeof t.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(t.images!==void 0){if(!Array.isArray(t.images))throw new TypeError("tags.images, when provided, must be an array.");for(let e of t.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(t.comment!==void 0&&typeof t.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(t.raw!==void 0){if(!t.raw||typeof t.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(let e of Object.values(t.raw))if(e!==null&&typeof e!="string"&&!(Array.isArray(e)&&e.every(r=>typeof r=="string"))&&!(e instanceof Uint8Array)&&!(Array.isArray(e)&&e.every(r=>r instanceof Uint8Array))&&!(e instanceof qe)&&!(e instanceof Et)&&!or(e))throw new TypeError("Each value in tags.raw must be a string, string array, Uint8Array, Uint8Array array, RichImageData, AttachedFile, Record<string, string>, or null.")}};var cr=t=>{if(!t||typeof t!="object")throw new TypeError("disposition must be an object.");if(t.default!==void 0&&typeof t.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(t.primary!==void 0&&typeof t.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(t.forced!==void 0&&typeof t.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(t.original!==void 0&&typeof t.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(t.commentary!==void 0&&typeof t.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(t.hearingImpaired!==void 0&&typeof t.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(t.visuallyImpaired!==void 0&&typeof t.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};var U=class t{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),r=this.bytes[e]??0,i=7-(this.pos&7),n=(r&1<<i)>>i;return this.pos++,n}readBits(e){if(e===1)return this.readBit();let r=0;for(let i=0;i<e;i++)r<<=1,r|=this.readBit();return r}writeBits(e,r){let i=this.pos+e;for(let n=this.pos;n<i;n++){let s=Math.floor(n/8),o=this.bytes[s],a=7-(n&7);o&=~(1<<a),o|=(r&1<<i-n-1)>>i-n-1<<a,this.bytes[s]=o}this.pos=i}copyBits(e,r){let i=0;for(i;i<e-7;i+=8)this.writeBits(8,r.readBits(8));let n=e-i;n>0&&this.writeBits(n,r.readBits(n))}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,r=this.bytes[e]??0;return this.pos+=8,r}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new t(this.bytes);return e.pos=this.pos,e}};var Qe=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],_t=[-1,1,2,3,4,5,6,8];var dr=t=>{let e=t.objectType===5||t.objectType===29,r=t.objectType===29,i=e?t.outputSampleRate/2:t.outputSampleRate,n=r?1:t.outputNumberOfChannels,s=_t.indexOf(n);if(s===-1)throw new TypeError(`Unsupported number of channels: ${t.outputNumberOfChannels}`);let o=16;t.objectType>=32&&(o+=6),St(i)===15&&(o+=24),e&&(o+=9,St(t.outputSampleRate)===15&&(o+=24));let a=Math.ceil(o/8),c=new Uint8Array(a),l=new U(c);return lr(l,t.objectType),ur(l,i),l.writeBits(4,s),e&&(ur(l,t.outputSampleRate),lr(l,2)),l.writeBits(3,0),c},lr=(t,e)=>{e<32?t.writeBits(5,e):(t.writeBits(5,31),t.writeBits(6,e-32))},ur=(t,e)=>{let r=St(e);t.writeBits(4,r),r===15&&t.writeBits(24,e)},St=t=>{let e=Qe.indexOf(t);return e===-1?15:e};var fr=[48e3,44100,32e3],mr=[24e3,22050,16e3];var yi="1.65.0",st=`Mediabunny v${yi}`;var je;(function(t){t[t.NON_IDR_SLICE=1]="NON_IDR_SLICE",t[t.SLICE_DPA=2]="SLICE_DPA",t[t.SLICE_DPB=3]="SLICE_DPB",t[t.SLICE_DPC=4]="SLICE_DPC",t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.AUD=9]="AUD",t[t.SPS_EXT=13]="SPS_EXT"})(je||(je={}));var oe;(function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.AUD_NUT=35]="AUD_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(oe||(oe={}));var ot=function*(t){let e=0,r=-1;for(;e<t.length-2;){let i=t.indexOf(0,e);if(i===-1||i>=t.length-2)break;e=i;let n=0;if(e+3<t.length&&t[e+1]===0&&t[e+2]===0&&t[e+3]===1?n=4:t[e+1]===0&&t[e+2]===1&&(n=3),n===0){e++;continue}r!==-1&&e>r&&(yield{offset:r,length:e-r}),r=e+n,e=r}r!==-1&&r<t.length&&(yield{offset:r,length:t.length-r})};var Ei=t=>t&31,kt=t=>{let e=new Uint8Array(t.length),r=t.length,i=0;for(let n=0;n<r;n++)n+2<r&&t[n]===0&&t[n+1]===0&&t[n+2]===3?(e[i++]=0,e[i++]=0,n+=2):e[i++]=t[n];return e.subarray(0,i)};var Us=new Uint8Array([0,0,0,1]);var xr=(t,e)=>{let r=t.reduce((s,o)=>s+e+o.byteLength,0),i=new Uint8Array(r),n=0;for(let s of t){let o=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(e){case 1:o.setUint8(n,s.byteLength);break;case 2:o.setUint16(n,s.byteLength,!1);break;case 3:Jt(o,n,s.byteLength,!1);break;case 4:o.setUint32(n,s.byteLength,!1);break}n+=e,i.set(s,n),n+=s.byteLength}return i};var Tr=t=>{try{let e=[],r=[],i=[];for(let a of ot(t)){let c=t.subarray(a.offset,a.offset+a.length),l=Ei(c[0]);l===je.SPS&&e.length<31?e.push(c):l===je.PPS&&r.length<255?r.push(c):l===je.SPS_EXT&&i.length<255&&i.push(c)}if(e.length===0||r.length===0)return null;let n=e[0],s=Si(n);if(!s)return null;let o=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:r,chromaFormat:o?s.chromaFormatIdc:null,bitDepthLumaMinus8:o?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?i:null}}catch(e){return W._error("Error building AVC Decoder Configuration Record:",e),null}},Cr=t=>{let e=[];e.push(t.configurationVersion),e.push(t.avcProfileIndication),e.push(t.profileCompatibility),e.push(t.avcLevelIndication),e.push(252|t.lengthSizeMinusOne&3),e.push(224|t.sequenceParameterSets.length&31);for(let r of t.sequenceParameterSets){let i=r.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(r[n])}e.push(t.pictureParameterSets.length);for(let r of t.pictureParameterSets){let i=r.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(r[n])}if((t.avcProfileIndication===100||t.avcProfileIndication===110||t.avcProfileIndication===122||t.avcProfileIndication===144)&&t.chromaFormat!==null){f(t.bitDepthLumaMinus8!==null),f(t.bitDepthChromaMinus8!==null),f(t.sequenceParameterSetExt!==null),e.push(252|t.chromaFormat&3),e.push(248|t.bitDepthLumaMinus8&7),e.push(248|t.bitDepthChromaMinus8&7),e.push(t.sequenceParameterSetExt.length);for(let r of t.sequenceParameterSetExt){let i=r.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(r[n])}}return new Uint8Array(e)};var Er={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Si=t=>{try{let e=kt(t),r=new U(e);if(r.skipBits(1),r.skipBits(2),r.readBits(5)!==7)return null;let n=r.readAlignedByte(),s=r.readAlignedByte(),o=r.readAlignedByte();m(r);let a=1,c=0,l=0,d=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(a=m(r),a===3&&(d=r.readBits(1)),c=m(r),l=m(r),r.skipBits(1),r.readBits(1))){for(let O=0;O<(a!==3?8:12);O++)if(r.readBits(1)){let I=O<6?16:64,_=8,F=8;for(let he=0;he<I;he++){if(F!==0){let be=ie(r);F=(_+be+256)%256}_=F===0?_:F}}}m(r);let p=m(r);if(p===0)m(r);else if(p===1){r.skipBits(1),ie(r),ie(r);let R=m(r);for(let O=0;O<R;O++)ie(r)}m(r),r.skipBits(1);let b=m(r),h=m(r),y=16*(b+1),T=16*(h+1),P=y,B=T,D=r.readBits(1);if(D||r.skipBits(1),r.skipBits(1),r.readBits(1)){let R=m(r),O=m(r),V=m(r),I=m(r),_,F;if((d===0?a:0)===0)_=1,F=2-D;else{let be=a===3?1:2,tt=a===1?2:1;_=be,F=tt*(2-D)}P-=_*(R+O),B-=F*(V+I)}if(P<=0||B<=0)return null;let fe=2,q=2,X=2,L=0,Z={num:1,den:1},Y=null,Q=null,g=null,S=null,v=r.pos;if(r.readBits(1)){if(r.readBits(1)){let be=r.readBits(8);if(be===255)Z={num:r.readBits(16),den:r.readBits(16)};else{let tt=Er[be];tt&&(Z=tt)}}r.readBits(1)&&r.skipBits(1),r.readBits(1)&&(r.skipBits(3),L=r.readBits(1),r.readBits(1)&&(fe=r.readBits(8),q=r.readBits(8),X=r.readBits(8))),r.readBits(1)&&(m(r),m(r)),r.readBits(1)&&(r.skipBits(32),r.skipBits(32),r.skipBits(1));let F=r.readBits(1);F&&pr(r);let he=r.readBits(1);he&&pr(r),(F||he)&&r.skipBits(1),r.skipBits(1),g=r.pos,S=r.readBits(1),S&&(r.skipBits(1),m(r),m(r),m(r),m(r),Y=Math.min(m(r),16),Q=Math.min(m(r),16))}if(Y===null){f(Q===null);let R=s&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&R)Y=0,Q=0;else{let O=b+1,V=h+1,I=(2-D)*V,_=Bt.find(he=>he.level>=o)??te(Bt),F=Math.min(Math.floor(_.maxDpbMbs/(O*I)),16);Y=F,Q=F}}return f(Q!==null),{emulationUnpreventedBytes:e,profileIdc:n,constraintFlags:s,levelIdc:o,frameMbsOnlyFlag:D,chromaFormatIdc:a,bitDepthLumaMinus8:c,bitDepthChromaMinus8:l,codedWidth:y,codedHeight:T,displayWidth:P,displayHeight:B,pixelAspectRatio:Z,colourPrimaries:fe,matrixCoefficients:X,transferCharacteristics:q,fullRangeFlag:L,numReorderFrames:Y,maxDecFrameBuffering:Q,vuiParametersFlagBitOffset:v,bitstreamRestrictionFlagBitOffset:g,bitstreamRestrictionFlag:S}}catch(e){return W._error("Error parsing AVC SPS:",e),null}},pr=t=>{let e=m(t);t.skipBits(4),t.skipBits(4);for(let r=0;r<=e;r++)m(t),m(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)};var hr=t=>t>>1&63,_i=t=>{try{let e=new U(kt(t));e.skipBits(16),e.readBits(4);let r=e.readBits(3),i=e.readBits(1),{general_profile_space:n,general_tier_flag:s,general_profile_idc:o,general_profile_compatibility_flags:a,general_constraint_indicator_flags:c,general_level_idc:l}=Bi(e,r);m(e);let d=m(e),p=0;d===3&&(p=e.readBits(1));let b=m(e),h=m(e),y=b,T=h;if(e.readBits(1)){let S=m(e),v=m(e),z=m(e),R=m(e),O=1,V=1,I=p===0?d:0;I===1?(O=2,V=2):I===2&&(O=2,V=1),y-=(S+v)*O,T-=(z+R)*V}if(y<=0||T<=0)return null;let P=m(e),B=m(e);m(e);let de=e.readBits(1)?0:r,fe=0;for(let S=de;S<=r;S++)m(e),fe=m(e),m(e);m(e),m(e),m(e),m(e),m(e),m(e),e.readBits(1)&&e.readBits(1)&&ki(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),m(e),m(e),e.skipBits(1));let q=m(e);if(vi(e,q),e.readBits(1)){let S=m(e);for(let v=0;v<S;v++)m(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let X=2,L=2,Z=2,Y=0,Q=0,g={num:1,den:1};if(e.readBits(1)){let S=Pi(e,r);g=S.pixelAspectRatio,X=S.colourPrimaries,L=S.transferCharacteristics,Z=S.matrixCoefficients,Y=S.fullRangeFlag,Q=S.minSpatialSegmentationIdc}return{displayWidth:y,displayHeight:T,pixelAspectRatio:g,colourPrimaries:X,transferCharacteristics:L,matrixCoefficients:Z,fullRangeFlag:Y,maxDecFrameBuffering:Math.min(fe+1,16),spsMaxSubLayersMinus1:r,spsTemporalIdNestingFlag:i,generalProfileSpace:n,generalTierFlag:s,generalProfileIdc:o,generalProfileCompatibilityFlags:a,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:d,bitDepthLumaMinus8:P,bitDepthChromaMinus8:B,minSpatialSegmentationIdc:Q}}catch(e){return W._error("Error parsing HEVC SPS:",e),null}},Sr=t=>{try{let e=[],r=[],i=[],n=[];for(let d of ot(t)){let p=t.subarray(d.offset,d.offset+d.length),b=hr(p[0]);b===oe.VPS_NUT&&e.length<65535?e.push(p):b===oe.SPS_NUT&&r.length<65535?r.push(p):b===oe.PPS_NUT&&i.length<65535?i.push(p):(b===oe.PREFIX_SEI_NUT||b===oe.SUFFIX_SEI_NUT)&&n.length<65535&&n.push(p)}if(r.length===0||i.length===0)return null;let o=_i(r[0]);if(!o)return null;let a=0;if(i.length>0){let d=i[0],p=new U(kt(d));p.skipBits(16),m(p),m(p),p.skipBits(1),p.skipBits(1),p.skipBits(3),p.skipBits(1),p.skipBits(1),m(p),m(p),ie(p),p.skipBits(1),p.skipBits(1),p.readBits(1)&&m(p),ie(p),ie(p),p.skipBits(1),p.skipBits(1),p.skipBits(1),p.skipBits(1);let b=p.readBits(1),h=p.readBits(1);!b&&!h?a=0:b&&!h?a=2:!b&&h?a=3:a=0}let c=[...e.length?[{arrayCompleteness:1,nalUnitType:oe.VPS_NUT,nalUnits:e}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:oe.SPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:oe.PPS_NUT,nalUnits:i}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:hr(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:o.generalProfileSpace,generalTierFlag:o.generalTierFlag,generalProfileIdc:o.generalProfileIdc,generalProfileCompatibilityFlags:o.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:o.generalConstraintIndicatorFlags,generalLevelIdc:o.generalLevelIdc,minSpatialSegmentationIdc:o.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:o.chromaFormatIdc,bitDepthLumaMinus8:o.bitDepthLumaMinus8,bitDepthChromaMinus8:o.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:o.spsMaxSubLayersMinus1+1,temporalIdNested:o.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:c}}catch(e){return W._error("Error building HEVC Decoder Configuration Record:",e),null}},Bi=(t,e)=>{let r=t.readBits(2),i=t.readBits(1),n=t.readBits(5),s=0;for(let d=0;d<32;d++)s=s<<1|t.readBits(1);let o=new Uint8Array(6);for(let d=0;d<6;d++)o[d]=t.readBits(8);let a=t.readBits(8),c=[],l=[];for(let d=0;d<e;d++)c.push(t.readBits(1)),l.push(t.readBits(1));if(e>0)for(let d=e;d<8;d++)t.skipBits(2);for(let d=0;d<e;d++)c[d]&&t.skipBits(88),l[d]&&t.skipBits(8);return{general_profile_space:r,general_tier_flag:i,general_profile_idc:n,general_profile_compatibility_flags:s,general_constraint_indicator_flags:o,general_level_idc:a}},ki=t=>{for(let e=0;e<4;e++)for(let r=0;r<(e===3?2:6);r++)if(!t.readBits(1))m(t);else{let n=Math.min(64,1<<4+(e<<1));e>1&&ie(t);for(let s=0;s<n;s++)ie(t)}},vi=(t,e)=>{let r=[];for(let i=0;i<e;i++)r[i]=Ii(t,i,e,r)},Ii=(t,e,r,i)=>{let n=0,s=0,o=0;if(e!==0&&(s=t.readBits(1)),s){if(e===r){let c=m(t);o=e-(c+1)}else o=e-1;t.readBits(1),m(t);let a=i[o]??0;for(let c=0;c<=a;c++)t.readBits(1)||t.readBits(1);n=i[o]}else{let a=m(t),c=m(t);for(let l=0;l<a;l++)m(t),t.readBits(1);for(let l=0;l<c;l++)m(t),t.readBits(1);n=a+c}return n},Pi=(t,e)=>{let r=2,i=2,n=2,s=0,o=0,a={num:1,den:1};if(t.readBits(1)){let c=t.readBits(8);if(c===255)a={num:t.readBits(16),den:t.readBits(16)};else{let l=Er[c];l&&(a=l)}}return t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),s=t.readBits(1),t.readBits(1)&&(r=t.readBits(8),i=t.readBits(8),n=t.readBits(8))),t.readBits(1)&&(m(t),m(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(m(t),m(t),m(t),m(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&m(t),t.readBits(1)&&Mi(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),o=m(t),m(t),m(t),m(t),m(t)),{pixelAspectRatio:a,colourPrimaries:r,transferCharacteristics:i,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:o}},Mi=(t,e,r)=>{let i=!1,n=!1,s=!1;e&&(i=t.readBits(1)===1,n=t.readBits(1)===1,(i||n)&&(s=t.readBits(1)===1,s&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),s&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5)));for(let o=0;o<=r;o++){let a=t.readBits(1)===1,c=!0;a||(c=t.readBits(1)===1);let l=!1;c?m(t):l=t.readBits(1)===1;let d=1;l||(d=m(t)+1),i&&Ar(t,d,s),n&&Ar(t,d,s)}},Ar=(t,e,r)=>{for(let i=0;i<e;i++)m(t),m(t),r&&(m(t),m(t)),t.readBits(1)},_r=t=>{let e=[];e.push(t.configurationVersion),e.push((t.generalProfileSpace&3)<<6|(t.generalTierFlag&1)<<5|t.generalProfileIdc&31),e.push(t.generalProfileCompatibilityFlags>>>24&255),e.push(t.generalProfileCompatibilityFlags>>>16&255),e.push(t.generalProfileCompatibilityFlags>>>8&255),e.push(t.generalProfileCompatibilityFlags&255),e.push(...t.generalConstraintIndicatorFlags),e.push(t.generalLevelIdc&255),e.push(240|t.minSpatialSegmentationIdc>>8&15),e.push(t.minSpatialSegmentationIdc&255),e.push(252|t.parallelismType&3),e.push(252|t.chromaFormatIdc&3),e.push(248|t.bitDepthLumaMinus8&7),e.push(248|t.bitDepthChromaMinus8&7),e.push(t.avgFrameRate>>8&255),e.push(t.avgFrameRate&255),e.push((t.constantFrameRate&3)<<6|(t.numTemporalLayers&7)<<3|(t.temporalIdNested&1)<<2|t.lengthSizeMinusOne&3),e.push(t.arrays.length&255);for(let r of t.arrays){e.push((r.arrayCompleteness&1)<<7|0|r.nalUnitType&63),e.push(r.nalUnits.length>>8&255),e.push(r.nalUnits.length&255);for(let i of r.nalUnits){e.push(i.length>>8&255),e.push(i.length&255);for(let n=0;n<i.length;n++)e.push(i[n])}}return new Uint8Array(e)};var gr;(function(t){t[t.audAllowed=0]="audAllowed",t[t.beforeFirstVcl=1]="beforeFirstVcl",t[t.afterFirstVcl=2]="afterFirstVcl",t[t.eoBitstreamAllowed=3]="eoBitstreamAllowed",t[t.noMoreDataAllowed=4]="noMoreDataAllowed"})(gr||(gr={}));var Br=t=>{if(t.byteLength<19)throw new Error("Invalid Opus identification header: too short.");let e=ne(t),r=e.getUint8(9),i=e.getUint16(10,!0),n=e.getUint32(12,!0),s=e.getInt16(16,!0),o=e.getUint8(18),a=null;return o&&(a=t.subarray(19,21+r)),{outputChannelCount:r,preSkip:i,inputSampleRate:n,outputGain:s,channelMappingFamily:o,channelMappingTable:a}},Ri=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],kr=t=>{let e=t[0]>>3,r=t[0]&3,i;return r===0?i=1:r===1||r===2?i=2:i=t[1]&63,{durationInSamples:Ri[e]*i}};var vr=(t,e)=>t==="truehd"?(e.byteLength>=8?ne(e).getUint32(4):null)===4168249274?"key":"delta":"key",wr;(function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"})(wr||(wr={}));var Ir=t=>{if(t.length<7||t[0]!==11||t[1]!==119)return null;let e=new U(t);e.skipBits(16),e.skipBits(16);let r=e.readBits(2);if(r===3)return null;let i=e.readBits(6),n=e.readBits(5);if(n>8)return null;let s=e.readBits(3),o=e.readBits(3);(o&1)!==0&&o!==1&&e.skipBits(2),(o&4)!==0&&e.skipBits(2),o===2&&e.skipBits(2);let a=e.readBits(1),c=Math.floor(i/2);return{fscod:r,bsid:n,bsmod:s,acmod:o,lfeon:a,bitRateCode:c}},zs=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,288*2,384,418,288*2,448,486,336*2,448,488,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2];var Vs=new Uint8Array([5,4,65,67,45,51]),Ls=new Uint8Array([5,4,69,65,67,51]),Fi=[1,2,3,6],Pr=t=>{if(t.length<6||t[0]!==11||t[1]!==119)return null;let e=new U(t);e.skipBits(16);let r=e.readBits(2);if(e.skipBits(3),r!==0&&r!==2)return null;let i=e.readBits(11),n=e.readBits(2),s=0,o;n===3?(s=e.readBits(2),o=3):o=e.readBits(2);let a=e.readBits(3),c=e.readBits(1),l=e.readBits(5);if(l<11||l>16)return null;let d=Fi[o],p;return n<3?p=fr[n]/1e3:p=mr[s]/1e3,{dataRate:Math.round((i+1)*p/(d*16)),substreams:[{fscod:n,fscod2:s,bsid:l,bsmod:0,acmod:a,lfeon:c,numDepSub:0,chanLoc:0}]}};var Oi=1683496997,Ui=18,zi=10;var br=32,Vi=20,Li=8,Wi=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Di=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],Ni=[16,16,20,20,0,24,24,0],yr=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Hi=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],qi=8;var Qi=[32e3,44100,48e3,0],ji=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],$i=[512,1024,2048,4096],Mr=t=>{let e=Gi(t),r=ne(t),i=e?Math.ceil(e.frameSize/4)*4:0,n=null;for(;i+4<=t.length&&r.getUint32(i)===Oi;){let o=Ki(t.subarray(i));if(!o)break;n??=o,i+=o.frameSize}if(e)return{frameSize:n?i:e.frameSize,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,sampleCount:e.sampleCount,channelLayout:e.channelLayout,pcmResolution:e.pcmResolution,bitRate:e.bitRate,core:e,hasExtensions:n!==null};if(!n?.asset)return null;let{asset:s}=n;return{frameSize:i,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels,sampleCount:s.sampleCount,channelLayout:s.channelLayout,pcmResolution:s.pcmResolution,bitRate:0,core:null,hasExtensions:!0}};var Gi=t=>{if(t.length<Ui||t[0]!==127||t[1]!==254||t[2]!==128||t[3]!==1)return null;let e=new U(t);if(e.skipBits(32),e.skipBits(1),e.readBits(5)!==br-1)return null;let r=e.readBits(1),i=e.readBits(7)+1;if(i%Li!==0)return null;let n=e.readBits(14)+1;if(n<96)return null;let s=e.readBits(6);if(s>=yr.length)return null;let o=Wi[e.readBits(4)];if(o===0)return null;let a=Di[e.readBits(5)];if(e.readBits(1)!==0)return null;e.skipBits(4),e.skipBits(5);let c=e.readBits(2);if(c===3)return null;e.skipBits(1),r&&e.skipBits(16),e.skipBits(7);let l=Ni[e.readBits(3)];if(l===0)return null;let d=c!==0;return{frameSize:n,sampleRate:o,numberOfChannels:yr[s]+(d?1:0),sampleCount:i*br,channelLayout:Hi[s]|(d?qi:0),amode:s,lfePresent:d,bitRate:a,pcmResolution:l}},Ki=t=>{if(t.length<zi||t[0]!==100||t[1]!==88||t[2]!==32||t[3]!==37)return null;let e=new U(t);e.skipBits(32),e.skipBits(8);let r=e.readBits(2),i=e.readBits(1),n=8+4*i,s=16+4*i;e.skipBits(n);let o=e.readBits(s)+1,a={frameSize:o,asset:null};if(!e.readBits(1))return a;let c=Qi[e.readBits(2)],l=512*(e.readBits(3)+1);e.readBits(1)&&e.skipBits(36);let d=e.readBits(3)+1,p=e.readBits(3)+1,b=[];for(let B=0;B<d;B++)b.push(e.readBits(r+1));for(let B of b)e.skipBits(8*tr(B));if(e.readBits(1)){e.skipBits(2);let B=e.readBits(2)+1<<2,D=e.readBits(2)+1;e.skipBits(D*B)}for(let B=0;B<p;B++)e.skipBits(s);e.skipBits(9),e.skipBits(3),e.readBits(1)&&e.skipBits(4),e.readBits(1)&&e.skipBits(24),e.readBits(1)&&e.skipBits(8*(e.readBits(10)+1));let h=e.readBits(5)+1,y=ji[e.readBits(4)],T=e.readBits(8)+1,P=0;if(e.readBits(1)&&(T>2&&e.skipBits(1),T>6&&e.skipBits(1),e.readBits(1))){let B=e.readBits(2)+1<<2;P=e.readBits(B)}return c===0||e.getBitsLeft()<0?a:{frameSize:o,asset:{sampleRate:y,numberOfChannels:T,sampleCount:Math.round(l*y/c),channelLayout:P,pcmResolution:h}}};var Rr=t=>{let e=new Uint8Array(Vi),r=ne(e);r.setUint32(0,t.sampleRate),r.setUint32(4,t.bitRate),r.setUint32(8,t.bitRate),e[12]=t.pcmResolution;let i=t.core&&!t.hasExtensions?1:0,n=new U(e);return n.seekToByte(13),n.writeBits(2,Math.max($i.indexOf(t.sampleCount),0)),n.writeBits(5,i),n.writeBits(1,t.core?.lfePresent?1:0),n.writeBits(6,t.core?.amode??0),n.writeBits(14,t.core?t.core.frameSize-1:0),n.writeBits(1,0),n.writeBits(3,0),n.writeBits(16,t.channelLayout),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(5,0),e};var vt=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;var Fr=t=>{let e=Math.floor(t/36e5),r=Math.floor(t%(3600*1e3)/(60*1e3)),i=Math.floor(t%(60*1e3)/1e3),n=t%1e3;return e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")};var Or=new Uint8Array(0),$=class t{constructor(e,r,i,n,s=-1,o,a){if(this.data=e,this.type=r,this.timestamp=i,this.duration=n,this.sequenceNumber=s,e===Or&&o===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(o===void 0&&(o=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!=="key"&&r!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(n)||n<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(s))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(o)||o<0)throw new TypeError("byteLength must be a non-negative integer.");if(a!==void 0&&(typeof a!="object"||!a))throw new TypeError("sideData, when provided, must be an object.");if(a?.alpha!==void 0&&!(a.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(a?.alphaByteLength!==void 0&&(!Number.isInteger(a.alphaByteLength)||a.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=o,this.sideData=a??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Or}get microsecondTimestamp(){return Math.trunc(Tt*this.timestamp)}get microsecondDuration(){return Math.trunc(Tt*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,r){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let i=new Uint8Array(e.byteLength);return e.copyTo(i),new t(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,r)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.data!==void 0&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(e?.type!==void 0&&e.type!=="key"&&e.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(e?.sequenceNumber!==void 0&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(e?.sideData!==void 0&&(typeof e.sideData!="object"||e.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new t(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}};var Ur=2082844800,zr=t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");if(t.codecStrings.length>0){let i=[...new Set(t.codecStrings)];r+=`; codecs="${i.join(", ")}"`}return r};var at=7,Vr=9,It=t=>{let e=t.filePos;if(t.remainingLength<at)return null;let r=Lr(t,at),i=new U(r);if(i.readBits(12)!==4095||(i.skipBits(1),i.readBits(2)!==0))return null;let o=i.readBits(1),a=i.readBits(2)+1,c=i.readBits(4);if(c>=Qe.length)return null;i.skipBits(1);let l=i.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);let d=i.readBits(13);i.skipBits(11);let p=i.readBits(2)+1;if(p!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let b=null;if(o===0){if(t.remainingLength<2)return null;b=Wr(t)}return d<t.filePos-e?null:{objectType:a,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:d,numberOfAacFrames:p,crcCheck:b,startPos:e}};var $e=class t{constructor(e,r,i,n,s){this.bytes=e,this.view=r,this.offset=i,this.start=n,this.end=s,this.bufferPos=n-i}static tempFromBytes(e){return new t(e,ne(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,r=this.end-e){if(e<this.start||e+r>this.end)throw new RangeError("Slicing outside of original slice.");return new t(this.bytes,this.view,this.offset,e,e+r)}},Dr=(t,e)=>{if(e<0||t.filePos<t.start||t.filePos+e>t.end)throw new RangeError(`Tried reading [${t.filePos}, ${t.filePos+e}), but slice is [${t.start}, ${t.end}). This is likely an internal error, please report it alongside the file that caused it.`)},Lr=(t,e)=>{Dr(t,e);let r=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,r};var Wr=t=>{Dr(t,2);let e=t.view.getUint16(t.bufferPos,!1);return t.bufferPos+=2,e};var ct=8,Pt=16;var ke=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._nominalBitrate=null}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},ve=class extends ke{constructor(e){if(super(),!ge.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${ge.join(", ")}.`);this._codec=e}},Xi=(t,e)=>{if(t.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},Ge=class extends ve{constructor(e){super(e)}add(e,r){if(!(e instanceof $))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(r!==void 0&&(!r||typeof r!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),Xi(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,r)}};var Ie=class extends ke{constructor(e){if(super(),!Pe.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${Pe.join(", ")}.`);this._codec=e}},Ke=class extends Ie{constructor(e){super(e)}add(e,r){if(!(e instanceof $))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(r!==void 0&&(!r||typeof r!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,r)}};var Xe=class extends ke{constructor(e){if(super(),!ye.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${ye.join(", ")}.`);this._codec=e}};var ge=["avc","hevc","vp9","av1","vp8","prores"],ae=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],lt=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts","truehd"],Pe=[...lt,...ae],ye=["webvtt"];var Bt=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}];var Ze=["ap4x","ap4h","apch","apcn","apcs","apco"],Rt=["dtsc","dtsh","dtsl","dtse"];var Nr=t=>{let e=t.split("."),n=(1<<7)+1,s=Number(e[1]),o=e[2],a=Number(o.slice(0,-1)),c=(s<<5)+a,l=o.slice(-1)==="H"?1:0,d=Number(e[3]),p=d===8?0:1,b=d===12?1:0,h=e[4]?Number(e[4]):0,y=e[5]?Number(e[5][0]):1,T=e[5]?Number(e[5][1]):1,P=e[5]?Number(e[5][2]):0,B=(l<<7)+(p<<6)+(b<<5)+(h<<4)+(y<<3)+(T<<2)+P;return[n,c,B,0]};var Mt=48e3,Hr=.4,qr=/^pcm-([usf])(\d+)(be)?$/,pe=t=>{if(f(ae.includes(t)),t==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(t==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=qr.exec(t);f(e);let r;e[1]==="u"?r="unsigned":e[1]==="s"?r="signed":r="float";let i=Number(e[2])/8,n=e[3]!=="be",s=t==="pcm-u8"?2**7:0;return{dataType:r,sampleSize:i,littleEndian:n,silentValue:s}},Qr=t=>t.startsWith("avc1")||t.startsWith("avc3")?"avc":t.startsWith("hev1")||t.startsWith("hvc1")?"hevc":t==="vp8"?"vp8":t.startsWith("vp09")?"vp9":t.startsWith("av01")?"av1":Ze.includes(t)?"prores":t==="mp3"||t==="mp4a.69"||t==="mp4a.6B"||t==="mp4a.6b"||t==="mp4a.40.34"?"mp3":t.startsWith("mp4a.40.")||t==="mp4a.67"?"aac":t==="opus"||t==="Opus"?"opus":t==="vorbis"?"vorbis":t==="flac"?"flac":t==="ac-3"||t==="ac3"?"ac3":t==="ec-3"||t==="eac3"?"eac3":Rt.includes(t)?"dts":t==="mlpa"?"truehd":t==="ulaw"?"ulaw":t==="alaw"?"alaw":qr.test(t)?t:t==="webvtt"?"webvtt":null;var Zi=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Ze],Yi=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Ji=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,en=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,tn=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,ut=(t,e)=>{if(!t)throw new TypeError("Video chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Video chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!Zi.some(r=>t.decoderConfig.codec.startsWith(r)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(t.decoderConfig.codedWidth)||t.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(t.decoderConfig.codedHeight)||t.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(t.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(t.decoderConfig.displayAspectWidth)||t.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(t.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(t.decoderConfig.displayAspectHeight)||t.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(t.decoderConfig.displayAspectWidth!==void 0!=(t.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(t.decoderConfig.description!==void 0&&!xt(t.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.colorSpace!==void 0){let{colorSpace:r}=t.decoderConfig;if(typeof r!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let i=Object.keys(We);if(r.primaries!=null&&!i.includes(r.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${i.join(", ")}.`);let n=Object.keys(De);if(r.transfer!=null&&!n.includes(r.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${n.join(", ")}.`);let s=Object.keys(Ne);if(r.matrix!=null&&!s.includes(r.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${s.join(", ")}.`);if(r.fullRange!=null&&typeof r.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(t.decoderConfig.codec.startsWith("avc1")||t.decoderConfig.codec.startsWith("avc3")){if(!Yi.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(t.decoderConfig.codec.startsWith("hev1")||t.decoderConfig.codec.startsWith("hvc1")){if(!Ji.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(t.decoderConfig.codec.startsWith("vp8")){if(t.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(t.decoderConfig.codec.startsWith("vp09")){if(!en.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(t.decoderConfig.codec.startsWith("av01")){if(!tn.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')}else if(Ze.some(r=>t.decoderConfig.codec.startsWith(r))&&!Ze.some(r=>t.decoderConfig.codec===r))throw new TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${Ze.join(", ")}.`);if(e!==null&&Qr(t.decoderConfig.codec)!==e)throw new TypeError(`Video chunk metadata decoder configuration codec string '${t.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},rn=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts","mlpa"],dt=(t,e)=>{if(!t)throw new TypeError("Audio chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!rn.some(r=>t.decoderConfig.codec.startsWith(r)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(t.decoderConfig.sampleRate)||t.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(t.decoderConfig.numberOfChannels)||t.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(t.decoderConfig.description!==void 0&&!xt(t.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.codec.startsWith("mp4a")&&t.decoderConfig.codec!=="mp4a.69"&&t.decoderConfig.codec!=="mp4a.6B"&&t.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(t.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("mp3")||t.decoderConfig.codec.startsWith("mp4a")){if(t.decoderConfig.codec!=="mp3"&&t.decoderConfig.codec!=="mp4a.69"&&t.decoderConfig.codec!=="mp4a.6B"&&t.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(t.decoderConfig.codec.startsWith("opus")){if(t.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(t.decoderConfig.description&&t.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(t.decoderConfig.codec.startsWith("vorbis")){if(t.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("flac")){if(t.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!t.decoderConfig.description||t.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("ac-3")||t.decoderConfig.codec.startsWith("ac3")){if(t.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(t.decoderConfig.codec.startsWith("ec-3")||t.decoderConfig.codec.startsWith("eac3")){if(t.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if(t.decoderConfig.codec.startsWith("dts")){if(!Rt.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${Rt.join(", ")}.`)}else if(t.decoderConfig.codec.startsWith("mlpa")){if(t.decoderConfig.codec!=="mlpa")throw new TypeError('Audio chunk metadata decoder configuration codec string for TrueHD must be "mlpa".')}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!ae.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${ae.join(", ")}).`);if(e!==null&&Qr(t.decoderConfig.codec)!==e)throw new TypeError(`Audio chunk metadata decoder configuration codec string '${t.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},jr=t=>{if(!t)throw new TypeError("Subtitle metadata must be provided.");if(typeof t!="object")throw new TypeError("Subtitle metadata must be an object.");if(!t.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof t.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof t.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};var ft=class{constructor(e){this.mutex=new _e,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,r,i){let n=this.trackTimestampInfo.get(e);if(n){if(i&&(n.maxTimestampBeforeLastKeyPacket=n.maxTimestamp),n.maxTimestampBeforeLastKeyPacket!==null&&r<n.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${r}s, but largest timestamp is ${n.maxTimestampBeforeLastKeyPacket}s.`);n.maxTimestamp=Math.max(n.maxTimestamp,r)}else{if(!i)throw new Error("First packet must be a key packet.");n={maxTimestamp:r,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,n)}}};var xe=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let r=0;r<e.length;r++)this.helperView.setUint8(r%8,e.charCodeAt(r)),r%8===7&&this.writer.write(this.helper);e.length%8!==0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let r=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let s of e.children)s&&this.writeBox(s);let i=this.writer.getPos(),n=e.size??i-r;this.writer.seek(r),this.writeBoxHeader(e,n),this.writer.seek(i)}}writeBoxHeader(e,r){this.writeU32(e.largeSize?1:r),this.writeAscii(e.type),e.largeSize&&this.writeU64(r)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let r=this.offsets.get(e);f(r!==void 0);let i=this.writer.getPos();this.writer.seek(r),this.writeBox(e),this.writer.seek(i)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let r=this.measureBoxHeader(e);if(e.contents&&(r+=e.contents.byteLength),e.children)for(let i of e.children)i&&(r+=this.measureBox(i));return r}}},x=new Uint8Array(8),K=new DataView(x.buffer),M=t=>[(t%256+256)%256],w=t=>(K.setUint16(0,t,!1),[x[0],x[1]]),mt=t=>(K.setInt16(0,t,!1),[x[0],x[1]]),Xr=t=>(K.setUint32(0,t,!1),[x[1],x[2],x[3]]),u=t=>(K.setUint32(0,t,!1),[x[0],x[1],x[2],x[3]]),ue=t=>(K.setInt32(0,t,!1),[x[0],x[1],x[2],x[3]]),ee=t=>(K.setUint32(0,Math.floor(t/2**32),!1),K.setUint32(4,t,!1),[x[0],x[1],x[2],x[3],x[4],x[5],x[6],x[7]]),$r=t=>(K.setInt32(0,Math.floor(t/2**32),!1),K.setUint32(4,t,!1),[x[0],x[1],x[2],x[3],x[4],x[5],x[6],x[7]]),Zr=t=>(K.setInt16(0,2**8*t,!1),[x[0],x[1]]),G=t=>(K.setInt32(0,2**16*t,!1),[x[0],x[1],x[2],x[3]]),Ft=t=>(K.setInt32(0,2**30*t,!1),[x[0],x[1],x[2],x[3]]),Ot=(t,e)=>{let r=[],i=t;do{let n=i&127;i>>=7,r.length>0&&(n|=128),r.push(n),e!==void 0&&e--}while(i>0||e);return r.reverse()},E=(t,e=!1)=>{let r=Array(t.length).fill(null).map((i,n)=>t.charCodeAt(n));return e&&r.push(0),r},Yr=t=>[G(t[0]),G(t[1]),Ft(t[2]),G(t[3]),G(t[4]),Ft(t[5]),G(t[6]),G(t[7]),Ft(t[8])],A=(t,e,r)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:r}),C=(t,e,r,i,n)=>A(t,[M(e),Xr(r),i??[]],n),Jr=t=>t.isQuickTime?A("ftyp",[E("qt "),u(512),E("qt ")]):t.fragmented?t.cmaf?A("ftyp",[E("iso5"),u(512),E("iso5"),E("iso6"),E("mp41"),E("cmfc"),E("dash")]):A("ftyp",[E("iso5"),u(512),E("iso5"),E("iso6"),E("mp41")]):A("ftyp",[E("isom"),u(512),E("isom"),t.holdsAvc?E("avc1"):[],E("mp41")]),zt=()=>A("styp",[E("iso5"),u(0),E("iso5"),E("iso6"),E("mp41"),E("cmfc"),E("dash")]),Vt=(t,e)=>{let r=Math.max(0,t.minWrittenTimestamp),i=Math.max(0,t.maxWrittenEndTimestamp-r);return Number.isFinite(i)||(i=0),C("sidx",1,0,[u(1),u(N),ee(k(r,N)),ee(0),w(0),w(1),u(e&2147483647),u(k(i,N)),u(0)])},Ye=t=>({type:"mdat",largeSize:t}),ei=t=>({type:"free",size:t}),Me=t=>A("moov",void 0,[nn(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>sn(e,t.creationTime)),t.isFragmented?jn(t.trackDatas):null,ts(t)]),nn=(t,e)=>{let r=Math.max(0,...e.map(o=>Math.max(0,k(Te(o),N)+k(o.startTimestampOffset??0,N)))),i=Math.max(0,...e.map(o=>o.track.id))+1,n=!re(t)||!re(r),s=n?ee:u;return C("mvhd",+n,0,[s(t),s(t),u(N),s(r),G(1),Zr(1),Array(10).fill(0),Yr(yt),Array(24).fill(0),u(i)])},sn=(t,e)=>{let r=ui(t),i=t.startTimestampOffset!==null&&t.startTimestampOffset!==0;return A("trak",void 0,[on(t,e),i?an(t):null,cn(t,e),r.name!==void 0?A("udta",void 0,[A("name",[...j.encode(r.name)])]):null])},on=(t,e)=>{let r=Math.max(0,k(Te(t),N)+k(t.startTimestampOffset??0,N)),i=!re(e)||!re(r),n=i?ee:u,s;if(t.type==="video"&&t.track.metadata.transformationMatrix)s=t.track.metadata.transformationMatrix;else if(t.type==="video"){let{rotation:c,flip:l}=t.track.metadata,d=rt(Gt(c??0),Kt(l?-1:1,1));s=$t(d,t.info.width,t.info.height)}else s=yt;let o=2;t.track.metadata.disposition?.default!==!1&&(o|=1);let a=t.type==="video"?0:t.type==="audio"?1:t.type==="subtitle"?2:Be(t);return C("tkhd",+i,o,[n(e),n(e),u(t.track.id),u(0),n(r),Array(8).fill(0),w(0),w(a),Zr(t.type==="audio"?1:0),w(0),Yr(s),G(t.type==="video"?t.info.width:0),G(t.type==="video"?t.info.height:0)])},an=t=>{let e=t.startTimestampOffset;if(f(e!==null),e>0){let r=k(e,N),i=k(Te(t),N),n=!re(r)||!re(i),s=n?ee:u,o=n?$r:ue;return A("edts",void 0,[C("elst",n?1:0,0,[u(2),s(r),o(-1),G(1),s(i),o(0),G(1)])])}else{let r=k(-e,t.timescale),i=Math.max(0,k(Te(t),N)+k(e,N)),n=!Xt(r)||!re(i),s=n?ee:u,o=n?$r:ue;return A("edts",void 0,[C("elst",n?1:0,0,[u(1),s(i),o(r),G(1)])])}},cn=(t,e)=>A("mdia",void 0,[ln(t,e),Lt(!0,un[t.type],dn[t.type]),fn(t)]),ln=(t,e)=>{let r=k(Te(t),t.timescale),i=!re(e)||!re(r),n=i?ee:u;return C("mdhd",+i,0,[n(e),n(e),u(t.timescale),n(r),w(li(t.track.metadata.languageCode??er)),w(0)])},un={video:"vide",audio:"soun",subtitle:"text"},dn={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Lt=(t,e,r,i="\0\0\0\0")=>C("hdlr",0,0,[t?E("mhlr"):u(0),E(e),E(i),u(0),u(0),E(r,!0)]),fn=t=>A("minf",void 0,[An[t.type](),gn(),yn(t)]),mn=()=>C("vmhd",0,1,[w(0),w(0),w(0),w(0)]),pn=()=>C("smhd",0,0,[w(0),w(0)]),hn=()=>C("nmhd",0,0),An={video:mn,audio:pn,subtitle:hn},gn=()=>A("dinf",void 0,[wn()]),wn=()=>C("dref",0,0,[u(1)],[bn()]),bn=()=>C("url ",0,1),yn=t=>{let e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(r=>r.sampleCompositionTimeOffset!==0);return A("stbl",void 0,[xn(t),Ln(t),e?qn(t):null,e?Qn(t):null,Dn(t),Nn(t),Hn(t),Wn(t),...ti(t.samples,!1)])},xn=t=>{let e;if(t.type==="video")e=Tn(os(t.track.source._codec,t.info.decoderConfig.codec),t);else if(t.type==="audio"){let r=ci(t.track.source._codec,t.info.decoderConfig.codec,t.muxer.isQuickTime);f(r),e=kn(r,t)}else t.type==="subtitle"&&(e=zn(ls[t.track.source._codec],t));return f(e),C("stsd",0,0,[u(1)],[e])},Tn=(t,e)=>A(t,[Array(6).fill(0),w(1),w(0),w(0),Array(12).fill(0),w(e.info.width),w(e.info.height),u(4718592),u(4718592),u(0),w(1),M(st.length),E(st),Array(31-st.length).fill(0),w(e.info.hasAlphaChannel?32:24),mt(65535)],[as[e.track.source._codec]?.(e)??null,Cn(e),Zt(e.info.decoderConfig.colorSpace)?null:En(e),Wt(e)]),Wt=t=>t.avgBitrate===0&&t.maxBitrate===0?null:A("btrt",[u(0),u(t.maxBitrate),u(t.avgBitrate)]),Cn=t=>t.info.pixelAspectRatio.num===t.info.pixelAspectRatio.den?null:A("pasp",[u(t.info.pixelAspectRatio.num),u(t.info.pixelAspectRatio.den)]),En=t=>{let e=t.info.decoderConfig.colorSpace;return A("colr",[E(t.muxer.isQuickTime?"nclc":"nclx"),w(e?.primaries!=null?We[e.primaries]:2),w(e?.transfer!=null?De[e.transfer]:2),w(e?.matrix!=null?Ne[e.matrix]:2),t.muxer.isQuickTime?[]:M((e?.fullRange?1:0)<<7)])},Sn=t=>t.info.decoderConfig&&A("avcC",[...me(t.info.decoderConfig.description)]),_n=t=>t.info.decoderConfig&&A("hvcC",[...me(t.info.decoderConfig.description)]),Gr=t=>{if(!t.info.decoderConfig)return null;let e=t.info.decoderConfig,r=e.codec.split("."),i=Number(r[1]),n=Number(r[2]),s=Number(r[3]),o=r[4]?Number(r[4]):1,a=r[8]?Number(r[8]):Number(e.colorSpace?.fullRange??0),c=(s<<4)+(o<<1)+a,l=r[5]?Number(r[5]):e.colorSpace?.primaries?We[e.colorSpace.primaries]:1,d=r[6]?Number(r[6]):e.colorSpace?.transfer?De[e.colorSpace.transfer]:1,p=r[7]?Number(r[7]):e.colorSpace?.matrix?Ne[e.colorSpace.matrix]:1;return C("vpcC",1,0,[M(i),M(n),M(c),M(l),M(d),M(p),w(0)])},Bn=t=>A("av1C",Nr(t.info.decoderConfig.codec)),kn=(t,e)=>{let r=0,i,n=16,s=ae.includes(e.track.source._codec);if(s){let o=e.track.source._codec,{sampleSize:a}=pe(o);n=8*a,n>16&&(r=1)}if(e.muxer.isQuickTime&&e.track.source._codec!=="truehd"&&(r=1),r===0)i=[Array(6).fill(0),w(1),w(r),w(0),u(0),w(e.info.numberOfChannels),w(n),w(0),w(0),e.track.source._codec==="truehd"?u(e.info.sampleRate):[w(e.info.sampleRate<2**16?e.info.sampleRate:0),w(0)]];else{let o=s?0:-2;i=[Array(6).fill(0),w(1),w(r),w(0),u(0),w(e.info.numberOfChannels),w(Math.min(n,16)),mt(o),w(0),w(e.info.sampleRate<2**16?e.info.sampleRate:0),w(0),s?[u(1),u(n/8),u(e.info.numberOfChannels*n/8)]:[u(0),u(0),u(0)],u(2)]}return A(t,i,[cs(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null,Wt(e)])},Ut=t=>{let e;switch(t.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${t.track.source._codec}`)}let r=[...M(e),...M(21),...Xr(0),...u(t.maxBitrate),...u(t.avgBitrate)];if(t.info.decoderConfig.description){let i=me(t.info.decoderConfig.description);r=[...r,...M(5),...Ot(i.byteLength),...i]}return r=[...w(1),...M(0),...M(4),...Ot(r.length),...r,...M(6),...M(1),...M(2)],r=[...M(3),...Ot(r.length),...r],C("esds",0,0,r)},we=t=>A("wave",void 0,[vn(t),In(t),A("\0\0\0\0")]),vn=t=>A("frma",[E(ci(t.track.source._codec,t.info.decoderConfig.codec,t.muxer.isQuickTime))]),In=t=>{let{littleEndian:e}=pe(t.track.source._codec);return A("enda",[w(+e)])},Pn=t=>{let e=t.info.numberOfChannels,r=312,i=t.info.sampleRate,n=0,s=0,o=new Uint8Array(0),a=t.info.decoderConfig?.description;if(a){f(a.byteLength>=18);let c=me(a),l=Br(c);e=l.outputChannelCount,r=l.preSkip,i=l.inputSampleRate,n=l.outputGain,s=l.channelMappingFamily,l.channelMappingTable&&(o=l.channelMappingTable)}return A("dOps",[M(0),M(e),w(r),u(i),mt(n),M(s),...o])},Mn=t=>{let e=t.info.decoderConfig?.description;f(e);let r=me(e);return C("dfLa",0,0,[...r.subarray(4)])},ce=t=>{let{littleEndian:e,sampleSize:r}=pe(t.track.source._codec),i=+e;return C("pcmC",0,0,[M(i),M(8*r)])},Rn=t=>{f(t.info.primingPacket);let e=Ir(t.info.primingPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");let r=new Uint8Array(3),i=new U(r);return i.writeBits(2,e.fscod),i.writeBits(5,e.bsid),i.writeBits(3,e.bsmod),i.writeBits(3,e.acmod),i.writeBits(1,e.lfeon),i.writeBits(5,e.bitRateCode),i.writeBits(5,0),A("dac3",[...r])},Fn=t=>{f(t.info.primingPacket);let e=Pr(t.info.primingPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let r=16;for(let o of e.substreams)r+=23,o.numDepSub>0?r+=9:r+=1;let i=Math.ceil(r/8),n=new Uint8Array(i),s=new U(n);s.writeBits(13,e.dataRate),s.writeBits(3,e.substreams.length-1);for(let o of e.substreams)s.writeBits(2,o.fscod),s.writeBits(5,o.bsid),s.writeBits(1,0),s.writeBits(1,0),s.writeBits(3,o.bsmod),s.writeBits(3,o.acmod),s.writeBits(1,o.lfeon),s.writeBits(3,0),s.writeBits(4,o.numDepSub),o.numDepSub>0?s.writeBits(9,o.chanLoc):s.writeBits(1,0);return A("dec3",[...n])},On=t=>{f(t.info.primingPacket);let e=Mr(t.info.primingPacket.data);if(!e)throw new Error("Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.");return A("ddts",[...Rr(e)])},Un=t=>{f(t.info.primingPacket);let e=t.info.primingPacket.data;if(vr("truehd",e)!=="key")throw new Error("Couldn't extract TrueHD stream info from the audio packet. Ensure the first packet is an access unit carrying a major sync.");let r=ne(e),i=r.getUint32(8),n=r.getUint16(18)&32767;return A("dmlp",[u(i),w(n<<1),u(0)])},zn=(t,e)=>A(t,[Array(6).fill(0),w(1)],[us[e.track.source._codec](e),Wt(e)]),Vn=t=>A("vttC",[...j.encode(t.info.config.description)]);var Ln=t=>C("stts",0,0,[u(t.timeToSampleTable.length),t.timeToSampleTable.map(e=>[u(e.sampleCount),u(e.sampleDelta)])]),Wn=t=>{if(t.samples.every(r=>r.type==="key"))return null;let e=[...t.samples.entries()].filter(([,r])=>r.type==="key");return C("stss",0,0,[u(e.length),e.map(([r])=>u(r+1))])},Dn=t=>C("stsc",0,0,[u(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(e=>[u(e.firstChunk),u(e.samplesPerChunk),u(1)])]),Nn=t=>{if(t.type==="audio"&&t.info.requiresPcmTransformation){let{sampleSize:e}=pe(t.track.source._codec);return C("stsz",0,0,[u(e*t.info.numberOfChannels),u(t.samples.reduce((r,i)=>r+k(i.duration,t.timescale),0))])}return C("stsz",0,0,[u(0),u(t.samples.length),t.samples.map(e=>u(e.size))])},Hn=t=>t.finalizedChunks.length>0&&te(t.finalizedChunks).offset>=2**32?C("co64",0,0,[u(t.finalizedChunks.length),t.finalizedChunks.map(e=>ee(e.offset))]):C("stco",0,0,[u(t.finalizedChunks.length),t.finalizedChunks.map(e=>u(e.offset))]),qn=t=>C("ctts",1,0,[u(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(e=>[u(e.sampleCount),ue(e.sampleCompositionTimeOffset)])]),Qn=t=>{if(f(t.compositionTimeOffsetTable.length>0),t.samples.length===0)return null;let e=1/0,r=-1/0,i=1/0,n=-1/0;for(let o=0;o<t.compositionTimeOffsetTable.length;o++){let a=t.compositionTimeOffsetTable[o];e=Math.min(e,a.sampleCompositionTimeOffset),r=Math.max(r,a.sampleCompositionTimeOffset)}for(let o=0;o<t.samples.length;o++){let a=t.samples[o];i=Math.min(i,k(a.timestamp,t.timescale)),n=Math.max(n,k(a.timestamp+a.duration,t.timescale))}let s=Math.max(-e,0);return n>=2**31?null:C("cslg",0,0,[ue(s),ue(e),ue(r),ue(i),ue(n)])},ti=(t,e)=>{let r=[];for(let s of t)if(r.length===0)r.push({sampleCount:1,prerollSamples:s.prerollSamples});else{let o=r[r.length-1];o.prerollSamples===s.prerollSamples?o.sampleCount++:r.push({sampleCount:1,prerollSamples:s.prerollSamples})}let i=r.filter(s=>s.prerollSamples!==0);if(i.length===0)return[];let n=e?65537:1;return[C("sgpd",1,0,[E("roll"),u(2),u(i.length),...i.map(s=>mt(s.prerollSamples))]),C("sbgp",0,0,[E("roll"),u(r.length),...r.map(s=>[u(s.sampleCount),u(s.prerollSamples!==0?n++:0)])])]},jn=t=>A("mvex",void 0,t.map($n)),$n=t=>C("trex",0,0,[u(t.track.id),u(1),u(0),u(0),u(0)]),Dt=(t,e)=>A("moof",void 0,[Gn(t),...e.map(Kn)]),Gn=t=>C("mfhd",0,0,[u(t)]),ri=t=>{let e=0,r=0,i=0,n=0,s=t.type==="delta";return r|=+s,s?e|=1:e|=2,e<<24|r<<16|i<<8|n},Kn=t=>A("traf",void 0,[Xn(t),Zn(t),Yn(t),...ti(t.currentChunk.samples,!0)]),Xn=t=>{f(t.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;let r=t.currentChunk.samples[1]??t.currentChunk.samples[0],i={duration:r.timescaleUnitsToNextSample,size:r.size,flags:ri(r)};return C("tfhd",0,e,[u(t.track.id),u(i.duration),u(i.size),u(i.flags)])},Zn=t=>(f(t.currentChunk),C("tfdt",1,0,[ee(k(t.currentChunk.startTimestamp,t.timescale))])),Yn=t=>{f(t.currentChunk);let e=t.currentChunk.samples.map(T=>T.timescaleUnitsToNextSample),r=t.currentChunk.samples.map(T=>T.size),i=t.currentChunk.samples.map(ri),n=t.currentChunk.samples.map(T=>k(T.timestamp-T.decodeTimestamp,t.timescale)),s=new Set(e),o=new Set(r),a=new Set(i),c=new Set(n),l=a.size===2&&i[0]!==i[1],d=s.size>1,p=o.size>1,b=!l&&a.size>1,h=c.size>1||[...c].some(T=>T!==0),y=0;return y|=1,y|=4*+l,y|=256*+d,y|=512*+p,y|=1024*+b,y|=2048*+h,C("trun",1,y,[u(t.currentChunk.samples.length),u(t.currentChunk.offset-t.currentChunk.moofOffset||0),l?u(i[0]):[],t.currentChunk.samples.map((T,P)=>[d?u(e[P]):[],p?u(r[P]):[],b?u(i[P]):[],h?ue(n[P]):[]])])},ii=t=>A("mfra",void 0,[...t.map(Jn),es()]),Jn=t=>{let r=[];for(let i of t.finalizedChunks){let n=i.samples.findIndex(o=>o.type==="key");if(n===-1)continue;let s=i.samples[n];r.push([ee(k(s.timestamp,t.timescale)),ee(i.moofOffset),u(i.trafIndex+1),u(1),u(n+1)])}return C("tfra",1,0,[u(t.track.id),u(63),u(r.length),r])},es=()=>C("mfro",0,0,[u(0)]),ni=()=>A("vtte"),si=(t,e,r,i,n)=>A("vttc",void 0,[n!==null?A("vsid",[ue(n)]):null,r!==null?A("iden",[...j.encode(r)]):null,e!==null?A("ctim",[...j.encode(Fr(e))]):null,i!==null?A("sttg",[...j.encode(i)]):null,A("payl",[...j.encode(t)])]),oi=t=>A("vtta",[...j.encode(t)]),ts=t=>{let e=[],r=t.format._options.metadataFormat??"auto",i=t.output._metadataTags;if(r==="mdir"||r==="auto"&&!t.isQuickTime){let n=ns(i);n&&e.push(n)}else if(r==="mdta"){let n=ss(i);n&&e.push(n)}else(r==="udta"||r==="auto"&&t.isQuickTime)&&rs(e,t.output._metadataTags);return e.length===0?null:A("udta",void 0,e)},rs=(t,e)=>{for(let{key:r,value:i}of it(e))switch(r){case"title":t.push(le("\xA9nam",i));break;case"description":t.push(le("\xA9des",i));break;case"artist":t.push(le("\xA9ART",i));break;case"album":t.push(le("\xA9alb",i));break;case"albumArtist":t.push(le("albr",i));break;case"genre":t.push(le("\xA9gen",i));break;case"date":t.push(le("\xA9day",i.toISOString().slice(0,10)));break;case"comment":t.push(le("\xA9cmt",i));break;case"lyrics":t.push(le("\xA9lyr",i));break;case"raw":break;case"creationTime":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"beatsPerMinute":case"images":break;default:Be(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||r.length!==4||t.some(n=>n.type===r)||(typeof i=="string"?t.push(le(r,i)):i instanceof Uint8Array&&t.push(A(r,Array.from(i))))}},le=(t,e)=>{let r=j.encode(e);return A(t,[w(r.length),w(li("und")),Array.from(r)])},Kr={"image/jpeg":13,"image/png":14,"image/bmp":27},is=new Set(["HMMT","loci","chpl"]),ai=(t,e)=>{let r=[];for(let{key:i,value:n}of it(t))switch(i){case"title":r.push({key:e?"title":"\xA9nam",value:J(n)});break;case"description":r.push({key:e?"description":"\xA9des",value:J(n)});break;case"artist":r.push({key:e?"artist":"\xA9ART",value:J(n)});break;case"album":r.push({key:e?"album":"\xA9alb",value:J(n)});break;case"albumArtist":r.push({key:e?"album_artist":"aART",value:J(n)});break;case"comment":r.push({key:e?"comment":"\xA9cmt",value:J(n)});break;case"genre":r.push({key:e?"genre":"\xA9gen",value:J(n)});break;case"beatsPerMinute":e||r.push({key:"tmpo",value:A("data",[u(21),u(0),w(n)])});break;case"lyrics":r.push({key:e?"lyrics":"\xA9lyr",value:J(n)});break;case"date":r.push({key:e?"date":"\xA9day",value:J(n.toISOString().slice(0,10))});break;case"images":for(let s of n)s.kind==="coverFront"&&r.push({key:"covr",value:A("data",[u(Kr[s.mimeType]??0),u(0),Array.from(s.data)])});break;case"trackNumber":if(e){let s=t.tracksTotal!==void 0?`${n}/${t.tracksTotal}`:n.toString();r.push({key:"track",value:J(s)})}else r.push({key:"trkn",value:A("data",[u(0),u(0),w(0),w(n),w(t.tracksTotal??0),w(0)])});break;case"discNumber":e||r.push({key:"disc",value:A("data",[u(0),u(0),w(0),w(n),w(t.discsTotal??0),w(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;case"creationTime":break;default:Be(i)}if(t.raw)for(let i in t.raw){let n=t.raw[i];n==null||!e&&(i.length!==4||is.has(i))||r.some(s=>s.key===i)||(typeof n=="string"?r.push({key:i,value:J(n)}):n instanceof Uint8Array?r.push({key:i,value:A("data",[u(0),u(0),Array.from(n)])}):n instanceof qe&&r.push({key:i,value:A("data",[u(Kr[n.mimeType]??0),u(0),Array.from(n.data)])}))}return r},ns=t=>{let e=ai(t,!1);return e.length===0?null:C("meta",0,0,void 0,[Lt(!1,"mdir","","appl"),A("ilst",void 0,e.map(r=>A(r.key,void 0,[r.value])))])},ss=t=>{let e=ai(t,!0);return e.length===0?null:A("meta",void 0,[Lt(!1,"mdta",""),C("keys",0,0,[u(e.length)],e.map(r=>A("mdta",[...j.encode(r.key)]))),A("ilst",void 0,e.map((r,i)=>{let n=String.fromCharCode(...u(i+1));return A(n,void 0,[r.value])}))])},J=t=>A("data",[u(1),u(0),...j.encode(t)]),os=(t,e)=>{switch(t){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";case"prores":return e}},as={avc:Sn,hevc:_n,vp8:Gr,vp9:Gr,av1:Bn,prores:null},ci=(t,e,r)=>{switch(t){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3";case"dts":return e;case"truehd":return"mlpa"}if(r)switch(t){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(t){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},cs=(t,e)=>{switch(t){case"aac":return Ut;case"mp3":return Ut;case"opus":return Pn;case"vorbis":return Ut;case"flac":return Mn;case"ac3":return Rn;case"eac3":return Fn;case"dts":return On;case"truehd":return Un}if(e)switch(t){case"pcm-s24":return we;case"pcm-s24be":return we;case"pcm-s32":return we;case"pcm-s32be":return we;case"pcm-f32":return we;case"pcm-f32be":return we;case"pcm-f64":return we;case"pcm-f64be":return we}else switch(t){case"pcm-s16":return ce;case"pcm-s16be":return ce;case"pcm-s24":return ce;case"pcm-s24be":return ce;case"pcm-s32":return ce;case"pcm-s32be":return ce;case"pcm-f32":return ce;case"pcm-f32be":return ce;case"pcm-f64":return ce;case"pcm-f64be":return ce}return null},ls={webvtt:"wvtt"},us={webvtt:Vn},li=t=>{f(t.length===3);let e=0;for(let r=0;r<3;r++)e<<=5,e+=t.charCodeAt(r)-96;return e};var Ce=class{constructor(e,r){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");this.target=e,e._setMonotonicity(r),e._writerAcquired=!0}start(){f(!this.started),this.target._start(),this.started=!0}write(e){f(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return f(this.started&&!this.finalized),this.target._flush()}async finalize(){f(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let r=this.getPos();if(r<this.trackedStart){if(r+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-r),r=0}let i=r+e.byteLength-this.trackedStart,n=this.trackedWrites.byteLength;for(;n<i;)n*=2;if(n!==this.trackedWrites.byteLength){let s=new Uint8Array(n);s.set(this.trackedWrites,0),this.trackedWrites=s}this.trackedWrites.set(e,r-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,r+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");let r={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,r}};var H=class extends Ae{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,r){this.onwrite?.(e,r),this._emit("write",{start:e,end:r})}slice(e){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");return new pt(this,e)}},Nt=2**16,Ht=2**32,Ee=class extends H{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!="object")throw new TypeError("BufferTarget options, when provided, must be an object.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");if(this._options=e,this._supportsResize="resize"in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(Nt,{maxByteLength:Ht})}catch{this._buffer=new ArrayBuffer(Nt),this._supportsResize=!1}else this._buffer=new ArrayBuffer(Nt);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){f(this._buffer),f(this._bytes);let r=this._buffer.byteLength;for(;r<e;)r*=2;if(r!==this._buffer.byteLength){if(r>Ht)throw new Error(`ArrayBuffer exceeded maximum size of ${Ht} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(r);else{let i=new ArrayBuffer(r),n=new Uint8Array(i);n.set(this._bytes,0),this._buffer=i,this._bytes=n}}}_start(){}_write(e,r){f(this._bytes),this._ensureSize(r+e.byteLength),this._bytes.set(e,r),this._maxPos=Math.max(this._maxPos,r+e.byteLength),this._dispatchWrite(r,r+e.byteLength)}async _flush(){}async _finalize(){f(this._buffer),"transferToFixedLength"in this._buffer?this.buffer=this._buffer.transferToFixedLength(this._maxPos):this.buffer=this._buffer.slice(0,this._maxPos),this._buffer=null,this._bytes=null,this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,r){return f(this._bytes),this._bytes.slice(e,r)}},ds=2**24,fs=2,Je=class extends H{constructor(e,r={}){if(super(),this._sections=[],this._lastWriteEnd=0,this._lastFlushEnd=0,this._streamWriter=null,this._writeError=null,this._chunks=[],!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(r!=null&&typeof r!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(r.chunked!==void 0&&typeof r.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(r.chunkSize!==void 0&&(!Number.isInteger(r.chunkSize)||r.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=r,this._chunked=r.chunked??!1,this._chunkSize=r.chunkSize??ds}_start(){this._streamWriter=this._writable.getWriter()}_write(e,r){if(r>this._lastWriteEnd){let i=r-this._lastWriteEnd;this._write(new Uint8Array(i),this._lastWriteEnd)}this._sections.push({data:e.slice(),start:r}),this._lastWriteEnd=Math.max(this._lastWriteEnd,r+e.byteLength),this._dispatchWrite(r,r+e.byteLength)}async _flush(){if(this._writeError!==null)throw this._writeError;if(f(this._streamWriter),this._sections.length===0)return;let e=[],r=[...this._sections].sort((i,n)=>i.start-n.start);e.push({start:r[0].start,size:r[0].data.byteLength});for(let i=1;i<r.length;i++){let n=e[e.length-1],s=r[i];s.start<=n.start+n.size?n.size=Math.max(n.size,s.start+s.data.byteLength-n.start):e.push({start:s.start,size:s.data.byteLength})}for(let i of e){i.data=new Uint8Array(i.size);for(let n of this._sections)i.start<=n.start&&n.start<i.start+i.size&&i.data.set(n.data,n.start-i.start);if(this._streamWriter.desiredSize!==null&&this._streamWriter.desiredSize<=0&&await this._streamWriter.ready,this._chunked)this._writeDataIntoChunks(i.data,i.start),this._tryToFlushChunks();else{if(this._monotonicity===!0&&i.start!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:i.data,position:i.start}).catch(n=>{this._writeError??=n}),this._lastFlushEnd=i.start+i.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,r){let i=this._chunks.findIndex(c=>c.start<=r&&r<c.start+this._chunkSize);i===-1&&(i=this._createChunk(r));let n=this._chunks[i],s=r-n.start,o=e.subarray(0,Math.min(this._chunkSize-s,e.byteLength));n.data.set(o,s);let a={start:s,end:s+o.byteLength};if(this._insertSectionIntoChunk(n,a),n.written[0].start===0&&n.written[0].end===this._chunkSize&&(n.shouldFlush=!0),this._chunks.length>fs){for(let c=0;c<this._chunks.length-1;c++)this._chunks[c].shouldFlush=!0;this._tryToFlushChunks()}o.byteLength<e.byteLength&&this._writeDataIntoChunks(e.subarray(o.byteLength),r+o.byteLength)}_insertSectionIntoChunk(e,r){let i=0,n=e.written.length-1,s=-1;for(;i<=n;){let o=Math.floor(i+(n-i+1)/2);e.written[o].start<=r.start?(i=o+1,s=o):n=o-1}for(e.written.splice(s+1,0,r),(s===-1||e.written[s].end<r.start)&&s++;s<e.written.length-1&&e.written[s].end>=e.written[s+1].start;)e.written[s].end=Math.max(e.written[s].end,e.written[s+1].end),e.written.splice(s+1,1)}_createChunk(e){let i={start:Math.floor(e/this._chunkSize)*this._chunkSize,data:new Uint8Array(this._chunkSize),written:[],shouldFlush:!1};return this._chunks.push(i),this._chunks.sort((n,s)=>n.start-s.start),this._chunks.indexOf(i)}_tryToFlushChunks(e=!1){f(this._streamWriter);for(let r=0;r<this._chunks.length;r++){let i=this._chunks[r];if(!(!i.shouldFlush&&!e)){for(let n of i.written){let s=i.start+n.start;if(this._monotonicity===!0&&s!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");let o=n.start!==0||n.end!==i.data.byteLength,a;o&&Ct()?a=i.data.slice(n.start,n.end):a=i.data.subarray(n.start,n.end),this._streamWriter.write({type:"write",data:a,position:s}).catch(c=>{this._writeError??=c}),this._lastFlushEnd=i.start+n.end}this._chunks.splice(r--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;f(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit("finalized")}async _close(){return this._streamWriter?.close()}};var pt=class extends H{constructor(e,r){super(),this._baseTarget=e,this._offset=r}_start(){}_write(e,r){this._baseTarget._write(e,this._offset+r),this._dispatchWrite(r,r+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}},Se=class{constructor(e,r){if(this.rootPath=e,this.getTarget=r,typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof r!="function")throw new TypeError("getTarget must be a function.")}};var N=57600,di=.5,ui=t=>{let e={},r=t.track;return r.metadata.name!==void 0&&(e.name=r.metadata.name),e},k=(t,e,r=!0)=>{let i=t*e;return r?Math.round(i):i},Te=t=>{if(t.samples.length===0)return 0;let e=1/0,r=-1/0;for(let i=0;i<t.samples.length;i++){let n=t.samples[i];n.timestamp<e&&(e=n.timestamp),n.timestamp+n.duration>r&&(r=n.timestamp+n.duration)}return e===1/0?0:r-e},ht=class extends ft{constructor(e,r){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Ee,this.auxWriter=new Ce(this.auxTarget,!1),this.auxBoxWriter=new xe(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Yt(),this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=r,this.formatOptions={...r._options},this.isQuickTime=r instanceof Fe,this.isCmaf=r instanceof Re,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(r instanceof Re?1/0:1),this.auxWriter.start()}async start(){let e=await this.mutex.acquire(),r=this.output._metadataTags.creationTime===void 0?new Date:this.output._metadataTags.creationTime;if(this.creationTime=r?Math.floor(r.getTime()/1e3)+Ur:0,r&&this.creationTime<=0)throw new Error("creationTime must be after 1904-01-01T00:00:00Z for MP4/QuickTime files.");if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(n=>this.formatOptions.fastStart!==void 0?this.formatOptions.fastStart==="fragmented":n instanceof Ee),this.boxWriter=new xe(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof Ee?"in-memory":!1),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");let n=await this.output._getInitTarget(),s=new Ce(n,!0);s.start(),this.initWriter=s,this.initBoxWriter=new xe(s)}let i=this.output.tracks.some(n=>n.isVideoTrack()&&n.source._codec==="avc");{let n=this.initBoxWriter??this.boxWriter;if(f(n),this.formatOptions.onFtyp&&n.writer.startTrackingWrites(),n.writeBox(Jr({isQuickTime:this.isQuickTime,holdsAvc:i,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:s,start:o}=n.writer.stopTrackingWrites();this.formatOptions.onFtyp(s,o)}this.ftypSize=n.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve")for(let n of this.output.tracks){if(n.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.");if(n.metadata.maximumPacketCount>2**32-1)throw new Error(`Track #${n.id} has a maximumPacketCount of ${n.metadata.maximumPacketCount}, which exceeds the maximum of ${2**32-1} packets per track that a non-fragmented file can hold.`)}else this.isFragmented||(f(this.writer),f(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ye(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush();for(let n of this.output.tracks)n.isVideoTrack()&&n.metadata.decoderConfig?this.getVideoTrackData(n,n.metadata.primingPacket??null,{decoderConfig:n.metadata.decoderConfig}):n.isAudioTrack()&&n.metadata.decoderConfig&&this.getAudioTrackData(n,n.metadata.primingPacket??null,{decoderConfig:n.metadata.decoderConfig});e()}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return zr({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,i){let n=this.trackDatas.find(h=>h.track===e);if(n)return n;ut(i,e.source._codec),f(i),f(i.decoderConfig);let s={...i.decoderConfig};f(s.codedWidth!==void 0),f(s.codedHeight!==void 0);let o=!1;if(e.source._codec==="avc"&&!s.description){if(!r)throw new Error("No AVC description provided; you must therefore provide a priming packet.");let h=Tr(r.data);if(!h)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=Cr(h),o=!0}else if(e.source._codec==="hevc"&&!s.description){if(!r)throw new Error("No HEVC description provided; you must therefore provide a priming packet.");let h=Sr(r.data);if(!h)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=_r(h),o=!0}let a=ir(1/(e.metadata.frameRate??N),1e6).den,c=s.displayAspectWidth,l=s.displayAspectHeight,d=c===void 0||l===void 0?{num:1,den:1}:sr({num:c*s.codedHeight,den:l*s.codedWidth}),p=s.codec==="ap4h"||s.codec==="ap4x",b={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:d,decoderConfig:s,requiresAnnexBTransformation:o,hasAlphaChannel:p},timescale:a,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(b),this.trackDatas.sort((h,y)=>h.track.id-y.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),b}getAudioTrackData(e,r,i){let n=this.trackDatas.find(c=>c.track===e);if(n)return n;dt(i,e.source._codec),f(i),f(i.decoderConfig);let s={...i.decoderConfig},o=!1;if(e.source._codec==="aac"&&!s.description){if(!r)throw new Error("No AAC description provided; you must therefore provide a priming packet.");let c=It($e.tempFromBytes(r.data));if(!c)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let l=Qe[c.samplingFrequencyIndex],d=_t[c.channelConfiguration];if(l===void 0||d===void 0)throw new Error("Invalid ADTS frame header.");s.description=dr({objectType:c.objectType,outputSampleRate:l,outputNumberOfChannels:d}),o=!0}if(!r){if(e.source._codec==="ac3"||e.source._codec==="eac3")throw new Error("AC-3/E-AC-3 require a priming packet.");if(e.source._codec==="dts")throw new Error("DTS requires a priming packet.");if(e.source._codec==="truehd")throw new Error("TrueHD requires a priming packet.")}let a={muxer:this,track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&ae.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,primingPacket:r,preroll:{packetCount:0,accumulatedAudioSamples:0,audioSampleDurationHistory:[]}},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(a),this.trackDatas.sort((c,l)=>c.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getSubtitleTrackData(e,r){let i=this.trackDatas.find(s=>s.track===e);if(i)return i;jr(r),f(r),f(r.config);let n={muxer:this,track:e,type:"subtitle",info:{config:r.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(n),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}async addEncodedVideoPacket(e,r,i){let n=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,r,i),o=r.data;if(s.info.requiresAnnexBTransformation){let c=[...ot(o)].map(l=>o.subarray(l.offset,l.offset+l.length));if(c.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");o=xr(c,4)}this.validateTimestamp(s.track,r.timestamp,r.type==="key");let a=this.createSampleForTrack(s,o,r.timestamp,r.duration,r.type,0);await this.registerSample(s,a)}finally{n()}}async addEncodedAudioPacket(e,r,i){let n=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,r,i),o=r.data;if(s.info.requiresAdtsStripping){let b=It($e.tempFromBytes(o));if(!b)throw new Error("Expected ADTS frame, didn't get one.");let h=b.crcCheck===null?at:Vr;o=o.subarray(h)}this.validateTimestamp(s.track,r.timestamp,r.type==="key");let a=r.timestamp,c=r.duration;if(s.info.requiresPcmTransformation){let h=pe(s.info.decoderConfig.codec).sampleSize*s.info.numberOfChannels;if(c=o.byteLength/h/s.info.sampleRate,s.info.expectedNextPcmPacketTimestamp!==null){let y=a-s.info.expectedNextPcmPacketTimestamp;if(y<.01)a=s.info.expectedNextPcmPacketTimestamp;else{let T=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,y);a=s.info.expectedNextPcmPacketTimestamp+T}}s.info.expectedNextPcmPacketTimestamp=a+c}let{preroll:l}=s.info,d=0;if(e.source._codec==="aac"||e.source._codec==="vorbis")d=-Math.min(1,l.packetCount);else if(e.source._codec==="mp3")d=-Math.min(2,l.packetCount);else if(e.source._codec==="opus"){let b=Math.round(Hr*Mt);d=-l.audioSampleDurationHistory.length;let h=kr(o);for(l.accumulatedAudioSamples+=h.durationInSamples,l.audioSampleDurationHistory.push(h.durationInSamples);l.accumulatedAudioSamples-l.audioSampleDurationHistory[0]>=b;)l.accumulatedAudioSamples-=l.audioSampleDurationHistory.shift(),f(l.audioSampleDurationHistory.length>0)}l.packetCount++;let p=this.createSampleForTrack(s,o,a,c,r.type,d);await this.registerSample(s,p)}finally{n()}}async padWithSilence(e,r,i){let n=k(i,e.timescale);if(i=n/e.timescale,n>0){let{sampleSize:s,silentValue:o}=pe(e.info.decoderConfig.codec),a=n*e.info.numberOfChannels,c=new Uint8Array(s*a).fill(o),l=this.createSampleForTrack(e,new Uint8Array(c.buffer),r,i,"key",0);await this.registerSample(e,l)}return i}async addSubtitleCue(e,r,i){let n=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,i);this.validateTimestamp(s.track,r.timestamp,!0),e.source._codec==="webvtt"&&(s.cueQueue.push(r),await this.processWebVTTCues(s,r.timestamp))}finally{n()}}async processWebVTTCues(e,r){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].timestamp);let i=new Set([]);for(let l of e.cueQueue)f(l.timestamp<=r),f(e.lastCueEndTimestamp<=l.timestamp+l.duration),i.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),i.add(l.timestamp+l.duration);let n=[...i].sort((l,d)=>l-d),s=n[0],o=n[1]??s;if(r<o)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);let l=ni();this.auxBoxWriter.writeBox(l);let d=this.auxTarget._getSlice(0,this.auxWriter.getPos()),p=this.createSampleForTrack(e,d,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key",0);await this.registerSample(e,p),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let l=0;l<e.cueQueue.length;l++){let d=e.cueQueue[l];if(d.timestamp>=o)break;vt.lastIndex=0;let p=vt.test(d.text),b=d.timestamp+d.duration,h=e.cueToSourceId.get(d);if(h===void 0&&o<b&&(h=e.nextSourceId++,e.cueToSourceId.set(d,h)),d.notes){let T=oi(d.notes);this.auxBoxWriter.writeBox(T)}let y=si(d.text,p?s:null,d.identifier??null,d.settings??null,h??null);this.auxBoxWriter.writeBox(y),b===o&&e.cueQueue.splice(l--,1)}let a=this.auxTarget._getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,a,s,o-s,"key",0);await this.registerSample(e,c),e.lastCueEndTimestamp=o}}createSampleForTrack(e,r,i,n,s,o){return{timestamp:i,decodeTimestamp:i,duration:n,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:k(n,e.timescale),prerollSamples:o}}processTimestamps(e,r){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){f(!this.isFragmented),e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp;let n=0;for(let s=0;s<e.timestampProcessingQueue.length;s++){let o=e.timestampProcessingQueue[s],a=k(o.duration,e.timescale);n+=a}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:n,sampleDelta:1});else{let s=te(e.timeToSampleTable);s.sampleCount+=n}e.timestampProcessingQueue.length=0;return}let i=e.timestampProcessingQueue.map(n=>n.timestamp).sort((n,s)=>n-s);this.isFragmented?e.startTimestampOffset??=Math.min(i[0],0):e.startTimestampOffset??=i[0];for(let n=0;n<e.timestampProcessingQueue.length;n++){let s=e.timestampProcessingQueue[n];s.decodeTimestamp=i[n];let o=k(s.timestamp-s.decodeTimestamp,e.timescale),a=k(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){f(e.lastSample);let c=k(s.decodeTimestamp,e.timescale,!1),l=Math.round(c-e.lastTimescaleUnits);if(f(l>=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let d=te(e.timeToSampleTable);if(f(d),d.sampleCount===1){d.sampleDelta=l;let b=e.timeToSampleTable[e.timeToSampleTable.length-2];b&&b.sampleDelta===l&&(b.sampleCount++,e.timeToSampleTable.pop(),d=b)}else d.sampleDelta!==l&&(d.sampleCount--,e.timeToSampleTable.push(d={sampleCount:1,sampleDelta:l}));d.sampleDelta===a?d.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let p=te(e.compositionTimeOffsetTable);f(p),p.sampleCompositionTimeOffset===o?p.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else e.lastTimescaleUnits=k(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,f(e.lastSample),f(e.lastTimescaleUnits!==null),r!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){f(r.type==="key");let n=k(r.timestamp,e.timescale,!1),s=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=s}}async registerSample(e,r){r.type==="key"&&this.processTimestamps(e,r),e.timestampProcessingQueue.push(r),e.sampleQueue.push(r),await this.interleaveSamples()}async addSampleToTrack(e,r){if(!this.isFragmented&&(e.samples.push(r),this.fastStart==="reserve")){let n=e.track.metadata.maximumPacketCount;if(f(n!==void 0),e.samples.length>n)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${n}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(!e.currentChunk)i=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,r.timestamp);let n=r.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let s=this.trackDatas.every(o=>{if(e===o)return r.type==="key";let a=o.sampleQueue[0];return a?a.type==="key":o.closed});n>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=n>=di}if(i){if(!this.isFragmented){let n=this.trackDatas.filter(s=>s.currentChunk&&r.timestamp-s.currentChunk.startTimestamp>=di).sort((s,o)=>s.currentChunk.startTimestamp-o.currentChunk.startTimestamp);for(let s of n)await this.finalizeCurrentChunk(s)}e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}}f(e.currentChunk),e.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,r.timestamp+r.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(e){f(!this.isFragmented),f(this.writer);let r=e.currentChunk;f(r),e.currentChunk=null,e.finalizedChunks.push(r),this.finalizedChunks.push(r);let i=r.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(i=r.samples.reduce((n,s)=>n+k(s.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||te(e.compactlyCodedChunkTable).samplesPerChunk!==i)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:i}),this.fastStart==="in-memory"){r.offset=0;return}r.offset=this.writer.getPos();for(let n of r.samples)f(n.data),this.writer.write(n.data),n.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(!(!e&&!this.allTracksAreKnown())){this.fastStart==="reserve"&&!this.mdat&&await this.createFastStartReserveMdat();e:for(;;){let r=null,i=1/0;for(let s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<i&&(r=s,i=s.sampleQueue[0].timestamp)}if(!r)break;let n=r.sampleQueue.shift();await this.addSampleToTrack(r,n)}}}async finalizeFragment(e=!this.isCmaf){if(f(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let h=this.initBoxWriter??this.boxWriter;f(h),this.formatOptions.onMoov&&h.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let y=Me(this);if(h.writeBox(y),this.formatOptions.onMoov){let{data:T,start:P}=h.writer.stopTrackingWrites();this.formatOptions.onMoov(T,P)}if(this.isCmaf){f(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new xe(this.writer);let T=this.boxWriter.measureBox(zt()),P=this.boxWriter.measureBox(Vt(this,0));this.segmentHeaderSize=T+P,this.writer.seek(this.segmentHeaderSize)}}f(this.writer),f(this.boxWriter);let r=this.trackDatas.filter(h=>h.currentChunk);if(r.length===0){e&&await this.writer.flush();return}let i=this.nextFragmentNumber++,n=Dt(i,r),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(n),a=o+ct,c=1/0;for(let h=0;h<r.length;h++){let y=r[h];f(y.currentChunk),f(y.startTimestampOffset!==null),y.currentChunk.offset=a,y.currentChunk.moofOffset=s,y.currentChunk.trafIndex=h,y.currentChunk.startTimestamp-=y.startTimestampOffset;for(let T of y.currentChunk.samples)a+=T.size,T.timestamp-=y.startTimestampOffset,T.decodeTimestamp-=y.startTimestampOffset;c=Math.min(c,y.currentChunk.startTimestamp)}let l=a-o,d=l>=2**32;if(d)for(let h of r)h.currentChunk.offset+=Pt-ct;this.formatOptions.onMoof&&this.writer.startTrackingWrites();let p=Dt(i,r);if(this.boxWriter.writeBox(p),this.formatOptions.onMoof){let{data:h,start:y}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(h,y,c)}f(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let b=Ye(d);b.size=l,this.boxWriter.writeBox(b),this.writer.seek(o+(d?Pt:ct));for(let h of r)for(let y of h.currentChunk.samples)this.writer.write(y.data),y.data=null;if(this.formatOptions.onMdat){let{data:h,start:y}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(h,y)}for(let h of r)h.finalizedChunks.push(h.currentChunk),this.finalizedChunks.push(h.currentChunk),h.currentChunk=null;e&&await this.writer.flush()}async createFastStartReserveMdat(){f(this.writer),f(this.boxWriter),this.ensureOneEnabledTrack();let e=Me(this),i=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;f(this.ftypSize!==null),this.writer.seek(this.ftypSize+i),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ye(!0),this.boxWriter.writeBox(this.mdat)}computeSampleTableSizeUpperBound(){f(this.fastStart==="reserve");let e=0;for(let r of this.trackDatas){let i=r.track.metadata.maximumPacketCount;f(i!==void 0),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i,r.type==="audio"&&(e+=2*i,e+=8*i)}return e}async onTrackClose(e){let r=await this.mutex.acquire(),i=this.trackDatas.find(n=>n.track===e);i&&(i.closed=!0,i.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveSamples(),r()}ensureOneEnabledTrack(){for(let e of["video","audio","subtitle"]){let r=this.trackDatas.filter(n=>n.type===e);if(r.length===0)continue;if(!r.some(n=>n.track.metadata.disposition?.default!==!1)){let n=r[0];n.track.metadata.disposition={...n.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){f(this.isFragmented);let e=await this.mutex.acquire();try{for(let r of this.trackDatas)r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack();for(let r of this.trackDatas)r.closed=!0,r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r);if(await this.interleaveSamples(!0),this.isFragmented)await this.finalizeFragment(!1);else{let r=this.trackDatas.filter(i=>i.currentChunk).sort((i,n)=>i.currentChunk.startTimestamp-n.currentChunk.startTimestamp);for(let i of r)await this.finalizeCurrentChunk(i);for(let i of this.trackDatas){let n=Te(i);if(n>0){let c=0;for(let l of i.samples)c+=l.size;i.avgBitrate=Math.round(8*c/n)}else i.avgBitrate=0;let s=0,o=0,a=0;for(let c=0;c<i.samples.length;c++){let l=i.samples[c];for(o+=l.size;l.decodeTimestamp-i.samples[s].decodeTimestamp>=1;)o-=i.samples[s].size,s++;a=Math.max(a,o)}if(i.maxBitrate=8*a,i.startTimestampOffset!==null)for(let c=0;c<i.samples.length;c++){let l=i.samples[c];l.timestamp-=i.startTimestampOffset,l.decodeTimestamp-=i.startTimestampOffset}}}if(f(this.writer),f(this.boxWriter),this.fastStart==="in-memory"){this.mdat=Ye(!1);let r;for(let n=0;n<2;n++){let s=Me(this),o=this.boxWriter.measureBox(s);r=this.boxWriter.measureBox(this.mdat);let a=this.writer.getPos()+o+r;for(let c of this.finalizedChunks){c.offset=a;for(let{data:l}of c.samples)f(l),a+=l.byteLength,r+=l.byteLength}if(a<2**32)break;r>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let i=Me(this);if(this.boxWriter.writeBox(i),this.formatOptions.onMoov){let{data:n,start:s}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(n,s)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,this.boxWriter.writeBox(this.mdat);for(let n of this.finalizedChunks)for(let s of n.samples)f(s.data),this.writer.write(s.data),s.data=null;if(this.formatOptions.onMdat){let{data:n,start:s}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(n,s)}}else if(this.isFragmented)if(this.isCmaf){let r=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(zt()),this.boxWriter.writeBox(Vt(this,r))}else{let r=this.writer.getPos(),i=ii(this.trackDatas);this.boxWriter.writeBox(i);let n=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{f(this.mdat);let r=this.boxWriter.offsets.get(this.mdat);f(r!==void 0);let i=this.writer.getPos()-r;if(this.mdat.size=i,this.mdat.largeSize=i>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){let{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(s,o)}let n=Me(this);if(this.fastStart==="reserve"){f(this.ftypSize!==null);let s=this.boxWriter.offsets.get(this.mdat)-this.ftypSize,o=this.boxWriter.measureBox(n);if(o+8>s)throw new Error(`The moov box (${o} bytes) plus a free box (8 bytes) exceed the space reserved for them (${s} bytes) with fastStart: 'reserve'. This is a bug; please report it.`);this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n),this.boxWriter.writeBox(ei(s-o))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.formatOptions.onMoov){let{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(s,o)}}e()}};var Oe=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}get requiresMaximumPacketCount(){return!1}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>ge.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Pe.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>ye.includes(e))}_codecUnsupportedHint(e){return""}_isFragmentedIsobmff(){return!1}},Ue=class extends Oe{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!nr(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:0,max:4294967295}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"full"}get requiresMaximumPacketCount(){return this._options.fastStart==="reserve"}_createMuxer(e){return new ht(e,this)}_isFragmentedIsobmff(){return this._options.fastStart==="fragmented"}},ze=class extends Ue{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ge,...lt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...ye]}_codecUnsupportedHint(e){return new Fe().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}},Re=class extends Ue{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ge,...lt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...ye]}},Fe=class extends Ue{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...ge,...Pe]}_codecUnsupportedHint(e){return new ze().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}};var fi=["video","audio","subtitle"],Ve=class t{constructor(e,r,i,n,s){this.id=e,this.output=r,this.type=i,this.source=n,this.metadata=s}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(e){if(!(e instanceof t))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;let r=nt(this.metadata.group),i=nt(e.metadata.group);for(let n of r)if(this.type!==e.type&&i.some(a=>n===a)||i.some(a=>n._pairedGroups.has(a)))return!0;return!1}},At=class extends Ve{constructor(e,r,i,n){super(e,r,"video",i,n)}},gt=class extends Ve{constructor(e,r,i,n){super(e,r,"audio",i,n)}},wt=class extends Ve{constructor(e,r,i,n){super(e,r,"subtitle",i,n)}},Le=class t{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof t))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}},qt=t=>{if(!t||typeof t!="object")throw new TypeError("metadata must be an object.");if(t.languageCode!==void 0&&!rr(t.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(t.name!==void 0&&typeof t.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(t.disposition!==void 0&&cr(t.disposition),t.maximumPacketCount!==void 0&&(!Number.isInteger(t.maximumPacketCount)||t.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(t.bitrate!==void 0&&(!Number.isFinite(t.bitrate)||t.bitrate<0))throw new TypeError("metadata.bitrate, when provided, must be a non-negative number.");if(t.averageBitrate!==void 0&&(!Number.isFinite(t.averageBitrate)||t.averageBitrate<0))throw new TypeError("metadata.averageBitrate, when provided, must be a non-negative number.");if(t.group!==void 0&&!(t.group instanceof Le)&&(!Array.isArray(t.group)||t.group.some(e=>!(e instanceof Le))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},et=class extends Ae{get target(){let e="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(e);let r=this._getRootTarget();if(He(r))throw new TypeError(e);return r}constructor(e){if(super(),this.state="pending",this.defaultTrackGroup=new Le,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new _e,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof Oe))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof H||e.target instanceof Se))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof H&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof H)&&typeof e.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof H&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){f(this._target instanceof Se);let r=this._target.getTarget(e),i=n=>{if(!(n instanceof H))throw new TypeError("getTarget must return a Target.");return n};return He(r)?r.then(i):i(r)}async _getTarget(e){f(this._target instanceof Se);let r=await this._getTargetValidated(e);return this._emit("target",{target:r,request:e,isRoot:e.isRoot}),this.state==="canceled"?await r._close():this._rememberTarget(r),r}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(f(this._initTarget!==null),this._initTarget instanceof H)return this._initTarget;let e=await this._initTarget();return this.state==="canceled"?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof H)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},r=this._getTargetValidated(e),i=n=>(this.state==="canceled"?n._close():this._rememberTarget(n),this._emit("target",{target:n,request:e,isRoot:!0}),this._rootTarget=n,n);return He(r)?this._rootTargetPromise=r.then(i):i(r)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let r=await this._getRootTarget(),i=new Ce(r,typeof e=="boolean"?e:e(r));return i.start(),i})()}addVideoTrack(e,r={}){if(!(e instanceof ve))throw new TypeError("source must be a VideoSource.");if(qt(r),r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError(`Invalid video rotation: ${r.rotation}. Has to be 0, 90, 180 or 270.`);if(r.flip!==void 0&&typeof r.flip!="boolean")throw new TypeError("metadata.flip, when provided, must be a boolean.");if(r.transformationMatrix!==void 0&&(!Array.isArray(r.transformationMatrix)||r.transformationMatrix.length!==9||!r.transformationMatrix.every(n=>Number.isFinite(n))))throw new TypeError("metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.");if(r.frameRate!==void 0&&(!Number.isFinite(r.frameRate)||r.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${r.frameRate}. Must be a positive number.`);if(r.hasOnlyKeyPackets!==void 0&&typeof r.hasOnlyKeyPackets!="boolean")throw new TypeError("metadata.hasOnlyKeyPackets, when provided, must be a boolean.");if(r.canBeTransparent!==void 0&&typeof r.canBeTransparent!="boolean")throw new TypeError("metadata.canBeTransparent, when provided, must be a boolean.");if(r.decoderConfig!==void 0&&ut({decoderConfig:r.decoderConfig},e._codec),r.primingPacket!==void 0){if(!(r.primingPacket instanceof $))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(r.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}let i={...r};return i.group??=this.defaultTrackGroup,this._addTrack(new At(this.tracks.length+1,this,e,i))}addAudioTrack(e,r={}){if(!(e instanceof Ie))throw new TypeError("source must be an AudioSource.");if(qt(r),r.decoderConfig!==void 0&&dt({decoderConfig:r.decoderConfig},e._codec),r.primingPacket!==void 0){if(!(r.primingPacket instanceof $))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(r.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}let i={...r};return i.group??=this.defaultTrackGroup,this._addTrack(new gt(this.tracks.length+1,this,e,i))}addSubtitleTrack(e,r={}){if(!(e instanceof Xe))throw new TypeError("source must be a SubtitleSource.");qt(r);let i={...r};return i.group??=this.defaultTrackGroup,this._addTrack(new wt(this.tracks.length+1,this,e,i))}setMetadataTags(e){if(ar(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(e.source._connectedTrack)throw new Error("Source is already used for a track.");let r=this.format.getSupportedTrackCounts(),i=this.tracks.reduce((o,a)=>o+(a.type===e.type?1:0),0),n=r[e.type].max;if(i===n)throw new Error(n===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${n} ${e.type} track${n===1?"":"s"}.`);let s=r.total.max;if(this.tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} tracks${s===1?"":"s"} in total.`);if(e.isVideoTrack()){let o=this.format.getSupportedVideoCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${o.map(a=>`'${a}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let o=this.format.getSupportedAudioCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${o.map(a=>`'${a}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let o=this.format.getSupportedSubtitleCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${o.map(a=>`'${a}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){let e=this.format.getSupportedTrackCounts();for(let i of fi){let n=this.tracks.reduce((o,a)=>o+(a.type===i?1:0),0),s=e[i].min;if(n<s)return!1}let r=e.total.min;return!(this.tracks.length<r)}async start(){let e=this.format.getSupportedTrackCounts();for(let i of fi){let n=this.tracks.reduce((o,a)=>o+(a.type===i?1:0),0),s=e[i].min;if(n<s)throw new Error(s===e[i].max?`${this.format._name} requires exactly ${s} ${i} track${s===1?"":"s"}.`:`${this.format._name} requires at least ${s} ${i} track${s===1?"":"s"}.`)}let r=e.total.min;if(this.tracks.length<r)throw new Error(r===e.total.max?`${this.format._name} requires exactly ${r} track${r===1?"":"s"}.`:`${this.format._name} requires at least ${r} track${r===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(W._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";let i=this._mutex.acquire();try{await this._muxer.start();let n=this.tracks.map(s=>s.source._start());await Promise.all(n)}finally{(await i)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this.state==="canceled")return this._cancelPromise??void 0;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&W._warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let e=await this._mutex.acquire();try{let r=this.tracks.map(i=>i.source._flushOrWaitForOngoingClose(!0));await Promise.all(r),await Promise.all([...this._unfinalizedTargets].map(i=>i._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(W._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";let e=await this._mutex.acquire();try{let r=this.tracks.map(i=>i.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(r),await this._muxer.finalize(),this._rootWriterPromise){let i=await this._rootWriterPromise;i.finalized||(await i.flush(),await i.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}catch(r){throw this.state="canceled",r}finally{await Promise.all([...this._unfinalizedTargets].map(r=>r._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}};var mi=Symbol.for("mediabunny loaded");globalThis[mi]&&W._error(`[WARNING]
3
+ Mediabunny was loaded twice. This will likely cause Mediabunny not to work correctly. Check if multiple dependencies are importing different versions of Mediabunny, or if something is being bundled incorrectly.`);globalThis[mi]=!0;var Qt=57600,pi=t=>Number((BigInt(t)*BigInt(Qt)+500000n)/1000000n);function hi(t){if(t.audio&&(t.audio.codec!=="mp4a.40.2"||t.audio.bitstreamFormat!=="aac"||![44100,48e3].includes(t.audio.sampleRate)||![1,2].includes(t.audio.numberOfChannels)))return"MP4 audio requires AAC-LC, raw aac framing, 44.1/48 kHz mono/stereo";if(!/^avc1\.42[0-9a-f]{4}$/i.test(t.video.codec)||t.video.bitstreamFormat!=="avc")return"MP4 adapter requires H.264 Baseline with avc framing"}function Pa(){return{format:Object.freeze({mimeType:"video/mp4",extension:"mp4"}),async checkSupport(t){let e=hi(t);return e?{supported:!1,reason:e}:{supported:!0}},async create(t,e){let r=hi(t);if(r)throw new DOMException(r,"NotSupportedError");let i,n,s,o=!1,a=!1,c,l=0,d=0,p=0,b,h=!1,y,T,P,B,D=g=>Math.sign(g)*Number((BigInt(Math.abs(g))*BigInt(t.audio.sampleRate)+500000n)/1000000n),de=0,fe,q=64*1024,X=new Map,L=()=>{if(fe)throw fe;if(o||e.signal.aborted)throw e.signal.reason??new DOMException("MP4 muxer disposed","AbortError")};function Z(){if(o)return;o=!0,e.signal.removeEventListener("abort",Z);let g=i;i=void 0,n=void 0,s=void 0,B=void 0,X.clear(),c=void 0,b=void 0,g&&g.state!=="finalized"&&g.state!=="canceled"&&g.cancel().catch(()=>{})}try{L();let g=new Je(new WritableStream({write({data:S,position:v}){L();let z=v+S.byteLength;if(e.maxOutputBytes!==void 0&&z>e.maxOutputBytes)throw new RangeError("MP4 maxOutputBytes exceeded");for(let R=0;R<S.byteLength;){let O=v+R,V=Math.floor(O/q),I=O%q,_=X.get(V);_||(_=new Uint8Array(q),X.set(V,_));let F=Math.min(q-I,S.byteLength-R);_.set(S.subarray(R,R+F),I),R+=F}de=Math.max(de,z)}}),{chunked:!1});g.on("write",({end:S})=>{e.maxOutputBytes!==void 0&&S>e.maxOutputBytes&&(fe??=new RangeError("MP4 maxOutputBytes exceeded"))}),n=new Ge("avc"),i=new et({format:new ze({fastStart:!1}),target:g}),i.addVideoTrack(n),t.audio&&(s=new Ke("aac"),i.addAudioTrack(s)),await i.start(),L(),e.signal.addEventListener("abort",Z,{once:!0}),L()}catch(g){throw Z(),g}function Y(g){if(e.maxOutputBytes!==void 0&&g>e.maxOutputBytes-p)throw new RangeError("MP4 maxOutputBytes exceeded");p+=g}async function Q(g,S){let v=b,z=t.audio.sampleRate,R=D(g.timestampUs);await s.add(new $(g.data,g.type,R/z,(S-R)/z),{decoderConfig:{codec:v.codec,sampleRate:z,numberOfChannels:v.numberOfChannels,description:v.description}}),L()}return{async write(g){if(L(),(g.type==="packet"?g.packet.track:g.track)==="audio"){if(!s||h)throw new Error("MP4 audio unavailable or ended");if(g.type==="config"&&g.track==="audio"){let I=g.config,_=I.description,F=t.audio.sampleRate;if(!_||_.length<2||_[0]>>3!==2||((_[0]&7)<<1|_[1]>>7)!==(F===48e3?3:4)||(_[1]>>3&15)!==t.audio.numberOfChannels)throw new Error("MP4 AAC AudioSpecificConfig mismatch");b={...I,description:_.slice()};return}if(!b)throw new Error("MP4 audio requires decoder configuration");if(g.type==="packet"){let I=g.packet,_=D(I.timestampUs),F=D(I.timestampUs+I.durationUs);if(_!==(P??_)||F-_!==1024||I.timestampUs!==I.decodeTimestampUs||I.data.byteLength+64>e.maxPendingBytes)throw new Error("MP4 invalid AAC packet interval/budget");Y(I.data.byteLength),B&&await Q(B,_),B={...I,data:I.data.slice()},T??=_,P=F;return}if(g.type!=="end"||g.track!=="audio"||!B||T!==-g.leadingDiscardSamples||P!==g.presentationSamples+g.trailingDiscardSamples)throw new Error("MP4 AAC trimming mismatch");if(D(B.timestampUs)>=g.presentationSamples)throw new Error("MP4 AAC tail exceeds final packet");await Q(B,g.presentationSamples),B=void 0,y=g.presentationSamples,h=!0,s.close();return}if(a)throw new Error("MP4 video track already ended");if(g.type==="config"&&g.track==="video"){if(!g.config.description?.byteLength)throw new Error("MP4 requires an AVCDecoderConfigurationRecord");c={...g.config,description:g.config.description.slice(),color:{...g.config.color}};return}if(g.type==="end"&&g.track==="video"){a=!0,n.close();return}if(g.type!=="packet"||g.packet.track!=="video"||!c)throw new Error("MP4 requires configured video packets");let v=g.packet,z=v.timestampUs+v.durationUs;if(v.timestampUs!==d||v.decodeTimestampUs!==v.timestampUs)throw new Error("MP4 requires contiguous, non-reordered video");let R=pi(v.timestampUs),O=pi(z),V=O-R;if(V<=0||V>4294967295)throw new RangeError("MP4 frame interval cannot be represented in the 57600 Hz timebase");Y(v.data.byteLength),await n.add(new $(v.data,v.type,R/Qt,V/Qt),{decoderConfig:{codec:c.codec,codedWidth:c.width,codedHeight:c.height,description:c.description,colorSpace:c.color}}),L(),l++,d=z},async finalize(g){if(L(),!a||l!==g.videoFrames||d!==g.durationUs||(t.audio?!h||y!==g.audioPresentationSamples:g.audioPresentationSamples!==void 0))throw new Error("MP4 final timeline does not match written tracks");if(await i.finalize(),L(),!de)throw new Error("MP4 output buffer missing");let S=[];for(let z=0;z<de;z+=q)S.push(X.get(z/q).subarray(0,Math.min(q,de-z)));let v=new Blob(S,{type:"video/mp4"});return X.clear(),v},dispose:Z}}}}export{Pa as createMp4Muxer};
4
+ /*! Bundled license information:
5
+
6
+ mediabunny/dist/modules/src/misc.js:
7
+ mediabunny/dist/modules/src/logging.js:
8
+ mediabunny/dist/modules/src/metadata.js:
9
+ mediabunny/dist/modules/shared/bitstream.js:
10
+ mediabunny/dist/modules/shared/aac-misc.js:
11
+ mediabunny/dist/modules/shared/ac3-misc.js:
12
+ mediabunny/dist/modules/src/version.js:
13
+ mediabunny/dist/modules/src/codec-data.js:
14
+ mediabunny/dist/modules/src/subtitles.js:
15
+ mediabunny/dist/modules/src/packet.js:
16
+ mediabunny/dist/modules/src/isobmff/isobmff-misc.js:
17
+ mediabunny/dist/modules/src/adts/adts-reader.js:
18
+ mediabunny/dist/modules/src/reader.js:
19
+ mediabunny/dist/modules/src/isobmff/isobmff-reader.js:
20
+ mediabunny/dist/modules/src/media-source.js:
21
+ mediabunny/dist/modules/src/codec.js:
22
+ mediabunny/dist/modules/src/muxer.js:
23
+ mediabunny/dist/modules/src/isobmff/isobmff-boxes.js:
24
+ mediabunny/dist/modules/src/writer.js:
25
+ mediabunny/dist/modules/src/target.js:
26
+ mediabunny/dist/modules/src/isobmff/isobmff-muxer.js:
27
+ mediabunny/dist/modules/src/output-format.js:
28
+ mediabunny/dist/modules/src/output.js:
29
+ mediabunny/dist/modules/src/index.js:
30
+ (*!
31
+ * Copyright (c) 2026-present, Vanilagy and contributors
32
+ *
33
+ * This Source Code Form is subject to the terms of the Mozilla Public
34
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
35
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
36
+ *)
37
+ */
38
+ //# sourceMappingURL=video-mp4.js.map