Your Name 1912bcd25b
Some checks failed
Lint / build (20) (push) Has been cancelled
Playwright Tests / test (push) Has been cancelled
chore: sync all remaining local workspace changes
2026-05-08 11:26:57 +08:00

204 lines
328 KiB
JavaScript

/*
* Extracted from browser-delivered Turbopack chunk: 95377ab54820c61e.6b6a744219.js
* Module id: 747112
* For reading/searching only; this factory depends on the original Turbopack runtime.
*/
const moduleFactory = (e) => {
"use strict";
class t {
_url;
_duration;
_frameHeight;
_frameCount;
_frames = [];
_aborted = !1;
_listeners = new Set();
_encodeProgressListeners = new Set();
_worker = null;
_encodeResolver = null;
_encodeRejecter = null;
constructor(e) {
(this._url = e.url),
(this._duration = e.duration),
(this._frameHeight = e.frameHeight ?? 64),
(this._frameCount = e.frameCount ?? 12),
e.worker &&
((this._worker = e.worker),
this._setupWorkerListeners(),
this._extractFramesViaWorker());
}
get frames() {
return this._frames;
}
get frameCount() {
return this._frameCount;
}
onFramesReady(e) {
return this._listeners.add(e), () => this._listeners.delete(e);
}
get supportsEncode() {
return !!this._worker;
}
get isWorkerReady() {
return !!this._worker;
}
onEncodeProgress(e) {
return (
this._encodeProgressListeners.add(e),
() => this._encodeProgressListeners.delete(e)
);
}
async encode(e, t) {
if (!this._worker) throw Error("Worker not available");
return new Promise((r, i) => {
(this._encodeResolver = r),
(this._encodeRejecter = i),
this._worker.postMessage({
type: "encode",
url: this._url,
startTime: e,
endTime: t,
});
});
}
dispose() {
(this._aborted = !0),
this._worker &&
(this._worker.postMessage({ type: "dispose" }),
this._worker.terminate(),
(this._worker = null)),
this._revokeFrameUrls(),
(this._convertCanvas = null),
(this._convertCtx = null),
this._listeners.clear(),
this._encodeProgressListeners.clear(),
(this._encodeResolver = null),
(this._encodeRejecter = null);
}
_setupWorkerListeners() {
this._worker &&
(this._worker.addEventListener("message", (e) => {
let t = e.data;
switch (
(console.log("[AVEditor] worker message:", t.type), t.type)
) {
case "frame":
this._handleSingleFrame(t.index, t.bitmap);
break;
case "frames-done":
console.log("[AVEditor] frames done, total:", t.total);
break;
case "encode-progress":
this._encodeProgressListeners.forEach((e) => e(t.percent));
break;
case "encode-complete":
this._encodeResolver &&
(this._encodeResolver(
new Blob([t.buffer], { type: "video/mp4" }),
),
(this._encodeResolver = null),
(this._encodeRejecter = null));
break;
case "error":
"encode" === t.source && this._encodeRejecter
? (this._encodeRejecter(Error(t.message)),
(this._encodeResolver = null),
(this._encodeRejecter = null))
: console.warn("[AVEditor Worker]", t.source, t.message);
}
}),
this._worker.addEventListener("error", (e) => {
console.error("[AVEditor Worker error]", e.message),
this._encodeRejecter &&
(this._encodeRejecter(Error(e.message)),
(this._encodeResolver = null),
(this._encodeRejecter = null));
}));
}
_extractFramesViaWorker() {
this._worker && this._url && !(this._duration <= 0)
? (console.log("[AVEditor] sending extract-frames to worker"),
this._worker.postMessage({
type: "extract-frames",
url: this._url,
duration: this._duration,
frameHeight: this._frameHeight,
frameCount: this._frameCount,
}))
: console.log("[AVEditor] skip extractFrames:", {
worker: !!this._worker,
url: !!this._url,
duration: this._duration,
});
}
_convertCanvas = null;
_convertCtx = null;
_handleSingleFrame(e, t) {
if (this._aborted) return void t?.close();
if (!t) {
(this._frames[e] = ""), this._notify();
return;
}
this._convertCanvas ||
((this._convertCanvas = document.createElement("canvas")),
(this._convertCtx = this._convertCanvas.getContext("2d")));
let r = this._convertCanvas,
i = this._convertCtx;
if (!i) {
t.close(), (this._frames[e] = ""), this._notify();
return;
}
(r.width = t.width),
(r.height = t.height),
i.drawImage(t, 0, 0),
t.close();
try {
this._frames[e] = r.toDataURL("image/jpeg", 0.6);
} catch {
this._frames[e] = "";
}
this._notify();
}
_revokeFrameUrls() {
for (let e of this._frames)
e.startsWith("blob:") && URL.revokeObjectURL(e);
this._frames = [];
}
_notify() {
let e = this._frames;
this._listeners.forEach((t) => t(e));
}
}
function r() {
return (
void 0 !== globalThis.VideoDecoder &&
void 0 !== globalThis.VideoEncoder &&
void 0 !== globalThis.AudioDecoder &&
void 0 !== globalThis.AudioEncoder &&
void 0 !== globalThis.EncodedVideoChunk
);
}
function i() {
let e = new Blob(
[
'"use strict";(()=>{function m(t){if(!t)throw new Error("Assertion failed.")}var qt=t=>{let e=(t%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${t}.`)},te=t=>t&&t[t.length-1],It=t=>t>=0&&t<2**32,P=t=>{let e=0;for(;t.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},je=t=>{let e=P(t);return e&1?e+1>>1:-(e>>1)};var we=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),oe=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),tt=new TextDecoder,Pe=new TextEncoder;var Xi=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),rt={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},qr=Xi(rt),it={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},jr=Xi(it),nt={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},$r=Xi(nt),ns=t=>!!t&&!!t.primaries&&!!t.transfer&&!!t.matrix&&t.fullRange!==void 0,jt=t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t),Ht=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}},Gi=t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join(""),Yi=t=>(t=t>>1&1431655765|(t&1431655765)<<1,t=t>>2&858993459|(t&858993459)<<2,t=t>>4&252645135|(t&252645135)<<4,t=t>>8&16711935|(t&16711935)<<8,t=t>>16&65535|(t&65535)<<16,t>>>0),Zi=(t,e,r)=>{let i=0,n=t.length-1,s=-1;for(;i<=n;){let o=i+n>>1,a=r(t[o]);a===e?(s=o,n=o-1):a<e?i=o+1:n=o-1}return s},se=(t,e,r)=>{let i=0,n=t.length-1,s=-1;for(;i<=n;){let o=i+(n-i+1)/2|0;r(t[o])<=e?(s=o,i=o+1):n=o-1}return s},Ji=(t,e,r)=>{let i=se(t,r(e),r);t.splice(i+1,0,e)},he=()=>{let t,e;return{promise:new Promise((i,n)=>{t=i,e=n}),resolve:t,reject:e}};var Qr=(t,e)=>{for(let r=t.length-1;r>=0;r--)if(e(t[r]))return r;return-1},ss=async function*(t){Symbol.iterator in t?yield*t[Symbol.iterator]():yield*t[Symbol.asyncIterator]()},os=t=>{if(!(Symbol.iterator in t)&&!(Symbol.asyncIterator in t))throw new TypeError("Argument must be an iterable or async iterable.")},Ae=t=>{throw new Error(`Unexpected value: ${t}`)},Ft=(t,e,r)=>{let i=t.getUint8(e),n=t.getUint8(e+1),s=t.getUint8(e+2);return r?i|n<<8|s<<16:i<<16|n<<8|s},as=(t,e,r)=>Ft(t,e,r)<<8>>8,fr=(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))},cs=(t,e,r,i)=>{r=fe(r,-8388608,8388607),r<0&&(r=r+16777216&16777215),fr(t,e,r,i)};var en=(t,e)=>({async next(){let r=await t.next();return r.done?{value:void 0,done:!0}:{value:e(r.value),done:!1}},return(){return t.return()},throw(r){return t.throw(r)},[Symbol.asyncIterator](){return this}}),fe=(t,e,r)=>Math.max(e,Math.min(r,t)),$e="und",Kr=t=>{let e=Math.round(t);return Math.abs(t/e-1)<10*Number.EPSILON?e:t},ls=(t,e)=>Math.round(t/e)*e;var No=/^[a-z]{3}$/,st=t=>No.test(t),Qe=1e6*(1+Number.EPSILON),tn=(t,e)=>{let r={...t,...e};if(t.headers||e.headers){let i=t.headers?is(t.headers):{},n=e.headers?is(e.headers):{},s={...i};Object.entries(n).forEach(([o,a])=>{let c=Object.keys(s).find(l=>l.toLowerCase()===o.toLowerCase());c&&delete s[c],s[o]=a}),r.headers=s}return r},is=t=>{if(t instanceof Headers){let e={};return t.forEach((r,i)=>{e[i]=r}),e}if(Array.isArray(t)){let e={};return t.forEach(([r,i])=>{e[r]=i}),e}return t},rn=async(t,e,r,i,n)=>{let s=0;for(;;)try{return await t(e,r)}catch(o){if(n())throw o;s++;let a=i(s,o,e);if(a===null)throw o;if(console.error("Retrying failed fetch. Error:",o),!Number.isFinite(a)||a<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(a>0&&await new Promise(c=>setTimeout(c,1e3*a)),n())throw o}},us=(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,u=c*o+n;if(u>e)return{numerator:r*s,denominator:o};if(i=s,n=o,s=l,o=u,a=1/(a-c),!isFinite(a))break}return{numerator:r*s,denominator:o}},Tt=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},ji=null,Rt=()=>ji!==null?ji:ji=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\\b(iPad|iPhone|iPod)\\b/.test(navigator.userAgent))),$i=null,Ke=()=>$i!==null?$i:$i=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),Qi=null,mr=()=>Qi!==null?Qi:Qi=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),Ki=null,ds=()=>{if(Ki!==null)return Ki;if(typeof navigator>"u")return null;let t=/\\bChrome\\/(\\d+)/.exec(navigator.userAgent);return t?Ki=Number(t[1]):null};var Xr=(t,e,r,i)=>t<=i&&r<=e,Gr=function*(t){for(let e in t){let r=t[e];r!==void 0&&(yield{key:e,value:r})}};var Yr=()=>{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},Zr=t=>typeof t=="number"&&!Number.isNaN(t),$t=t=>{m(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}},nn=(t,e)=>{if(typeof t!="object"||!t)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)};var Ne=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.")}},pr=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.")}},gr=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.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"&&!(e instanceof Uint8Array)&&!(e instanceof Ne)&&!(e instanceof pr))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}};var Jr={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},hs=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.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 ie=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}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 wr=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],ei=[-1,1,2,3,4,5,6,8],Qt=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new ie(t),r=e.readBits(5);r===31&&(r=32+e.readBits(6));let i=e.readBits(4),n=null;i===15?n=e.readBits(24):i<wr.length&&(n=wr[i]);let s=e.readBits(4),o=null;return s>=1&&s<=7&&(o=ei[s]),{objectType:r,frequencyIndex:i,sampleRate:n,channelConfiguration:s,numberOfChannels:o}},ti=t=>{let e=wr.indexOf(t.sampleRate),r=null;e===-1&&(e=15,r=t.sampleRate);let i=ei.indexOf(t.numberOfChannels);if(i===-1)throw new TypeError(`Unsupported number of channels: ${t.numberOfChannels}`);let n=13;t.objectType>=32&&(n+=6),e===15&&(n+=24);let s=Math.ceil(n/8),o=new Uint8Array(s),a=new ie(o);return t.objectType<32?a.writeBits(5,t.objectType):(a.writeBits(5,31),a.writeBits(6,t.objectType-32)),a.writeBits(4,e),e===15&&a.writeBits(24,r),a.writeBits(4,i),o};var Ce=["avc","hevc","vp9","av1","vp8"],le=["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"],Bt=["aac","opus","mp3","vorbis","flac","ac3","eac3"],_e=[...Bt,...le],Dt=["webvtt"],br=[{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}],fs=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],ot=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],ms=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],ps=".01.01.01.01.00",gs=".0.110.01.01.01.0",ws=(t,e,r,i)=>{if(t==="avc"){let s=Math.ceil(e/16)*Math.ceil(r/16),o=br.find(d=>s<=d.maxMacroblocks&&i<=d.maxBitrate)??te(br),a=o?o.level:0,c="64".padStart(2,"0"),l="00",u=a.toString(16).padStart(2,"0");return`avc1.${c}${l}${u}`}else if(t==="hevc"){let n="",o="6",a=e*r,c=fs.find(u=>a<=u.maxPictureSize&&i<=u.maxBitrate)??te(fs);return`hev1.${n}1.${o}.${c.tier}${c.level}.B0`}else{if(t==="vp8")return"vp8";if(t==="vp9"){let n="00",s=e*r,o=ot.find(c=>s<=c.maxPictureSize&&i<=c.maxBitrate)??te(ot);return`vp09.${n}.${o.level.toString().padStart(2,"0")}.08`}else if(t==="av1"){let s=e*r,o=ms.find(l=>s<=l.maxPictureSize&&i<=l.maxBitrate)??te(ms);return`av01.0.${o.level.toString().padStart(2,"0")}${o.tier}.08`}}throw new TypeError(`Unhandled codec \'${t}\'.`)};var bs=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])===8?0:1,f=0,p=e[4]?Number(e[4]):0,g=e[5]?Number(e[5][0]):1,y=e[5]?Number(e[5][1]):1,w=e[5]?Number(e[5][2]):0,b=(l<<7)+(d<<6)+(f<<5)+(p<<4)+(g<<3)+(y<<2)+w;return[n,c,b,0]},ri=t=>{let{codec:e,codecDescription:r,colorSpace:i,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:o,av1CodecInfo:a}=t;if(e==="avc"){if(m(t.avcType!==null),n){let c=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${t.avcType}.${Gi(c)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${t.avcType}.${Gi(r.subarray(1,4))}`}else if(e==="hevc"){let c,l,u,d,f,p;if(s)c=s.generalProfileSpace,l=s.generalProfileIdc,u=Yi(s.generalProfileCompatibilityFlags),d=s.generalTierFlag,f=s.generalLevelIdc,p=[...s.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let y=oe(r),w=y.getUint8(1);c=w>>6&3,l=w&31,u=Yi(y.getUint32(2)),d=w>>5&1,f=y.getUint8(12),p=[];for(let b=0;b<6;b++)p.push(y.getUint8(6+b))}let g="hev1.";for(g+=["","A","B","C"][c]+l,g+=".",g+=u.toString(16).toUpperCase(),g+=".",g+=d===0?"L":"H",g+=f;p.length>0&&p[p.length-1]===0;)p.pop();return p.length>0&&(g+=".",g+=p.map(y=>y.toString(16).toUpperCase()).join(".")),g}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!o){let b=t.width*t.height,T=te(ot).level;for(let S of ot)if(b<=S.maxPictureSize){T=S.level;break}return`vp09.00.${T.toString().padStart(2,"0")}.08`}let c=o.profile.toString().padStart(2,"0"),l=o.level.toString().padStart(2,"0"),u=o.bitDepth.toString().padStart(2,"0"),d=o.chromaSubsampling.toString().padStart(2,"0"),f=o.colourPrimaries.toString().padStart(2,"0"),p=o.transferCharacteristics.toString().padStart(2,"0"),g=o.matrixCoefficients.toString().padStart(2,"0"),y=o.videoFullRangeFlag.toString().padStart(2,"0"),w=`vp09.${c}.${l}.${u}.${d}`;return w+=`.${f}.${p}.${g}.${y}`,w.endsWith(ps)&&(w=w.slice(0,-ps.length)),w}else if(e==="av1"){if(!a){let S=t.width*t.height,D=te(ot).level;for(let B of ot)if(S<=B.maxPictureSize){D=B.level;break}return`av01.0.${D.toString().padStart(2,"0")}M.08`}let c=a.profile,l=a.level.toString().padStart(2,"0"),u=a.tier?"H":"M",d=a.bitDepth.toString().padStart(2,"0"),f=a.monochrome?"1":"0",p=100*a.chromaSubsamplingX+10*a.chromaSubsamplingY+1*(a.chromaSubsamplingX&&a.chromaSubsamplingY?a.chromaSamplePosition:0),g=i?.primaries?rt[i.primaries]:1,y=i?.transfer?it[i.transfer]:1,w=i?.matrix?nt[i.matrix]:1,b=i?.fullRange?1:0,T=`av01.${c}.${l}${u}.${d}`;return T+=`.${f}.${p.toString().padStart(3,"0")}`,T+=`.${g.toString().padStart(2,"0")}`,T+=`.${y.toString().padStart(2,"0")}`,T+=`.${w.toString().padStart(2,"0")}`,T+=`.${b}`,T.endsWith(gs)&&(T=T.slice(0,-gs.length)),T}}throw new TypeError(`Unhandled codec \'${e}\'.`)},ys=(t,e,r)=>{if(t==="aac")return e>=2&&r<=24e3?"mp4a.40.29":r<=24e3?"mp4a.40.5":"mp4a.40.2";if(t==="mp3")return"mp3";if(t==="opus")return"opus";if(t==="vorbis")return"vorbis";if(t==="flac")return"flac";if(t==="ac3")return"ac-3";if(t==="eac3")return"ec-3";if(le.includes(t))return t;throw new TypeError(`Unhandled codec \'${t}\'.`)},ii=t=>{let{codec:e,codecDescription:r,aacCodecInfo:i}=t;if(e==="aac"){if(!i)throw new TypeError("AAC codec info must be provided.");if(i.isMpeg2)return"mp4a.67";{let n;return i.objectType!==null?n=i.objectType:n=Qt(r).objectType,`mp4a.40.${n}`}}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e==="ac3")return"ac-3";if(e==="eac3")return"ec-3";if(e&&le.includes(e))return e}throw new TypeError(`Unhandled codec \'${e}\'.`)},ni=48e3,Ts=/^pcm-([usf])(\\d+)+(be)?$/,Ie=t=>{if(m(le.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=Ts.exec(t);m(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}},sn=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":t.startsWith("mp4a.40")||t==="mp4a.67"?"aac":t==="mp3"||t==="mp4a.69"||t==="mp4a.6B"||t==="mp4a.6b"?"mp3":t==="opus"?"opus":t==="vorbis"?"vorbis":t==="flac"?"flac":t==="ac-3"||t==="ac3"?"ac3":t==="ec-3"||t==="eac3"?"eac3":t==="ulaw"?"ulaw":t==="alaw"?"alaw":Ts.test(t)?t:t==="webvtt"?"webvtt":null,ks=t=>t==="avc"?{avc:{format:"avc"}}:t==="hevc"?{hevc:{format:"hevc"}}:{},xs=t=>t==="aac"?{aac:{format:"aac"}}:t==="opus"?{opus:{format:"opus"}}:{},Vo=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],Wo=/^(avc1|avc3)\\.[0-9a-fA-F]{6}$/,Lo=/^(hev1|hvc1)\\.(?:[ABC]?\\d+)\\.[0-9a-fA-F]{1,8}\\.[LH]\\d+(?:\\.[0-9a-fA-F]{1,2}){0,6}$/,Ho=/^vp09(?:\\.\\d{2}){3}(?:(?:\\.\\d{2}){5})?$/,qo=/^av01\\.\\d\\.\\d{2}[MH]\\.\\d{2}(?:\\.\\d\\.\\d{3}\\.\\d{2}\\.\\d{2}\\.\\d{2}\\.\\d)?$/,Ss=t=>{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(!Vo.some(e=>t.decoderConfig.codec.startsWith(e)))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.description!==void 0&&!jt(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:e}=t.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let r=Object.keys(rt);if(e.primaries!=null&&!r.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);let i=Object.keys(it);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`);let n=Object.keys(nt);if(e.matrix!=null&&!n.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${n.join(", ")}.`);if(e.fullRange!=null&&typeof e.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(!Wo.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(!Lo.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(!Ho.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")&&!qo.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/.\')},jo=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],Cs=t=>{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(!jo.some(e=>t.decoderConfig.codec.startsWith(e)))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&&!jt(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("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!le.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${le.join(", ")}).`)},_s=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 yr=[48e3,44100,32e3],on=[24e3,22050,16e3];var at;(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"})(at||(at={}));var ke;(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"})(ke||(ke={}));var Kt=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})},Ps=function*(t,e){let r=0,i=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;r+e<=t.length;){let n;e===1?n=i.getUint8(r):e===2?n=i.getUint16(r,!1):e===3?n=Ft(i,r,!1):(m(e===4),n=i.getUint32(r,!1)),r+=e,yield{offset:r,length:n},r+=n}},cn=(t,e)=>{if(e.description){let n=(we(e.description)[4]&3)+1;return Ps(t,n)}else return Kt(t)},oi=t=>t&31,ai=t=>{let e=[],r=t.length;for(let i=0;i<r;i++)i+2<r&&t[i]===0&&t[i+1]===0&&t[i+2]===3?(e.push(0,0),i+=2):e.push(t[i]);return new Uint8Array(e)},an=new Uint8Array([0,0,0,1]),$o=t=>{let e=t.reduce((n,s)=>n+an.byteLength+s.byteLength,0),r=new Uint8Array(e),i=0;for(let n of t)r.set(an,i),i+=an.byteLength,r.set(n,i),i+=n.byteLength;return r},ln=(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:fr(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},As=(t,e)=>{if(e.description){let n=(we(e.description)[4]&3)+1;return ln(t,n)}else return $o(t)},ci=t=>{try{let e=[],r=[],i=[];for(let a of Kt(t)){let c=t.subarray(a.offset,a.offset+a.length),l=oi(c[0]);l===at.SPS?e.push(c):l===at.PPS?r.push(c):l===at.SPS_EXT&&i.push(c)}if(e.length===0||r.length===0)return null;let n=e[0],s=un(n);m(s!==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 console.error("Error building AVC Decoder Configuration Record:",e),null}},Is=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){m(t.chromaFormat!==null),m(t.bitDepthLumaMinus8!==null),m(t.bitDepthChromaMinus8!==null),m(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)},Fs=t=>{try{let e=oe(t),r=0,i=e.getUint8(r++),n=e.getUint8(r++),s=e.getUint8(r++),o=e.getUint8(r++),a=e.getUint8(r++)&3,c=e.getUint8(r++)&31,l=[];for(let p=0;p<c;p++){let g=e.getUint16(r,!1);r+=2,l.push(t.subarray(r,r+g)),r+=g}let u=e.getUint8(r++),d=[];for(let p=0;p<u;p++){let g=e.getUint16(r,!1);r+=2,d.push(t.subarray(r,r+g)),r+=g}let f={configurationVersion:i,avcProfileIndication:n,profileCompatibility:s,avcLevelIndication:o,lengthSizeMinusOne:a,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((n===100||n===110||n===122||n===144)&&r+4<=t.length){let p=e.getUint8(r++)&3,g=e.getUint8(r++)&7,y=e.getUint8(r++)&7,w=e.getUint8(r++);f.chromaFormat=p,f.bitDepthLumaMinus8=g,f.bitDepthChromaMinus8=y;let b=[];for(let T=0;T<w;T++){let S=e.getUint16(r,!1);r+=2,b.push(t.subarray(r,r+S)),r+=S}f.sequenceParameterSetExt=b}return f}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}},Rs={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}},un=t=>{try{let e=new ie(ai(t));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let i=e.readAlignedByte(),n=e.readAlignedByte(),s=e.readAlignedByte();P(e);let o=1,a=0,c=0,l=0;if((i===100||i===110||i===122||i===244||i===44||i===83||i===86||i===118||i===128)&&(o=P(e),o===3&&(l=e.readBits(1)),a=P(e),c=P(e),e.skipBits(1),e.readBits(1))){for(let z=0;z<(o!==3?8:12);z++)if(e.readBits(1)){let J=z<6?16:64,re=8,ee=8;for(let Z=0;Z<J;Z++){if(ee!==0){let ae=je(e);ee=(re+ae+256)%256}re=ee===0?re:ee}}}P(e);let u=P(e);if(u===0)P(e);else if(u===1){e.skipBits(1),je(e),je(e);let j=P(e);for(let z=0;z<j;z++)je(e)}P(e),e.skipBits(1);let d=P(e),f=P(e),p=16*(d+1),g=16*(f+1),y=p,w=g,b=e.readBits(1);if(b||e.skipBits(1),e.skipBits(1),e.readBits(1)){let j=P(e),z=P(e),W=P(e),J=P(e),re,ee;if((l===0?o:0)===0)re=1,ee=2-b;else{let ae=o===3?1:2,de=o===1?2:1;re=ae,ee=de*(2-b)}y-=re*(j+z),w-=ee*(W+J)}let S=2,D=2,B=2,I=0,U={num:1,den:1},R=null,$=null;if(e.readBits(1)){if(e.readBits(1)){let de=e.readBits(8);if(de===255)U={num:e.readBits(16),den:e.readBits(16)};else{let Be=Rs[de];Be&&(U=Be)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),I=e.readBits(1),e.readBits(1)&&(S=e.readBits(8),D=e.readBits(8),B=e.readBits(8))),e.readBits(1)&&(P(e),P(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));let ee=e.readBits(1);ee&&Es(e);let Z=e.readBits(1);Z&&Es(e),(ee||Z)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),P(e),P(e),P(e),P(e),R=P(e),$=P(e))}if(R===null){m($===null);let j=n&16;if((i===44||i===86||i===100||i===110||i===122||i===244)&&j)R=0,$=0;else{let z=d+1,W=f+1,J=(2-b)*W,re=br.find(Z=>Z.level>=s)??te(br),ee=Math.min(Math.floor(re.maxDpbMbs/(z*J)),16);R=ee,$=ee}}return m($!==null),{profileIdc:i,constraintFlags:n,levelIdc:s,frameMbsOnlyFlag:b,chromaFormatIdc:o,bitDepthLumaMinus8:a,bitDepthChromaMinus8:c,codedWidth:p,codedHeight:g,displayWidth:y,displayHeight:w,pixelAspectRatio:U,colourPrimaries:S,matrixCoefficients:B,transferCharacteristics:D,fullRangeFlag:I,numReorderFrames:R,maxDecFrameBuffering:$}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},Es=t=>{let e=P(t);t.skipBits(4),t.skipBits(4);for(let r=0;r<=e;r++)P(t),P(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)},dn=(t,e)=>{if(e.description){let n=(we(e.description)[21]&3)+1;return Ps(t,n)}else return Kt(t)},Tr=t=>t>>1&63,Qo=t=>{try{let e=new ie(ai(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}=Ko(e,r);P(e);let u=P(e),d=0;u===3&&(d=e.readBits(1));let f=P(e),p=P(e),g=f,y=p;if(e.readBits(1)){let z=P(e),W=P(e),J=P(e),re=P(e),ee=1,Z=1,ae=d===0?u:0;ae===1?(ee=2,Z=2):ae===2&&(ee=2,Z=1),g-=(z+W)*ee,y-=(J+re)*Z}let w=P(e),b=P(e);P(e);let S=e.readBits(1)?0:r,D=0;for(let z=S;z<=r;z++)P(e),D=P(e),P(e);P(e),P(e),P(e),P(e),P(e),P(e),e.readBits(1)&&e.readBits(1)&&Xo(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),P(e),P(e),e.skipBits(1));let B=P(e);if(Go(e,B),e.readBits(1)){let z=P(e);for(let W=0;W<z;W++)P(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let I=2,U=2,R=2,$=0,me=0,j={num:1,den:1};if(e.readBits(1)){let z=Zo(e,r);j=z.pixelAspectRatio,I=z.colourPrimaries,U=z.transferCharacteristics,R=z.matrixCoefficients,$=z.fullRangeFlag,me=z.minSpatialSegmentationIdc}return{displayWidth:g,displayHeight:y,pixelAspectRatio:j,colourPrimaries:I,transferCharacteristics:U,matrixCoefficients:R,fullRangeFlag:$,maxDecFrameBuffering:D+1,spsMaxSubLayersMinus1:r,spsTemporalIdNestingFlag:i,generalProfileSpace:n,generalTierFlag:s,generalProfileIdc:o,generalProfileCompatibilityFlags:a,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:w,bitDepthChromaMinus8:b,minSpatialSegmentationIdc:me}}catch(e){return console.error("Error parsing HEVC SPS:",e),null}},li=t=>{try{let e=[],r=[],i=[],n=[];for(let l of Kt(t)){let u=t.subarray(l.offset,l.offset+l.length),d=Tr(u[0]);d===ke.VPS_NUT?e.push(u):d===ke.SPS_NUT?r.push(u):d===ke.PPS_NUT?i.push(u):(d===ke.PREFIX_SEI_NUT||d===ke.SUFFIX_SEI_NUT)&&n.push(u)}if(r.length===0||i.length===0)return null;let s=Qo(r[0]);if(!s)return null;let o=0;if(i.length>0){let l=i[0],u=new ie(ai(l));u.skipBits(16),P(u),P(u),u.skipBits(1),u.skipBits(1),u.skipBits(3),u.skipBits(1),u.skipBits(1),P(u),P(u),je(u),u.skipBits(1),u.skipBits(1),u.readBits(1)&&P(u),je(u),je(u),u.skipBits(1),u.skipBits(1),u.skipBits(1),u.skipBits(1);let d=u.readBits(1),f=u.readBits(1);!d&&!f?o=0:d&&!f?o=2:!d&&f?o=3:o=0}let a=[...e.length?[{arrayCompleteness:1,nalUnitType:ke.VPS_NUT,nalUnits:e}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:ke.SPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:ke.PPS_NUT,nalUnits:i}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Tr(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:o,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:a}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},Ko=(t,e)=>{let r=t.readBits(2),i=t.readBits(1),n=t.readBits(5),s=0;for(let u=0;u<32;u++)s=s<<1|t.readBits(1);let o=new Uint8Array(6);for(let u=0;u<6;u++)o[u]=t.readBits(8);let a=t.readBits(8),c=[],l=[];for(let u=0;u<e;u++)c.push(t.readBits(1)),l.push(t.readBits(1));if(e>0)for(let u=e;u<8;u++)t.skipBits(2);for(let u=0;u<e;u++)c[u]&&t.skipBits(88),l[u]&&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}},Xo=t=>{for(let e=0;e<4;e++)for(let r=0;r<(e===3?2:6);r++)if(!t.readBits(1))P(t);else{let n=Math.min(64,1<<4+(e<<1));e>1&&je(t);for(let s=0;s<n;s++)je(t)}},Go=(t,e)=>{let r=[];for(let i=0;i<e;i++)r[i]=Yo(t,i,e,r)},Yo=(t,e,r,i)=>{let n=0,s=0,o=0;if(e!==0&&(s=t.readBits(1)),s){if(e===r){let c=P(t);o=e-(c+1)}else o=e-1;t.readBits(1),P(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=P(t),c=P(t);for(let l=0;l<a;l++)P(t),t.readBits(1);for(let l=0;l<c;l++)P(t),t.readBits(1);n=a+c}return n},Zo=(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=Rs[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)&&(P(t),P(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(P(t),P(t),P(t),P(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&P(t),t.readBits(1)&&Jo(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),o=P(t),P(t),P(t),P(t),P(t)),{pixelAspectRatio:a,colourPrimaries:r,transferCharacteristics:i,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:o}},Jo=(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?P(t):l=t.readBits(1)===1;let u=1;l||(u=P(t)+1),i&&vs(t,u,s),n&&vs(t,u,s)}},vs=(t,e,r)=>{for(let i=0;i<e;i++)P(t),P(t),r&&(P(t),P(t)),t.readBits(1)},Bs=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 ui=t=>{let e=new ie(t);if(e.readBits(2)!==2)return null;let i=e.readBits(1),s=(e.readBits(1)<<1)+i;if(s===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;s>=2&&(l=e.readBits(1)?12:10);let u=e.readBits(3),d=0,f=0;if(u!==7)if(f=e.readBits(1),s===1||s===3){let U=e.readBits(1),R=e.readBits(1);d=!U&&!R?3:U&&!R?2:1,e.skipBits(1)}else d=1;else d=3,f=1;let p=e.readBits(16),g=e.readBits(16),y=p+1,w=g+1,b=y*w,T=te(ot).level;for(let I of ot)if(b<=I.maxPictureSize){T=I.level;break}return{profile:s,level:T,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:u===2?1:u===1?6:2,transferCharacteristics:u===2?1:u===1?6:2,matrixCoefficients:u===7?0:u===2?1:u===1?6:2}},Ds=function*(t){let e=new ie(t),r=()=>{let i=0;for(let n=0;n<8;n++){let s=e.readAlignedByte();if(i|=(s&127)<<n*7,!(s&128))break;if(n===7&&s&128)return null}return i>=2**32-1?null:i};for(;e.getBitsLeft()>=8;){e.skipBits(1);let i=e.readBits(4),n=e.readBits(1),s=e.readBits(1);e.skipBits(1),n&&e.skipBits(8);let o;if(s){let a=r();if(a===null)return;o=a}else o=Math.floor(e.getBitsLeft()/8);m(e.pos%8===0),yield{type:i,data:t.subarray(e.pos/8,e.pos/8+o)},e.skipBits(o*8)}},di=t=>{for(let{type:e,data:r}of Ds(t)){if(e!==1)continue;let i=new ie(r),n=i.readBits(3),s=i.readBits(1),o=i.readBits(1),a=0,c=0,l=0;if(o)a=i.readBits(5);else{if(i.readBits(1)&&(i.skipBits(32),i.skipBits(32),i.readBits(1)))return null;let I=i.readBits(1);I&&(l=i.readBits(5),i.skipBits(32),i.skipBits(5),i.skipBits(5));let U=i.readBits(5);for(let R=0;R<=U;R++){i.skipBits(12);let $=i.readBits(5);if(R===0&&(a=$),$>7){let j=i.readBits(1);R===0&&(c=j)}if(I&&i.readBits(1)){let z=l+1;i.skipBits(z),i.skipBits(z),i.skipBits(1)}i.readBits(1)&&i.skipBits(4)}}let u=i.readBits(4),d=i.readBits(4),f=u+1;i.skipBits(f);let p=d+1;i.skipBits(p);let g=0;if(o?g=0:g=i.readBits(1),g&&(i.skipBits(4),i.skipBits(3)),i.skipBits(1),i.skipBits(1),i.skipBits(1),!o){i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);let B=i.readBits(1);B&&(i.skipBits(1),i.skipBits(1));let I=i.readBits(1),U=0;I?U=2:U=i.readBits(1),U>0&&(i.readBits(1)||i.skipBits(1)),B&&i.skipBits(3)}i.skipBits(1),i.skipBits(1),i.skipBits(1);let y=i.readBits(1),w=8;n===2&&y?w=i.readBits(1)?12:10:n<=2&&(w=y?10:8);let b=0;n!==1&&(b=i.readBits(1));let T=1,S=1,D=0;return b||(n===0?(T=1,S=1):n===1?(T=0,S=0):w===12&&(T=i.readBits(1),T&&(S=i.readBits(1))),T&&S&&(D=i.readBits(2))),{profile:n,level:a,tier:c,bitDepth:w,monochrome:b,chromaSubsamplingX:T,chromaSubsamplingY:S,chromaSamplePosition:D}}return null},Ms=t=>{let e=oe(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}};var hi=(t,e,r)=>{switch(t){case"avc":{for(let i of cn(r,e)){let n=r[i.offset],s=oi(n);if(s>=at.NON_IDR_SLICE&&s<=at.SLICE_DPC)return"delta";if(s===at.IDR)return"key";if(s===at.SEI&&(!mr()||ds()>=144)){let o=r.subarray(i.offset,i.offset+i.length),a=ai(o),c=1;do{let l=0;for(;;){let f=a[c++];if(f===void 0||(l+=f,f<255))break}let u=0;for(;;){let f=a[c++];if(f===void 0||(u+=f,f<255))break}if(l===6){let f=new ie(a);f.pos=8*c;let p=P(f),g=f.readBits(1);if(p===0&&g===1)return"key"}c+=u}while(c<a.length-1)}}return"delta"}case"hevc":{for(let i of dn(r,e)){let n=Tr(r[i.offset]);if(n<ke.BLA_W_LP)return"delta";if(n<=ke.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(r[0]&1)===0?"key":"delta";case"vp9":{let i=new ie(r);if(i.readBits(2)!==2)return null;let n=i.readBits(1);return(i.readBits(1)<<1)+n===3&&i.skipBits(1),i.readBits(1)?null:i.readBits(1)===0?"key":"delta"}case"av1":{let i=!1;for(let{type:n,data:s}of Ds(r))if(n===1){let o=new ie(s);o.skipBits(4),i=!!o.readBits(1)}else if(n===3||n===6||n===7){if(i)return"key";let o=new ie(s);return o.readBits(1)?null:o.readBits(2)===0?"key":"delta"}return null}default:Ae(t),m(!1)}},si;(function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"})(si||(si={}));var hn=[2,1,2,3,3,4,4,5],zs=t=>{if(t.length<7||t[0]!==11||t[1]!==119)return null;let e=new ie(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&&o!==1&&e.skipBits(2),o&4&&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}},Oc=[64*2,69*2,96*2,64*2,70*2,96*2,80*2,87*2,120*2,80*2,88*2,120*2,96*2,104*2,144*2,96*2,105*2,144*2,112*2,121*2,168*2,112*2,122*2,168*2,128*2,139*2,192*2,128*2,140*2,192*2,160*2,174*2,240*2,160*2,175*2,240*2,192*2,208*2,288*2,192*2,209*2,288*2,224*2,243*2,336*2,224*2,244*2,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 Uc=new Uint8Array([5,4,65,67,45,51]),Nc=new Uint8Array([5,4,69,65,67,51]),ea=[1,2,3,6],Os=t=>{if(t.length<6||t[0]!==11||t[1]!==119)return null;let e=new ie(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 u=ea[o],d;return n<3?d=yr[n]/1e3:d=on[s]/1e3,{dataRate:Math.round((i+1)*d/(u*16)),substreams:[{fscod:n,fscod2:s,bsid:l,bsmod:0,acmod:a,lfeon:c,numDepSub:0,chanLoc:0}]}},Us=t=>{if(t.length<2)return null;let e=new ie(t),r=e.readBits(13),i=e.readBits(3),n=[];for(let s=0;s<=i&&!(Math.ceil(e.pos/8)+3>t.length);s++){let o=e.readBits(2),a=e.readBits(5);e.skipBits(1),e.skipBits(1);let c=e.readBits(3),l=e.readBits(3),u=e.readBits(1);e.skipBits(3);let d=e.readBits(4),f=0;d>0?f=e.readBits(9):e.skipBits(1),n.push({fscod:o,fscod2:null,bsid:a,bsmod:c,acmod:l,lfeon:u,numDepSub:d,chanLoc:f})}return n.length===0?null:{dataRate:r,substreams:n}},Ns=t=>{let e=t.substreams[0];return m(e),e.fscod<3?yr[e.fscod]:e.fscod2!==null&&e.fscod2<3?on[e.fscod2]:null},Vs=t=>{let e=t.substreams[0];m(e);let r=hn[e.acmod]+e.lfeon;if(e.numDepSub>0){let i=[2,2,1,1,2,2,2,1,1];for(let n=0;n<9;n++)e.chanLoc&1<<8-n&&(r+=i[n])}return r};var Xt=class{constructor(e){this.input=e}};var fi=[],mi=[],kr=[],xr=[];var kt=new Uint8Array(0),ce=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===kt&&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===kt}get microsecondTimestamp(){return Math.trunc(Qe*this.timestamp)}get microsecondDuration(){return Math.trunc(Qe*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("Your browser does not support EncodedVideoChunk.");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("Your browser does not support EncodedVideoChunk.");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("Your browser does not support EncodedAudioChunk.");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 Ws=t=>{let i=t,n=4096,s=0,o=12,a=0;for(i<0&&(i=-i,s=128),i+=33,i>8191&&(i=8191);(i&n)!==n&&o>=5;)n>>=1,o--;return a=i>>o-4&15,~(s|o-5<<4|a)&255},Ls=t=>{let r=0,i=0,n=~t;n&128&&(n&=-129,r=-1),i=((n&240)>>4)+5;let s=(1<<i|(n&15)<<i-4|1<<i-5)-33;return r===0?s:-s},Hs=t=>{let r=2048,i=0,n=11,s=0,o=t;for(o<0&&(o=-o,i=128),o>4095&&(o=4095);(o&r)!==r&&n>=5;)r>>=1,n--;return s=o>>(n===4?1:n-4)&15,(i|n-4<<4|s)^85},qs=t=>{let e=0,r=0,i=t^85;i&128&&(i&=-129,e=-1),r=((i&240)>>4)+4;let n=0;return r!==4?n=1<<r|(i&15)<<r-4|1<<r-5:n=i<<1|1,e===0?n:-n};Yr();var js=-1/0,$s=-1/0,_r=null;typeof FinalizationRegistry<"u"&&(_r=new FinalizationRegistry(t=>{let e=Date.now();t.type==="video"?(e-js>=1e3&&(console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you\'re done using them."),js=e),typeof VideoFrame<"u"&&t.data instanceof VideoFrame&&t.data.close()):(e-$s>=1e3&&(console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you\'re done using them."),$s=e),typeof AudioData<"u"&&t.data instanceof AudioData&&t.data.close())}));var Ks=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],ta=new Set(Ks),xe=class t{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(Qe*this.timestamp)}get microsecondDuration(){return Math.trunc(Qe*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,r){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.format===void 0||!ta.has(r.format))throw new TypeError("init.format must be one of: "+Ks.join(", "));if(!Number.isInteger(r.codedWidth)||r.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(r.codedHeight)||r.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(r.layout!==void 0){if(!Array.isArray(r.layout))throw new TypeError("init.layout, when provided, must be an array.");for(let i of r.layout){if(!i||typeof i!="object"||Array.isArray(i))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(i.offset)||i.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(i.stride)||i.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(r.visibleRect!==void 0&&nn(r.visibleRect,"init.visibleRect"),r.displayWidth!==void 0&&(!Number.isInteger(r.displayWidth)||r.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(r.displayHeight!==void 0&&(!Number.isInteger(r.displayHeight)||r.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(r.displayWidth!==void 0!=(r.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this._data=we(e).slice(),this._layout=r.layout??ra(r.format,r.codedWidth,r.codedHeight),this.format=r.format,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new Cr(r.colorSpace),this.visibleRect={left:r.visibleRect?.left??0,top:r.visibleRect?.top??0,width:r.visibleRect?.width??r.codedWidth,height:r.visibleRect?.height??r.codedHeight},r.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?r.displayWidth:r.displayHeight,this.squarePixelHeight=this.rotation%180===0?r.displayHeight:r.displayWidth):(this.squarePixelWidth=this.codedWidth,this.squarePixelHeight=this.codedHeight)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(r?.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(r?.timestamp!==void 0&&!Number.isFinite(r?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(r?.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");r?.visibleRect!==void 0&&nn(r.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=r?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=r?.timestamp??e.timestamp/1e6,this.duration=r?.duration??(e.duration??0)/1e6,this.colorSpace=new Cr(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new t(new VideoFrame(e,{timestamp:Math.trunc(r.timestamp*Qe),duration:Math.trunc((r.duration??0)*Qe)||void 0}),r);let i=0,n=0;if("naturalWidth"in e?(i=e.naturalWidth,n=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,n=e.videoHeight):"width"in e&&(i=Number(e.width),n=Number(e.height)),!i||!n)throw new TypeError("Could not determine dimensions.");let s=new OffscreenCanvas(i,n),o=s.getContext("2d",{alpha:Ke(),willReadFrequently:!0});m(o),o.drawImage(e,0,0),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:i,height:n},this.squarePixelWidth=i,this.squarePixelHeight=n,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new Cr({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");this.pixelAspectRatio=$t({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),_r?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return m(this._data!==null),Mt(this._data)?new t(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(m(this._layout),new t(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})):new t(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})}close(){this._closed||(_r?.unregister(this),Mt(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Qs(e),this._closed)throw new Error("VideoSample is closed.");if(this.format===null)throw new Error("Cannot get allocation size when format is null. Sorry!");if(m(this._data!==null),!Mt(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let r=this.toVideoFrame(),i=r.allocationSize(e);return r.close(),i}return Mt(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,r={}){if(!jt(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Qs(r),this._closed)throw new Error("VideoSample is closed.");if(this.format===null)throw new Error("Cannot copy video sample data when format is null. Sorry!");if(m(this._data!==null),!Mt(this._data)&&(r.colorSpace||r.format&&r.format!==this.format||r.layout||r.rect)){let i=this.toVideoFrame(),n=await i.copyTo(e,r);return i.close(),n}if(Mt(this._data))return this._data.copyTo(e,r);if(this._data instanceof Uint8Array)return m(this._layout),we(e).set(this._data),this._layout;{let n=this._data.getContext("2d");m(n);let s=n.getImageData(0,0,this.codedWidth,this.codedHeight);return we(e).set(s.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return m(this._data!==null),Mt(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,r,i,n,s,o,a,c,l){let u=0,d=0,f=this.displayWidth,p=this.displayHeight,g=0,y=0,w=this.displayWidth,b=this.displayHeight;if(o!==void 0?(u=r,d=i,f=n,p=s,g=o,y=a,c!==void 0?(w=c,b=l):(w=f,b=p)):(g=r,y=i,n!==void 0&&(w=n,b=s)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(p)||p<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(g))throw new TypeError("dx must be a number.");if(!Number.isFinite(y))throw new TypeError("dy must be a number.");if(!Number.isFinite(w)||w<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(b)||b<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:u,sy:d,sWidth:f,sHeight:p}=this._rotateSourceRegion(u,d,f,p,this.rotation));let T=this.toCanvasImageSource();e.save();let S=g+w/2,D=y+b/2;e.translate(S,D),e.rotate(this.rotation*Math.PI/180);let B=this.rotation%180===0?1:w/b;e.scale(1/B,B),e.drawImage(T,u,d,f,p,-w/2,-b/2,w,b),e.restore()}drawWithFit(e,r){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(r.fit))throw new TypeError("options.fit must be \'fill\', \'contain\', or \'cover\'.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");r.crop!==void 0&&vr(r.crop,"options.");let i=e.canvas.width,n=e.canvas.height,s=r.rotation??this.rotation,[o,a]=s%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];r.crop&&Er(r.crop,o,a);let c,l,u,d,{sx:f,sy:p,sWidth:g,sHeight:y}=this._rotateSourceRegion(r.crop?.left??0,r.crop?.top??0,r.crop?.width??o,r.crop?.height??a,s);if(r.fit==="fill")c=0,l=0,u=i,d=n;else{let[b,T]=r.crop?[r.crop.width,r.crop.height]:[o,a],S=r.fit==="contain"?Math.min(i/b,n/T):Math.max(i/b,n/T);u=b*S,d=T*S,c=(i-u)/2,l=(n-d)/2}e.save();let w=s%180===0?1:u/d;e.translate(i/2,n/2),e.rotate(s*Math.PI/180),e.scale(1/w,w),e.translate(-i/2,-n/2),e.drawImage(this.toCanvasImageSource(),f,p,g,y,c,l,u,d),e.restore()}_rotateSourceRegion(e,r,i,n,s){return s===90?[e,r,i,n]=[r,this.squarePixelHeight-e-i,n,i]:s===180?[e,r]=[this.squarePixelWidth-e-i,this.squarePixelHeight-r-n]:s===270&&([e,r,i,n]=[this.squarePixelWidth-r-n,e,n,i]),{sx:e,sy:r,sWidth:i,sHeight:n}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(m(this._data!==null),this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}},Cr=class{constructor(e){if(e!==void 0){if(!e||typeof e!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");let r=Object.keys(rt);if(e.primaries!=null&&!r.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${r.join(", ")}.`);let i=Object.keys(it);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);let n=Object.keys(nt);if(e.matrix!=null&&!n.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${n.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},Mt=t=>typeof VideoFrame<"u"&&t instanceof VideoFrame,Er=(t,e,r)=>{t.left=Math.min(t.left,e),t.top=Math.min(t.top,r),t.width=Math.min(t.width,e-t.left),t.height=Math.min(t.height,r-t.top),m(t.width>=0),m(t.height>=0)},vr=(t,e)=>{if(!t||typeof t!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},Qs=t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.colorSpace!==void 0&&!["display-p3","srgb"].includes(t.colorSpace))throw new TypeError("options.colorSpace, when provided, must be \'display-p3\' or \'srgb\'.");if(t.format!==void 0&&typeof t.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let e of t.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.rect!==void 0){if(!t.rect||typeof t.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(t.rect.x!==void 0&&(!Number.isInteger(t.rect.x)||t.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(t.rect.y!==void 0&&(!Number.isInteger(t.rect.y)||t.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(t.rect.width!==void 0&&(!Number.isInteger(t.rect.width)||t.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(t.rect.height!==void 0&&(!Number.isInteger(t.rect.height)||t.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},ra=(t,e,r)=>{let i=ia(t),n=[],s=0;for(let o of i){let a=Math.ceil(e/o.widthDivisor),c=Math.ceil(r/o.heightDivisor),l=a*o.sampleBytes,u=l*c;n.push({offset:s,stride:l}),s+=u}return n},ia=t=>{let e=(r,i,n,s,o)=>{let a=[{sampleBytes:r,widthDivisor:1,heightDivisor:1},{sampleBytes:i,widthDivisor:n,heightDivisor:s},{sampleBytes:i,widthDivisor:n,heightDivisor:s}];return o&&a.push({sampleBytes:r,widthDivisor:1,heightDivisor:1}),a};switch(t){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Ae(t),m(!1)}},fn=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),Me=class t{get microsecondTimestamp(){return Math.trunc(Qe*this.timestamp)}get microsecondDuration(){return Math.trunc(Qe*this.duration)}constructor(e){if(this._closed=!1,Sr(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!fn.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");let r=e.data.byteLength/(zt(e.format)*e.numberOfChannels);if(!Number.isInteger(r))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=r,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=r/e.sampleRate;let i;if(e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let n=this.numberOfFrames*this.numberOfChannels*zt(this.format);if(i.byteLength<n)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}_r?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!fn.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let r=e.format??this.format,i=e.frameOffset??0;if(i>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let n=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-i;if(n>this.numberOfFrames-i)throw new RangeError("frameCount out of range");let s=zt(r),o=Gt(r);if(o&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!o&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(o?n:n*this.numberOfChannels)*s}copyTo(e,r){if(!jt(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(r.planeIndex)||r.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(r.format!==void 0&&!fn.has(r.format))throw new TypeError("Invalid format.");if(r.frameOffset!==void 0&&(!Number.isInteger(r.frameOffset)||r.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(r.frameCount!==void 0&&(!Number.isInteger(r.frameCount)||r.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{planeIndex:i,format:n,frameCount:s,frameOffset:o}=r,a=this.format,c=n??this.format;if(!c)throw new Error("Destination format not determined");let l=this.numberOfFrames,u=this.numberOfChannels,d=o??0;if(d>=l)throw new RangeError("frameOffset out of range");let f=s!==void 0?s:l-d;if(f>l-d)throw new RangeError("frameCount out of range");let p=zt(c),g=Gt(c);if(g&&i>=u)throw new RangeError("planeIndex out of range");if(!g&&i!==0)throw new RangeError("planeIndex out of range");let w=(g?f:f*u)*p;if(e.byteLength<w)throw new RangeError("Destination buffer is too small");let b=oe(e),T=Gs(c);if(Sr(this._data))Rt()&&u>2&&c!==a?na(this._data,b,a,c,u,i,d,f):this._data.copyTo(e,{planeIndex:i,frameOffset:d,frameCount:f,format:c});else{let S=this._data,D=oe(S),B=Xs(a),I=zt(a),U=Gt(a);for(let R=0;R<f;R++)if(g){let $=R*p,me;U?me=(i*l+(R+d))*I:me=((R+d)*u+i)*I;let j=B(D,me);T(b,$,j)}else for(let $=0;$<u;$++){let j=(R*u+$)*p,z;U?z=($*l+(R+d))*I:z=((R+d)*u+$)*I;let W=B(D,z);T(b,j,W)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(Sr(this._data)){let e=new t(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new t({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(_r?.unregister(this),Sr(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(Sr(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(Gt(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),r=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(new Uint8Array(r,i*e,e),{planeIndex:i,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:r})}else{let e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),r=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(r,{planeIndex:i,format:"f32-planar"}),e.copyToChannel(r,i);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let i=48e3*5,n=e.numberOfChannels,s=e.sampleRate,o=e.length,a=Math.floor(i/n),c=0,l=o;for(;l>0;){let u=Math.min(a,l),d=new Float32Array(n*u);for(let f=0;f<n;f++)e.copyFromChannel(d.subarray(f*u,(f+1)*u),f,c);yield new t({format:"f32-planar",sampleRate:s,numberOfFrames:u,numberOfChannels:n,timestamp:r+c/s,data:d}),c+=u,l-=u}}static fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let i=48e3*5,n=e.numberOfChannels,s=e.sampleRate,o=e.length,a=Math.floor(i/n),c=0,l=o,u=[];for(;l>0;){let d=Math.min(a,l),f=new Float32Array(n*d);for(let g=0;g<n;g++)e.copyFromChannel(f.subarray(g*d,(g+1)*d),g,c);let p=new t({format:"f32-planar",sampleRate:s,numberOfFrames:d,numberOfChannels:n,timestamp:r+c/s,data:f});u.push(p),c+=d,l-=d}return u}},zt=t=>{switch(t){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},Gt=t=>{switch(t){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Xs=t=>{switch(t){case"u8":case"u8-planar":return(e,r)=>(e.getUint8(r)-128)/128;case"s16":case"s16-planar":return(e,r)=>e.getInt16(r,!0)/32768;case"s32":case"s32-planar":return(e,r)=>e.getInt32(r,!0)/2147483648;case"f32":case"f32-planar":return(e,r)=>e.getFloat32(r,!0)}},Gs=t=>{switch(t){case"u8":case"u8-planar":return(e,r,i)=>e.setUint8(r,fe((i+1)*127.5,0,255));case"s16":case"s16-planar":return(e,r,i)=>e.setInt16(r,fe(Math.round(i*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,r,i)=>e.setInt32(r,fe(Math.round(i*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,r,i)=>e.setFloat32(r,i,!0)}},Sr=t=>typeof AudioData<"u"&&t instanceof AudioData,na=(t,e,r,i,n,s,o,a)=>{let c=Xs(r),l=Gs(i),u=zt(r),d=zt(i),f=Gt(r);if(Gt(i))if(f){let g=new ArrayBuffer(a*u),y=oe(g);t.copyTo(g,{planeIndex:s,frameOffset:o,frameCount:a,format:r});for(let w=0;w<a;w++){let b=w*u,T=w*d,S=c(y,b);l(e,T,S)}}else{let g=new ArrayBuffer(a*n*u),y=oe(g);t.copyTo(g,{planeIndex:0,frameOffset:o,frameCount:a,format:r});for(let w=0;w<a;w++){let b=(w*n+s)*u,T=w*d,S=c(y,b);l(e,T,S)}}else if(f){let g=a*u,y=new ArrayBuffer(g),w=oe(y);for(let b=0;b<n;b++){t.copyTo(y,{planeIndex:b,frameOffset:o,frameCount:a,format:r});for(let T=0;T<a;T++){let S=T*u,D=(T*n+b)*d,B=c(w,S);l(e,D,B)}}}else{let g=new ArrayBuffer(a*n*u),y=oe(g);t.copyTo(g,{planeIndex:0,frameOffset:o,frameCount:a,format:r});for(let w=0;w<a;w++)for(let b=0;b<n;b++){let T=w*n+b,S=T*u,D=T*d,B=c(y,S);l(e,D,B)}}};var Ot=t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.metadataOnly!==void 0&&typeof t.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(t.verifyKeyPackets!==void 0&&typeof t.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(t.verifyKeyPackets&&t.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},xt=t=>{if(!Zr(t))throw new TypeError("timestamp must be a number.")},mn=(t,e,r)=>r.verifyKeyPackets?e.then(async i=>{if(!i||i.type==="delta")return i;let n=await t.determinePacketType(i);return n&&(i.type=n),i}):e,Xe=class{constructor(e){if(!(e instanceof Zt))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(Ot(e),this._track.input._disposed)throw new be;return mn(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Ot(e);let r=await this.getFirstPacket(e);return r?r.type==="key"?r:this.getNextKeyPacket(r,e):null}getPacket(e,r={}){if(xt(e),Ot(r),this._track.input._disposed)throw new be;return mn(this._track,this._track._backing.getPacket(e,r),r)}getNextPacket(e,r={}){if(!(e instanceof ce))throw new TypeError("packet must be an EncodedPacket.");if(Ot(r),this._track.input._disposed)throw new be;return mn(this._track,this._track._backing.getNextPacket(e,r),r)}async getKeyPacket(e,r={}){if(xt(e),Ot(r),this._track.input._disposed)throw new be;if(!r.verifyKeyPackets)return this._track._backing.getKeyPacket(e,r);let i=await this._track._backing.getKeyPacket(e,r);return i&&(m(i.type==="key"),await this._track.determinePacketType(i)==="delta"?this.getKeyPacket(i.timestamp-1/this._track.timeResolution,r):i)}async getNextKeyPacket(e,r={}){if(!(e instanceof ce))throw new TypeError("packet must be an EncodedPacket.");if(Ot(r),this._track.input._disposed)throw new be;if(!r.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,r);let i=await this._track._backing.getNextKeyPacket(e,r);return i&&(m(i.type==="key"),await this._track.determinePacketType(i)==="delta"?this.getNextKeyPacket(i,r):i)}packets(e,r,i={}){if(e!==void 0&&!(e instanceof ce))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!i?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(r!==void 0&&!(r instanceof ce))throw new TypeError("endPacket must be an EncodedPacket.");if(Ot(i),this._track.input._disposed)throw new be;let n=[],{promise:s,resolve:o}=he(),{promise:a,resolve:c}=he(),l=!1,u=!1,d=null,f=[],p=()=>Math.max(2,f.length);(async()=>{let y=e??await this.getFirstPacket(i);for(;y&&!u&&!this._track.input._disposed&&!(r&&y.sequenceNumber>=r?.sequenceNumber);){if(n.length>p()){({promise:a,resolve:c}=he()),await a;continue}n.push(y),o(),{promise:s,resolve:o}=he(),y=await this.getNextPacket(y,i)}l=!0,o()})().catch(y=>{d||(d=y,o())});let g=this._track;return{async next(){for(;;){if(g.input._disposed)throw new be;if(u)return{value:void 0,done:!0};if(d)throw d;if(n.length>0){let y=n.shift(),w=performance.now();for(f.push(w);f.length>0&&w-f[0]>=1e3;)f.shift();return c(),{value:y,done:!1}}else{if(l)return{value:void 0,done:!0};await s}}},async return(){return u=!0,c(),o(),{value:void 0,done:!0}},async throw(y){throw y},[Symbol.asyncIterator](){return this}}}},Pr=class{constructor(e,r){this.onSample=e,this.onError=r}},Ar=class{mediaSamplesInRange(e=0,r=1/0){xt(e),xt(r);let i=[],n=!1,s=null,{promise:o,resolve:a}=he(),{promise:c,resolve:l}=he(),u=!1,d=!1,f=!1,p=null;(async()=>{let w=await this._createDecoder(I=>{if(l(),I.timestamp>=r&&(d=!0),d){I.close();return}s&&(I.timestamp>e?(i.push(s),n=!0):s.close()),I.timestamp>=e&&(i.push(I),n=!0),s=n?null:I,i.length>0&&(a(),{promise:o,resolve:a}=he())},I=>{p||(p=I,a())}),b=this._createPacketSink(),T=await b.getKeyPacket(e,{verifyKeyPackets:!0})??await b.getFirstKeyPacket({verifyKeyPackets:!0}),S=T,B=b.packets(T??void 0,void 0);for(await B.next();S&&!d&&!this._track.input._disposed;){let I=Ys(i.length);if(i.length+w.getDecodeQueueSize()>I){({promise:c,resolve:l}=he()),await c;continue}w.decode(S);let U=await B.next();if(U.done)break;S=U.value}await B.return(),!f&&!this._track.input._disposed&&await w.flush(),w.close(),!n&&s&&i.push(s),u=!0,a()})().catch(w=>{p||(p=w,a())});let g=this._track,y=()=>{s?.close();for(let w of i)w.close()};return{async next(){for(;;){if(g.input._disposed)throw y(),new be;if(f)return{value:void 0,done:!0};if(p)throw y(),p;if(i.length>0){let w=i.shift();return l(),{value:w,done:!1}}else if(!u)await o;else return{value:void 0,done:!0}}},async return(){return f=!0,d=!0,l(),a(),y(),{value:void 0,done:!0}},async throw(w){throw w},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){os(e);let r=ss(e),i=[],n=[],{promise:s,resolve:o}=he(),{promise:a,resolve:c}=he(),l=!1,u=!1,d=null,f=y=>{n.push(y),o(),{promise:s,resolve:o}=he()};(async()=>{let y=await this._createDecoder(I=>{if(c(),u){I.close();return}let U=0;for(;i.length>0&&I.timestamp-i[0]>-1e-10;)U++,i.shift();if(U>0)for(let R=0;R<U;R++)f(R<U-1?I.clone():I);else I.close()},I=>{d||(d=I,o())}),w=this._createPacketSink(),b=null,T=null,S=-1,D=async()=>{m(T);let I=T;for(y.decode(I);I.sequenceNumber<S;){let U=Ys(n.length);for(;n.length+y.getDecodeQueueSize()>U&&!u;)({promise:a,resolve:c}=he()),await a;if(u)break;let R=await w.getNextPacket(I);m(R),y.decode(R),I=R}S=-1},B=async()=>{await y.flush();for(let I=0;I<i.length;I++)f(null);i.length=0};for await(let I of r){if(xt(I),u||this._track.input._disposed)break;let U=await w.getPacket(I),R=U&&await w.getKeyPacket(I,{verifyKeyPackets:!0});if(!R){S!==-1&&(await D(),await B()),f(null),b=null;continue}b&&(R.sequenceNumber!==T.sequenceNumber||U.timestamp<b.timestamp)&&(await D(),await B()),i.push(U.timestamp),S=Math.max(U.sequenceNumber,S),b=U,T=R}!u&&!this._track.input._disposed&&(S!==-1&&await D(),await B()),y.close(),l=!0,o()})().catch(y=>{d||(d=y,o())});let p=this._track,g=()=>{for(let y of n)y?.close()};return{async next(){for(;;){if(p.input._disposed)throw g(),new be;if(u)return{value:void 0,done:!0};if(d)throw g(),d;if(n.length>0){let y=n.shift();return m(y!==void 0),c(),{value:y,done:!1}}else if(!l)await s;else return{value:void 0,done:!0}}},async return(){return u=!0,c(),o(),g(),{value:void 0,done:!0}},async throw(y){throw y},[Symbol.asyncIterator](){return this}}}},Ys=t=>t===0?40:8,pn=class extends Pr{constructor(e,r,i,n,s,o){super(e,r),this.codec=i,this.decoderConfig=n,this.rotation=s,this.timeResolution=o,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Tt,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;let a=fi.find(c=>c.supports(i,n));if(a)this.customDecoder=new a,this.customDecoder.codec=i,this.customDecoder.config=n,this.customDecoder.onSample=c=>{if(!(c instanceof xe))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=u=>{if(this.alphaQueue.length>0){let d=this.alphaQueue.shift();m(d!==void 0),this.mergeAlpha(u,d)}else this.colorQueue.push(u)};if(i==="avc"&&this.decoderConfig.description&&mr()){let u=Fs(we(this.decoderConfig.description));if(u&&u.sequenceParameterSets.length>0){let d=un(u.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let l=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:u=>{try{c(u)}catch(d){this.onError(d)}},error:u=>{u.stack=l,this.onError(u)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(m(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(m(this.decoder),Rt()||Ji(this.inputTimestamps,e.timestamp,r=>r),mr()&&this.currentPacketIndex===0&&this.codec==="avc"){let r=[];for(let n of cn(e.data,this.decoderConfig)){let s=oi(e.data[n.offset]);s>=20&&s<=31||r.push(e.data.subarray(n.offset,n.offset+n.length))}let i=As(r,this.decoderConfig);e=new ce(i,e.type,e.timestamp,e.duration)}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed){this.pushNullAlphaFrame();return}if(!this.merger)try{this.merger=new gn}catch(i){console.error("Due to an error, only color data will be decoded.",i),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let i=s=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let o=this.colorQueue.shift();m(o!==void 0),this.mergeAlpha(o,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let o=this.colorQueue.shift();m(o!==void 0),this.mergeAlpha(o,null)}else this.alphaQueue.push(null)},n=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{i(s)}catch(o){this.onError(o)}},error:s=>{s.stack=n,this.onError(s)}}),this.alphaDecoder.configure(this.decoderConfig)}let r=hi(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=r==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(r??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let r of dn(e,this.decoderConfig)){let i=Tr(e[r.offset]);if(i===ke.RASL_N||i===ke.RASL_R)return!0}return!1}sampleHandler(e){if(Rt()){if(this.sampleQueue.length>0&&e.timestamp>=te(this.sampleQueue).timestamp){for(let r of this.sampleQueue)this.finalizeAndEmitSample(r);this.sampleQueue.length=0}Ji(this.sampleQueue,e,r=>r.timestamp)}else{let r=this.inputTimestamps.shift();m(r!==void 0),e.setTimestamp(r),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,r){if(!r){let s=new xe(e);this.sampleHandler(s);return}m(this.merger),this.merger.update(e,r),e.close(),r.close();let i=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),n=new xe(i);this.sampleHandler(n)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(m(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Rt()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(m(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},gn=class{constructor(){typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");let e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn\'t acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es\n in vec2 a_position;\n in vec2 a_texCoord;\n out vec2 v_texCoord;\n \n void main() {\n gl_Position = vec4(a_position, 0.0, 1.0);\n v_texCoord = a_texCoord;\n }\n `),r=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es\n precision highp float;\n \n uniform sampler2D u_colorTexture;\n uniform sampler2D u_alphaTexture;\n in vec2 v_texCoord;\n out vec4 fragColor;\n \n void main() {\n vec3 color = texture(u_colorTexture, v_texCoord).rgb;\n float alpha = texture(u_alphaTexture, v_texCoord).r;\n fragColor = vec4(color, alpha);\n }\n `),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,r),this.gl.linkProgram(i),i}createShader(e,r){let i=this.gl.createShader(e);return this.gl.shaderSource(i,r),this.gl.compileShader(i),i}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let r=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,r,this.gl.STATIC_DRAW);let n=this.gl.getAttribLocation(this.program,"a_position"),s=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,r){(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}},ct=class extends Ar{constructor(e){if(!(e instanceof Ge))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,r){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let i=this._track.codec,n=this._track.rotation,s=await this._track.getDecoderConfig(),o=this._track.timeResolution;return m(i&&s),new pn(e,r,i,s,n,o)}_createPacketSink(){return new Xe(this._track)}async getSample(e){xt(e);for await(let r of this.mediaSamplesAtTimestamps([e]))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,r=1/0){return this.mediaSamplesInRange(e,r)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}},Ir=class{constructor(e,r={}){if(this._nextCanvasIndex=0,!(e instanceof Ge))throw new TypeError("videoTrack must be an InputVideoTrack.");if(r&&typeof r!="object")throw new TypeError("options must be an object.");if(r.alpha!==void 0&&typeof r.alpha!="boolean")throw new TypeError("options.alpha, when provided, must be a boolean.");if(r.width!==void 0&&(!Number.isInteger(r.width)||r.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(r.height!==void 0&&(!Number.isInteger(r.height)||r.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(r.fit!==void 0&&!["fill","contain","cover"].includes(r.fit))throw new TypeError(\'options.fit, when provided, must be one of "fill", "contain", or "cover".\');if(r.width!==void 0&&r.height!==void 0&&r.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(r.crop!==void 0&&vr(r.crop,"options."),r.poolSize!==void 0&&(typeof r.poolSize!="number"||!Number.isInteger(r.poolSize)||r.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");let i=r.rotation??e.rotation,[n,s]=i%180===0?[e.squarePixelWidth,e.squarePixelHeight]:[e.squarePixelHeight,e.squarePixelWidth],o=r.crop;o&&Er(o,n,s);let[a,c]=o?[o.width,o.height]:[n,s],l=a/c;r.width!==void 0&&r.height===void 0?(a=r.width,c=Math.round(a/l)):r.width===void 0&&r.height!==void 0?(c=r.height,a=Math.round(c*l)):r.width!==void 0&&r.height!==void 0&&(a=r.width,c=r.height),this._videoTrack=e,this._alpha=r.alpha??!1,this._width=a,this._height=c,this._rotation=i,this._crop=o,this._fit=r.fit??"fill",this._videoSampleSink=new ct(e),this._canvasPool=Array.from({length:r.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let r=this._canvasPool[this._nextCanvasIndex],i=!1;r||(typeof document<"u"?(r=document.createElement("canvas"),r.width=this._width,r.height=this._height):r=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=r),i=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let n=r.getContext("2d",{alpha:this._alpha||Ke()});m(n),n.resetTransform(),i||(!this._alpha&&Ke()?(n.fillStyle="black",n.fillRect(0,0,this._width,this._height)):n.clearRect(0,0,this._width,this._height)),e.drawWithFit(n,{fit:this._fit,rotation:this._rotation,crop:this._crop});let s={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),s}async getCanvas(e){xt(e);let r=await this._videoSampleSink.getSample(e);return r&&this._videoSampleToWrappedCanvas(r)}canvases(e=0,r=1/0){return en(this._videoSampleSink.samples(e,r),i=>this._videoSampleToWrappedCanvas(i))}canvasesAtTimestamps(e){return en(this._videoSampleSink.samplesAtTimestamps(e),r=>r&&this._videoSampleToWrappedCanvas(r))}},wn=class extends Pr{constructor(e,r,i,n){super(e,r),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Tt,this.customDecoderQueueSize=0,this.currentTimestamp=null;let s=a=>{(this.currentTimestamp===null||Math.abs(a.timestamp-this.currentTimestamp)>=a.duration)&&(this.currentTimestamp=a.timestamp);let c=this.currentTimestamp;if(this.currentTimestamp+=a.duration,a.numberOfFrames===0){a.close();return}let l=n.sampleRate;a.setTimestamp(Math.round(c*l)/l),e(a)},o=mi.find(a=>a.supports(i,n));if(o)this.customDecoder=new o,this.customDecoder.codec=i,this.customDecoder.config=n,this.customDecoder.onSample=a=>{if(!(a instanceof Me))throw new TypeError("The argument passed to onSample must be an AudioSample.");s(a)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let a=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:c=>{try{s(new Me(c))}catch(l){this.onError(l)}},error:c=>{c.stack=a,this.onError(c)}}),this.decoder.configure(n)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(m(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(m(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(m(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(m(this.decoder),this.decoder.close())}},bn=class extends Pr{constructor(e,r,i){super(e,r),this.decoderConfig=i,this.currentTimestamp=null,m(le.includes(i.codec)),this.codec=i.codec;let{dataType:n,sampleSize:s,littleEndian:o}=Ie(this.codec);switch(this.inputSampleSize=s,s){case 1:n==="unsigned"?this.readInputValue=(a,c)=>a.getUint8(c)-2**7:n==="signed"?this.readInputValue=(a,c)=>a.getInt8(c):n==="ulaw"?this.readInputValue=(a,c)=>Ls(a.getUint8(c)):n==="alaw"?this.readInputValue=(a,c)=>qs(a.getUint8(c)):m(!1);break;case 2:n==="unsigned"?this.readInputValue=(a,c)=>a.getUint16(c,o)-2**15:n==="signed"?this.readInputValue=(a,c)=>a.getInt16(c,o):m(!1);break;case 3:n==="unsigned"?this.readInputValue=(a,c)=>Ft(a,c,o)-2**23:n==="signed"?this.readInputValue=(a,c)=>as(a,c,o):m(!1);break;case 4:n==="unsigned"?this.readInputValue=(a,c)=>a.getUint32(c,o)-2**31:n==="signed"?this.readInputValue=(a,c)=>a.getInt32(c,o):n==="float"?this.readInputValue=(a,c)=>a.getFloat32(c,o):m(!1);break;case 8:n==="float"?this.readInputValue=(a,c)=>a.getFloat64(c,o):m(!1);break;default:Ae(s),m(!1)}switch(s){case 1:n==="ulaw"||n==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(a,c,l)=>a.setInt16(c,l,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(a,c,l)=>a.setUint8(c,l+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(a,c,l)=>a.setInt16(c,l,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(a,c,l)=>a.setInt32(c,l<<8,!0);break;case 4:this.outputSampleSize=4,n==="float"?(this.outputFormat="f32",this.writeOutputValue=(a,c,l)=>a.setFloat32(c,l,!0)):(this.outputFormat="s32",this.writeOutputValue=(a,c,l)=>a.setInt32(c,l,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(a,c,l)=>a.setFloat32(c,l,!0);break;default:Ae(s),m(!1)}}getDecodeQueueSize(){return 0}decode(e){let r=oe(e.data),i=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,n=i*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(n),o=new DataView(s);for(let u=0;u<i*this.decoderConfig.numberOfChannels;u++){let d=u*this.inputSampleSize,f=u*this.outputSampleSize,p=this.readInputValue(r,d);this.writeOutputValue(o,f,p)}let a=i/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=a)&&(this.currentTimestamp=e.timestamp);let c=this.currentTimestamp;this.currentTimestamp+=a;let l=new Me({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:c});this.onSample(l)}async flush(){}close(){}},Yt=class extends Ar{constructor(e){if(!(e instanceof lt))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,r){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");let i=this._track.codec,n=await this._track.getDecoderConfig();return m(i&&n),le.includes(n.codec)?new bn(e,r,n):new wn(e,r,i,n)}_createPacketSink(){return new Xe(this._track)}async getSample(e){xt(e);for await(let r of this.mediaSamplesAtTimestamps([e]))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,r=1/0){return this.mediaSamplesInRange(e,r)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}};var Zt=class{constructor(e,r){this.input=e,this._backing=r}isVideoTrack(){return this instanceof Ge}isAudioTrack(){return this instanceof lt}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){let r=new Xe(this),i=1/0,n=-1/0,s=0,o=0;for await(let a of r.packets(void 0,void 0,{metadataOnly:!0})){if(s>=e&&a.timestamp>=n)break;i=Math.min(i,a.timestamp),n=Math.max(n,a.timestamp+a.duration),s++,o+=a.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(n-i)).toPrecision(16)):0,averageBitrate:s?Number((8*o/(n-i)).toPrecision(16)):0}}},Ge=class extends Zt{constructor(e,r){super(e,r),this._backing=r,this.pixelAspectRatio=$t({num:this._backing.getSquarePixelWidth()*this._backing.getCodedHeight(),den:this._backing.getSquarePixelHeight()*this._backing.getCodedWidth()})}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get squarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelHeight(){return this._backing.getSquarePixelHeight()}get displayWidth(){return this._backing.getRotation()%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this._backing.getRotation()%180===0?this.squarePixelHeight:this.squarePixelWidth}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pg"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let r=this._backing.getCodec();return m(r!==null),fi.some(n=>n.supports(r,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ce))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");if(this.codec===null)return null;let r=await this.getDecoderConfig();return m(r),hi(this.codec,r,e.data)}},lt=class extends Zt{constructor(e,r){super(e,r),this._backing=r}get type(){return"audio"}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let r=this._backing.getCodec();return m(r!==null),mi.some(i=>i.supports(r,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ce))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}};var pi=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 Ve=8,ut=16,dt=t=>{let e=F(t),r=ft(t,4),i=8;e===1&&(e=Fe(t),i=16);let s=e-i;return s<0?null:{name:r,totalSize:e,headerSize:i,contentSize:s}},St=t=>ht(t)/65536,gi=t=>ht(t)/1073741824,wi=t=>{let e=0;for(let r=0;r<4;r++){e<<=7;let i=V(t);if(e|=i&127,!(i&128))break}return e},We=t=>{let e=Se(t);return t.skip(2),e=Math.min(e,t.remainingLength),tt.decode(G(t,e))},Zs=t=>{let e=dt(t);if(!e||e.name!=="data"||t.remainingLength<8)return null;let r=F(t);t.skip(4);let i=G(t,e.contentSize-8);switch(r){case 1:return tt.decode(i);case 2:return new TextDecoder("utf-16be").decode(i);case 13:return new Ne(i,"image/jpeg");case 14:return new Ne(i,"image/png");case 27:return new Ne(i,"image/bmp");default:return i}};var bi=class extends Xt{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(i=>i.computeDuration()));return Math.max(0,...r)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(r=>r.inputTrack.getCodecParameterString()));return pi({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(r=>r.info?.type==="video"),hasAudio:this.tracks.some(r=>r.info?.type==="audio"),codecStrings:e.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,Ve,ut);if(r instanceof Promise&&(r=await r),!r)break;let i=e,n=dt(r);if(!n)break;if(n.name==="ftyp"){let s=ft(r,4);this.isQuickTime=s==="qt "}else if(n.name==="moov"){let s=this.reader.requestSlice(r.filePos,n.contentSize);if(s instanceof Promise&&(s=await s),!s)break;this.moovSlice=s,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((o,a)=>Number(a.disposition.default)-Number(o.disposition.default));for(let o of this.tracks){let a=o.editListPreviousSegmentDurations/this.movieTimescale;o.editListOffset-=Math.round(a*o.timescale)}break}e=i+n.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let r=this.reader.requestSlice(this.reader.fileSize-4,4);r instanceof Promise&&(r=await r),m(r);let i=F(r),n=this.reader.fileSize-i;if(n>=0&&n<=this.reader.fileSize-ut){let s=this.reader.requestSliceRange(n,Ve,ut);if(s instanceof Promise&&(s=await s),s){let o=dt(s);if(o&&o.name==="mfra"){let a=this.reader.requestSlice(s.filePos,o.contentSize);a instanceof Promise&&(a=await a),a&&this.readContiguousBoxes(a)}}}}})())}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=r,m(this.moovSlice);let i=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(i),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&le.includes(e.info.codec)&&r.sampleCompositionTimeOffsets.length===0){m(e.info?.type==="audio");let s=Ie(e.info.codec),o=[],a=[];for(let c=0;c<r.sampleToChunk.length;c++){let l=r.sampleToChunk[c],u=r.sampleToChunk[c+1],d=(u?u.startChunkIndex:r.chunkOffsets.length)-l.startChunkIndex;for(let f=0;f<d;f++){let p=l.startSampleIndex+f*l.samplesPerChunk,g=p+l.samplesPerChunk,y=se(r.sampleTimingEntries,p,R=>R.startIndex),w=r.sampleTimingEntries[y],b=se(r.sampleTimingEntries,g,R=>R.startIndex),T=r.sampleTimingEntries[b],S=w.startDecodeTimestamp+(p-w.startIndex)*w.delta,B=T.startDecodeTimestamp+(g-T.startIndex)*T.delta-S,I=te(o);I&&I.delta===B?I.count++:o.push({startIndex:l.startChunkIndex+f,startDecodeTimestamp:S,count:1,delta:B});let U=l.samplesPerChunk*s.sampleSize*e.info.numberOfChannels;a.push(U)}l.startSampleIndex=l.startChunkIndex,l.samplesPerChunk=1}r.sampleTimingEntries=o,r.sampleSizes=a}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(let s of r.sampleTimingEntries)for(let o=0;o<s.count;o++)r.presentationTimestamps.push({presentationTimestamp:s.startDecodeTimestamp+o*s.delta,sampleIndex:s.startIndex+o});for(let s of r.sampleCompositionTimeOffsets)for(let o=0;o<s.count;o++){let a=s.startIndex+o,c=r.presentationTimestamps[a];c&&(c.presentationTimestamp+=s.offset)}r.presentationTimestamps.sort((s,o)=>s.presentationTimestamp-o.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let s=0;s<r.presentationTimestamps.length;s++)r.presentationTimestampIndexMap[r.presentationTimestamps[s].sampleIndex]=s}return r}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let r=this.reader.requestSliceRange(e,Ve,ut);r instanceof Promise&&(r=await r),m(r);let i=dt(r);m(i?.name==="moof");let n=this.reader.requestSlice(e,i.totalSize);n instanceof Promise&&(n=await n),m(n),this.traverseBox(n);let s=this.lastReadFragment;m(s&&s.moofOffset===e);for(let[,o]of s.trackData){let a=o.track,{fragmentPositionCache:c}=a;if(!o.startTimestampIsFinal){let u=a.fragmentLookupTable.find(d=>d.moofOffset===s.moofOffset);if(u)yn(o,u.timestamp);else{let d=se(c,s.moofOffset-1,f=>f.moofOffset);if(d!==-1){let f=c[d];yn(o,f.endTimestamp)}}o.startTimestampIsFinal=!0}let l=se(c,o.startTimestamp,u=>u.startTimestamp);(l===-1||c[l].moofOffset!==s.moofOffset)&&c.splice(l+1,0,{moofOffset:s.moofOffset,startTimestamp:o.startTimestamp,endTimestamp:o.endTimestamp})}return s}readContiguousBoxes(e){let r=e.filePos;for(;e.filePos-r<=e.length-Ve&&this.traverseBox(e););}*iterateContiguousBoxes(e){let r=e.filePos;for(;e.filePos-r<=e.length-Ve;){let i=e.filePos,n=dt(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=i+n.totalSize}}traverseBox(e){var o,a,c,l,u,d,f,p,g,y,w,b,T,S,D,B,I,U,R,$,me,j,z,W,J,re,ee,Z,ae,de,Be,Oe,hr;let r=e.filePos,i=dt(e);if(!i)return!1;let n=e.filePos,s=r+i.totalSize;switch(i.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(e.slice(n,i.contentSize));break;case"mvhd":{let h=V(e);e.skip(3),h===1?(e.skip(16),this.movieTimescale=F(e),this.movieDurationInTimescale=Fe(e)):(e.skip(8),this.movieTimescale=F(e),this.movieDurationInTimescale=F(e))}break;case"trak":{let h={id:-1,demuxer:this,inputTrack:null,disposition:{...Jr},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:$e,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=h,this.readContiguousBoxes(e.slice(n,i.contentSize)),h.id!==-1&&h.timescale!==-1&&h.info!==null){if(h.info.type==="video"&&h.info.width!==-1){let _=h;h.inputTrack=new Ge(this.input,new Tn(_)),this.tracks.push(h)}else if(h.info.type==="audio"&&h.info.numberOfChannels!==-1){let _=h;h.inputTrack=new lt(this.input,new kn(_)),this.tracks.push(h)}}this.currentTrack=null}break;case"tkhd":{let h=this.currentTrack;if(!h)break;let _=V(e),C=!!(Jt(e)&1);if(h.disposition.default=C,_===0)e.skip(8),h.id=F(e),e.skip(4),h.durationInMovieTimescale=F(e);else if(_===1)e.skip(16),h.id=F(e),e.skip(4),h.durationInMovieTimescale=Fe(e);else throw new Error(`Incorrect track header version ${_}.`);e.skip(2*4+2+2+2+2);let N=[St(e),St(e),gi(e),St(e),St(e),gi(e),St(e),St(e),gi(e)],v=qt(ls(ca(N),90));m(v===0||v===90||v===180||v===270),h.rotation=v}break;case"elst":{let h=this.currentTrack;if(!h)break;let _=V(e);e.skip(3);let x=!1,C=0,N=F(e);for(let v=0;v<N;v++){let A=_===1?Fe(e):F(e),Q=_===1?eo(e):ht(e),q=St(e);if(A!==0){if(x){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(Q===-1){C+=A;continue}if(q!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}h.editListPreviousSegmentDurations=C,h.editListOffset=Q,x=!0}}}break;case"mdhd":{let h=this.currentTrack;if(!h)break;let _=V(e);e.skip(3),_===0?(e.skip(8),h.timescale=F(e),h.durationInMediaTimescale=F(e)):_===1&&(e.skip(16),h.timescale=F(e),h.durationInMediaTimescale=Fe(e));let x=Se(e);if(x>0){h.languageCode="";for(let C=0;C<3;C++)h.languageCode=String.fromCharCode(96+(x&31))+h.languageCode,x>>=5;st(h.languageCode)||(h.languageCode=$e)}}break;case"hdlr":{let h=this.currentTrack;if(!h)break;e.skip(8);let _=ft(e,4);_==="vide"?h.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:_==="soun"&&(h.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{let h=this.currentTrack;if(!h)break;h.sampleTableByteOffset=r,this.readContiguousBoxes(e.slice(n,i.contentSize))}break;case"stsd":{let h=this.currentTrack;if(!h||h.info===null||h.sampleTable)break;let _=V(e);e.skip(3);let x=F(e);for(let C=0;C<x;C++){let N=e.filePos,v=dt(e);if(!v)break;h.internalCodecId=v.name;let A=v.name.toLowerCase();if(h.info.type==="video")A==="avc1"||A==="avc3"?(h.info.codec="avc",h.info.avcType=A==="avc1"?1:3):A==="hvc1"||A==="hev1"?h.info.codec="hevc":A==="vp08"?h.info.codec="vp8":A==="vp09"?h.info.codec="vp9":A==="av01"?h.info.codec="av1":console.warn(`Unsupported video codec (sample entry type \'${v.name}\').`),e.skip(6*1+2+2+2+3*4),h.info.width=Se(e),h.info.height=Se(e),h.info.squarePixelWidth=h.info.width,h.info.squarePixelHeight=h.info.height,e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,N+v.totalSize-e.filePos));else{A==="mp4a"||(A==="opus"?h.info.codec="opus":A==="flac"?h.info.codec="flac":A==="twos"||A==="sowt"||A==="raw "||A==="in24"||A==="in32"||A==="fl32"||A==="fl64"||A==="lpcm"||A==="ipcm"||A==="fpcm"||(A==="ulaw"?h.info.codec="ulaw":A==="alaw"?h.info.codec="alaw":A==="ac-3"?h.info.codec="ac3":A==="ec-3"?h.info.codec="eac3":console.warn(`Unsupported audio codec (sample entry type \'${v.name}\').`))),e.skip(6*1+2);let Q=Se(e);e.skip(3*2);let q=Se(e),L=Se(e);e.skip(2*2);let pe=F(e)/65536;if(_===0&&Q>0){if(Q===1)e.skip(4),L=8*F(e),e.skip(2*4);else if(Q===2){e.skip(4),pe=Ti(e),q=F(e),e.skip(4),L=F(e);let ge=F(e);if(e.skip(2*4),A==="lpcm"){let K=L+7>>3,De=!!(ge&1),ne=!!(ge&2),Hi=ge&4?-1:0;L>0&&L<=64&&(De?L===32&&(h.info.codec=ne?"pcm-f32be":"pcm-f32"):Hi&1<<K-1?K===1?h.info.codec="pcm-s8":K===2?h.info.codec=ne?"pcm-s16be":"pcm-s16":K===3?h.info.codec=ne?"pcm-s24be":"pcm-s24":K===4&&(h.info.codec=ne?"pcm-s32be":"pcm-s32"):K===1&&(h.info.codec="pcm-u8")),h.info.codec===null&&console.warn("Unsupported PCM format.")}}}h.info.codec==="opus"&&(pe=ni),h.info.numberOfChannels=q,h.info.sampleRate=pe,A==="twos"?L===8?h.info.codec="pcm-s8":L===16?h.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${L} for codec \'twos\'.`),h.info.codec=null):A==="sowt"?L===8?h.info.codec="pcm-s8":L===16?h.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${L} for codec \'sowt\'.`),h.info.codec=null):A==="raw "?h.info.codec="pcm-u8":A==="in24"?h.info.codec="pcm-s24be":A==="in32"?h.info.codec="pcm-s32be":A==="fl32"?h.info.codec="pcm-f32be":A==="fl64"?h.info.codec="pcm-f64be":A==="ipcm"?h.info.codec="pcm-s16be":A==="fpcm"&&(h.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,N+v.totalSize-e.filePos))}}}break;case"avcC":{let h=this.currentTrack;if(!h)break;m(h.info),h.info.codecDescription=G(e,i.contentSize)}break;case"hvcC":{let h=this.currentTrack;if(!h)break;m(h.info),h.info.codecDescription=G(e,i.contentSize)}break;case"vpcC":{let h=this.currentTrack;if(!h)break;m(h.info?.type==="video"),e.skip(4);let _=V(e),x=V(e),C=V(e),N=C>>4,v=C>>1&7,A=C&1,Q=V(e),q=V(e),L=V(e);h.info.vp9CodecInfo={profile:_,level:x,bitDepth:N,chromaSubsampling:v,videoFullRangeFlag:A,colourPrimaries:Q,transferCharacteristics:q,matrixCoefficients:L}}break;case"av1C":{let h=this.currentTrack;if(!h)break;m(h.info?.type==="video"),e.skip(1);let _=V(e),x=_>>5,C=_&31,N=V(e),v=N>>7,A=N>>6&1,Q=N>>5&1,q=N>>4&1,L=N>>3&1,pe=N>>2&1,ge=N&3,K=x===2&&A?Q?12:10:A?10:8;h.info.av1CodecInfo={profile:x,level:C,tier:v,bitDepth:K,monochrome:q,chromaSubsamplingX:L,chromaSubsamplingY:pe,chromaSamplePosition:ge}}break;case"colr":{let h=this.currentTrack;if(!h||(m(h.info?.type==="video"),ft(e,4)!=="nclx"))break;let x=Se(e),C=Se(e),N=Se(e),v=!!(V(e)&128);h.info.colorSpace={primaries:qr[x],transfer:jr[C],matrix:$r[N],fullRange:v}}break;case"pasp":{let h=this.currentTrack;if(!h)break;m(h.info?.type==="video");let _=F(e),x=F(e);_>x?h.info.squarePixelWidth=Math.round(h.info.width*_/x):h.info.squarePixelHeight=Math.round(h.info.height*x/_)}break;case"wave":this.readContiguousBoxes(e.slice(n,i.contentSize));break;case"esds":{let h=this.currentTrack;if(!h)break;m(h.info?.type==="audio"),e.skip(4);let _=V(e);m(_===3),wi(e),e.skip(2);let x=V(e),C=(x&128)!==0,N=(x&64)!==0,v=(x&32)!==0;if(C&&e.skip(2),N){let pe=V(e);e.skip(pe)}v&&e.skip(2);let A=V(e);m(A===4);let Q=wi(e),q=e.filePos,L=V(e);if(L===64||L===103?(h.info.codec="aac",h.info.aacCodecInfo={isMpeg2:L===103,objectType:null}):L===105||L===107?h.info.codec="mp3":L===221?h.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${L}) - discarding track.`),e.skip(12),Q>e.filePos-q){let pe=V(e);m(pe===5);let ge=wi(e);if(h.info.codecDescription=G(e,ge),h.info.codec==="aac"){let K=Qt(h.info.codecDescription);K.numberOfChannels!==null&&(h.info.numberOfChannels=K.numberOfChannels),K.sampleRate!==null&&(h.info.sampleRate=K.sampleRate)}}}break;case"enda":{let h=this.currentTrack;if(!h)break;m(h.info?.type==="audio"),Se(e)&255&&(h.info.codec==="pcm-s16be"?h.info.codec="pcm-s16":h.info.codec==="pcm-s24be"?h.info.codec="pcm-s24":h.info.codec==="pcm-s32be"?h.info.codec="pcm-s32":h.info.codec==="pcm-f32be"?h.info.codec="pcm-f32":h.info.codec==="pcm-f64be"&&(h.info.codec="pcm-f64"))}break;case"pcmC":{let h=this.currentTrack;if(!h)break;m(h.info?.type==="audio"),e.skip(4);let x=!!(V(e)&1),C=V(e);h.info.codec==="pcm-s16be"?x?C===16?h.info.codec="pcm-s16":C===24?h.info.codec="pcm-s24":C===32?h.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${C}.`),h.info.codec=null):C===16?h.info.codec="pcm-s16be":C===24?h.info.codec="pcm-s24be":C===32?h.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${C}.`),h.info.codec=null):h.info.codec==="pcm-f32be"&&(x?C===32?h.info.codec="pcm-f32":C===64?h.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${C}.`),h.info.codec=null):C===32?h.info.codec="pcm-f32be":C===64?h.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${C}.`),h.info.codec=null));break}case"dOps":{let h=this.currentTrack;if(!h)break;m(h.info?.type==="audio"),e.skip(1);let _=V(e),x=Se(e),C=F(e),N=Fr(e),v=V(e),A;v!==0?A=G(e,2+_):A=new Uint8Array(0);let Q=new Uint8Array(19+A.byteLength),q=new DataView(Q.buffer);q.setUint32(0,1332770163,!1),q.setUint32(4,1214603620,!1),q.setUint8(8,1),q.setUint8(9,_),q.setUint16(10,x,!0),q.setUint32(12,C,!0),q.setInt16(16,N,!0),q.setUint8(18,v),Q.set(A,19),h.info.codecDescription=Q,h.info.numberOfChannels=_}break;case"dfLa":{let h=this.currentTrack;if(!h)break;m(h.info?.type==="audio"),e.skip(4);let _=127,x=128,C=e.filePos;for(;e.filePos<s;){let q=V(e),L=Jt(e);if((q&_)===si.STREAMINFO){e.skip(10);let ge=F(e),K=ge>>>12,De=(ge>>9&7)+1;h.info.sampleRate=K,h.info.numberOfChannels=De,e.skip(20)}else e.skip(L);if(q&x)break}let N=e.filePos;e.filePos=C;let v=G(e,N-C),A=new Uint8Array(4+v.byteLength);new DataView(A.buffer).setUint32(0,1716281667,!1),A.set(v,4),h.info.codecDescription=A}break;case"dac3":{let h=this.currentTrack;if(!h)break;m(h.info?.type==="audio");let _=G(e,3),x=new ie(_),C=x.readBits(2);x.skipBits(8);let N=x.readBits(3),v=x.readBits(1);C<3&&(h.info.sampleRate=yr[C]),h.info.numberOfChannels=hn[N]+v}break;case"dec3":{let h=this.currentTrack;if(!h)break;m(h.info?.type==="audio");let _=G(e,i.contentSize),x=Us(_);if(!x){console.warn("Invalid dec3 box contents, ignoring.");break}let C=Ns(x);C!==null&&(h.info.sampleRate=C),h.info.numberOfChannels=Vs(x)}break;case"stts":{let h=this.currentTrack;if(!h||!h.sampleTable)break;e.skip(4);let _=F(e),x=0,C=0;for(let N=0;N<_;N++){let v=F(e),A=F(e);h.sampleTable.sampleTimingEntries.push({startIndex:x,startDecodeTimestamp:C,count:v,delta:A}),x+=v,C+=v*A}}break;case"ctts":{let h=this.currentTrack;if(!h||!h.sampleTable)break;e.skip(4);let _=F(e),x=0;for(let C=0;C<_;C++){let N=F(e),v=ht(e);h.sampleTable.sampleCompositionTimeOffsets.push({startIndex:x,count:N,offset:v}),x+=N}}break;case"stsz":{let h=this.currentTrack;if(!h||!h.sampleTable)break;e.skip(4);let _=F(e),x=F(e);if(_===0)for(let C=0;C<x;C++){let N=F(e);h.sampleTable.sampleSizes.push(N)}else h.sampleTable.sampleSizes.push(_)}break;case"stz2":{let h=this.currentTrack;if(!h||!h.sampleTable)break;e.skip(4),e.skip(3);let _=V(e),x=F(e),C=G(e,Math.ceil(x*_/8)),N=new ie(C);for(let v=0;v<x;v++){let A=N.readBits(_);h.sampleTable.sampleSizes.push(A)}}break;case"stss":{let h=this.currentTrack;if(!h||!h.sampleTable)break;e.skip(4),h.sampleTable.keySampleIndices=[];let _=F(e);for(let x=0;x<_;x++){let C=F(e)-1;h.sampleTable.keySampleIndices.push(C)}h.sampleTable.keySampleIndices[0]!==0&&h.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let h=this.currentTrack;if(!h||!h.sampleTable)break;e.skip(4);let _=F(e);for(let C=0;C<_;C++){let N=F(e)-1,v=F(e),A=F(e);h.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:N,samplesPerChunk:v,sampleDescriptionIndex:A})}let x=0;for(let C=0;C<h.sampleTable.sampleToChunk.length;C++)if(h.sampleTable.sampleToChunk[C].startSampleIndex=x,C<h.sampleTable.sampleToChunk.length-1){let v=h.sampleTable.sampleToChunk[C+1].startChunkIndex-h.sampleTable.sampleToChunk[C].startChunkIndex;x+=v*h.sampleTable.sampleToChunk[C].samplesPerChunk}}break;case"stco":{let h=this.currentTrack;if(!h||!h.sampleTable)break;e.skip(4);let _=F(e);for(let x=0;x<_;x++){let C=F(e);h.sampleTable.chunkOffsets.push(C)}}break;case"co64":{let h=this.currentTrack;if(!h||!h.sampleTable)break;e.skip(4);let _=F(e);for(let x=0;x<_;x++){let C=Fe(e);h.sampleTable.chunkOffsets.push(C)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(n,i.contentSize));break;case"mehd":{let h=V(e);e.skip(3);let _=h===1?Fe(e):F(e);this.movieDurationInTimescale=_}break;case"trex":{e.skip(4);let h=F(e),_=F(e),x=F(e),C=F(e),N=F(e);this.fragmentTrackDefaults.push({trackId:h,defaultSampleDescriptionIndex:_,defaultSampleDuration:x,defaultSampleSize:C,defaultSampleFlags:N})}break;case"tfra":{let h=V(e);e.skip(3);let _=F(e),x=this.tracks.find(K=>K.id===_);if(!x)break;let C=F(e),N=(C&48)>>4,v=(C&12)>>2,A=C&3,Q=[V,Se,Jt,F],q=Q[N],L=Q[v],pe=Q[A],ge=F(e);for(let K=0;K<ge;K++){let De=h===1?Fe(e):F(e),ne=h===1?Fe(e):F(e);q(e),L(e),pe(e),x.fragmentLookupTable.push({timestamp:De,moofOffset:ne})}x.fragmentLookupTable.sort((K,De)=>K.timestamp-De.timestamp);for(let K=0;K<x.fragmentLookupTable.length-1;K++){let De=x.fragmentLookupTable[K],ne=x.fragmentLookupTable[K+1];De.timestamp===ne.timestamp&&(x.fragmentLookupTable.splice(K+1,1),K--)}}break;case"moof":this.currentFragment={moofOffset:r,moofSize:i.totalSize,implicitBaseDataOffset:r,trackData:new Map},this.readContiguousBoxes(e.slice(n,i.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(m(this.currentFragment),this.readContiguousBoxes(e.slice(n,i.contentSize)),this.currentTrack){let h=this.currentFragment.trackData.get(this.currentTrack.id);if(h){let{currentFragmentState:_}=this.currentTrack;m(_),_.startTimestamp!==null&&(yn(h,_.startTimestamp),h.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{m(this.currentFragment),e.skip(1);let h=Jt(e),_=!!(h&1),x=!!(h&2),C=!!(h&8),N=!!(h&16),v=!!(h&32),A=!!(h&65536),Q=!!(h&131072),q=F(e),L=this.tracks.find(ge=>ge.id===q);if(!L)break;let pe=this.fragmentTrackDefaults.find(ge=>ge.trackId===q);this.currentTrack=L,L.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:pe?.defaultSampleDescriptionIndex??null,defaultSampleDuration:pe?.defaultSampleDuration??null,defaultSampleSize:pe?.defaultSampleSize??null,defaultSampleFlags:pe?.defaultSampleFlags??null,startTimestamp:null},_?L.currentFragmentState.baseDataOffset=Fe(e):Q&&(L.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),x&&(L.currentFragmentState.sampleDescriptionIndex=F(e)),C&&(L.currentFragmentState.defaultSampleDuration=F(e)),N&&(L.currentFragmentState.defaultSampleSize=F(e)),v&&(L.currentFragmentState.defaultSampleFlags=F(e)),A&&(L.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let h=this.currentTrack;if(!h)break;m(h.currentFragmentState);let _=V(e);e.skip(3);let x=_===0?F(e):Fe(e);h.currentFragmentState.startTimestamp=x}break;case"trun":{let h=this.currentTrack;if(!h)break;if(m(this.currentFragment),m(h.currentFragmentState),this.currentFragment.trackData.has(h.id)){console.warn("Can\'t have two trun boxes for the same track in one fragment. Ignoring...");break}let _=V(e),x=Jt(e),C=!!(x&1),N=!!(x&4),v=!!(x&256),A=!!(x&512),Q=!!(x&1024),q=!!(x&2048),L=F(e),pe=h.currentFragmentState.baseDataOffset;C&&(pe+=ht(e));let ge=null;N&&(ge=F(e));let K=pe;if(L===0){this.currentFragment.implicitBaseDataOffset=K;break}let De=0,ne={track:h,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(h.id,ne);for(let ve=0;ve<L;ve++){let Ue;v?Ue=F(e):(m(h.currentFragmentState.defaultSampleDuration!==null),Ue=h.currentFragmentState.defaultSampleDuration);let yt;A?yt=F(e):(m(h.currentFragmentState.defaultSampleSize!==null),yt=h.currentFragmentState.defaultSampleSize);let Lt;Q?Lt=F(e):(m(h.currentFragmentState.defaultSampleFlags!==null),Lt=h.currentFragmentState.defaultSampleFlags),ve===0&&ge!==null&&(Lt=ge);let qi=0;q&&(_===0?qi=F(e):qi=ht(e));let Uo=!(Lt&65536);ne.samples.push({presentationTimestamp:De+qi,duration:Ue,byteOffset:K,byteSize:yt,isKeyFrame:Uo}),K+=yt,De+=Ue}ne.presentationTimestamps=ne.samples.map((ve,Ue)=>({presentationTimestamp:ve.presentationTimestamp,sampleIndex:Ue})).sort((ve,Ue)=>ve.presentationTimestamp-Ue.presentationTimestamp);for(let ve=0;ve<ne.presentationTimestamps.length;ve++){let Ue=ne.presentationTimestamps[ve],yt=ne.samples[Ue.sampleIndex];if(ne.firstKeyFrameTimestamp===null&&yt.isKeyFrame&&(ne.firstKeyFrameTimestamp=yt.presentationTimestamp),ve<ne.presentationTimestamps.length-1){let Lt=ne.presentationTimestamps[ve+1];yt.duration=Lt.presentationTimestamp-Ue.presentationTimestamp}}let Hi=ne.samples[ne.presentationTimestamps[0].sampleIndex],rs=ne.samples[te(ne.presentationTimestamps).sampleIndex];ne.startTimestamp=Hi.presentationTimestamp,ne.endTimestamp=rs.presentationTimestamp+rs.duration,this.currentFragment.implicitBaseDataOffset=K}break;case"udta":{let h=this.iterateContiguousBoxes(e.slice(n,i.contentSize));for(let{boxInfo:_,slice:x}of h){if(_.name!=="meta"&&!this.currentTrack){let C=x.filePos;(o=this.metadataTags).raw??(o.raw={}),_.name[0]==="\\xA9"?(a=this.metadataTags.raw)[c=_.name]??(a[c]=We(x)):(l=this.metadataTags.raw)[u=_.name]??(l[u]=G(x,_.contentSize)),x.filePos=C}switch(_.name){case"meta":x.skip(-_.headerSize),this.traverseBox(x);break;case"\\xA9nam":case"name":this.currentTrack?this.currentTrack.name=tt.decode(G(x,_.contentSize)):(d=this.metadataTags).title??(d.title=We(x));break;case"\\xA9des":this.currentTrack||((f=this.metadataTags).description??(f.description=We(x)));break;case"\\xA9ART":this.currentTrack||((p=this.metadataTags).artist??(p.artist=We(x)));break;case"\\xA9alb":this.currentTrack||((g=this.metadataTags).album??(g.album=We(x)));break;case"albr":this.currentTrack||((y=this.metadataTags).albumArtist??(y.albumArtist=We(x)));break;case"\\xA9gen":this.currentTrack||((w=this.metadataTags).genre??(w.genre=We(x)));break;case"\\xA9day":if(!this.currentTrack){let C=new Date(We(x));Number.isNaN(C.getTime())||((b=this.metadataTags).date??(b.date=C))}break;case"\\xA9cmt":this.currentTrack||((T=this.metadataTags).comment??(T.comment=We(x)));break;case"\\xA9lyr":this.currentTrack||((S=this.metadataTags).lyrics??(S.lyrics=We(x)));break}}}break;case"meta":{if(this.currentTrack)break;let _=F(e)!==0;this.currentMetadataKeys=new Map,_?this.readContiguousBoxes(e.slice(n,i.contentSize)):this.readContiguousBoxes(e.slice(n+4,i.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let h=F(e);for(let _=0;_<h;_++){let x=F(e);e.skip(4);let C=tt.decode(G(e,x-8));this.currentMetadataKeys.set(_+1,C)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let h=this.iterateContiguousBoxes(e.slice(n,i.contentSize));for(let{boxInfo:_,slice:x}of h){let C=_.name,N=(C.charCodeAt(0)<<24)+(C.charCodeAt(1)<<16)+(C.charCodeAt(2)<<8)+C.charCodeAt(3);this.currentMetadataKeys.has(N)&&(C=this.currentMetadataKeys.get(N));let v=Zs(x);switch((D=this.metadataTags).raw??(D.raw={}),(B=this.metadataTags.raw)[C]??(B[C]=v),C){case"\\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof v=="string"&&((I=this.metadataTags).title??(I.title=v));break;case"\\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof v=="string"&&((U=this.metadataTags).description??(U.description=v));break;case"\\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof v=="string"&&((R=this.metadataTags).artist??(R.artist=v));break;case"\\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof v=="string"&&(($=this.metadataTags).album??($.album=v));break;case"aART":case"album_artist":typeof v=="string"&&((me=this.metadataTags).albumArtist??(me.albumArtist=v));break;case"\\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof v=="string"&&((j=this.metadataTags).comment??(j.comment=v));break;case"\\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof v=="string"&&((z=this.metadataTags).genre??(z.genre=v));break;case"\\xA9lyr":case"lyrics":typeof v=="string"&&((W=this.metadataTags).lyrics??(W.lyrics=v));break;case"\\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof v=="string"){let A=new Date(v);Number.isNaN(A.getTime())||((J=this.metadataTags).date??(J.date=A))}break;case"covr":case"com.apple.quicktime.artwork":v instanceof Ne?((re=this.metadataTags).images??(re.images=[]),this.metadataTags.images.push({data:v.data,kind:"coverFront",mimeType:v.mimeType})):v instanceof Uint8Array&&((ee=this.metadataTags).images??(ee.images=[]),this.metadataTags.images.push({data:v,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof v=="string"){let A=v.split("/"),Q=Number.parseInt(A[0],10),q=A[1]&&Number.parseInt(A[1],10);Number.isInteger(Q)&&Q>0&&((Z=this.metadataTags).trackNumber??(Z.trackNumber=Q)),q&&Number.isInteger(q)&&q>0&&((ae=this.metadataTags).tracksTotal??(ae.tracksTotal=q))}break;case"trkn":if(v instanceof Uint8Array&&v.length>=6){let A=oe(v),Q=A.getUint16(2,!1),q=A.getUint16(4,!1);Q>0&&((de=this.metadataTags).trackNumber??(de.trackNumber=Q)),q>0&&((Be=this.metadataTags).tracksTotal??(Be.tracksTotal=q))}break;case"disc":case"disk":if(v instanceof Uint8Array&&v.length>=6){let A=oe(v),Q=A.getUint16(2,!1),q=A.getUint16(4,!1);Q>0&&((Oe=this.metadataTags).discNumber??(Oe.discNumber=Q)),q>0&&((hr=this.metadataTags).discsTotal??(hr.discsTotal=q))}break}}}break}return e.filePos=s,!0}},yi=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,i=this.internalTrack.inputTrack.type,n=0;for(let s of e.tracks)if(s.inputTrack.type===i&&n++,s===this.internalTrack)break;return n}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket(e){let r=await this.fetchPacketForSampleIndex(0,e);return r||!this.internalTrack.demuxer.isFragmented?r:this.performFragmentedLookup(null,i=>i.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Kr(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,r){let i=this.mapTimestampIntoTimescale(e),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=xn(n,i),o=await this.fetchPacketForSampleIndex(s,r);return!Js(n)||!this.internalTrack.demuxer.isFragmented?o:this.performFragmentedLookup(null,a=>{let c=a.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=se(c.presentationTimestamps,i,f=>f.presentationTimestamp),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&i<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},i,i,r)}async getNextPacket(e,r){let i=this.packetToSampleIndex.get(e);if(i!==void 0)return this.fetchPacketForSampleIndex(i+1,r);let n=this.packetToFragmentLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,s=>{if(s===n.fragment){let o=s.trackData.get(this.internalTrack.id);if(n.sampleIndex+1<o.samples.length)return{sampleIndex:n.sampleIndex+1,correctSampleFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,r)}async getKeyPacket(e,r){let i=this.mapTimestampIntoTimescale(e),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=sa(n,i),o=await this.fetchPacketForSampleIndex(s,r);return!Js(n)||!this.internalTrack.demuxer.isFragmented?o:this.performFragmentedLookup(null,a=>{let c=a.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=Qr(c.presentationTimestamps,f=>c.samples[f.sampleIndex].isKeyFrame&&f.presentationTimestamp<=i),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&i<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},i,i,r)}async getNextKeyPacket(e,r){let i=this.packetToSampleIndex.get(e);if(i!==void 0){let s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),o=aa(s,i);return this.fetchPacketForSampleIndex(o,r)}let n=this.packetToFragmentLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,s=>{if(s===n.fragment){let a=s.trackData.get(this.internalTrack.id).samples.findIndex((c,l)=>c.isKeyFrame&&l>n.sampleIndex);if(a!==-1)return{sampleIndex:a,correctSampleFound:!0}}else{let o=s.trackData.get(this.internalTrack.id);if(o&&o.firstKeyFrameTimestamp!==null){let a=o.samples.findIndex(c=>c.isKeyFrame);return m(a!==-1),{sampleIndex:a,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,r)}async fetchPacketForSampleIndex(e,r){if(e===-1)return null;let i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=oa(i,e);if(!n)return null;let s;if(r.metadataOnly)s=kt;else{let l=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);l instanceof Promise&&(l=await l),m(l),s=G(l,n.sampleSize)}let o=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=n.duration/this.internalTrack.timescale,c=new ce(s,n.isKeyFrame?"key":"delta",o,a,e,n.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,r,i){if(r===-1)return null;let s=e.trackData.get(this.internalTrack.id).samples[r];m(s);let o;if(i.metadataOnly)o=kt;else{let u=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);u instanceof Promise&&(u=await u),m(u),o=G(u,s.byteSize)}let a=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=s.duration/this.internalTrack.timescale,l=new ce(o,s.isKeyFrame?"key":"delta",a,c,e.moofOffset+r,s.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:r}),l}async performFragmentedLookup(e,r,i,n,s){let o=this.internalTrack.demuxer,a=null,c=null,l=-1;if(e){let{sampleIndex:w,correctSampleFound:b}=r(e);if(b)return this.fetchPacketInFragment(e,w,s);w!==-1&&(c=e,l=w)}let u=se(this.internalTrack.fragmentLookupTable,i,w=>w.timestamp),d=u!==-1?this.internalTrack.fragmentLookupTable[u]:null,f=se(this.internalTrack.fragmentPositionCache,i,w=>w.startTimestamp),p=f!==-1?this.internalTrack.fragmentPositionCache[f]:null,g=Math.max(d?.moofOffset??0,p?.moofOffset??0)||null,y;for(e?g===null||e.moofOffset>=g?(y=e.moofOffset+e.moofSize,a=e):y=g:y=g??0;;){if(a){let S=a.trackData.get(this.internalTrack.id);if(S&&S.startTimestamp>n)break}let w=o.reader.requestSliceRange(y,Ve,ut);if(w instanceof Promise&&(w=await w),!w)break;let b=y,T=dt(w);if(!T)break;if(T.name==="moof"){a=await o.readFragment(b);let{sampleIndex:S,correctSampleFound:D}=r(a);if(D)return this.fetchPacketInFragment(a,S,s);S!==-1&&(c=a,l=S)}y=b+T.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){let w=this.internalTrack.fragmentLookupTable[u-1];m(!w||w.timestamp<d.timestamp);let b=w?.timestamp??-1/0;return this.performFragmentedLookup(null,r,b,n,s)}return c?this.fetchPacketInFragment(c,l,s):null}},Tn=class extends yi{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??(this.decoderConfigPromise=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&ui(e.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&di(e.data)}return{codec:ri(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,displayAspectWidth:this.internalTrack.info.squarePixelWidth,displayAspectHeight:this.internalTrack.info.squarePixelHeight,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})()):null}},kn=class extends yi{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??(this.decoderConfig={codec:ii(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}):null}},xn=(t,e)=>{if(t.presentationTimestamps){let r=se(t.presentationTimestamps,e,i=>i.presentationTimestamp);return r===-1?-1:t.presentationTimestamps[r].sampleIndex}else{let r=se(t.sampleTimingEntries,e,n=>n.startDecodeTimestamp);if(r===-1)return-1;let i=t.sampleTimingEntries[r];return i.startIndex+Math.min(Math.floor((e-i.startDecodeTimestamp)/i.delta),i.count-1)}},sa=(t,e)=>{if(!t.keySampleIndices)return xn(t,e);if(t.presentationTimestamps){let r=se(t.presentationTimestamps,e,i=>i.presentationTimestamp);if(r===-1)return-1;for(let i=r;i>=0;i--){let n=t.presentationTimestamps[i].sampleIndex;if(Zi(t.keySampleIndices,n,o=>o)!==-1)return n}return-1}else{let r=xn(t,e),i=se(t.keySampleIndices,r,n=>n);return t.keySampleIndices[i]??-1}},oa=(t,e)=>{let r=se(t.sampleTimingEntries,e,b=>b.startIndex),i=t.sampleTimingEntries[r];if(!i||i.startIndex+i.count<=e)return null;let s=i.startDecodeTimestamp+(e-i.startIndex)*i.delta,o=se(t.sampleCompositionTimeOffsets,e,b=>b.startIndex),a=t.sampleCompositionTimeOffsets[o];a&&e-a.startIndex<a.count&&(s+=a.offset);let c=t.sampleSizes[Math.min(e,t.sampleSizes.length-1)],l=se(t.sampleToChunk,e,b=>b.startSampleIndex),u=t.sampleToChunk[l];m(u);let d=u.startChunkIndex+Math.floor((e-u.startSampleIndex)/u.samplesPerChunk),f=t.chunkOffsets[d],p=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk,g=0,y=f;if(t.sampleSizes.length===1)y+=c*(e-p),g+=c*u.samplesPerChunk;else for(let b=p;b<p+u.samplesPerChunk;b++){let T=t.sampleSizes[b];b<e&&(y+=T),g+=T}let w=i.delta;if(t.presentationTimestamps){let b=t.presentationTimestampIndexMap[e];m(b!==void 0),b<t.presentationTimestamps.length-1&&(w=t.presentationTimestamps[b+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:w,sampleOffset:y,sampleSize:c,chunkOffset:f,chunkSize:g,isKeyFrame:t.keySampleIndices?Zi(t.keySampleIndices,e,b=>b)!==-1:!0}},aa=(t,e)=>{if(!t.keySampleIndices)return e+1;let r=se(t.keySampleIndices,e,i=>i);return t.keySampleIndices[r+1]??-1},yn=(t,e)=>{t.startTimestamp+=e,t.endTimestamp+=e;for(let r of t.samples)r.presentationTimestamp+=e;for(let r of t.presentationTimestamps)r.presentationTimestamp+=e},ca=t=>{let[e,,,r]=t,i=Math.hypot(e,r),n=e/i,s=r/i,o=-Math.atan2(s,n)*(180/Math.PI);return Number.isFinite(o)?o:0},Js=t=>t.sampleSizes.length===0;var k;(function(t){t[t.EBML=440786851]="EBML",t[t.EBMLVersion=17030]="EBMLVersion",t[t.EBMLReadVersion=17143]="EBMLReadVersion",t[t.EBMLMaxIDLength=17138]="EBMLMaxIDLength",t[t.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",t[t.DocType=17026]="DocType",t[t.DocTypeVersion=17031]="DocTypeVersion",t[t.DocTypeReadVersion=17029]="DocTypeReadVersion",t[t.Void=236]="Void",t[t.Segment=408125543]="Segment",t[t.SeekHead=290298740]="SeekHead",t[t.Seek=19899]="Seek",t[t.SeekID=21419]="SeekID",t[t.SeekPosition=21420]="SeekPosition",t[t.Duration=17545]="Duration",t[t.Info=357149030]="Info",t[t.TimestampScale=2807729]="TimestampScale",t[t.MuxingApp=19840]="MuxingApp",t[t.WritingApp=22337]="WritingApp",t[t.Tracks=374648427]="Tracks",t[t.TrackEntry=174]="TrackEntry",t[t.TrackNumber=215]="TrackNumber",t[t.TrackUID=29637]="TrackUID",t[t.TrackType=131]="TrackType",t[t.FlagEnabled=185]="FlagEnabled",t[t.FlagDefault=136]="FlagDefault",t[t.FlagForced=21930]="FlagForced",t[t.FlagOriginal=21934]="FlagOriginal",t[t.FlagHearingImpaired=21931]="FlagHearingImpaired",t[t.FlagVisualImpaired=21932]="FlagVisualImpaired",t[t.FlagCommentary=21935]="FlagCommentary",t[t.FlagLacing=156]="FlagLacing",t[t.Name=21358]="Name",t[t.Language=2274716]="Language",t[t.LanguageBCP47=2274717]="LanguageBCP47",t[t.CodecID=134]="CodecID",t[t.CodecPrivate=25506]="CodecPrivate",t[t.CodecDelay=22186]="CodecDelay",t[t.SeekPreRoll=22203]="SeekPreRoll",t[t.DefaultDuration=2352003]="DefaultDuration",t[t.Video=224]="Video",t[t.PixelWidth=176]="PixelWidth",t[t.PixelHeight=186]="PixelHeight",t[t.DisplayWidth=21680]="DisplayWidth",t[t.DisplayHeight=21690]="DisplayHeight",t[t.DisplayUnit=21682]="DisplayUnit",t[t.AlphaMode=21440]="AlphaMode",t[t.Audio=225]="Audio",t[t.SamplingFrequency=181]="SamplingFrequency",t[t.Channels=159]="Channels",t[t.BitDepth=25188]="BitDepth",t[t.SimpleBlock=163]="SimpleBlock",t[t.BlockGroup=160]="BlockGroup",t[t.Block=161]="Block",t[t.BlockAdditions=30113]="BlockAdditions",t[t.BlockMore=166]="BlockMore",t[t.BlockAdditional=165]="BlockAdditional",t[t.BlockAddID=238]="BlockAddID",t[t.BlockDuration=155]="BlockDuration",t[t.ReferenceBlock=251]="ReferenceBlock",t[t.Cluster=524531317]="Cluster",t[t.Timestamp=231]="Timestamp",t[t.Cues=475249515]="Cues",t[t.CuePoint=187]="CuePoint",t[t.CueTime=179]="CueTime",t[t.CueTrackPositions=183]="CueTrackPositions",t[t.CueTrack=247]="CueTrack",t[t.CueClusterPosition=241]="CueClusterPosition",t[t.Colour=21936]="Colour",t[t.MatrixCoefficients=21937]="MatrixCoefficients",t[t.TransferCharacteristics=21946]="TransferCharacteristics",t[t.Primaries=21947]="Primaries",t[t.Range=21945]="Range",t[t.Projection=30320]="Projection",t[t.ProjectionType=30321]="ProjectionType",t[t.ProjectionPoseRoll=30325]="ProjectionPoseRoll",t[t.Attachments=423732329]="Attachments",t[t.AttachedFile=24999]="AttachedFile",t[t.FileDescription=18046]="FileDescription",t[t.FileName=18030]="FileName",t[t.FileMediaType=18016]="FileMediaType",t[t.FileData=18012]="FileData",t[t.FileUID=18094]="FileUID",t[t.Chapters=272869232]="Chapters",t[t.Tags=307544935]="Tags",t[t.Tag=29555]="Tag",t[t.Targets=25536]="Targets",t[t.TargetTypeValue=26826]="TargetTypeValue",t[t.TargetType=25546]="TargetType",t[t.TagTrackUID=25541]="TagTrackUID",t[t.TagEditionUID=25545]="TagEditionUID",t[t.TagChapterUID=25540]="TagChapterUID",t[t.TagAttachmentUID=25542]="TagAttachmentUID",t[t.SimpleTag=26568]="SimpleTag",t[t.TagName=17827]="TagName",t[t.TagLanguage=17530]="TagLanguage",t[t.TagString=17543]="TagString",t[t.TagBinary=17541]="TagBinary",t[t.ContentEncodings=28032]="ContentEncodings",t[t.ContentEncoding=25152]="ContentEncoding",t[t.ContentEncodingOrder=20529]="ContentEncodingOrder",t[t.ContentEncodingScope=20530]="ContentEncodingScope",t[t.ContentCompression=20532]="ContentCompression",t[t.ContentCompAlgo=16980]="ContentCompAlgo",t[t.ContentCompSettings=16981]="ContentCompSettings",t[t.ContentEncryption=20533]="ContentEncryption"})(k||(k={}));var la=[k.EBML,k.Segment],er=[k.SeekHead,k.Info,k.Cluster,k.Tracks,k.Cues,k.Attachments,k.Chapters,k.Tags],Rr=[...la,...er];var Sn=8,Ee=2,Le=2*Sn,Cn=t=>{if(t.remainingLength<1)return null;let e=V(t);if(t.skip(-1),e===0)return null;let r=1,i=128;for(;!(e&i);)r++,i>>=1;return t.remainingLength<r?null:r},tr=t=>{if(t.remainingLength<1)return null;let e=V(t);if(e===0)return null;let r=1,i=128;for(;!(e&i);)r++,i>>=1;if(t.remainingLength<r-1)return null;let n=e&i-1;for(let s=1;s<r;s++)n*=256,n+=V(t);return n},H=(t,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let r=0;for(let i=0;i<e;i++)r*=256,r+=V(t);return r},to=(t,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let r=0n;for(let i=0;i<e;i++)r<<=8n,r+=BigInt(V(t));return r};var ki=t=>{let e=Cn(t);return e===null||t.remainingLength<e?null:H(t,e)},_n=t=>{if(t.remainingLength<1)return null;if(V(t)===255)return;t.skip(-1);let r=tr(t);if(r===null)return null;if(r!==72057594037927940)return r},He=t=>{m(t.remainingLength>=Ee);let e=ki(t);if(e===null)return null;let r=_n(t);return r===null?null:{id:e,size:r}},Ct=(t,e)=>{let r=G(t,e),i=0;for(;i<e&&r[i]!==0;)i+=1;return String.fromCharCode(...r.subarray(0,i))},rr=(t,e)=>{let r=G(t,e),i=0;for(;i<e&&r[i]!==0;)i+=1;return tt.decode(r.subarray(0,i))},xi=(t,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?ro(t):Ti(t)},Si=async(t,e,r,i)=>{let n=new Set(r),s=e;for(;i===null||s<i;){let o=t.requestSliceRange(s,Ee,Le);if(o instanceof Promise&&(o=await o),!o)break;let a=He(o);if(!a)break;if(n.has(a.id))return{pos:s,found:!0};mt(a.size),s=o.filePos+a.size}return{pos:i!==null&&i>s?i:s,found:!1}},En=async(t,e,r,i)=>{let s=new Set(r),o=e;for(;o<i;){let a=t.requestSliceRange(o,0,Math.min(65536,i-o));if(a instanceof Promise&&(a=await a),!a||a.length<Sn)break;for(let c=0;c<a.length-Sn;c++){a.filePos=o;let l=ki(a);if(l!==null&&s.has(l))return o;o++}}return null},Re={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function mt(t){if(t===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}var io=t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isWebM?"webm":"x-matroska");if(t.codecStrings.length>0){let i=[...new Set(t.codecStrings.filter(Boolean))];r+=`; codecs="${i.join(", ")}"`}return r};var pt;(function(t){t[t.None=0]="None",t[t.Xiph=1]="Xiph",t[t.FixedSize=2]="FixedSize",t[t.Ebml=3]="Ebml"})(pt||(pt={}));var Ci;(function(t){t[t.Block=1]="Block",t[t.Private=2]="Private",t[t.Next=4]="Next"})(Ci||(Ci={}));var Br;(function(t){t[t.Zlib=0]="Zlib",t[t.Bzlib=1]="Bzlib",t[t.lzo1x=2]="lzo1x",t[t.HeaderStripping=3]="HeaderStripping"})(Br||(Br={}));var vn=[{id:k.SeekHead,flag:"seekHeadSeen"},{id:k.Info,flag:"infoSeen"},{id:k.Tracks,flag:"tracksSeen"},{id:k.Cues,flag:"cuesSeen"}],no=10*2**20,_i=class extends Xt{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(i=>i.computeDuration()));return Math.max(0,...r)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(r=>r.inputTrack))}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),r=await Promise.all(e.map(i=>i.getCodecParameterString()));return io({isWebM:this.isWebM,hasVideo:this.segments.some(i=>i.tracks.some(n=>n.info?.type==="video")),hasAudio:this.segments.some(i=>i.tracks.some(n=>n.info?.type==="audio")),codecStrings:r.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let r of this.segments)r.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(r),r.metadataTagsCollected=!0);let e={};for(let r of this.segments)e={...e,...r.metadataTags};return e}readMetadata(){return this.readMetadataPromise??(this.readMetadataPromise=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,Ee,Le);if(r instanceof Promise&&(r=await r),!r)break;let i=He(r);if(!i)break;let n=i.id,s=i.size,o=r.filePos;if(n===k.EBML){mt(s);let a=this.reader.requestSlice(o,s);if(a instanceof Promise&&(a=await a),!a)break;this.readContiguousElements(a)}else if(n===k.Segment){if(await this.readSegment(o,s),s===void 0||this.reader.fileSize===null)break}else if(n===k.Cluster){if(this.reader.fileSize===null)break;s===void 0&&(s=(await Si(this.reader,o,Rr,this.reader.fileSize)).pos-o);let a=te(this.segments);a&&(a.elementEndPos=o+s)}mt(s),e=o+s}})())}async readSegment(e,r){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:r===void 0?null:e+r,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let i=e;for(;this.currentSegment.elementEndPos===null||i<this.currentSegment.elementEndPos;){let a=this.reader.requestSliceRange(i,Ee,Le);if(a instanceof Promise&&(a=await a),!a)break;let c=i,l=He(a);if(!l||!er.includes(l.id)&&l.id!==k.Void){let g=await En(this.reader,c,er,Math.min(this.currentSegment.elementEndPos??1/0,c+no));if(g){i=g;continue}else break}let{id:u,size:d}=l,f=a.filePos,p=vn.findIndex(g=>g.id===u);if(p!==-1){let g=vn[p].flag;this.currentSegment[g]=!0,mt(d);let y=this.reader.requestSlice(f,d);y instanceof Promise&&(y=await y),y&&this.readContiguousElements(y)}else if(u===k.Tags||u===k.Attachments){u===k.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,mt(d);let g=this.reader.requestSlice(f,d);g instanceof Promise&&(g=await g),g&&this.readContiguousElements(g)}else if(u===k.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(d===void 0)break;i=f+d}if(this.currentSegment.seekEntries.sort((a,c)=>a.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(let a of this.currentSegment.seekEntries){let c=vn.find(g=>g.id===a.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+a.segmentPosition,Ee,Le);if(l instanceof Promise&&(l=await l),!l)continue;let u=He(l);if(!u)continue;let{id:d,size:f}=u;if(d!==c.id)continue;mt(f),this.currentSegment[c.flag]=!0;let p=this.reader.requestSlice(l.filePos,f);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(let a of this.currentSegment.tracks)a.defaultDurationNs!==null&&(a.defaultDuration=this.currentSegment.timestampFactor*a.defaultDurationNs/1e9);this.currentSegment.tracks.sort((a,c)=>Number(c.disposition.default)-Number(a.disposition.default));let n=new Map(this.currentSegment.tracks.map(a=>[a.id,a]));for(let a of this.currentSegment.cuePoints){let c=n.get(a.trackId);c&&c.cuePoints.push(a)}for(let a of this.currentSegment.tracks){a.cuePoints.sort((c,l)=>c.time-l.time);for(let c=0;c<a.cuePoints.length-1;c++){let l=a.cuePoints[c],u=a.cuePoints[c+1];l.time===u.time&&(a.cuePoints.splice(c+1,1),c--)}}let s=null,o=-1/0;for(let a of this.currentSegment.tracks)a.cuePoints.length>o&&(o=a.cuePoints.length,s=a);for(let a of this.currentSegment.tracks)a.cuePoints.length===0&&(a.cuePoints=s.cuePoints);this.currentSegment=null}async readCluster(e,r){if(r.lastReadCluster?.elementStartPos===e)return r.lastReadCluster;let i=this.reader.requestSliceRange(e,Ee,Le);i instanceof Promise&&(i=await i),m(i);let n=e,s=He(i);m(s);let o=s.id;m(o===k.Cluster);let a=s.size,c=i.filePos;a===void 0&&(a=(await Si(this.reader,c,Rr,r.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,a);l instanceof Promise&&(l=await l);let u={segment:r,elementStartPos:n,elementEndPos:c+a,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){let d=this.readContiguousElements(l,Rr);u.elementEndPos=d}for(let[,d]of u.trackData){let f=d.track;m(d.blocks.length>0);let p=!1;for(let b=0;b<d.blocks.length;b++){let T=d.blocks[b];T.timestamp+=u.timestamp,p||(p=T.lacing!==pt.None)}d.presentationTimestamps=d.blocks.map((b,T)=>({timestamp:b.timestamp,blockIndex:T})).sort((b,T)=>b.timestamp-T.timestamp);for(let b=0;b<d.presentationTimestamps.length;b++){let T=d.presentationTimestamps[b],S=d.blocks[T.blockIndex];if(d.firstKeyFrameTimestamp===null&&S.isKeyFrame&&(d.firstKeyFrameTimestamp=S.timestamp),b<d.presentationTimestamps.length-1){let D=d.presentationTimestamps[b+1];S.duration=D.timestamp-S.timestamp}else S.duration===0&&f.defaultDuration!=null&&S.lacing===pt.None&&(S.duration=f.defaultDuration)}p&&(this.expandLacedBlocks(d.blocks,f),d.presentationTimestamps=d.blocks.map((b,T)=>({timestamp:b.timestamp,blockIndex:T})).sort((b,T)=>b.timestamp-T.timestamp));let g=d.blocks[d.presentationTimestamps[0].blockIndex],y=d.blocks[te(d.presentationTimestamps).blockIndex];d.startTimestamp=g.timestamp,d.endTimestamp=y.timestamp+y.duration;let w=se(f.clusterPositionCache,d.startTimestamp,b=>b.startTimestamp);(w===-1||f.clusterPositionCache[w].elementStartPos!==n)&&f.clusterPositionCache.splice(w+1,0,{elementStartPos:u.elementStartPos,startTimestamp:d.startTimestamp})}return r.lastReadCluster=u,u}getTrackDataInCluster(e,r){let i=e.trackData.get(r);if(!i){let n=e.segment.tracks.find(s=>s.id===r);if(!n)return null;i={track:n,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(r,i)}return i}expandLacedBlocks(e,r){for(let i=0;i<e.length;i++){let n=e[i];if(n.lacing===pt.None)continue;n.decoded||(n.data=this.decodeBlockData(r,n.data),n.decoded=!0);let s=gt.tempFromBytes(n.data),o=[],a=V(s)+1;switch(n.lacing){case pt.Xiph:{let l=0;for(let u=0;u<a-1;u++){let d=0;for(;s.bufferPos<s.length;){let f=V(s);if(d+=f,f<255){o.push(d),l+=d;break}}}o.push(s.length-(s.bufferPos+l))}break;case pt.FixedSize:{let l=s.length-1,u=Math.floor(l/a);for(let d=0;d<a;d++)o.push(u)}break;case pt.Ebml:{let l=tr(s);m(l!==null);let u=l;o.push(u);let d=u;for(let f=1;f<a-1;f++){let p=s.bufferPos,g=tr(s);m(g!==null);let y=g,b=(1<<(s.bufferPos-p)*7-1)-1,T=y-b;u+=T,o.push(u),d+=u}o.push(s.length-(s.bufferPos+d))}break;default:m(!1)}m(o.length===a),e.splice(i,1);let c=n.duration||a*(r.defaultDuration??0);for(let l=0;l<a;l++){let u=o[l],d=G(s,u),f=n.timestamp+c*l/a,p=c/a;e.splice(i+l,0,{timestamp:f,duration:p,isKeyFrame:n.isKeyFrame,data:d,lacing:pt.None,decoded:!0,mainAdditional:n.mainAdditional})}i+=a,i--}}async loadSegmentMetadata(e){for(let r of e.seekEntries){if(!(r.id===k.Tags&&!e.tagsSeen)){if(!(r.id===k.Attachments&&!e.attachmentsSeen))continue}let i=this.reader.requestSliceRange(e.dataStartPos+r.segmentPosition,Ee,Le);if(i instanceof Promise&&(i=await i),!i)continue;let n=He(i);if(!n||n.id!==r.id)continue;let{size:s}=n;mt(s),m(!this.currentSegment),this.currentSegment=e;let o=this.reader.requestSlice(i.filePos,s);o instanceof Promise&&(o=await o),o&&this.readContiguousElements(o),this.currentSegment=null,r.id===k.Tags?e.tagsSeen=!0:r.id===k.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,r){for(;e.remainingLength>=Ee;){let i=e.filePos;if(!this.traverseElement(e,r))return i}return e.filePos}traverseElement(e,r){let i=He(e);if(!i||r&&r.includes(i.id))return!1;let{id:n,size:s}=i,o=e.filePos;switch(mt(s),n){case k.DocType:this.isWebM=Ct(e,s)==="webm";break;case k.Seek:{if(!this.currentSegment)break;let a={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(a),this.readContiguousElements(e.slice(o,s)),(a.id===-1||a.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case k.SeekID:{let a=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!a)break;a.id=H(e,s)}break;case k.SeekPosition:{let a=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!a)break;a.segmentPosition=H(e,s)}break;case k.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=H(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case k.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=xi(e,s)}break;case k.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...Jr},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:$e,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(o,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(a=>a.data?.type!=="decompress"||a.scope!==Ci.Block||a.data.algorithm!==Br.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let a=this.currentTrack.codecId.indexOf("/"),c=a===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,a);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){let d=this.currentTrack.info.displayWidth*this.currentTrack.info.height,f=this.currentTrack.info.displayHeight*this.currentTrack.info.width;d>f?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*d/f):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*f/d)}this.currentTrack.codecId===Re.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Re.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Re.vp8?this.currentTrack.info.codec="vp8":c===Re.vp9?this.currentTrack.info.codec="vp9":c===Re.av1&&(this.currentTrack.info.codec="av1");let l=this.currentTrack,u=new Ge(this.input,new Pn(l));this.currentTrack.inputTrack=u,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){c===Re.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Re.mp3?this.currentTrack.info.codec="mp3":c===Re.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=ni):c===Re.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Re.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Re.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Re.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));let l=this.currentTrack,u=new lt(this.input,new An(l));this.currentTrack.inputTrack=u,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case k.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=H(e,s)}break;case k.TrackType:{if(!this.currentTrack)break;let a=H(e,s);a===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:a===2&&(this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case k.FlagEnabled:{if(!this.currentTrack)break;H(e,s)||(this.currentTrack=null)}break;case k.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!H(e,s)}break;case k.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!H(e,s)}break;case k.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!H(e,s)}break;case k.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!H(e,s)}break;case k.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!H(e,s)}break;case k.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!H(e,s)}break;case k.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=Ct(e,s)}break;case k.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=G(e,s)}break;case k.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=H(e,s)}break;case k.Name:{if(!this.currentTrack)break;this.currentTrack.name=rr(e,s)}break;case k.Language:{if(!this.currentTrack||this.currentTrack.languageCode!==$e)break;this.currentTrack.languageCode=Ct(e,s),st(this.currentTrack.languageCode)||(this.currentTrack.languageCode=$e)}break;case k.LanguageBCP47:{if(!this.currentTrack)break;let c=Ct(e,s).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=$e}break;case k.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(o,s))}break;case k.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=H(e,s)}break;case k.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=H(e,s)}break;case k.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=H(e,s)}break;case k.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=H(e,s)}break;case k.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=H(e,s)}break;case k.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=H(e,s)===1}break;case k.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(o,s))}break;case k.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=H(e,s),c=$r[a]??null;this.currentTrack.info.colorSpace.matrix=c}break;case k.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=H(e,s)===2}break;case k.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=H(e,s),c=jr[a]??null;this.currentTrack.info.colorSpace.transfer=c}break;case k.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=H(e,s),c=qr[a]??null;this.currentTrack.info.colorSpace.primaries=c}break;case k.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(o,s))}break;case k.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let c=-xi(e,s);try{this.currentTrack.info.rotation=qt(c)}catch{}}break;case k.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(o,s))}break;case k.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=xi(e,s)}break;case k.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=H(e,s)}break;case k.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=H(e,s)}break;case k.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(o,s)),this.currentCueTime=null}break;case k.CueTime:this.currentCueTime=H(e,s);break;case k.CueTrackPositions:{if(this.currentCueTime===null)break;m(this.currentSegment);let a={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(a),this.readContiguousElements(e.slice(o,s)),(a.trackId===-1||a.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case k.CueTrack:{let a=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!a)break;a.trackId=H(e,s)}break;case k.CueClusterPosition:{let a=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!a)break;m(this.currentSegment),a.clusterPosition=this.currentSegment.dataStartPos+H(e,s)}break;case k.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=H(e,s)}break;case k.SimpleBlock:{if(!this.currentCluster)break;let a=tr(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let l=Fr(e),u=V(e),d=u>>1&3,f=!!(u&128);c.track.info?.type==="audio"&&c.track.info.codec&&(f=!0);let p=G(e,s-(e.filePos-o)),g=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:f,data:p,lacing:d,decoded:!g,mainAdditional:null})}break;case k.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(o,s)),this.currentBlock=null}break;case k.Block:{if(!this.currentCluster)break;let a=tr(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let l=Fr(e),d=V(e)>>1&3,f=G(e,s-(e.filePos-o)),p=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:f,lacing:d,decoded:!p,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case k.BlockAdditions:this.readContiguousElements(e.slice(o,s));break;case k.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(o,s)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case k.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=G(e,s)}break;case k.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=H(e,s)}break;case k.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=H(e,s)}break;case k.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case k.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(o,s));break;case k.Targets:this.readContiguousElements(e.slice(o,s));break;case k.TargetTypeValue:H(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case k.TagTrackUID:case k.TagEditionUID:case k.TagChapterUID:case k.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case k.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(o,s))}break;case k.TagName:this.currentSimpleTagName=rr(e,s);break;case k.TagString:{if(!this.currentSimpleTagName)break;let a=rr(e,s);this.processTagValue(this.currentSimpleTagName,a)}break;case k.TagBinary:{if(!this.currentSimpleTagName)break;let a=G(e,s);this.processTagValue(this.currentSimpleTagName,a)}break;case k.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(o,s));let a=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(a.raw??(a.raw={}),a.raw[this.currentAttachedFile.fileUid.toString()]=new pr(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let c=this.currentAttachedFile.fileName,l="unknown";if(c){let u=c.toLowerCase();u.startsWith("cover.")?l="coverFront":u.startsWith("back.")&&(l="coverBack")}a.images??(a.images=[]),a.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:l,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case k.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=to(e,s)}break;case k.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=rr(e,s)}break;case k.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Ct(e,s)}break;case k.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=G(e,s)}break;case k.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=rr(e,s)}break;case k.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(o,s)),this.currentTrack.decodingInstructions.sort((a,c)=>c.order-a.order)}break;case k.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Ci.Block,data:null},this.readContiguousElements(e.slice(o,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case k.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=H(e,s)}break;case k.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=H(e,s)}break;case k.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Br.Zlib,settings:null},this.readContiguousElements(e.slice(o,s))}break;case k.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=H(e,s)}break;case k.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=G(e,s)}break;case k.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=o+s,!0}decodeBlockData(e,r){m(e.decodingInstructions.length>0);let i=r;for(let n of e.decodingInstructions)switch(m(n.data),n.data.type){case"decompress":switch(n.data.algorithm){case Br.HeaderStripping:if(n.data.settings&&n.data.settings.length>0){let s=n.data.settings,o=new Uint8Array(s.length+i.length);o.set(s,0),o.set(i,s.length),i=o}break;default:}break;default:}return i}processTagValue(e,r){var n;if(!this.currentSegment?.metadataTags)return;let i=this.currentSegment.metadataTags;if(i.raw??(i.raw={}),(n=i.raw)[e]??(n[e]=r),typeof r=="string")switch(e.toLowerCase()){case"title":i.title??(i.title=r);break;case"description":i.description??(i.description=r);break;case"artist":i.artist??(i.artist=r);break;case"album":i.album??(i.album=r);break;case"album_artist":i.albumArtist??(i.albumArtist=r);break;case"genre":i.genre??(i.genre=r);break;case"comment":i.comment??(i.comment=r);break;case"lyrics":i.lyrics??(i.lyrics=r);break;case"date":{let s=new Date(r);Number.isNaN(s.getTime())||(i.date??(i.date=s))}break;case"track_number":case"part_number":{let s=r.split("/"),o=Number.parseInt(s[0],10),a=s[1]&&Number.parseInt(s[1],10);Number.isInteger(o)&&o>0&&(i.trackNumber??(i.trackNumber=o)),a&&Number.isInteger(a)&&a>0&&(i.tracksTotal??(i.tracksTotal=a))}break;case"disc_number":case"disc":{let s=r.split("/"),o=Number.parseInt(s[0],10),a=s[1]&&Number.parseInt(s[1],10);Number.isInteger(o)&&o>0&&(i.discNumber??(i.discNumber=o)),a&&Number.isInteger(a)&&a>0&&(i.discsTotal??(i.discsTotal=a))}break}}},Ei=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,i=this.internalTrack.inputTrack.type,n=0;for(let s of e.segments)for(let o of s.tracks)if(o.inputTrack.type===i&&n++,o===this.internalTrack)break;return n}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket(e){return this.performClusterLookup(null,r=>r.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Kr(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,r){let i=this.intoTimescale(e);return this.performClusterLookup(null,n=>{let s=n.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};let o=se(s.presentationTimestamps,i,l=>l.timestamp),a=o!==-1?s.presentationTimestamps[o].blockIndex:-1,c=o!==-1&&i<s.endTimestamp;return{blockIndex:a,correctBlockFound:c}},i,i,r)}async getNextPacket(e,r){let i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,n=>{if(n===i.cluster){let s=n.trackData.get(this.internalTrack.id);if(i.blockIndex+1<s.blocks.length)return{blockIndex:i.blockIndex+1,correctBlockFound:!0}}else if(n.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,r)}async getKeyPacket(e,r){let i=this.intoTimescale(e);return this.performClusterLookup(null,n=>{let s=n.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};let o=Qr(s.presentationTimestamps,l=>s.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=i),a=o!==-1?s.presentationTimestamps[o].blockIndex:-1,c=o!==-1&&i<s.endTimestamp;return{blockIndex:a,correctBlockFound:c}},i,i,r)}async getNextKeyPacket(e,r){let i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,n=>{if(n===i.cluster){let o=n.trackData.get(this.internalTrack.id).blocks.findIndex((a,c)=>a.isKeyFrame&&c>i.blockIndex);if(o!==-1)return{blockIndex:o,correctBlockFound:!0}}else{let s=n.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){let o=s.blocks.findIndex(a=>a.isKeyFrame);return m(o!==-1),{blockIndex:o,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,r)}async fetchPacketInCluster(e,r,i){if(r===-1)return null;let s=e.trackData.get(this.internalTrack.id).blocks[r];m(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0);let o=i.metadataOnly?kt:s.data,a=s.timestamp/this.internalTrack.segment.timestampFactor,c=s.duration/this.internalTrack.segment.timestampFactor,l={};s.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=i.metadataOnly?kt:s.mainAdditional,l.alphaByteLength=s.mainAdditional.byteLength);let u=new ce(o,s.isKeyFrame?"key":"delta",a,c,e.dataStartPos+r,s.data.byteLength,l);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:r}),u}async performClusterLookup(e,r,i,n,s){let{demuxer:o,segment:a}=this.internalTrack,c=null,l=null,u=-1;if(e){let{blockIndex:b,correctBlockFound:T}=r(e);if(T)return this.fetchPacketInCluster(e,b,s);b!==-1&&(l=e,u=b)}let d=se(this.internalTrack.cuePoints,i,b=>b.time),f=d!==-1?this.internalTrack.cuePoints[d]:null,p=se(this.internalTrack.clusterPositionCache,i,b=>b.startTimestamp),g=p!==-1?this.internalTrack.clusterPositionCache[p]:null,y=Math.max(f?.clusterPosition??0,g?.elementStartPos??0)||null,w;for(e?y===null||e.elementStartPos>=y?(w=e.elementEndPos,c=e):w=y:w=y??a.clusterSeekStartPos;a.elementEndPos===null||w<=a.elementEndPos-Ee;){if(c){let R=c.trackData.get(this.internalTrack.id);if(R&&R.startTimestamp>n)break}let b=o.reader.requestSliceRange(w,Ee,Le);if(b instanceof Promise&&(b=await b),!b)break;let T=w,S=He(b);if(!S||!er.includes(S.id)&&S.id!==k.Void){let R=await En(o.reader,T,er,Math.min(a.elementEndPos??1/0,T+no));if(R){w=R;continue}else break}let D=S.id,B=S.size,I=b.filePos;if(D===k.Cluster){c=await o.readCluster(T,a),B=c.elementEndPos-I;let{blockIndex:R,correctBlockFound:$}=r(c);if($)return this.fetchPacketInCluster(c,R,s);R!==-1&&(l=c,u=R)}B===void 0&&(m(D!==k.Cluster),B=(await Si(o.reader,I,Rr,a.elementEndPos)).pos-I);let U=I+B;if(a.elementEndPos===null){let R=o.reader.requestSliceRange(U,Ee,Le);if(R instanceof Promise&&(R=await R),!R)break;if(ki(R)===k.Segment){a.elementEndPos=U;break}}w=U}if(f&&(!l||l.elementStartPos<f.clusterPosition)){let b=this.internalTrack.cuePoints[d-1];m(!b||b.time<f.time);let T=b?.time??-1/0;return this.performClusterLookup(null,r,T,n,s)}return l?this.fetchPacketInCluster(l,u,s):null}},Pn=class extends Ei{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??(this.decoderConfigPromise=(async()=>{let e=null;return(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({})),{codec:ri({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?ci(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?li(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?ui(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?di(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,displayAspectWidth:this.internalTrack.info.squarePixelWidth,displayAspectHeight:this.internalTrack.info.squarePixelHeight,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})()):null}},An=class extends Ei{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??(this.decoderConfig={codec:ii({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}):null}};var so=7,oo=9,In=t=>{let e=t.filePos,r=G(t,9),i=new ie(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===15)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 u=i.readBits(13);i.skipBits(11);let d=i.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let f=null;return o===1?t.filePos-=2:f=i.readBits(16),{objectType:a,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:u,numberOfAacFrames:d,crcCheck:f,startPos:e}};var Ut=class{},Dr=class extends Ut{async _getMajorBrand(e){let r=e._reader.requestSlice(0,12);return r instanceof Promise&&(r=await r),!r||(r.skip(4),ft(r,4)!=="ftyp")?null:ft(r,4)}_createDemuxer(e){return new bi(e)}},vi=class extends Dr{async _canReadInput(e){let r=await this._getMajorBrand(e);return!!r&&r!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},Pi=class extends Dr{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},Ai=class extends Ut{async isSupportedEBMLOfDocType(e,r){let i=e._reader.requestSlice(0,Le);if(i instanceof Promise&&(i=await i),!i)return!1;let n=Cn(i);if(n===null||n<1||n>8||H(i,n)!==k.EBML)return!1;let o=_n(i);if(typeof o!="number")return!1;let a=e._reader.requestSlice(i.filePos,o);if(a instanceof Promise&&(a=await a),!a)return!1;let c=i.filePos;for(;a.filePos<=c+o-Ee;){let l=He(a);if(!l)break;let{id:u,size:d}=l,f=a.filePos;if(d===void 0)return!1;switch(u){case k.EBMLVersion:if(H(a,d)!==1)return!1;break;case k.EBMLReadVersion:if(H(a,d)!==1)return!1;break;case k.DocType:if(Ct(a,d)!==r)return!1;break;case k.DocTypeVersion:if(H(a,d)>4)return!1;break}a.filePos=f+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new _i(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},Ii=class extends Ai{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}};var Fn=new vi,Rn=new Pi;var Bn=new Ii;var ir=class{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new be;return this._sizePromise??(this._sizePromise=Promise.resolve(this._retrieveSize()))}async getSize(){if(this._disposed)throw new be;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}};var ao=.5*2**20,ua=(t,e,r)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))){let n=null;try{typeof window<"u"&&typeof window.location<"u"&&(n=new URL(r instanceof Request?r.url:r,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&n!==null&&n!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the \'getRetryDelay\' option."),null}return Math.min(2**(t-2),16)},nr=class extends ir{constructor(e,r={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.requestInit!==void 0&&(!r.requestInit||typeof r.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(r.getRetryDelay!==void 0&&typeof r.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(r.maxCacheSize!==void 0&&(!Zr(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(r.parallelism!==void 0&&(!Number.isInteger(r.parallelism)||r.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(r.fetchFn!==void 0&&typeof r.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");super(),this._existingResponses=new WeakMap,this._url=e,this._options=r,this._getRetryDelay=r.getRetryDelay??ua;let i=2;this._orchestrator=new Dn({maxCacheSize:r.maxCacheSize??64*2**20,maxWorkerCount:r.parallelism??i,runWorker:this._runWorker.bind(this),prefetchProfile:da.network})}async _retrieveSize(){let e=new AbortController,r=await rn(this._options.fetchFn??fetch,this._url,tn(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:e.signal}),this._getRetryDelay,()=>this._disposed);if(!r.ok)throw new Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);let i,n;if(r.status===206)n=this._getTotalLengthFromRangeResponse(r),i=this._orchestrator.createWorker(0,Math.min(n,ao));else{let s=r.headers.get("Content-Length");if(s)n=Number(s),i=this._orchestrator.createWorker(0,n),this._orchestrator.options.maxCacheSize=1/0,console.warn("HTTP server did not respond with 206 Partial Content, meaning the entire remote resource now has to be downloaded. For efficient media file streaming across a network, please make sure your server supports range requests.");else throw new Error(`HTTP response (status ${r.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=n,this._existingResponses.set(i,{response:r,abortController:e}),this._orchestrator.runWorker(i),n}_read(e,r){return this._orchestrator.read(e,r)}async _runWorker(e){for(;;){let r=this._existingResponses.get(e);this._existingResponses.delete(e);let i=r?.abortController,n=r?.response;if(i||(i=new AbortController,n=await rn(this._options.fetchFn??fetch,this._url,tn(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:i.signal}),this._getRetryDelay,()=>this._disposed)),m(n),!n.ok)throw new Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);if(e.currentPos>0&&n.status!==206)throw new Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!n.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let s=n.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){i.abort(),e.running=!1;return}let o;try{o=await s.read()}catch(l){if(this._disposed)throw l;let u=this._getRetryDelay(1,l,this._url);if(u!==null){console.error("Error while reading response stream. Attempting to resume.",l),await new Promise(d=>setTimeout(d,1e3*u));break}else throw l}if(e.aborted)continue;let{done:a,value:c}=o;if(a){if(e.currentPos>=e.targetPos){this._orchestrator.forgetWorker(e),e.running=!1;return}break}this.onread?.(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}}}_getTotalLengthFromRangeResponse(e){let r=e.headers.get("Content-Range");if(r){let n=/\\/(\\d+)/.exec(r);if(n)return Number(n[1])}let i=e.headers.get("Content-Length");if(i)return Number(i);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}};var da={none:(t,e)=>({start:t,end:e}),fileSystem:(t,e)=>(t=Math.floor((t-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:t,end:e}),network:(t,e,r)=>{t=Math.max(0,Math.floor((t-65536)/65536)*65536);for(let n of r){let o=Math.max((n.startPos+n.targetPos)/2,n.targetPos-8388608);if(Xr(t,e,o,n.targetPos)){let a=n.targetPos-n.startPos,c=Math.ceil((a+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(a+1)),u=Math.min(l,c);e=Math.max(e,n.startPos+u)}}return e=Math.max(e,t+ao),{start:t,end:e}}},Dn=class{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,r){m(this.fileSize!==null);let i=this.options.prefetchProfile(e,r,this.workers),n=Math.max(i.start,0),s=Math.min(i.end,this.fileSize);m(n<=e&&r<=s);let o=null,a=se(this.cache,e,T=>T.start),c=a!==-1?this.cache[a]:null;c&&c.start<=e&&r<=c.end&&(c.age=this.nextAge++,o={bytes:c.bytes,view:c.view,offset:c.start});let l=se(this.cache,n,T=>T.start),u=o?null:new Uint8Array(r-e),d=0,f=n,p=[];if(l!==-1){for(let T=l;T<this.cache.length;T++){let S=this.cache[T];if(S.start>=s)break;if(S.end<=n)continue;let D=Math.max(n,S.start),B=Math.min(s,S.end);if(m(D<=B),f<D&&p.push({start:f,end:D}),f=B,u){let I=Math.max(e,S.start),U=Math.min(r,S.end);if(I<U){let R=I-e;u.set(S.bytes.subarray(I-S.start,U-S.start),R),R===d&&(d=U-e)}}S.age=this.nextAge++}f<s&&p.push({start:f,end:s})}else p.push({start:n,end:s});if(u&&d>=u.length&&(o={bytes:u,view:oe(u),offset:e}),p.length===0)return m(o),o;let{promise:g,resolve:y,reject:w}=he(),b=[];for(let T of p){let S=Math.max(e,T.start),D=Math.min(r,T.end);S===T.start&&D===T.end?b.push(T):S<D&&b.push({start:S,end:D})}for(let T of p){let S=u&&{start:e,bytes:u,holes:b,resolve:y,reject:w},D=!1;for(let B of this.workers)if(Xr(T.start-131072,T.start,B.currentPos,B.targetPos)){B.targetPos=Math.max(B.targetPos,T.end),D=!0,S&&!B.pendingSlices.includes(S)&&B.pendingSlices.push(S),B.running||this.runWorker(B);break}if(!D){let B=this.createWorker(T.start,T.end);S&&(B.pendingSlices=[S]),this.runWorker(B)}}return o||(m(u),o=g.then(T=>({bytes:T,view:oe(T),offset:e}))),o}createWorker(e,r){let i={startPos:e,currentPos:e,targetPos:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(i);this.workers.length>this.options.maxWorkerCount;){let n=0,s=this.workers[0];for(let o=1;o<this.workers.length;o++){let a=this.workers[o];a.age<s.age&&(n=o,s=a)}if(s.running&&s.pendingSlices.length>0)break;s.aborted=!0,this.workers.splice(n,1)}return i}runWorker(e){m(!e.running),m(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(r=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(i=>i.reject(r)),e.pendingSlices.length=0;else throw r})}supplyWorkerData(e,r){m(!e.aborted);let i=e.currentPos,n=i+r.length;this.insertIntoCache({start:i,end:n,bytes:r,view:oe(r),age:this.nextAge++}),e.currentPos+=r.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let s=0;s<e.pendingSlices.length;s++){let o=e.pendingSlices[s],a=Math.max(i,o.start),c=Math.min(n,o.start+o.bytes.length);a<c&&o.bytes.set(r.subarray(a-i,c-i),a-o.start);for(let l=0;l<o.holes.length;l++){let u=o.holes[l];i<=u.start&&n>u.start&&(u.start=n),u.end<=u.start&&(o.holes.splice(l,1),l--)}o.holes.length===0&&(o.resolve(o.bytes),e.pendingSlices.splice(s,1),s--)}for(let s=0;s<this.workers.length;s++){let o=this.workers[s];e===o||o.running||Xr(i,n,o.currentPos,o.targetPos)&&(this.workers.splice(s,1),s--)}}forgetWorker(e){let r=this.workers.indexOf(e);m(r!==-1),this.workers.splice(r,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let r=se(this.cache,e.start,i=>i.start)+1;if(r>0){let i=this.cache[r-1];if(i.end>=e.end)return;if(i.end>e.start){let n=new Uint8Array(e.end-i.start);n.set(i.bytes,0),n.set(e.bytes,e.start-i.start),this.currentCacheSize+=e.end-i.end,i.bytes=n,i.view=oe(n),i.end=e.end,r--,e=i}else this.cache.splice(r,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(r,0,e),this.currentCacheSize+=e.bytes.length;for(let i=r+1;i<this.cache.length;i++){let n=this.cache[i];if(e.end<=n.start)break;if(e.end>=n.end){this.cache.splice(i,1),this.currentCacheSize-=n.bytes.length,i--;continue}let s=new Uint8Array(n.end-e.start);s.set(e.bytes,0),s.set(n.bytes,n.start-e.start),this.currentCacheSize-=e.end-n.start,e.bytes=s,e.view=oe(s),e.end=n.end,this.cache.splice(i,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let i=0,n=this.cache[0];for(let s=1;s<this.cache.length;s++){let o=this.cache[s];o.age<n.age&&(i=s,n=o)}if(this.currentCacheSize-n.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(i,1),this.currentCacheSize-=n.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}};Yr();var _t=class{get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(r=>!(r instanceof Ut)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof ir))throw new TypeError("options.source must be a Source.");if(e.source._disposed)throw new Error("options.source must not be disposed.");this._formats=e.formats,this._source=e.source,this._reader=new Fi(e.source)}_getDemuxer(){return this._demuxerPromise??(this._demuxerPromise=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw new Error("Input has an unsupported or unrecognizable format.")})())}get source(){return this._source}async getFormat(){return await this._getDemuxer(),m(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getFirstTimestamp(){let e=await this.getTracks();if(e.length===0)return 0;let r=await Promise.all(e.map(i=>i.getFirstTimestamp()));return Math.min(...r)}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(r=>r.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(r=>r.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(r=>r.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(r=>r.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){this._disposed||(this._disposed=!0,this._source._disposed=!0,this._source._dispose())}[Symbol.dispose](){this.dispose()}},be=class extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}};var Fi=class{constructor(e){this.source=e}requestSlice(e,r){if(this.source._disposed)throw new be;if(e<0||this.fileSize!==null&&e+r>this.fileSize)return null;let i=e+r,n=this.source._read(e,i);return n instanceof Promise?n.then(s=>s?new gt(s.bytes,s.view,s.offset,e,i):null):n?new gt(n.bytes,n.view,n.offset,e,i):null}requestSliceRange(e,r,i){if(this.source._disposed)throw new be;if(e<0)return null;if(this.fileSize!==null)return this.requestSlice(e,fe(this.fileSize-e,r,i));{let n=this.requestSlice(e,i),s=o=>{if(o)return o;let a=l=>(m(l!==null),this.requestSlice(e,fe(l-e,r,i))),c=this.source._retrieveSize();return c instanceof Promise?c.then(a):a(c)};return n instanceof Promise?n.then(s):s(n)}}},gt=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,oe(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)}},Ye=(t,e)=>{if(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.`)},G=(t,e)=>{Ye(t,e);let r=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,r},V=t=>(Ye(t,1),t.view.getUint8(t.bufferPos++));var Se=t=>{Ye(t,2);let e=t.view.getUint16(t.bufferPos,!1);return t.bufferPos+=2,e},Jt=t=>{Ye(t,3);let e=Ft(t.view,t.bufferPos,!1);return t.bufferPos+=3,e},Fr=t=>{Ye(t,2);let e=t.view.getInt16(t.bufferPos,!1);return t.bufferPos+=2,e};var F=t=>{Ye(t,4);let e=t.view.getUint32(t.bufferPos,!1);return t.bufferPos+=4,e};var ht=t=>{Ye(t,4);let e=t.view.getInt32(t.bufferPos,!1);return t.bufferPos+=4,e};var Fe=t=>{let e=F(t),r=F(t);return e*4294967296+r},eo=t=>{let e=ht(t),r=F(t);return e*4294967296+r};var ro=t=>{Ye(t,4);let e=t.view.getFloat32(t.bufferPos,!1);return t.bufferPos+=4,e},Ti=t=>{Ye(t,8);let e=t.view.getFloat64(t.bufferPos,!1);return t.bufferPos+=8,e},ft=(t,e)=>{Ye(t,e);let r="";for(let i=0;i<e;i++)r+=String.fromCharCode(t.bytes[t.bufferPos++]);return r};var Ri=class{constructor(e){this.mutex=new Ht,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,r,i){r+=e.source._timestampOffset;let n=this.trackTimestampInfo.get(e);if(!n){if(!i)throw new Error("First packet must be a key packet.");n={maxTimestamp:r,maxTimestampBeforeLastKeyPacket:r},this.trackTimestampInfo.set(e,n)}if(r<0)throw new Error(`Timestamps must be non-negative (got ${r}s).`);if(i&&(n.maxTimestampBeforeLastKeyPacket=n.maxTimestamp),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.`);return n.maxTimestamp=Math.max(n.maxTimestamp,r),r}};var Mn=/<(?:(\\d{2}):)?(\\d{2}):(\\d{2}).(\\d{3})>/g;var co=t=>{let e=Math.floor(t/36e5),r=Math.floor(t%(60*60*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 Mr=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);m(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),et=new DataView(X.buffer),ue=t=>[(t%256+256)%256],O=t=>(et.setUint16(0,t,!1),[X[0],X[1]]),Nn=t=>(et.setInt16(0,t,!1),[X[0],X[1]]),ho=t=>(et.setUint32(0,t,!1),[X[1],X[2],X[3]]),E=t=>(et.setUint32(0,t,!1),[X[0],X[1],X[2],X[3]]),vt=t=>(et.setInt32(0,t,!1),[X[0],X[1],X[2],X[3]]),Nt=t=>(et.setUint32(0,Math.floor(t/2**32),!1),et.setUint32(4,t,!1),[X[0],X[1],X[2],X[3],X[4],X[5],X[6],X[7]]),fo=t=>(et.setInt16(0,2**8*t,!1),[X[0],X[1]]),wt=t=>(et.setInt32(0,2**16*t,!1),[X[0],X[1],X[2],X[3]]),zn=t=>(et.setInt32(0,2**30*t,!1),[X[0],X[1],X[2],X[3]]),On=(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()},Te=(t,e=!1)=>{let r=Array(t.length).fill(null).map((i,n)=>t.charCodeAt(n));return e&&r.push(0),r},Vn=t=>{let e=null;for(let r of t)(!e||r.timestamp>e.timestamp)&&(e=r);return e},mo=t=>{let e=t*(Math.PI/180),r=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[r,i,0,-i,r,0,0,0,1]},po=mo(0),go=t=>[wt(t[0]),wt(t[1]),zn(t[2]),wt(t[3]),wt(t[4]),zn(t[5]),wt(t[6]),wt(t[7]),zn(t[8])],M=(t,e,r)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:r}),Y=(t,e,r,i,n)=>M(t,[ue(e),ho(r),i??[]],n),wo=t=>t.isQuickTime?M("ftyp",[Te("qt "),E(512),Te("qt ")]):t.fragmented?M("ftyp",[Te("iso5"),E(512),Te("iso5"),Te("iso6"),Te("mp41")]):M("ftyp",[Te("isom"),E(512),Te("isom"),t.holdsAvc?Te("avc1"):[],Te("mp41")]),zr=t=>({type:"mdat",largeSize:t}),bo=t=>({type:"free",size:t}),sr=t=>M("moov",void 0,[ha(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>fa(e,t.creationTime)),t.isFragmented?Ya(t.trackDatas):null,oc(t)]),ha=(t,e)=>{let r=ye(Math.max(0,...e.filter(o=>o.samples.length>0).map(o=>{let a=Vn(o.samples);return a.timestamp+a.duration})),Bi),i=Math.max(0,...e.map(o=>o.track.id))+1,n=!It(t)||!It(r),s=n?Nt:E;return Y("mvhd",+n,0,[s(t),s(t),E(Bi),s(r),wt(1),fo(1),Array(10).fill(0),go(po),Array(24).fill(0),E(i)])},fa=(t,e)=>{let r=vo(t);return M("trak",void 0,[ma(t,e),pa(t,e),r.name!==void 0?M("udta",void 0,[M("name",[...Pe.encode(r.name)])]):null])},ma=(t,e)=>{let r=Vn(t.samples),i=ye(r?r.timestamp+r.duration:0,Bi),n=!It(e)||!It(i),s=n?Nt:E,o;if(t.type==="video"){let c=t.track.metadata.rotation;o=mo(c??0)}else o=po;let a=2;return t.track.metadata.disposition?.default!==!1&&(a|=1),Y("tkhd",+n,a,[s(e),s(e),E(t.track.id),E(0),s(i),Array(8).fill(0),O(0),O(t.track.id),fo(t.type==="audio"?1:0),O(0),go(o),wt(t.type==="video"?t.info.width:0),wt(t.type==="video"?t.info.height:0)])},pa=(t,e)=>M("mdia",void 0,[ga(t,e),Wn(!0,wa[t.type],ba[t.type]),ya(t)]),ga=(t,e)=>{let r=Vn(t.samples),i=ye(r?r.timestamp+r.duration:0,t.timescale),n=!It(e)||!It(i),s=n?Nt:E;return Y("mdhd",+n,0,[s(e),s(e),E(t.timescale),s(i),O(Eo(t.track.metadata.languageCode??$e)),O(0)])},wa={video:"vide",audio:"soun",subtitle:"text"},ba={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Wn=(t,e,r,i="\\0\\0\\0\\0")=>Y("hdlr",0,0,[t?Te("mhlr"):E(0),Te(e),Te(i),E(0),E(0),Te(r,!0)]),ya=t=>M("minf",void 0,[Sa[t.type](),Ca(),va(t)]),Ta=()=>Y("vmhd",0,1,[O(0),O(0),O(0),O(0)]),ka=()=>Y("smhd",0,0,[O(0),O(0)]),xa=()=>Y("nmhd",0,0),Sa={video:Ta,audio:ka,subtitle:xa},Ca=()=>M("dinf",void 0,[_a()]),_a=()=>Y("dref",0,0,[E(1)],[Ea()]),Ea=()=>Y("url ",0,1),va=t=>{let e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(r=>r.sampleCompositionTimeOffset!==0);return M("stbl",void 0,[Pa(t),qa(t),e?Xa(t):null,e?Ga(t):null,$a(t),Qa(t),Ka(t),ja(t)])},Pa=t=>{let e;if(t.type==="video")e=Aa(uc(t.track.source._codec,t.info.decoderConfig.codec),t);else if(t.type==="audio"){let r=_o(t.track.source._codec,t.muxer.isQuickTime);m(r),e=Ma(r,t)}else t.type==="subtitle"&&(e=La(fc[t.track.source._codec],t));return m(e),Y("stsd",0,0,[E(1)],[e])},Aa=(t,e)=>M(t,[Array(6).fill(0),O(1),O(0),O(0),Array(12).fill(0),O(e.info.width),O(e.info.height),E(4718592),E(4718592),E(0),O(1),Array(32).fill(0),O(24),Nn(65535)],[dc[e.track.source._codec](e),Ia(e),ns(e.info.decoderConfig.colorSpace)?Fa(e):null]),Ia=t=>t.info.pixelAspectRatio.num===t.info.pixelAspectRatio.den?null:M("pasp",[E(t.info.pixelAspectRatio.num),E(t.info.pixelAspectRatio.den)]),Fa=t=>M("colr",[Te("nclx"),O(rt[t.info.decoderConfig.colorSpace.primaries]),O(it[t.info.decoderConfig.colorSpace.transfer]),O(nt[t.info.decoderConfig.colorSpace.matrix]),ue((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Ra=t=>t.info.decoderConfig&&M("avcC",[...we(t.info.decoderConfig.description)]),Ba=t=>t.info.decoderConfig&&M("hvcC",[...we(t.info.decoderConfig.description)]),lo=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?rt[e.colorSpace.primaries]:2,u=r[6]?Number(r[6]):e.colorSpace?.transfer?it[e.colorSpace.transfer]:2,d=r[7]?Number(r[7]):e.colorSpace?.matrix?nt[e.colorSpace.matrix]:2;return Y("vpcC",1,0,[ue(i),ue(n),ue(c),ue(l),ue(u),ue(d),O(0)])},Da=t=>M("av1C",bs(t.info.decoderConfig.codec)),Ma=(t,e)=>{let r=0,i,n=16,s=le.includes(e.track.source._codec);if(s){let o=e.track.source._codec,{sampleSize:a}=Ie(o);n=8*a,n>16&&(r=1)}if(e.muxer.isQuickTime&&(r=1),r===0)i=[Array(6).fill(0),O(1),O(r),O(0),E(0),O(e.info.numberOfChannels),O(n),O(0),O(0),O(e.info.sampleRate<2**16?e.info.sampleRate:0),O(0)];else{let o=s?0:-2;i=[Array(6).fill(0),O(1),O(r),O(0),E(0),O(e.info.numberOfChannels),O(Math.min(n,16)),Nn(o),O(0),O(e.info.sampleRate<2**16?e.info.sampleRate:0),O(0),s?[E(1),E(n/8),E(e.info.numberOfChannels*n/8)]:[E(0),E(0),E(0)],E(2)]}return M(t,i,[hc(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},Un=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=[...ue(e),...ue(21),...ho(0),...E(0),...E(0)];if(t.info.decoderConfig.description){let i=we(t.info.decoderConfig.description);r=[...r,...ue(5),...On(i.byteLength),...i]}return r=[...O(1),...ue(0),...ue(4),...On(r.length),...r,...ue(6),...ue(1),...ue(2)],r=[...ue(3),...On(r.length),...r],Y("esds",0,0,r)},Et=t=>M("wave",void 0,[za(t),Oa(t),M("\\0\\0\\0\\0")]),za=t=>M("frma",[Te(_o(t.track.source._codec,t.muxer.isQuickTime))]),Oa=t=>{let{littleEndian:e}=Ie(t.track.source._codec);return M("enda",[O(+e)])},Ua=t=>{let e=t.info.numberOfChannels,r=3840,i=t.info.sampleRate,n=0,s=0,o=new Uint8Array(0),a=t.info.decoderConfig?.description;if(a){m(a.byteLength>=18);let c=we(a),l=Ms(c);e=l.outputChannelCount,r=l.preSkip,i=l.inputSampleRate,n=l.outputGain,s=l.channelMappingFamily,l.channelMappingTable&&(o=l.channelMappingTable)}return M("dOps",[ue(0),ue(e),O(r),E(i),Nn(n),ue(s),...o])},Na=t=>{let e=t.info.decoderConfig?.description;m(e);let r=we(e);return Y("dfLa",0,0,[...r.subarray(4)])},Ze=t=>{let{littleEndian:e,sampleSize:r}=Ie(t.track.source._codec),i=+e;return Y("pcmC",0,0,[ue(i),ue(8*r)])},Va=t=>{let e=zs(t.info.firstPacket.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 ie(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),M("dac3",[...r])},Wa=t=>{let e=Os(t.info.firstPacket.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 ie(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 M("dec3",[...n])},La=(t,e)=>M(t,[Array(6).fill(0),O(1)],[mc[e.track.source._codec](e)]),Ha=t=>M("vttC",[...Pe.encode(t.info.config.description)]);var qa=t=>Y("stts",0,0,[E(t.timeToSampleTable.length),t.timeToSampleTable.map(e=>[E(e.sampleCount),E(e.sampleDelta)])]),ja=t=>{if(t.samples.every(r=>r.type==="key"))return null;let e=[...t.samples.entries()].filter(([,r])=>r.type==="key");return Y("stss",0,0,[E(e.length),e.map(([r])=>E(r+1))])},$a=t=>Y("stsc",0,0,[E(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(e=>[E(e.firstChunk),E(e.samplesPerChunk),E(1)])]),Qa=t=>{if(t.type==="audio"&&t.info.requiresPcmTransformation){let{sampleSize:e}=Ie(t.track.source._codec);return Y("stsz",0,0,[E(e*t.info.numberOfChannels),E(t.samples.reduce((r,i)=>r+ye(i.duration,t.timescale),0))])}return Y("stsz",0,0,[E(0),E(t.samples.length),t.samples.map(e=>E(e.size))])},Ka=t=>t.finalizedChunks.length>0&&te(t.finalizedChunks).offset>=2**32?Y("co64",0,0,[E(t.finalizedChunks.length),t.finalizedChunks.map(e=>Nt(e.offset))]):Y("stco",0,0,[E(t.finalizedChunks.length),t.finalizedChunks.map(e=>E(e.offset))]),Xa=t=>Y("ctts",1,0,[E(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(e=>[E(e.sampleCount),vt(e.sampleCompositionTimeOffset)])]),Ga=t=>{let e=1/0,r=-1/0,i=1/0,n=-1/0;m(t.compositionTimeOffsetTable.length>0),m(t.samples.length>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,ye(a.timestamp,t.timescale)),n=Math.max(n,ye(a.timestamp+a.duration,t.timescale))}let s=Math.max(-e,0);return n>=2**31?null:Y("cslg",0,0,[vt(s),vt(e),vt(r),vt(i),vt(n)])},Ya=t=>M("mvex",void 0,t.map(Za)),Za=t=>Y("trex",0,0,[E(t.track.id),E(1),E(0),E(0),E(0)]),Ln=(t,e)=>M("moof",void 0,[Ja(t),...e.map(ec)]),Ja=t=>Y("mfhd",0,0,[E(t)]),yo=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},ec=t=>M("traf",void 0,[tc(t),rc(t),ic(t)]),tc=t=>{m(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:yo(r)};return Y("tfhd",0,e,[E(t.track.id),E(i.duration),E(i.size),E(i.flags)])},rc=t=>(m(t.currentChunk),Y("tfdt",1,0,[Nt(ye(t.currentChunk.startTimestamp,t.timescale))])),ic=t=>{m(t.currentChunk);let e=t.currentChunk.samples.map(y=>y.timescaleUnitsToNextSample),r=t.currentChunk.samples.map(y=>y.size),i=t.currentChunk.samples.map(yo),n=t.currentChunk.samples.map(y=>ye(y.timestamp-y.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],u=s.size>1,d=o.size>1,f=!l&&a.size>1,p=c.size>1||[...c].some(y=>y!==0),g=0;return g|=1,g|=4*+l,g|=256*+u,g|=512*+d,g|=1024*+f,g|=2048*+p,Y("trun",1,g,[E(t.currentChunk.samples.length),E(t.currentChunk.offset-t.currentChunk.moofOffset||0),l?E(i[0]):[],t.currentChunk.samples.map((y,w)=>[u?E(e[w]):[],d?E(r[w]):[],f?E(i[w]):[],p?vt(n[w]):[]])])},To=t=>M("mfra",void 0,[...t.map(nc),sc()]),nc=(t,e)=>Y("tfra",1,0,[E(t.track.id),E(63),E(t.finalizedChunks.length),t.finalizedChunks.map(i=>[Nt(ye(i.samples[0].timestamp,t.timescale)),Nt(i.moofOffset),E(e+1),E(1),E(1)])]),sc=()=>Y("mfro",0,0,[E(0)]),ko=()=>M("vtte"),xo=(t,e,r,i,n)=>M("vttc",void 0,[n!==null?M("vsid",[vt(n)]):null,r!==null?M("iden",[...Pe.encode(r)]):null,e!==null?M("ctim",[...Pe.encode(co(e))]):null,i!==null?M("sttg",[...Pe.encode(i)]):null,M("payl",[...Pe.encode(t)])]),So=t=>M("vtta",[...Pe.encode(t)]),oc=t=>{let e=[],r=t.format._options.metadataFormat??"auto",i=t.output._metadataTags;if(r==="mdir"||r==="auto"&&!t.isQuickTime){let n=cc(i);n&&e.push(n)}else if(r==="mdta"){let n=lc(i);n&&e.push(n)}else(r==="udta"||r==="auto"&&t.isQuickTime)&&ac(e,t.output._metadataTags);return e.length===0?null:M("udta",void 0,e)},ac=(t,e)=>{for(let{key:r,value:i}of Gr(e))switch(r){case"title":t.push(Je("\\xA9nam",i));break;case"description":t.push(Je("\\xA9des",i));break;case"artist":t.push(Je("\\xA9ART",i));break;case"album":t.push(Je("\\xA9alb",i));break;case"albumArtist":t.push(Je("albr",i));break;case"genre":t.push(Je("\\xA9gen",i));break;case"date":t.push(Je("\\xA9day",i.toISOString().slice(0,10)));break;case"comment":t.push(Je("\\xA9cmt",i));break;case"lyrics":t.push(Je("\\xA9lyr",i));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:Ae(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(Je(r,i)):i instanceof Uint8Array&&t.push(M(r,Array.from(i))))}},Je=(t,e)=>{let r=Pe.encode(e);return M(t,[O(r.length),O(Eo("und")),Array.from(r)])},uo={"image/jpeg":13,"image/png":14,"image/bmp":27},Co=(t,e)=>{let r=[];for(let{key:i,value:n}of Gr(t))switch(i){case"title":r.push({key:e?"title":"\\xA9nam",value:qe(n)});break;case"description":r.push({key:e?"description":"\\xA9des",value:qe(n)});break;case"artist":r.push({key:e?"artist":"\\xA9ART",value:qe(n)});break;case"album":r.push({key:e?"album":"\\xA9alb",value:qe(n)});break;case"albumArtist":r.push({key:e?"album_artist":"aART",value:qe(n)});break;case"comment":r.push({key:e?"comment":"\\xA9cmt",value:qe(n)});break;case"genre":r.push({key:e?"genre":"\\xA9gen",value:qe(n)});break;case"lyrics":r.push({key:e?"lyrics":"\\xA9lyr",value:qe(n)});break;case"date":r.push({key:e?"date":"\\xA9day",value:qe(n.toISOString().slice(0,10))});break;case"images":for(let s of n)s.kind==="coverFront"&&r.push({key:"covr",value:M("data",[E(uo[s.mimeType]??0),E(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:qe(s)})}else r.push({key:"trkn",value:M("data",[E(0),E(0),O(0),O(n),O(t.tracksTotal??0),O(0)])});break;case"discNumber":e||r.push({key:"disc",value:M("data",[E(0),E(0),O(0),O(n),O(t.discsTotal??0),O(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:Ae(i)}if(t.raw)for(let i in t.raw){let n=t.raw[i];n==null||!e&&i.length!==4||r.some(s=>s.key===i)||(typeof n=="string"?r.push({key:i,value:qe(n)}):n instanceof Uint8Array?r.push({key:i,value:M("data",[E(0),E(0),Array.from(n)])}):n instanceof Ne&&r.push({key:i,value:M("data",[E(uo[n.mimeType]??0),E(0),Array.from(n.data)])}))}return r},cc=t=>{let e=Co(t,!1);return e.length===0?null:Y("meta",0,0,void 0,[Wn(!1,"mdir","","appl"),M("ilst",void 0,e.map(r=>M(r.key,void 0,[r.value])))])},lc=t=>{let e=Co(t,!0);return e.length===0?null:M("meta",void 0,[Wn(!1,"mdta",""),Y("keys",0,0,[E(e.length)],e.map(r=>M("mdta",[...Pe.encode(r.key)]))),M("ilst",void 0,e.map((r,i)=>{let n=String.fromCharCode(...E(i+1));return M(n,void 0,[r.value])}))])},qe=t=>M("data",[E(1),E(0),...Pe.encode(t)]),uc=(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"}},dc={avc:Ra,hevc:Ba,vp8:lo,vp9:lo,av1:Da},_o=(t,e)=>{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"}if(e)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"}},hc=(t,e)=>{switch(t){case"aac":return Un;case"mp3":return Un;case"opus":return Ua;case"vorbis":return Un;case"flac":return Na;case"ac3":return Va;case"eac3":return Wa}if(e)switch(t){case"pcm-s24":return Et;case"pcm-s24be":return Et;case"pcm-s32":return Et;case"pcm-s32be":return Et;case"pcm-f32":return Et;case"pcm-f32be":return Et;case"pcm-f64":return Et;case"pcm-f64be":return Et}else switch(t){case"pcm-s16":return Ze;case"pcm-s16be":return Ze;case"pcm-s24":return Ze;case"pcm-s24be":return Ze;case"pcm-s32":return Ze;case"pcm-s32be":return Ze;case"pcm-f32":return Ze;case"pcm-f32be":return Ze;case"pcm-f64":return Ze;case"pcm-f64be":return Ze}return null},fc={webvtt:"wvtt"},mc={webvtt:Ha},Eo=t=>{m(t.length===3);let e=0;for(let r=0;r<3;r++)e<<=5,e+=t.charCodeAt(r)-96;return e};var Di=class{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}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}},Hn=2**16,qn=2**32,or=class extends Di{constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(Hn,{maxByteLength:qn})}catch{this.buffer=new ArrayBuffer(Hn),this.supportsResize=!1}else this.buffer=new ArrayBuffer(Hn);this.bytes=new Uint8Array(this.buffer)}ensureSize(e){let r=this.buffer.byteLength;for(;r<e;)r*=2;if(r!==this.buffer.byteLength){if(r>qn)throw new Error(`ArrayBuffer exceeded maximum size of ${qn} 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}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,r){return this.bytes.slice(e,r)}},Tu=2**24;var Mi=class extends Di{constructor(e){super(),this.target=e,this.pos=0}write(e){this.maybeTrackWrites(e),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength}getPos(){return this.pos}seek(e){this.pos=e}async flush(){}async finalize(){}async close(){}};var Vt=class{constructor(){this._output=null,this.onwrite=null}},Wt=class extends Vt{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new or(this)}};var Or=class extends Vt{_createWriter(){return new Mi(this)}};var Bi=1e3,pc=2082844800,vo=t=>{let e={},r=t.track;return r.metadata.name!==void 0&&(e.name=r.metadata.name),e},ye=(t,e,r=!0)=>{let i=t*e;return r?Math.round(i):i},zi=class extends Ri{constructor(e,r){super(e),this.auxTarget=new Wt,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new Mr(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=he(),this.creationTime=Math.floor(Date.now()/1e3)+pc,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=r,this.writer=e._writer,this.boxWriter=new Mr(this.writer),this.isQuickTime=r instanceof ar;let i=this.writer instanceof or?"in-memory":!1;this.fastStart=r._options.fastStart??i,this.isFragmented=this.fastStart==="fragmented",(this.fastStart==="in-memory"||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=r._options.minimumFragmentDuration??1}async start(){let e=await this.mutex.acquire(),r=this.output._tracks.some(i=>i.type==="video"&&i.source._codec==="avc");if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(wo({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented})),this.format._options.onFtyp){let{data:i,start:n}=this.writer.stopTrackingWrites();this.format._options.onFtyp(i,n)}if(this.ftypSize=this.writer.getPos(),this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(let i of this.output._tracks)if(i.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: \'reserve\'.")}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=zr(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),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 pi({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(f=>f.track===e);if(n)return n;Ss(i),m(i),m(i.decoderConfig);let s={...i.decoderConfig};m(s.codedWidth!==void 0),m(s.codedHeight!==void 0);let o=!1;if(e.source._codec==="avc"&&!s.description){let f=ci(r.data);if(!f)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=Is(f),o=!0}else if(e.source._codec==="hevc"&&!s.description){let f=li(r.data);if(!f)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=Bs(f),o=!0}let a=us(1/(e.metadata.frameRate??57600),1e6).denominator,c=s.displayAspectWidth,l=s.displayAspectHeight,u=c===void 0||l===void 0?{num:1,den:1}:$t({num:c*s.codedHeight,den:l*s.codedWidth}),d={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:u,decoderConfig:s,requiresAnnexBTransformation:o},timescale:a,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(d),this.trackDatas.sort((f,p)=>f.track.id-p.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,r,i){let n=this.trackDatas.find(c=>c.track===e);if(n)return n;Cs(i),m(i),m(i.decoderConfig);let s={...i.decoderConfig},o=!1;if(e.source._codec==="aac"&&!s.description){let c=In(gt.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=wr[c.samplingFrequencyIndex],u=ei[c.channelConfiguration];if(l===void 0||u===void 0)throw new Error("Invalid ADTS frame header.");s.description=ti({objectType:c.objectType,sampleRate:l,numberOfChannels:u}),o=!0}let a={muxer:this,track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&le.includes(e.source._codec),requiresAdtsStripping:o,firstPacket:r},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};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;_s(r),m(r),m(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,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,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 l=[...Kt(o)].map(u=>o.subarray(u.offset,u.offset+u.length));if(l.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=ln(l,4)}let a=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),c=this.createSampleForTrack(s,o,a,r.duration,r.type);await this.registerSample(s,c)}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 l=In(gt.tempFromBytes(o));if(!l)throw new Error("Expected ADTS frame, didn\'t get one.");let u=l.crcCheck===null?so:oo;o=o.subarray(u)}let a=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),c=this.createSampleForTrack(s,o,a,r.duration,r.type);s.info.requiresPcmTransformation&&await this.maybePadWithSilence(s,a),await this.registerSample(s,c)}finally{n()}}async maybePadWithSilence(e,r){let i=te(e.samples),n=i?i.timestamp+i.duration:0,s=r-n,o=ye(s,e.timescale);if(o>0){let{sampleSize:a,silentValue:c}=Ie(e.info.decoderConfig.codec),l=o*e.info.numberOfChannels,u=new Uint8Array(a*l).fill(c),d=this.createSampleForTrack(e,new Uint8Array(u.buffer),n,s,"key");await this.registerSample(e,d)}}async addSubtitleCue(e,r,i){let n=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,i);this.validateAndNormalizeTimestamp(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;){let i=new Set([]);for(let l of e.cueQueue)m(l.timestamp<=r),m(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,u)=>l-u),s=n[0],o=n[1]??s;if(r<o)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);let l=ko();this.auxBoxWriter.writeBox(l);let u=this.auxWriter.getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,u,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let l=0;l<e.cueQueue.length;l++){let u=e.cueQueue[l];if(u.timestamp>=o)break;Mn.lastIndex=0;let d=Mn.test(u.text),f=u.timestamp+u.duration,p=e.cueToSourceId.get(u);if(p===void 0&&o<f&&(p=e.nextSourceId++,e.cueToSourceId.set(u,p)),u.notes){let y=So(u.notes);this.auxBoxWriter.writeBox(y)}let g=xo(u.text,d?s:null,u.identifier??null,u.settings??null,p??null);this.auxBoxWriter.writeBox(g),f===o&&e.cueQueue.splice(l--,1)}let a=this.auxWriter.getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,a,s,o-s,"key");await this.registerSample(e,c),e.lastCueEndTimestamp=o}}createSampleForTrack(e,r,i,n,s){return{timestamp:i,decodeTimestamp:i,duration:n,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:ye(n,e.timescale)}}processTimestamps(e,r){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){let n=0;for(let s=0;s<e.timestampProcessingQueue.length;s++){let o=e.timestampProcessingQueue[s],a=ye(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);for(let n=0;n<e.timestampProcessingQueue.length;n++){let s=e.timestampProcessingQueue[n];s.decodeTimestamp=i[n],!this.isFragmented&&e.lastTimescaleUnits===null&&(s.decodeTimestamp=0);let o=ye(s.timestamp-s.decodeTimestamp,e.timescale),a=ye(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){m(e.lastSample);let c=ye(s.decodeTimestamp,e.timescale,!1),l=Math.round(c-e.lastTimescaleUnits);if(m(l>=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let u=te(e.timeToSampleTable);if(m(u),u.sampleCount===1){u.sampleDelta=l;let f=e.timeToSampleTable[e.timeToSampleTable.length-2];f&&f.sampleDelta===l&&(f.sampleCount++,e.timeToSampleTable.pop(),u=f)}else u.sampleDelta!==l&&(u.sampleCount--,e.timeToSampleTable.push(u={sampleCount:1,sampleDelta:l}));u.sampleDelta===a?u.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let d=te(e.compositionTimeOffsetTable);m(d),d.sampleCompositionTimeOffset===o?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else e.lastTimescaleUnits=ye(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,m(e.lastSample),m(e.lastTimescaleUnits!==null),r!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){m(r.type==="key");let n=ye(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),this.isFragmented?(e.sampleQueue.push(r),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,r):await this.addSampleToTrack(e,r)}async addSampleToTrack(e,r){if(!this.isFragmented&&(e.samples.push(r),this.fastStart==="reserve")){let n=e.track.metadata.maximumPacketCount;if(m(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.track.source._closed});n>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=n>=.5}i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null}),m(e.currentChunk),e.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(e){if(m(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let r=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(r=e.currentChunk.samples.reduce((i,n)=>i+ye(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||te(e.compactlyCodedChunkTable).samplesPerChunk!==r)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:r}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let i of e.currentChunk.samples)m(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(m(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let r=null,i=1/0;for(let s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.track.source._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=!0){m(this.isFragmented);let r=this.nextFragmentNumber++;if(r===1){this.format._options.onMoov&&this.writer.startTrackingWrites();let p=sr(this);if(this.boxWriter.writeBox(p),this.format._options.onMoov){let{data:g,start:y}=this.writer.stopTrackingWrites();this.format._options.onMoov(g,y)}}let i=this.trackDatas.filter(p=>p.currentChunk),n=Ln(r,i),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(n),a=o+Ve,c=1/0;for(let p of i){p.currentChunk.offset=a,p.currentChunk.moofOffset=s;for(let g of p.currentChunk.samples)a+=g.size;c=Math.min(c,p.currentChunk.startTimestamp)}let l=a-o,u=l>=2**32;if(u)for(let p of i)p.currentChunk.offset+=ut-Ve;this.format._options.onMoof&&this.writer.startTrackingWrites();let d=Ln(r,i);if(this.boxWriter.writeBox(d),this.format._options.onMoof){let{data:p,start:g}=this.writer.stopTrackingWrites();this.format._options.onMoof(p,g,c)}m(this.writer.getPos()===o),this.format._options.onMdat&&this.writer.startTrackingWrites();let f=zr(u);f.size=l,this.boxWriter.writeBox(f),this.writer.seek(o+(u?ut:Ve));for(let p of i)for(let g of p.currentChunk.samples)this.writer.write(g.data),g.data=null;if(this.format._options.onMdat){let{data:p,start:g}=this.writer.stopTrackingWrites();this.format._options.onMdat(p,g)}for(let p of i)p.finalizedChunks.push(p.currentChunk),this.finalizedChunks.push(p.currentChunk),p.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,r){if(this.allTracksAreKnown()){if(!this.mdat){let i=sr(this),s=this.boxWriter.measureBox(i)+this.computeSampleTableSizeUpperBound()+4096;m(this.ftypSize!==null),this.writer.seek(this.ftypSize+s),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=zr(!0),this.boxWriter.writeBox(this.mdat);for(let o of this.trackDatas){for(let a of o.sampleQueue)await this.addSampleToTrack(o,a);o.sampleQueue.length=0}}await this.addSampleToTrack(e,r)}else e.sampleQueue.push(r)}computeSampleTableSizeUpperBound(){m(this.fastStart==="reserve");let e=0;for(let r of this.trackDatas){let i=r.track.metadata.maximumPacketCount;m(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}return e}async onTrackClose(e){let r=await this.mutex.acquire(),i=this.trackDatas.find(n=>n.track===e);i&&(i.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let r of this.trackDatas)await this.finalizeCurrentChunk(r);if(this.fastStart==="in-memory"){this.mdat=zr(!1);let r;for(let n=0;n<2;n++){let s=sr(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)m(l),a+=l.byteLength,r+=l.byteLength}if(a<2**32)break;r>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let i=sr(this);if(this.boxWriter.writeBox(i),this.format._options.onMoov){let{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onMoov(n,s)}this.format._options.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)m(s.data),this.writer.write(s.data),s.data=null;if(this.format._options.onMdat){let{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onMdat(n,s)}}else if(this.isFragmented){let r=this.writer.getPos(),i=To(this.trackDatas);this.boxWriter.writeBox(i);let n=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{m(this.mdat);let r=this.boxWriter.offsets.get(this.mdat);m(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.format._options.onMdat){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,o)}let n=sr(this);if(this.fastStart==="reserve"){m(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);let s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(bo(s))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.format._options.onMoov){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,o)}}e()}};var cr=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Ce.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>_e.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Dt.includes(e))}_codecUnsupportedHint(e){return""}},Ur=class extends cr{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&&(!Number.isFinite(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:1,max:4294967295}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new zi(e,this)}},Pt=class extends Ur{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Ce,...Bt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Dt]}_codecUnsupportedHint(e){return new ar().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}},ar=class extends Ur{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Ce,..._e]}_codecUnsupportedHint(e){return new Pt().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}};var Po=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!Ce.includes(t.codec))throw new TypeError(`Invalid video codec \'${t.codec}\'. Must be one of: ${Ce.join(", ")}.`);if(!(t.bitrate instanceof ze)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(t.keyFrameInterval!==void 0&&(!Number.isFinite(t.keyFrameInterval)||t.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(t.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be \'deny\', \'passThrough\', \'fill\', \'contain\' or \'cover\'.");if(t.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(t.onEncoderConfig!==void 0&&typeof t.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");Ao(t.codec,t)},Ao=(t,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be \'discard\' or \'keep\'.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be \'constant\' or \'variable\'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be \'quality\' or \'realtime\'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&sn(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be \'no-preference\', \'prefer-hardware\' or \'prefer-software\'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},Oi=t=>{let e=t.bitrate instanceof ze?t.bitrate._toVideoBitrate(t.codec,t.width,t.height):t.bitrate;return{codec:t.fullCodecString??ws(t.codec,t.width,t.height,e),width:t.width,height:t.height,displayWidth:t.squarePixelWidth,displayHeight:t.squarePixelHeight,bitrate:e,bitrateMode:t.bitrateMode,alpha:t.alpha??"discard",framerate:t.framerate,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,scalabilityMode:t.scalabilityMode,contentHint:t.contentHint,...ks(t.codec)}},Io=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!_e.includes(t.codec))throw new TypeError(`Invalid audio codec \'${t.codec}\'. Must be one of: ${_e.join(", ")}.`);if(t.bitrate===void 0&&(!le.includes(t.codec)||t.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(t.bitrate!==void 0&&!(t.bitrate instanceof ze)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(t.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(t.onEncoderConfig!==void 0&&typeof t.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");Fo(t.codec,t)},Fo=(t,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be \'constant\' or \'variable\'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&sn(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`)},Ui=t=>{let e=t.bitrate instanceof ze?t.bitrate._toAudioBitrate(t.codec):t.bitrate;return{codec:t.fullCodecString??ys(t.codec,t.numberOfChannels,t.sampleRate),numberOfChannels:t.numberOfChannels,sampleRate:t.sampleRate,bitrate:e,bitrateMode:t.bitrateMode,...xs(t.codec)}},ze=class{constructor(e){this._factor=e}_toVideoBitrate(e,r,i){let n=r*i,s={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},o=1920*1080,a=3e6,c=Math.pow(n/o,.95),d=a*c*s[e]*this._factor;return Math.ceil(d/1e3)*1e3}_toAudioBitrate(e){if(le.includes(e)||e==="flac")return;let i={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[e];if(!i)throw new Error(`Unhandled codec: ${e}`);let n=i*this._factor;return e==="aac"?n=[96e3,128e3,16e4,192e3].reduce((o,a)=>Math.abs(a-n)<Math.abs(o-n)?a:o):e==="opus"||e==="vorbis"?n=Math.max(6e3,n):e==="mp3"&&(n=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((o,a)=>Math.abs(a-n)<Math.abs(o-n)?a:o)),Math.round(n/1e3)*1e3}};var jn=new ze(2);var gc=async(t,e={})=>{let{width:r=1280,height:i=720,bitrate:n=1e6,...s}=e;if(!Ce.includes(t))return!1;if(!Number.isInteger(r)||r<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("height must be a positive integer.");if(!(n instanceof ze)&&(!Number.isInteger(n)||n<=0))throw new TypeError("bitrate must be a positive integer or a quality.");Ao(t,s);let o=null;return kr.length>0&&(o??(o=Oi({codec:t,width:r,height:i,bitrate:n,framerate:void 0,...s})),kr.some(l=>l.supports(t,o)))?!0:typeof VideoEncoder>"u"||(r%2===1||i%2===1)&&(t==="avc"||t==="hevc")||(o??(o=Oi({codec:t,width:r,height:i,bitrate:n,framerate:void 0,...s,alpha:"discard"})),!(await VideoEncoder.isConfigSupported(o)).supported)?!1:Ke()?new Promise(async l=>{try{let u=new VideoEncoder({output:()=>{},error:()=>l(!1)});u.configure(o);let d=new Uint8Array(r*i*4),f=new VideoFrame(d,{format:"RGBA",codedWidth:r,codedHeight:i,timestamp:0});u.encode(f),f.close(),await u.flush(),l(!0)}catch{l(!1)}}):!0},wc=async(t,e={})=>{let{numberOfChannels:r=2,sampleRate:i=48e3,bitrate:n=128e3,...s}=e;if(!_e.includes(t))return!1;if(!Number.isInteger(r)||r<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("sampleRate must be a positive integer.");if(!(n instanceof ze)&&(!Number.isInteger(n)||n<=0))throw new TypeError("bitrate must be a positive integer.");Fo(t,s);let o=null;return xr.length>0&&(o??(o=Ui({codec:t,numberOfChannels:r,sampleRate:i,bitrate:n,...s})),xr.some(c=>c.supports(t,o)))||le.includes(t)?!0:typeof AudioEncoder>"u"?!1:(o??(o=Ui({codec:t,numberOfChannels:r,sampleRate:i,bitrate:n,...s})),(await AudioEncoder.isConfigSupported(o)).supported===!0)};var $n=async(t=_e,e)=>{let r=await Promise.all(t.map(i=>wc(i,e)));return t.filter((i,n)=>r[n])};var Ro=async(t,e)=>{for(let r of t)if(await gc(r,e))return r;return null};var Nr=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_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??(this._closingPromise=(async()=>{await this._flushAndClose(e),this._closed=!0})())}},lr=class extends Nr{constructor(e){if(super(),this._connectedTrack=null,!Ce.includes(e))throw new TypeError(`Invalid video codec \'${e}\'. Must be one of: ${Ce.join(", ")}.`);this._codec=e}},Ni=class extends lr{constructor(e){super(e)}add(e,r){if(!(e instanceof ce))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.addEncodedVideoPacket(this._connectedTrack,e,r)}},Qn=class{constructor(e,r){this.source=e,this.encodingConfig=r,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.codedWidth=null,this.codedHeight=null,this.resizeCanvas=null,this.customEncoder=null,this.customEncoderCallSerializer=new Tt,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null}async add(e,r,i){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.codedWidth!==null&&this.codedHeight!==null){if(e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight){let a=this.encodingConfig.sizeChangeBehavior??"deny";if(a!=="passThrough"){if(a==="deny")throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \\`sizeChangeBehavior\\` to a value other than \'strict\' in the encoding options.`);{let c=!1;this.resizeCanvas||(typeof document<"u"?(this.resizeCanvas=document.createElement("canvas"),this.resizeCanvas.width=this.codedWidth,this.resizeCanvas.height=this.codedHeight):this.resizeCanvas=new OffscreenCanvas(this.codedWidth,this.codedHeight),c=!0);let l=this.resizeCanvas.getContext("2d",{alpha:Ke()});m(l),c||(Ke()?(l.fillStyle="black",l.fillRect(0,0,this.codedWidth,this.codedHeight)):l.clearRect(0,0,this.codedWidth,this.codedHeight)),e.drawWithFit(l,{fit:a}),r&&e.close(),e=new xe(this.resizeCanvas,{timestamp:e.timestamp,duration:e.duration,rotation:e.rotation}),r=!0}}}}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),m(this.encoderInitialized);let n=this.encodingConfig.keyFrameInterval??5,s=Math.floor(e.timestamp/n),o={...i,keyFrame:i?.keyFrame||n===0||s!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=s,this.customEncoder){this.customEncoderQueueSize++;let a=e.clone(),c=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(a,o)).then(()=>this.customEncoderQueueSize--).catch(l=>this.error??(this.error=l)).finally(()=>{a.close()});this.customEncoderQueueSize>=4&&await c}else{m(this.encoder);let a=e.toVideoFrame();if(!this.alphaEncoder)this.encoder.encode(a,o),a.close();else if(!!a.format&&!a.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(a,o),a.close();else{let l=a.displayWidth,u=a.displayHeight;if(!this.splitter)try{this.splitter=new Kn(l,u)}catch(d){console.error("Due to an error, only color data will be encoded.",d),this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(a,o),a.close()}if(this.splitter){let d=this.splitter.extractColor(a),f=this.splitter.extractAlpha(a);this.alphaFrameQueue.push(f),this.encoder.encode(d,o),d.close(),a.close()}}r&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(c=>this.encoder.addEventListener("dequeue",c,{once:!0}))}await this.muxer.mutex.currentPromise}finally{r&&e.close()}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let r=Oi({width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(r);let i=kr.find(n=>n.supports(this.encodingConfig.codec,r));if(i)this.customEncoder=new i,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=r,this.customEncoder.onPacket=(n,s)=>{if(!(n instanceof ce))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(s!==void 0&&(!s||typeof s!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(n,s),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,n,s).catch(o=>{this.error??(this.error=o)})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(r.alpha="discard",this.encodingConfig.alpha==="keep"&&(r.latencyMode="quality"),(r.width%2===1||r.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${r.width}x${r.height} are not supported for codec \'${this.encodingConfig.codec}\'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(r)).supported)throw new Error(`This specific encoder configuration (${r.codec}, ${r.bitrate} bps, ${r.width}x${r.height}, hardware acceleration: ${r.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);let o=[],a=[],c=0,l=0,u=(f,p,g)=>{let y={};if(p){let b=new Uint8Array(p.byteLength);p.copyTo(b),y.alpha=b}let w=ce.fromEncodedChunk(f,y);this.encodingConfig.onEncodedPacket?.(w,g),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,w,g).catch(b=>{this.error??(this.error=b)})},d=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(f,p)=>{if(!this.alphaEncoder){u(f,null,p);return}let g=this.alphaFrameQueue.shift();m(g!==void 0),g?(this.alphaEncoder.encode(g,{keyFrame:f.type==="key"}),l++,g.close(),o.push({chunk:f,meta:p})):l===0?u(f,null,p):(a.push(c+l),o.push({chunk:f,meta:p}))},error:f=>{f.stack=d,this.error??(this.error=f)}}),this.encoder.configure(r),this.encodingConfig.alpha==="keep"){let f=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(p,g)=>{l--;let y=o.shift();for(m(y!==void 0),u(y.chunk,p,y.meta),c++;a.length>0&&a[0]===c;){a.shift();let w=o.shift();m(w!==void 0),u(w.chunk,null,w.meta)}},error:p=>{p.stack=f,this.error??(this.error=p)}}),this.alphaEncoder.configure(r)}}m(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(r=>r?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},Kn=class{constructor(e,r){this.lastFrame=null,typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(e,r):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=r);let i=this.canvas.getContext("webgl2",{alpha:!0});if(!i)throw new Error("Couldn\'t acquire WebGL 2 context.");this.gl=i,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}createVertexShader(){return this.createShader(this.gl.VERTEX_SHADER,`#version 300 es\n in vec2 a_position;\n in vec2 a_texCoord;\n out vec2 v_texCoord;\n \n void main() {\n gl_Position = vec4(a_position, 0.0, 1.0);\n v_texCoord = a_texCoord;\n }\n `)}createColorProgram(){let e=this.createVertexShader(),r=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es\n precision highp float;\n \n uniform sampler2D u_sourceTexture;\n in vec2 v_texCoord;\n out vec4 fragColor;\n \n void main() {\n vec4 source = texture(u_sourceTexture, v_texCoord);\n fragColor = vec4(source.rgb, 1.0);\n }\n `),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,r),this.gl.linkProgram(i),i}createAlphaProgram(){let e=this.createVertexShader(),r=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es\n precision highp float;\n \n uniform sampler2D u_sourceTexture;\n uniform vec2 u_resolution; // The width and height of the canvas\n in vec2 v_texCoord;\n out vec4 fragColor;\n\n // This function determines the value for a single byte in the YUV stream\n float getByteValue(float byteOffset) {\n float width = u_resolution.x;\n float height = u_resolution.y;\n\n float yPlaneSize = width * height;\n\n if (byteOffset < yPlaneSize) {\n // This byte is in the luma plane. Find the corresponding pixel coordinates to sample from\n float y = floor(byteOffset / width);\n float x = mod(byteOffset, width);\n \n // Add 0.5 to sample the center of the texel\n vec2 sampleCoord = (vec2(x, y) + 0.5) / u_resolution;\n \n // The luma value is the alpha from the source texture\n return texture(u_sourceTexture, sampleCoord).a;\n } else {\n // Write a fixed value for chroma and beyond\n return 128.0 / 255.0;\n }\n }\n \n void main() {\n // Each fragment writes 4 bytes (R, G, B, A)\n float pixelIndex = floor(gl_FragCoord.y) * u_resolution.x + floor(gl_FragCoord.x);\n float baseByteOffset = pixelIndex * 4.0;\n\n vec4 result;\n for (int i = 0; i < 4; i++) {\n float currentByteOffset = baseByteOffset + float(i);\n result[i] = getByteValue(currentByteOffset);\n }\n \n fragColor = result;\n }\n `),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,r),this.gl.linkProgram(i),i}createShader(e,r){let i=this.gl.createShader(e);return this.gl.shaderSource(i,r),this.gl.compileShader(i),this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS)||console.error("Shader compile error:",this.gl.getShaderInfoLog(i)),i}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let r=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,r,this.gl.STATIC_DRAW);let n=this.gl.getAttribLocation(this.colorProgram,"a_position"),s=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}updateTexture(e){this.lastFrame!==e&&((e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.lastFrame=e)}extractColor(e){return this.updateTexture(e),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:"discard"})}extractAlpha(e){this.updateTexture(e),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);let{width:r,height:i}=this.canvas,n=Math.ceil(r/2)*Math.ceil(i/2),s=r*i+n*2,o=Math.ceil(s/(r*4)),a=new Uint8Array(4*r*o);this.gl.readPixels(0,0,r,o,this.gl.RGBA,this.gl.UNSIGNED_BYTE,a),a=a.subarray(0,s),m(a[r*i]===128),m(a[a.length-1]===128);let c={format:"I420",codedWidth:r,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[a.buffer]};return new VideoFrame(a,c)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}},Vr=class extends lr{constructor(e){Po(e),super(e.codec),this._encoder=new Qn(this,e)}add(e,r){if(!(e instanceof xe))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,r)}_flushAndClose(e){return this._encoder.flushAndClose(e)}};var ur=class extends Nr{constructor(e){if(super(),this._connectedTrack=null,!_e.includes(e))throw new TypeError(`Invalid audio codec \'${e}\'. Must be one of: ${_e.join(", ")}.`);this._codec=e}},Vi=class extends ur{constructor(e){super(e)}add(e,r){if(!(e instanceof ce))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)}},Xn=class{constructor(e,r){this.source=e,this.encodingConfig=r,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new Tt,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.error=null}async add(e,r){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),m(this.encoderInitialized);{let i=Math.round(e.timestamp*e.sampleRate),n=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let s=i-this.lastEndSampleIndex;if(s>=64){let o=new Me({data:new Float32Array(s*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:s,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.add(o,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.customEncoder){this.customEncoderQueueSize++;let i=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(i)).then(()=>this.customEncoderQueueSize--).catch(s=>this.error??(this.error=s)).finally(()=>{i.close()});this.customEncoderQueueSize>=4&&await n,await this.muxer.mutex.currentPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,r);else{m(this.encoder);let i=e.toAudioData();this.encoder.encode(i),i.close(),r&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(n=>this.encoder.addEventListener("dequeue",n,{once:!0})),await this.muxer.mutex.currentPromise}}finally{r&&e.close()}}async doPcmEncoding(e,r){m(this.outputSampleSize),m(this.writeOutputValue);let{numberOfChannels:i,numberOfFrames:n,sampleRate:s,timestamp:o}=e,a=2048,c=[];for(let f=0;f<n;f+=a){let p=Math.min(a,e.numberOfFrames-f),g=p*i*this.outputSampleSize,y=new ArrayBuffer(g),w=new DataView(y);c.push({frameCount:p,view:w})}let l=e.allocationSize({planeIndex:0,format:"f32-planar"}),u=new Float32Array(l/Float32Array.BYTES_PER_ELEMENT);for(let f=0;f<i;f++){e.copyTo(u,{planeIndex:f,format:"f32-planar"});for(let p=0;p<c.length;p++){let{frameCount:g,view:y}=c[p];for(let w=0;w<g;w++)this.writeOutputValue(y,(w*i+f)*this.outputSampleSize,u[p*a+w])}}r&&e.close();let d={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:i,sampleRate:s}};for(let f=0;f<c.length;f++){let{frameCount:p,view:g}=c[f],y=g.buffer,w=f*a,b=new ce(new Uint8Array(y),"key",o+w/s,p/s);this.encodingConfig.onEncodedPacket?.(b,d),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,b,d)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:r,sampleRate:i}=e,n=Ui({numberOfChannels:r,sampleRate:i,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(n);let s=xr.find(o=>o.supports(this.encodingConfig.codec,n));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(o,a)=>{if(!(o instanceof ce))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(a!==void 0&&(!a||typeof a!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(o,a),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,o,a).catch(c=>{this.error??(this.error=c)})},await this.customEncoder.init();else if(le.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(n)).supported)throw new Error(`This specific encoder configuration (${n.codec}, ${n.bitrate} bps, ${n.numberOfChannels} channels, ${n.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);let a=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(c,l)=>{if(this.encodingConfig.codec==="aac"&&l?.decoderConfig){let d=!1;if(!l.decoderConfig.description||l.decoderConfig.description.byteLength<2?d=!0:d=Qt(we(l.decoderConfig.description)).objectType===0,d){let f=Number(te(n.codec.split(".")));l.decoderConfig.description=ti({objectType:f,numberOfChannels:l.decoderConfig.numberOfChannels,sampleRate:l.decoderConfig.sampleRate})}}let u=ce.fromEncodedChunk(c);this.encodingConfig.onEncodedPacket?.(u,l),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,u,l).catch(d=>{this.error??(this.error=d)})},error:c=>{c.stack=a,this.error??(this.error=c)}}),this.encoder.configure(n)}m(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:r,sampleSize:i,littleEndian:n}=Ie(e);switch(this.outputSampleSize=i,i){case 1:r==="unsigned"?this.writeOutputValue=(s,o,a)=>s.setUint8(o,fe((a+1)*127.5,0,255)):r==="signed"?this.writeOutputValue=(s,o,a)=>{s.setInt8(o,fe(Math.round(a*128),-128,127))}:r==="ulaw"?this.writeOutputValue=(s,o,a)=>{let c=fe(Math.floor(a*32767),-32768,32767);s.setUint8(o,Ws(c))}:r==="alaw"?this.writeOutputValue=(s,o,a)=>{let c=fe(Math.floor(a*32767),-32768,32767);s.setUint8(o,Hs(c))}:m(!1);break;case 2:r==="unsigned"?this.writeOutputValue=(s,o,a)=>s.setUint16(o,fe((a+1)*32767.5,0,65535),n):r==="signed"?this.writeOutputValue=(s,o,a)=>s.setInt16(o,fe(Math.round(a*32767),-32768,32767),n):m(!1);break;case 3:r==="unsigned"?this.writeOutputValue=(s,o,a)=>fr(s,o,fe((a+1)*83886075e-1,0,16777215),n):r==="signed"?this.writeOutputValue=(s,o,a)=>cs(s,o,fe(Math.round(a*8388607),-8388608,8388607),n):m(!1);break;case 4:r==="unsigned"?this.writeOutputValue=(s,o,a)=>s.setUint32(o,fe((a+1)*21474836475e-1,0,4294967295),n):r==="signed"?this.writeOutputValue=(s,o,a)=>s.setInt32(o,fe(Math.round(a*2147483647),-2147483648,2147483647),n):r==="float"?this.writeOutputValue=(s,o,a)=>s.setFloat32(o,a,n):m(!1);break;case 8:r==="float"?this.writeOutputValue=(s,o,a)=>s.setFloat64(o,a,n):m(!1);break;default:Ae(i),m(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.state!=="closed"&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},Wr=class extends ur{constructor(e){Io(e),super(e.codec),this._encoder=new Xn(this,e)}add(e){if(!(e instanceof Me))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}};var Wi=class extends Nr{constructor(e){if(super(),this._connectedTrack=null,!Dt.includes(e))throw new TypeError(`Invalid subtitle codec \'${e}\'. Must be one of: ${Dt.join(", ")}.`);this._codec=e}};var bc=["video","audio","subtitle"],Gn=t=>{if(!t||typeof t!="object")throw new TypeError("metadata must be an object.");if(t.languageCode!==void 0&&!st(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&&hs(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.")},At=class{constructor(e){if(this.state="pending",this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Ht,this._metadataTags={},!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof cr))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof Vt))throw new TypeError("options.target must be a Target.");if(e.target._output)throw new Error("Target is already used for another output.");e.target._output=this,this.format=e.format,this.target=e.target,this._writer=e.target._createWriter(),this._muxer=e.format._createMuxer(this)}addVideoTrack(e,r={}){if(!(e instanceof lr))throw new TypeError("source must be a VideoSource.");if(Gn(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(!this.format.supportsVideoRotationMetadata&&r.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);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.`);this._addTrack("video",e,r)}addAudioTrack(e,r={}){if(!(e instanceof ur))throw new TypeError("source must be an AudioSource.");Gn(r),this._addTrack("audio",e,r)}addSubtitleTrack(e,r={}){if(!(e instanceof Wi))throw new TypeError("source must be a SubtitleSource.");Gn(r),this._addTrack("subtitle",e,r)}setMetadataTags(e){if(gr(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e,r,i){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(r._connectedTrack)throw new Error("Source is already used for a track.");let n=this.format.getSupportedTrackCounts(),s=this._tracks.reduce((l,u)=>l+(u.type===e?1:0),0),o=n[e].max;if(s===o)throw new Error(o===0?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${o} ${e} track${o===1?"":"s"}.`);let a=n.total.max;if(this._tracks.length===a)throw new Error(`${this.format._name} does not support more than ${a} tracks${a===1?"":"s"} in total.`);let c={id:this._tracks.length+1,output:this,type:e,source:r,metadata:i};if(c.type==="video"){let l=this.format.getSupportedVideoCodecs();if(l.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!l.includes(c.source._codec))throw new Error(`Codec \'${c.source._codec}\' cannot be contained within ${this.format._name}. Supported video codecs are: ${l.map(u=>`\'${u}\'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}else if(c.type==="audio"){let l=this.format.getSupportedAudioCodecs();if(l.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!l.includes(c.source._codec))throw new Error(`Codec \'${c.source._codec}\' cannot be contained within ${this.format._name}. Supported audio codecs are: ${l.map(u=>`\'${u}\'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}else if(c.type==="subtitle"){let l=this.format.getSupportedSubtitleCodecs();if(l.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!l.includes(c.source._codec))throw new Error(`Codec \'${c.source._codec}\' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${l.map(u=>`\'${u}\'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}this._tracks.push(c),r._connectedTrack=c}async start(){let e=this.format.getSupportedTrackCounts();for(let i of bc){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?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started",this._writer.start();let i=await this._mutex.acquire();await this._muxer.start();let n=this._tracks.map(s=>s.source._start());await Promise.all(n),i()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return console.warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){console.warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let e=await this._mutex.acquire(),r=this._tracks.map(i=>i.source._flushOrWaitForOngoingClose(!0));await Promise.all(r),await this._writer.close(),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?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";let e=await this._mutex.acquire(),r=this._tracks.map(i=>i.source._flushOrWaitForOngoingClose(!1));await Promise.all(r),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",e()})()}};var Bo=t=>{if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("options.video, when provided, must be an object.");if(t?.discard!==void 0&&typeof t.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if(t?.forceTranscode!==void 0&&typeof t.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if(t?.codec!==void 0&&!Ce.includes(t.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${Ce.join(", ")}.`);if(t?.bitrate!==void 0&&!(t.bitrate instanceof ze)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if(t?.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if(t?.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if(t?.fit!==void 0&&!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.video.fit, when provided, must be one of \'fill\', \'contain\', or \'cover\'.");if(t?.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw new TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if(t?.rotate!==void 0&&![0,90,180,270].includes(t.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if(t?.allowRotationMetadata!==void 0&&typeof t.allowRotationMetadata!="boolean")throw new TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if(t?.crop!==void 0&&vr(t.crop,"options.video."),t?.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError("options.video.frameRate, when provided, must be a finite positive number.");if(t?.alpha!==void 0&&!["discard","keep"].includes(t.alpha))throw new TypeError("options.video.alpha, when provided, must be either \'discard\' or \'keep\'.");if(t?.keyFrameInterval!==void 0&&(!Number.isFinite(t.keyFrameInterval)||t.keyFrameInterval<0))throw new TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if(t?.process!==void 0&&typeof t.process!="function")throw new TypeError("options.video.process, when provided, must be a function.");if(t?.processedWidth!==void 0&&(!Number.isInteger(t.processedWidth)||t.processedWidth<=0))throw new TypeError("options.video.processedWidth, when provided, must be a positive integer.");if(t?.processedHeight!==void 0&&(!Number.isInteger(t.processedHeight)||t.processedHeight<=0))throw new TypeError("options.video.processedHeight, when provided, must be a positive integer.");if(t?.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(t.hardwareAcceleration))throw new TypeError("options.video.hardwareAcceleration, when provided, must be \'no-preference\', \'prefer-hardware\' or \'prefer-software\'.")},Do=t=>{if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("options.audio, when provided, must be an object.");if(t?.discard!==void 0&&typeof t.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if(t?.forceTranscode!==void 0&&typeof t.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if(t?.codec!==void 0&&!_e.includes(t.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${_e.join(", ")}.`);if(t?.bitrate!==void 0&&!(t.bitrate instanceof ze)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if(t?.numberOfChannels!==void 0&&(!Number.isInteger(t.numberOfChannels)||t.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if(t?.sampleRate!==void 0&&(!Number.isInteger(t.sampleRate)||t.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if(t?.process!==void 0&&typeof t.process!="function")throw new TypeError("options.audio.process, when provided, must be a function.");if(t?.processedNumberOfChannels!==void 0&&(!Number.isInteger(t.processedNumberOfChannels)||t.processedNumberOfChannels<=0))throw new TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if(t?.processedSampleRate!==void 0&&(!Number.isInteger(t.processedSampleRate)||t.processedSampleRate<=0))throw new TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.")},Yn=2,Zn=48e3,Lr=class t{static async init(e){let r=new t(e);return await r._init(),r}constructor(e){if(this._addedCounts={video:0,audio:0,subtitle:0},this._totalTrackCount=0,this._trackPromises=[],this._executed=!1,this._synchronizer=new Jn,this._totalDuration=null,this._maxTimestamps=new Map,this._canceled=!1,this.onProgress=void 0,this._computeProgress=!1,this._lastProgress=0,this.isValid=!1,this.utilizedTracks=[],this.discardedTracks=[],!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.input instanceof _t))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof At))throw new TypeError("options.output must be an Output.");if(e.output._tracks.length>0||Object.keys(e.output._metadataTags).length>0||e.output.state!=="pending")throw new TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");if(typeof e.video!="function"&&Bo(e.video),typeof e.audio!="function"&&Do(e.audio),e.trim!==void 0&&(!e.trim||typeof e.trim!="object"))throw new TypeError("options.trim, when provided, must be an object.");if(e.trim?.start!==void 0&&!Number.isFinite(e.trim.start))throw new TypeError("options.trim.start, when provided, must be a finite number.");if(e.trim?.end!==void 0&&!Number.isFinite(e.trim.end))throw new TypeError("options.trim.end, when provided, must be a finite number.");if(e.trim?.start!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");if(e.tags!==void 0&&(typeof e.tags!="object"||!e.tags)&&typeof e.tags!="function")throw new TypeError("options.tags, when provided, must be an object or a function.");if(typeof e.tags=="object"&&gr(e.tags),e.showWarnings!==void 0&&typeof e.showWarnings!="boolean")throw new TypeError("options.showWarnings, when provided, must be a boolean.");this._options=e,this.input=e.input,this.output=e.output;let{promise:r,resolve:i}=he();this._started=r,this._start=i}async _init(){this._startTimestamp=this._options.trim?.start??Math.max(await this.input.getFirstTimestamp(),0),this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp);let e=await this.input.getTracks(),r=this.output.format.getSupportedTrackCounts(),i=1,n=1;for(let l of e){let u;if(l.isVideoTrack()?this._options.video&&(typeof this._options.video=="function"?(u=await this._options.video(l,i),Bo(u),i++):u=this._options.video):l.isAudioTrack()?this._options.audio&&(typeof this._options.audio=="function"?(u=await this._options.audio(l,n),Do(u),n++):u=this._options.audio):m(!1),u?.discard){this.discardedTracks.push({track:l,reason:"discarded_by_user"});continue}if(this._totalTrackCount===r.total.max){this.discardedTracks.push({track:l,reason:"max_track_count_reached"});continue}if(this._addedCounts[l.type]===r[l.type].max){this.discardedTracks.push({track:l,reason:"max_track_count_of_type_reached"});continue}l.isVideoTrack()?await this._processVideoTrack(l,u??{}):l.isAudioTrack()&&await this._processAudioTrack(l,u??{})}let s=await this.input.getMetadataTags(),o;if(this._options.tags){let l=typeof this._options.tags=="function"?await this._options.tags(s):this._options.tags;gr(l),o=l}else o=s;let a=(await this.input.getFormat()).mimeType===this.output.format.mimeType,c=s.raw===o.raw;if(s.raw&&c&&!a&&delete o.raw,this.output.setMetadataTags(o),this.isValid=this._totalTrackCount>=r.total.min&&this._addedCounts.video>=r.video.min&&this._addedCounts.audio>=r.audio.min&&this._addedCounts.subtitle>=r.subtitle.min,this._options.showWarnings??!0){let l=[],u=this.discardedTracks.filter(d=>d.reason!=="discarded_by_user");u.length>0&&l.push("Some tracks had to be discarded from the conversion:",u),this.isValid||l.push(`\n\n`+this._getInvalidityExplanation().join("")),l.length>0&&console.warn(...l)}}_getInvalidityExplanation(){let e=[];if(this.discardedTracks.length===0)e.push("Due to missing tracks, this conversion cannot be executed.");else{let r=this.discardedTracks.every(i=>i.reason==="discarded_by_user"||i.reason==="no_encodable_target_codec");if(e.push("Due to discarded tracks, this conversion cannot be executed."),r){let i=this.discardedTracks.flatMap(n=>n.reason==="discarded_by_user"?[]:n.track.type==="video"?this.output.format.getSupportedVideoCodecs():n.track.type==="audio"?this.output.format.getSupportedAudioCodecs():this.output.format.getSupportedSubtitleCodecs());i.length===1?e.push(`\nTracks were discarded because your environment is not able to encode \'${i[0]}\'.`):e.push(`\nTracks were discarded because your environment is not able to encode any of the following codecs: ${i.map(n=>`\'${n}\'`).join(", ")}.`),i.includes("mp3")&&e.push(`\nThe @mediabunny/mp3-encoder extension package provides support for encoding MP3.`),i.includes("aac")&&e.push(`\nThe @mediabunny/aac-encoder extension package provides support for encoding AAC.`),(i.includes("ac3")||i.includes("eac3"))&&e.push(`\nThe @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),i.includes("flac")&&e.push(`\nThe @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else e.push(`\nCheck the discardedTracks field for more info.`)}return e}async execute(){if(!this.isValid)throw new Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.\n`+this._getInvalidityExplanation().join(""));if(this._executed)throw new Error("Conversion cannot be executed twice.");if(this._executed=!0,this.onProgress){let e=this.utilizedTracks.map(i=>i.computeDuration()),r=Math.max(0,...await Promise.all(e));this._computeProgress=!0,this._totalDuration=Math.min(r-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let i of this.utilizedTracks)this._maxTimestamps.set(i.id,0);this.onProgress?.(0)}await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(e){throw this._canceled||this.cancel(),e}if(this._canceled)throw new Li;await this.output.finalize(),this._computeProgress&&this.onProgress?.(1)}async cancel(){if(!(this.output.state==="finalizing"||this.output.state==="finalized")){if(this._canceled){console.warn("Conversion already canceled.");return}this._canceled=!0,await this.output.cancel()}}async _processVideoTrack(e,r){let i=e.codec;if(!i){this.discardedTracks.push({track:e,reason:"unknown_source_codec"});return}let n,s=qt(e.rotation+(r.rotate??0)),o=s,a=this.output.format.supportsVideoRotationMetadata&&(r.allowRotationMetadata??!0),[c,l]=s%180===0?[e.squarePixelWidth,e.squarePixelHeight]:[e.squarePixelHeight,e.squarePixelWidth],u=r.crop;u&&Er(u,c,l);let[d,f]=u?[u.width,u.height]:[c,l],p=d,g=f,y=p/g,w=B=>Math.ceil(B/2)*2;r.width!==void 0&&r.height===void 0?(p=w(r.width),g=w(Math.round(p/y))):r.width===void 0&&r.height!==void 0?(g=w(r.height),p=w(Math.round(g*y))):r.width!==void 0&&r.height!==void 0&&(p=w(r.width),g=w(r.height));let b=await e.getFirstTimestamp(),T=this.output.format.getSupportedVideoCodecs(),S=!!r.forceTranscode||b<this._startTimestamp||!!r.frameRate||r.keyFrameInterval!==void 0||r.process!==void 0||r.bitrate!==void 0||!T.includes(i)||r.codec&&r.codec!==i||p!==d||g!==f||s!==0&&!a||!!u,D=r.alpha??"discard";if(S){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec"});return}r.codec&&(T=T.filter(j=>j===r.codec));let I=r.bitrate??jn,U=await Ro(T,{width:r.process&&r.processedWidth?r.processedWidth:p,height:r.process&&r.processedHeight?r.processedHeight:g,bitrate:I});if(!U){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec"});return}let R={codec:U,bitrate:I,keyFrameInterval:r.keyFrameInterval,sizeChangeBehavior:r.fit??"passThrough",alpha:D,hardwareAcceleration:r.hardwareAcceleration},$=new Vr(R);n=$;let me=p!==d||g!==f||s!==0&&(!a||r.process!==void 0)||!!u||e.squarePixelWidth!==e.codedWidth||e.squarePixelHeight!==e.codedHeight;if(!me){let j=new At({format:new Pt,target:new Or}),z=new Vr(R);j.addVideoTrack(z),await j.start();let J=await new ct(e).getSample(b);if(J)try{await z.add(J),J.close(),await j.finalize()}catch(re){console.info("Error when probing encoder support. Falling back to rerender path.",re),me=!0,j.cancel()}else await j.cancel()}me?this._trackPromises.push((async()=>{await this._started;let z=new Ir(e,{width:p,height:g,fit:r.fit??"fill",rotation:s,crop:r.crop,poolSize:1,alpha:D==="keep"}).canvases(this._startTimestamp,this._endTimestamp),W=r.frameRate;o=0;let J=null,re=null,ee=null,Z=async ae=>{m(J),m(W!==void 0);let de=Math.round((ae-re)*W);for(let Be=1;Be<de;Be++){let Oe=new xe(J,{timestamp:re+Be/W,duration:1/W});await this._registerVideoSample(e,r,$,Oe),Oe.close()}};for await(let{canvas:ae,timestamp:de,duration:Be}of z){if(this._canceled)return;let Oe=Math.max(de-this._startTimestamp,0);if(ee=Oe+Be,W!==void 0){let h=Math.floor(Oe*W)/W;if(J!==null)if(h<=re){J=ae,re=h;continue}else await Z(h);Oe=h}let hr=new xe(ae,{timestamp:Oe,duration:W!==void 0?1/W:Be});await this._registerVideoSample(e,r,$,hr),hr.close(),W!==void 0&&(J=ae,re=Oe)}J&&(m(ee!==null),m(W!==void 0),await Z(Math.floor(ee*W)/W)),$.close(),this._synchronizer.closeTrack(e.id)})()):this._trackPromises.push((async()=>{await this._started;let j=new ct(e),z=r.frameRate,W=null,J=null,re=null,ee=async Z=>{m(W),m(z!==void 0);let ae=Math.round((Z-J)*z);for(let de=1;de<ae;de++)W.setTimestamp(J+de/z),W.setDuration(1/z),await this._registerVideoSample(e,r,$,W);W.close()};for await(let Z of j.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled){Z.close(),W?.close();return}let ae=Math.max(Z.timestamp-this._startTimestamp,0);if(re=ae+Z.duration,z!==void 0){let de=Math.floor(ae*z)/z;if(W!==null)if(de<=J){W.close(),W=Z,J=de;continue}else await ee(de);ae=de,Z.setDuration(1/z)}Z.setTimestamp(ae),await this._registerVideoSample(e,r,$,Z),z!==void 0?(W=Z,J=ae):Z.close()}W&&(m(re!==null),m(z!==void 0),await ee(Math.floor(re*z)/z)),$.close(),this._synchronizer.closeTrack(e.id)})())}else{let B=new Ni(i);n=B,this._trackPromises.push((async()=>{await this._started;let I=new Xe(e),R={decoderConfig:await e.getDecoderConfig()??void 0},$=Number.isFinite(this._endTimestamp)?await I.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let me of I.packets(void 0,$,{verifyKeyPackets:!0})){if(this._canceled)return;let j=me.clone({timestamp:me.timestamp-this._startTimestamp,sideData:D==="discard"?{}:me.sideData});m(j.timestamp>=0),this._reportProgress(e.id,j.timestamp),await B.add(j,R),this._synchronizer.shouldWait(e.id,j.timestamp)&&await this._synchronizer.wait(j.timestamp)}B.close(),this._synchronizer.closeTrack(e.id)})())}this.output.addVideoTrack(n,{frameRate:r.frameRate,languageCode:st(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition,rotation:o}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerVideoSample(e,r,i,n){if(this._canceled)return;this._reportProgress(e.id,n.timestamp);let s;if(!r.process)s=[n];else{let o=r.process(n);o instanceof Promise&&(o=await o),Array.isArray(o)||(o=o===null?[]:[o]),s=o.map(a=>a instanceof xe?a:typeof VideoFrame<"u"&&a instanceof VideoFrame?new xe(a):new xe(a,{timestamp:n.timestamp,duration:n.duration}))}for(let o of s){if(this._canceled)break;await i.add(o),this._synchronizer.shouldWait(e.id,o.timestamp)&&await this._synchronizer.wait(o.timestamp)}for(let o of s)o!==n&&o.close()}async _processAudioTrack(e,r){let i=e.codec;if(!i){this.discardedTracks.push({track:e,reason:"unknown_source_codec"});return}let n,s=e.numberOfChannels,o=e.sampleRate,a=await e.getFirstTimestamp(),c=r.numberOfChannels??s,l=r.sampleRate??o,u=c!==s||l!==o||a<this._startTimestamp||a>this._startTimestamp&&!this.output.format.supportsTimestampedMediaData,d=this.output.format.getSupportedAudioCodecs();if(!r.forceTranscode&&!r.bitrate&&!u&&d.includes(i)&&(!r.codec||r.codec===i)&&!r.process){let f=new Vi(i);n=f,this._trackPromises.push((async()=>{await this._started;let p=new Xe(e),y={decoderConfig:await e.getDecoderConfig()??void 0},w=Number.isFinite(this._endTimestamp)?await p.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let b of p.packets(void 0,w)){if(this._canceled)return;let T=b.clone({timestamp:b.timestamp-this._startTimestamp});m(T.timestamp>=0),this._reportProgress(e.id,T.timestamp),await f.add(T,y),this._synchronizer.shouldWait(e.id,T.timestamp)&&await this._synchronizer.wait(T.timestamp)}f.close(),this._synchronizer.closeTrack(e.id)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec"});return}let p=null;r.codec&&(d=d.filter(w=>w===r.codec));let g=r.bitrate??jn,y=await $n(d,{numberOfChannels:r.process&&r.processedNumberOfChannels?r.processedNumberOfChannels:c,sampleRate:r.process&&r.processedSampleRate?r.processedSampleRate:l,bitrate:g});if(!y.some(w=>Bt.includes(w))&&d.some(w=>Bt.includes(w))&&(c!==Yn||l!==Zn)){let b=(await $n(d,{numberOfChannels:Yn,sampleRate:Zn,bitrate:g})).find(T=>Bt.includes(T));b&&(u=!0,p=b,c=Yn,l=Zn)}else p=y[0]??null;if(p===null){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec"});return}if(u)n=this._resampleAudio(e,r,p,c,l,g);else{let w=new Wr({codec:p,bitrate:g});n=w,this._trackPromises.push((async()=>{await this._started;let b=new Yt(e);for await(let T of b.samples(void 0,this._endTimestamp)){if(this._canceled){T.close();return}T.setTimestamp(T.timestamp-this._startTimestamp),await this._registerAudioSample(e,r,w,T),T.close()}w.close(),this._synchronizer.closeTrack(e.id)})())}}this.output.addAudioTrack(n,{languageCode:st(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerAudioSample(e,r,i,n){if(this._canceled)return;this._reportProgress(e.id,n.timestamp);let s;if(!r.process)s=[n];else{let o=r.process(n);if(o instanceof Promise&&(o=await o),Array.isArray(o)||(o=o===null?[]:[o]),!o.every(a=>a instanceof Me))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");s=o}for(let o of s){if(this._canceled)break;await i.add(o),this._synchronizer.shouldWait(e.id,o.timestamp)&&await this._synchronizer.wait(o.timestamp)}for(let o of s)o!==n&&o.close()}_resampleAudio(e,r,i,n,s,o){let a=new Wr({codec:i,bitrate:o});return this._trackPromises.push((async()=>{await this._started;let c=new es({targetNumberOfChannels:n,targetSampleRate:s,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async d=>{await this._registerAudioSample(e,r,a,d),d.close()}}),u=new Yt(e).samples(this._startTimestamp,this._endTimestamp);for await(let d of u){if(this._canceled){d.close();return}await c.add(d),d.close()}await c.finalize(),a.close(),this._synchronizer.closeTrack(e.id)})()),a}_reportProgress(e,r){if(!this._computeProgress)return;m(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(r,this._maxTimestamps.get(e)));let i=Math.min(...this._maxTimestamps.values()),n=fe(i/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n))}},Li=class extends Error{constructor(e="Conversion has been canceled."){super(e),this.name="ConversionCanceledError"}},Mo=5,Jn=class{constructor(){this.maxTimestamps=new Map,this.resolvers=[]}computeMinAndMaybeResolve(){let e=1/0;for(let[,r]of this.maxTimestamps)e=Math.min(e,r);for(let r=0;r<this.resolvers.length;r++){let i=this.resolvers[r];i.timestamp-e<Mo&&(i.resolve(),this.resolvers.splice(r,1),r--)}return e}shouldWait(e,r){this.maxTimestamps.set(e,Math.max(r,this.maxTimestamps.get(e)??-1/0));let i=this.computeMinAndMaybeResolve();return r-i>=Mo}wait(e){let{promise:r,resolve:i}=he();return this.resolvers.push({timestamp:e,resolve:i}),r}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}},es=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.startTime=e.startTime,this.endTime=e.endTime,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=0,this.maxWrittenFrame=-1}doChannelMixerSetup(){m(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,r=this.targetNumberOfChannels;e===1&&r===2?this.channelMixer=(i,n)=>i[n*e]:e===1&&r===4?this.channelMixer=(i,n,s)=>i[n*e]*+(s<2):e===1&&r===6?this.channelMixer=(i,n,s)=>i[n*e]*+(s===2):e===2&&r===1?this.channelMixer=(i,n)=>{let s=n*e;return .5*(i[s]+i[s+1])}:e===2&&r===4?this.channelMixer=(i,n,s)=>i[n*e+s]*+(s<2):e===2&&r===6?this.channelMixer=(i,n,s)=>i[n*e+s]*+(s<2):e===4&&r===1?this.channelMixer=(i,n)=>{let s=n*e;return .25*(i[s]+i[s+1]+i[s+2]+i[s+3])}:e===4&&r===2?this.channelMixer=(i,n,s)=>{let o=n*e;return .5*(i[o+s]+i[o+s+2])}:e===4&&r===6?this.channelMixer=(i,n,s)=>{let o=n*e;return s<2?i[o+s]:s===2||s===3?0:i[o+s-2]}:e===6&&r===1?this.channelMixer=(i,n)=>{let s=n*e;return Math.SQRT1_2*(i[s]+i[s+1])+i[s+2]+.5*(i[s+4]+i[s+5])}:e===6&&r===2?this.channelMixer=(i,n,s)=>{let o=n*e;return i[o+s]+Math.SQRT1_2*(i[o+2]+i[o+s+4])}:e===6&&r===4?this.channelMixer=(i,n,s)=>{let o=n*e;return s<2?i[o+s]+Math.SQRT1_2*i[o+2]:i[o+s+2]}:this.channelMixer=(i,n,s)=>s<e?i[n*e+s]:0}ensureTempBufferSize(e){let r=this.tempSourceBuffer.length;for(;r<e;)r*=2;if(r!==this.tempSourceBuffer.length){let i=new Float32Array(r);i.set(this.tempSourceBuffer),this.tempSourceBuffer=i}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup());let r=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(r);let i=e.allocationSize({planeIndex:0,format:"f32"}),n=new Float32Array(this.tempSourceBuffer.buffer,0,i/4);e.copyTo(n,{planeIndex:0,format:"f32"});let s=e.timestamp-this.startTime,o=e.numberOfFrames/this.sourceSampleRate,a=Math.min(s+o,this.endTime-this.startTime),c=Math.floor(s*this.targetSampleRate),l=Math.ceil(a*this.targetSampleRate);for(let u=c;u<l;u++){if(u<this.bufferStartFrame)continue;for(;u>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let d=u-this.bufferStartFrame;m(d<this.bufferSizeInFrames);let g=(u/this.targetSampleRate-s)*this.sourceSampleRate,y=Math.floor(g),w=Math.ceil(g),b=g-y;for(let T=0;T<this.targetNumberOfChannels;T++){let S=0,D=0;y>=0&&y<e.numberOfFrames&&(S=this.channelMixer(n,y,T)),w>=0&&w<e.numberOfFrames&&(D=this.channelMixer(n,w,T));let B=S+b*(D-S),I=d*this.targetNumberOfChannels+T;this.outputBuffer[I]+=B}this.maxWrittenFrame=Math.max(this.maxWrittenFrame,d)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame<0)return;let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,r=new Float32Array(e);r.set(this.outputBuffer.subarray(0,e));let i=this.bufferStartFrame/this.targetSampleRate,n=new Me({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:i,data:r});await this.onSample(n),this.outputBuffer.fill(0),this.maxWrittenFrame=-1}finalize(){return this.finalizeCurrentBuffer()}};var zo=Symbol.for("mediabunny loaded");globalThis[zo]&&console.error(`[WARNING]\nMediabunny 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[zo]=!0;var Oo=[Fn,Rn,Bn],ts=self,Hr=null,dr=null;function bt(t,e){e?.length?ts.postMessage(t,e):ts.postMessage(t)}async function yc(t,e,r,i){try{console.log("[AV Worker] extractFrames start:",{url:t,duration:e,frameHeight:r,frameCount:i});let n=new _t({source:new nr(t),formats:Oo});dr=n;let s=await n.getPrimaryVideoTrack();if(console.log("[AV Worker] videoTrack:",s?{codec:s.codec,displayWidth:s.displayWidth,displayHeight:s.displayHeight}:null),!s){n.dispose(),dr=null,bt({type:"frames-done"});return}let o=new ct(s),a=[];for(let g=0;g<i;g++)a.push(g/i*e);console.log("[AV Worker] timestamps:",a);let c=r/s.displayHeight,l=Math.round(s.displayWidth*c),u=r;console.log("[AV Worker] thumb size:",l,"x",u);let d=new OffscreenCanvas(l,u),f=d.getContext("2d");if(console.log("[AV Worker] offCtx:",!!f),!f){console.error("[AV Worker] Failed to get 2d context from OffscreenCanvas"),n.dispose(),dr=null,bt({type:"frames-done"});return}let p=0;for await(let g of o.samplesAtTimestamps(a)){if(!g){bt({type:"frame",index:p,bitmap:null}),p++;continue}f.clearRect(0,0,l,u),g.draw(f,0,0,l,u),g.close();let y=await createImageBitmap(d);bt({type:"frame",index:p,bitmap:y},[y]),p++}console.log("[AV Worker] extractFrames done, total:",p),bt({type:"frames-done",total:p}),n.dispose(),dr=null}catch(n){console.error("[AV Worker] extractFrames error:",n),bt({type:"error",source:"frames",message:n instanceof Error?n.message:String(n)})}}async function Tc(t,e,r){let i=null;try{i=new _t({source:new nr(t),formats:Oo});let n=new Wt,s=new At({format:new Pt,target:n}),o=await Lr.init({input:i,output:s,trim:{start:e,end:r},showWarnings:!1});if(Hr=o,!o.isValid){let a=o.discardedTracks.map(c=>c.reason).join("; ");throw new Error(`Conversion invalid: ${a}`)}if(o.onProgress=a=>{bt({type:"encode-progress",percent:Math.round(a*100)})},await o.execute(),Hr=null,!n.buffer)throw new Error("Encode produced no output");bt({type:"encode-complete",buffer:n.buffer},[n.buffer])}catch(n){Hr=null,bt({type:"error",source:"encode",message:n instanceof Error?n.message:String(n)})}finally{i?.dispose()}}function kc(){Hr?.cancel(),Hr=null,dr?.dispose(),dr=null}ts.addEventListener("message",t=>{let e=t.data;switch(e.type){case"extract-frames":yc(e.url,e.duration,e.frameHeight,e.frameCount);break;case"encode":Tc(e.url,e.startTime,e.endTime);break;case"dispose":kc();break}});})();\n/*! Bundled license information:\n\nmediabunny/dist/modules/src/misc.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/metadata.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/shared/bitstream.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/shared/aac-misc.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/codec.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/shared/ac3-misc.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/codec-data.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/demuxer.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/custom-coder.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/packet.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/pcm.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/sample.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/media-sink.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/input-track.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/isobmff/isobmff-misc.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/isobmff/isobmff-reader.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/isobmff/isobmff-demuxer.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/matroska/ebml.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/matroska/matroska-misc.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/matroska/matroska-demuxer.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/adts/adts-reader.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/input-format.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/source.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/input.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/reader.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/muxer.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/subtitles.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/isobmff/isobmff-boxes.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/writer.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/target.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/isobmff/isobmff-muxer.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/output-format.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/encode.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/media-source.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/output.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/conversion.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n\nmediabunny/dist/modules/src/index.js:\n (*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n *)\n*/\n',
],
{ type: "application/javascript" },
),
t = URL.createObjectURL(e),
r = new Worker(t);
return URL.revokeObjectURL(t), r;
}
e.s([], 938719),
e.s(["supportsWebCodecs", () => r], 702316),
e.s([], 497566),
e.s(["createAVWorker", () => i], 447720),
e.s([], 380586),
e.s([], 348469),
e.i(938719),
e.s(["AVEditor", () => t], 747112);
};
export default moduleFactory;