baize-compress 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +165 -0
  2. package/README.md +82 -2
  3. package/dist/assets/compress-BQao8LZ4.js +501 -0
  4. package/dist/assets/compress-CRhfuN3_.js +4 -0
  5. package/dist/assets/compress-Di96HUYT.js +1 -0
  6. package/dist/assets/compress-I5veHSQ1.js +110 -0
  7. package/dist/assets/compress-XlJOQ9AQ.js +1 -0
  8. package/dist/assets/pool.worker-BZcE0nvO.js +4 -0
  9. package/dist/index.js +150 -0
  10. package/dist/plugins/gif.js +16 -0
  11. package/dist/plugins/jpeg-webp.js +12 -0
  12. package/dist/plugins/media.js +32 -0
  13. package/dist/plugins/png.js +12 -0
  14. package/dist/plugins/svg.js +14 -0
  15. package/dist/types/config.d.ts +1 -0
  16. package/dist/types/main.d.ts +14 -0
  17. package/dist/types/plugins/gif/compress.d.ts +2 -0
  18. package/dist/types/plugins/gif/index.d.ts +6 -0
  19. package/dist/types/plugins/jpeg-webp/compress.d.ts +2 -0
  20. package/dist/types/plugins/jpeg-webp/index.d.ts +2 -0
  21. package/dist/types/plugins/media/compress.d.ts +2 -0
  22. package/dist/types/plugins/media/index.d.ts +23 -0
  23. package/dist/types/plugins/png/compress.d.ts +2 -0
  24. package/dist/types/plugins/png/index.d.ts +2 -0
  25. package/dist/types/plugins/svg/compress.d.ts +2 -0
  26. package/dist/types/plugins/svg/index.d.ts +6 -0
  27. package/dist/types/pool.worker.d.ts +1 -0
  28. package/dist/types/types.d.ts +45 -0
  29. package/dist/types/utils.d.ts +4 -0
  30. package/dist/types/workerManage.d.ts +15 -0
  31. package/dist/types/workerTask.d.ts +16 -0
  32. package/dist/utils-DHI2QTd1.js +8 -0
  33. package/index.d.ts +2 -0
  34. package/package.json +100 -4
  35. package/plugins/gif.d.ts +2 -0
  36. package/plugins/jpeg-webp.d.ts +2 -0
  37. package/plugins/media.d.ts +2 -0
  38. package/plugins/png.d.ts +2 -0
  39. package/plugins/svg.d.ts +2 -0
@@ -0,0 +1,501 @@
1
+ var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports);
2
+ /*!
3
+ * Copyright (c) 2026-present, Vanilagy and contributors
4
+ *
5
+ * This Source Code Form is subject to the terms of the Mozilla Public
6
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
7
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
8
+ */
9
+ function t(e){if(!e)throw Error(`Assertion failed.`)}const n=Math.PI/180,r=180/Math.PI,i=e=>{let t=(e%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw Error(`Invalid rotation ${e}.`)},a=[1,0,0,0,1,0,0,0,1],o=(e,t,n)=>{let[r,i,,a,o]=e,s=Math.abs(r)*t+Math.abs(a)*n,c=Math.abs(i)*t+Math.abs(o)*n;return f(f(u(-t/2,-n/2),e),u(s/2,c/2))},s=e=>{let[t,n]=e,a=Math.atan2(n,c(e)?-t:t);return i(je(a*r,90))},c=e=>{let[t,n,,r,i]=e;return t*i-n*r<0},l=e=>{let t=e*n,r=Math.round(Math.cos(t)),i=Math.round(Math.sin(t));return[r,i,0,-i,r,0,0,0,1]},u=(e,t)=>[1,0,0,0,1,0,e,t,1],d=(e,t)=>[e,0,0,0,t,0,0,0,1],f=(e,t)=>{let n=Array(9);for(let r=0;r<3;r++)for(let i=0;i<3;i++)n[3*r+i]=e[3*r]*t[i]+e[3*r+1]*t[3+i]+e[3*r+2]*t[6+i];return n},p=(e,t,n,r)=>({rotation:i(e+(t?-n:n)),flip:t!==r}),m=e=>e&&e[e.length-1],h=e=>e>=0&&e<2**32,g=e=>e>=-(2**31)&&e<2**31,_=e=>{let t=0;for(;e.readBits(1)===0&&t<32;)t++;if(t>=32)throw Error(`Invalid exponential-Golomb code.`);return 2**t-1+e.readBits(t)},v=(e,t)=>{let n=t+1,r=Math.floor(Math.log2(n));e.writeBits(r,0),e.writeBits(1,1),e.writeBits(r,n-2**r)},y=e=>{let t=_(e);return t%2==0?-(t/2):(t+1)/2},b=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),x=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),S=globalThis.TextEncoder===void 0?class{constructor(){this.encoding=`utf-8`}encode(e=``){let t=new Uint8Array(3*e.length),n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i<128)t[n++]=i;else if(i<2048)t[n++]=192|i>>6,t[n++]=128|i&63;else if(i<55296||i>57343)t[n++]=224|i>>12,t[n++]=128|i>>6&63,t[n++]=128|i&63;else{let a=r+1<e.length?e.charCodeAt(r+1):0;i<56320&&a>=56320&&a<=57343?(i=65536+(i-55296<<10)+(a-56320),r++,t[n++]=240|i>>18,t[n++]=128|i>>12&63,t[n++]=128|i>>6&63,t[n++]=128|i&63):(t[n++]=239,t[n++]=191,t[n++]=189)}}return t.slice(0,n)}}:globalThis.TextEncoder,C=globalThis.TextDecoder===void 0?class{constructor(e=`utf-8`){let t=e.trim().toLowerCase();if(t===`utf-8`||t===`utf8`||t===`unicode-1-1-utf-8`)this.encoding=`utf-8`;else if(t===`utf-16le`||t===`utf-16`)this.encoding=`utf-16le`;else if(t===`utf-16be`)this.encoding=`utf-16be`;else throw RangeError(`The encoding label provided ('${e}') is invalid.`)}decode(e){let t=e?b(e):/* @__PURE__ */ new Uint8Array,n=[];if(this.encoding===`utf-8`){let e=t.length>=3&&t[0]===239&&t[1]===187&&t[2]===191?3:0;for(;e<t.length;){let r=t[e];if(r<128){n.push(r),e++;continue}let i,a;if(r>=194&&r<224)i=1,a=r&31;else if(r>=224&&r<240)i=2,a=r&15;else if(r>=240&&r<245)i=3,a=r&7;else{n.push(65533),e++;continue}let o=r===224?160:r===240?144:128,s=r===237?159:r===244?143:191,c=1;for(;c<=i;c++){let n=e+c<t.length?t[e+c]:0;if(n<o||n>s)break;a=a<<6|n&63,o=128,s=191}e+=c,c<=i?n.push(65533):a>=65536?(a-=65536,n.push(55296|a>>10,56320|a&1023)):n.push(a)}}else{let e=this.encoding===`utf-16le`,r=e?255:254,i=e?254:255,a=t.length>=2&&t[0]===r&&t[1]===i?2:0;for(;a+1<t.length;){let r=e?t[a]|t[a+1]<<8:t[a]<<8|t[a+1];if(a+=2,r>=55296&&r<=56319){let i=a+1<t.length?e?t[a]|t[a+1]<<8:t[a]<<8|t[a+1]:-1;i>=56320&&i<=57343?(n.push(r,i),a+=2):(n.push(65533),a+1===t.length&&a++)}else r>=56320&&r<=57343?n.push(65533):n.push(r)}a<t.length&&n.push(65533)}let r=``;for(let e=0;e<n.length;e+=8192)r+=String.fromCharCode(...n.slice(e,e+8192));return r}}:globalThis.TextDecoder,w=/* #__PURE__ */ new C,ee=/* #__PURE__ */ new C(`utf-8`,{fatal:!0}),T=/* #__PURE__ */ new S,te=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),E={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ne=/* #__PURE__ */ te(E),re={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},ie=/* #__PURE__ */ te(re),ae={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},oe=/* #__PURE__ */ te(ae),se=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&e.fullRange!=null,ce=e=>!e||e.primaries==null&&e.transfer==null&&e.matrix==null&&e.fullRange==null,le={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},ue=e=>e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);var de=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(t=>{let n=!1;e=()=>{n||=(t(),this.pending--,!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}};const fe=/^[0-9a-fA-F]+$/,pe=e=>[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``),me=e=>{t(e.length%2==0);let n=new Uint8Array(e.length/2);for(let t=0;t<e.length;t+=2)n[t/2]=parseInt(e.slice(t,t+2),16);return n},he=e=>(e=e>>1&1431655765|(e&1431655765)<<1,e=e>>2&858993459|(e&858993459)<<2,e=e>>4&252645135|(e&252645135)<<4,e=e>>8&16711935|(e&16711935)<<8,e=e>>16&65535|(e&65535)<<16,e>>>0),ge=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+i>>1,s=n(e[o]);s===t?(a=o,i=o-1):s<t?r=o+1:i=o-1}return a},D=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+(i-r+1)/2|0;n(e[o])<=t?(a=o,r=o+1):i=o-1}return a},_e=(e,t,n)=>{let r=D(e,n(t),n);e.splice(r+1,0,t)},O=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},ve=(e,t)=>{let n=e.indexOf(t);n!==-1&&e.splice(n,1)},ye=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]},be=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1},xe=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()},Se=e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw TypeError(`Argument must be an iterable or async iterable.`)},k=e=>{throw Error(`Unexpected value: ${e}`)},Ce=(e,t,n)=>{let r=e.getUint8(t),i=e.getUint8(t+1),a=e.getUint8(t+2);return n?r|i<<8|a<<16:r<<16|i<<8|a},we=(e,t,n)=>Ce(e,t,n)<<8>>8,Te=(e,t,n,r)=>{n>>>=0,n&=16777215,r?(e.setUint8(t,n&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n>>>16&255)):(e.setUint8(t,n>>>16&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n&255))},Ee=(e,t,n,r)=>{n=A(n,-8388608,8388607),n<0&&(n=n+16777216&16777215),Te(e,t,n,r)},De=(e,t,n,r)=>{n=Math.trunc(n),r?(e.setUint32(t+0,n,!0),e.setInt32(t+4,Math.floor(n/2**32),!0)):(e.setInt32(t+0,Math.floor(n/2**32),!1),e.setUint32(t+4,n,!1))},A=(e,t,n)=>Math.max(t,Math.min(n,e)),Oe=(e,t,n)=>e+(t-e)*n,ke=(e,t)=>e-Math.floor(e/t)*t,Ae=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*2**-52?t:e},je=(e,t)=>Math.round(e/t)*t,Me=(e,t)=>Math.round(e*t)/t,Ne=(e,t)=>Math.floor(e/t)*t,Pe=(e,t)=>Math.floor(e*t)/t,Fe=e=>{let t=0;for(;e;)t++,e>>=1;return t},Ie=e=>{let t=0;for(;e!==0;)e&=e-1,t++;return t},Le=/^[a-z]{3}$/,Re=e=>Le.test(e),ze=1e6*(1+2**-52),Be=(e,t)=>{let n=e<0?-1:1;e=Math.abs(e);let r=0,i=1,a=1,o=0,s=e;for(;;){let e=Math.floor(s),c=e*a+r,l=e*o+i;if(l>t)return{num:n*a,den:o};if(r=a,i=o,a=c,o=l,s=1/(s-e),!isFinite(s))break}return{num:n*a,den:o}};var Ve=class{constructor(){this.currentPromise=Promise.resolve()}call(e){let t=this.currentPromise.then(e);return this.currentPromise=t.catch(()=>{}),t}};let He=null;const Ue=()=>He===null?He=!!(typeof navigator<`u`&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))):He;let We=null;const Ge=()=>We===null?We=typeof navigator<`u`&&navigator.userAgent?.includes(`Firefox`):We;let Ke=null;const qe=()=>Ke===null?Ke=!(typeof navigator>`u`||!navigator.vendor?.includes(`Google Inc`)&&!/Chrome/.test(navigator.userAgent)):Ke;let Je=null;const Ye=()=>{if(Je!==null)return Je;if(typeof navigator>`u`)return null;let e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?Je=Number(e[1]):null};let Xe=null;const Ze=()=>Xe===null?Xe=typeof navigator<`u`&&/Android/.test(navigator.userAgent):Xe,Qe=e=>globalThis.isSecureContext!==void 0&&!globalThis.isSecureContext?`${e} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`:`${e} is not available in this environment.`,$e=e=>e instanceof DOMException&&e.name===`QuotaExceededError`&&/reclaimed/i.test(e.message),et=(async()=>{})().constructor,j=e=>e instanceof et||e instanceof Promise||typeof e?.then==`function`,tt=(e,t)=>e===-1?t:e,nt=function*(e){for(let t in e){let n=e[t];n!==void 0&&(yield{key:t,value:n})}},rt=e=>{switch(e.toLowerCase()){case`image/jpeg`:case`image/jpg`:return`.jpg`;case`image/png`:return`.png`;case`image/gif`:return`.gif`;case`image/webp`:return`.webp`;case`image/bmp`:return`.bmp`;case`image/svg+xml`:return`.svg`;case`image/tiff`:return`.tiff`;case`image/avif`:return`.avif`;case`image/x-icon`:case`image/vnd.microsoft.icon`:return`.ico`;default:return null}},it=e=>{let t;try{t=atob(e)}catch{throw Error(`Invalid base64 string.`)}let n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},at=e=>{let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)},ot=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},st=()=>{Symbol.dispose??=Symbol(`Symbol.dispose`)},ct=e=>typeof e==`number`&&!Number.isNaN(e),lt=(e,t)=>{if(/^(?:[a-z][a-z0-9+.-]*:\/\/|(?:data|blob):)/i.test(t))return t;if(e.includes(`://`)){let t=e.search(/[?#]/);t!==-1&&(e=e.slice(0,t))}let n=t.search(/[?#]/),r=n===-1?``:t.slice(n);n!==-1&&(t=t.slice(0,n));let i;if(t===``)i=e;else if(t.startsWith(`/`)){let n=e.indexOf(`://`);if(n===-1)i=t;else if(t.startsWith(`//`))i=e.slice(0,n+1)+t;else{let r=e.indexOf(`/`,n+3);i=r===-1?e+t:e.slice(0,r)+t}}else{let n=e.indexOf(`://`),r=e.lastIndexOf(`/`);i=n!==-1&&r===n+2?e+`/`+t:r===-1?t:e.slice(0,r+1)+t}let a=``,o=i.indexOf(`://`);if(o!==-1){let e=i.indexOf(`/`,o+3);e!==-1&&(a=i.slice(0,e),i=i.slice(e))}let s=i.split(`/`),c=[];for(let e of s)e===`..`?c.length===0||c[c.length-1]===`..`?c.push(`..`):(c.length!==1||c[0]!==``)&&c.pop():e!==`.`&&c.push(e);return a+c.join(`/`)+r},ut=(e,t)=>{let n=e.indexOf(`#`),r=n===-1?e:e.slice(0,n),i=r.indexOf(`?`);return i===-1?null:new URLSearchParams(r.slice(i+1)).get(t)},dt=(e,t)=>{let n=0;for(let r=0;r<e.length;r++)t(e[r])&&n++;return n},ft=(e,t)=>{let n=-1,r=1/0;for(let i=0;i<e.length;i++){let a=t(e[i]);(n===-1||a<r)&&(r=a,n=i)}return n},pt=e=>{t(Number.isInteger(e.num)),t(Number.isInteger(e.den)),t(e.den!==0);let n=Math.abs(e.num),r=Math.abs(e.den);for(;r!==0;){let e=n%r;n=r,r=e}let i=n||1;return{num:e.num/i,den:e.den/i}},mt=(e,t)=>{if(typeof e!=`object`||!e)throw TypeError(`${t} must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw TypeError(`${t}.height must be a non-negative integer.`)},ht=e=>new Promise(t=>setTimeout(t,e)),gt=e=>Array.isArray(e)?e:[e];var _t=class{constructor(){this._listeners=/* @__PURE__ */ new Map}on(e,t,n){this._listeners.has(e)||this._listeners.set(e,/* @__PURE__ */ new Set);let r={fn:t,once:n?.once??!1};return this._listeners.get(e).add(r),()=>{this._listeners.get(e)?.delete(r)}}_emit(...e){let[t,n]=e,r=this._listeners.get(t);if(r){for(let e of[...r])if(r.has(e)){e.once&&r.delete(e);try{e.fn(n)}catch(e){console.error(e)}}}}};const vt=e=>Math.ceil(e/2)*2,yt=e=>typeof e==`object`&&!!e&&Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(e=>typeof e==`string`),bt=(e,t=0,n=1)=>{let r=/* @__PURE__ */ new Date(0);return r.setUTCFullYear(e,t,n),r},xt=/^(\d{4})(?:-(\d{2})(?:-(\d{2})(?:[T ](\d{2})(?::(\d{2})(?::(\d{2})(?:\.(\d+))?)?)?)?)?)?(?:Z|([+-])(\d{2})(?::?(\d{2}))?)?$/,St=e=>{let t=xt.exec(e);if(!t)return null;let[,n,r=`01`,i=`01`,a=`00`,o=`00`,s=`00`,c=``,l=`+`,u=`00`,d=`00`]=t,f=`${n}-${r}-${i}T${a}:${o}:${s}`,p=/* @__PURE__ */ new Date(`${f}.${c.padEnd(3,`0`).slice(0,3)}Z`);if(Number.isNaN(p.getTime())||!p.toISOString().startsWith(f)||Number(u)>23||Number(d)>59)return null;let m=(l===`-`?-1:1)*(60*Number(u)+Number(d));return p.setTime(p.getTime()-6e4*m),p};
10
+ /*!
11
+ * Copyright (c) 2026-present, Vanilagy and contributors
12
+ *
13
+ * This Source Code Form is subject to the terms of the Mozilla Public
14
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
15
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
16
+ */
17
+ var Ct;(function(e){e[e.Silent=0]=`Silent`,e[e.Errors=1]=`Errors`,e[e.Warnings=2]=`Warnings`,e[e.Info=3]=`Info`})(Ct||={});var M=class e{constructor(){}static get level(){return e._level}static set level(t){if(t!==Ct.Silent&&t!==Ct.Errors&&t!==Ct.Warnings&&t!==Ct.Info)throw TypeError(`Invalid log level. Use one of the values of the LogLevel enum.`);e._level=t}static get _emitter(){return e._emitterInstance??=new _t}static on(t,n,r){return e._emitter.on(t,n,r)}static _error(...t){e._emitter._emit(`error`,t),e._level>=Ct.Errors&&console.error(...t)}static _warn(...t){e._emitter._emit(`warn`,t),e._level>=Ct.Warnings&&console.warn(...t)}static _info(...t){e._emitter._emit(`info`,t),e._level>=Ct.Info&&console.info(...t)}};M._level=Ct.Info,M._emitterInstance=null;
18
+ /*!
19
+ * Copyright (c) 2026-present, Vanilagy and contributors
20
+ *
21
+ * This Source Code Form is subject to the terms of the Mozilla Public
22
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
23
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
24
+ */
25
+ var wt=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(typeof t!=`string`)throw TypeError(`mimeType must be a string.`)}},Tt=class{constructor(e,t,n,r){if(this.data=e,this.mimeType=t,this.name=n,this.description=r,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==void 0&&typeof t!=`string`)throw TypeError(`mimeType, when provided, must be a string.`);if(n!==void 0&&typeof n!=`string`)throw TypeError(`name, when provided, must be a string.`);if(r!==void 0&&typeof r!=`string`)throw TypeError(`description, when provided, must be a string.`)}};const Et=e=>{if(!e||typeof e!=`object`)throw TypeError(`tags must be an object.`);if(e.title!==void 0&&typeof e.title!=`string`)throw TypeError(`tags.title, when provided, must be a string.`);if(e.description!==void 0&&typeof e.description!=`string`)throw TypeError(`tags.description, when provided, must be a string.`);if(e.artist!==void 0&&typeof e.artist!=`string`)throw TypeError(`tags.artist, when provided, must be a string.`);if(e.album!==void 0&&typeof e.album!=`string`)throw TypeError(`tags.album, when provided, must be a string.`);if(e.albumArtist!==void 0&&typeof e.albumArtist!=`string`)throw TypeError(`tags.albumArtist, when provided, must be a string.`);if(e.trackNumber!==void 0&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw TypeError(`tags.trackNumber, when provided, must be a positive integer.`);if(e.tracksTotal!==void 0&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw TypeError(`tags.tracksTotal, when provided, must be a positive integer.`);if(e.discNumber!==void 0&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw TypeError(`tags.discNumber, when provided, must be a positive integer.`);if(e.discsTotal!==void 0&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw TypeError(`tags.discsTotal, when provided, must be a positive integer.`);if(e.genre!==void 0&&typeof e.genre!=`string`)throw TypeError(`tags.genre, when provided, must be a string.`);if(e.date!==void 0&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw TypeError(`tags.date, when provided, must be a valid Date.`);if(e.creationTime!==void 0&&e.creationTime!==null&&(!(e.creationTime instanceof Date)||Number.isNaN(e.creationTime.getTime())))throw TypeError(`tags.creationTime, when provided, must be a valid Date or null.`);if(e.beatsPerMinute!==void 0&&(!Number.isInteger(e.beatsPerMinute)||e.beatsPerMinute<=0))throw TypeError(`tags.beatsPerMinute, when provided, must be a positive integer.`);if(e.lyrics!==void 0&&typeof e.lyrics!=`string`)throw TypeError(`tags.lyrics, when provided, must be a string.`);if(e.images!==void 0){if(!Array.isArray(e.images))throw TypeError(`tags.images, when provided, must be an array.`);for(let t of e.images){if(!t||typeof t!=`object`)throw TypeError(`Each image in tags.images must be an object.`);if(!(t.data instanceof Uint8Array))throw TypeError(`Each image.data must be a Uint8Array.`);if(typeof t.mimeType!=`string`)throw TypeError(`Each image.mimeType must be a string.`);if(![`coverFront`,`coverBack`,`unknown`].includes(t.kind))throw TypeError(`Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.`);if(t.name!==void 0&&typeof t.name!=`string`)throw TypeError(`Each image.name, when provided, must be a string.`);if(t.description!==void 0&&typeof t.description!=`string`)throw TypeError(`Each image.description, when provided, must be a string.`)}}if(e.comment!==void 0&&typeof e.comment!=`string`)throw TypeError(`tags.comment, when provided, must be a string.`);if(e.raw!==void 0){if(!e.raw||typeof e.raw!=`object`)throw TypeError(`tags.raw, when provided, must be an object.`);for(let t of Object.values(e.raw))if(t!==null&&typeof t!=`string`&&!(Array.isArray(t)&&t.every(e=>typeof e==`string`))&&!(t instanceof Uint8Array)&&!(Array.isArray(t)&&t.every(e=>e instanceof Uint8Array))&&!(t instanceof wt)&&!(t instanceof Tt)&&!yt(t))throw TypeError(`Each value in tags.raw must be a string, string array, Uint8Array, Uint8Array array, RichImageData, AttachedFile, Record<string, string>, or null.`)}},Dt={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},Ot=e=>{if(!e||typeof e!=`object`)throw TypeError(`disposition must be an object.`);if(e.default!==void 0&&typeof e.default!=`boolean`)throw TypeError(`disposition.default must be a boolean.`);if(e.primary!==void 0&&typeof e.primary!=`boolean`)throw TypeError(`disposition.primary must be a boolean.`);if(e.forced!==void 0&&typeof e.forced!=`boolean`)throw TypeError(`disposition.forced must be a boolean.`);if(e.original!==void 0&&typeof e.original!=`boolean`)throw TypeError(`disposition.original must be a boolean.`);if(e.commentary!==void 0&&typeof e.commentary!=`boolean`)throw TypeError(`disposition.commentary must be a boolean.`);if(e.hearingImpaired!==void 0&&typeof e.hearingImpaired!=`boolean`)throw TypeError(`disposition.hearingImpaired must be a boolean.`);if(e.visuallyImpaired!==void 0&&typeof e.visuallyImpaired!=`boolean`)throw TypeError(`disposition.visuallyImpaired must be a boolean.`)};
26
+ /*!
27
+ * Copyright (c) 2026-present, Vanilagy and contributors
28
+ *
29
+ * This Source Code Form is subject to the terms of the Mozilla Public
30
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
31
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
32
+ */
33
+ var N=class e{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),r=(t&1<<n)>>n;return this.pos++,r}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t=2*t+this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let e=this.pos;e<n;e++){let r=Math.floor(e/8),i=this.bytes[r],a=7-(e&7),o=Math.floor(t/2**(n-e-1))&1;i&=~(1<<a),i|=o<<a,this.bytes[r]=i}this.pos=n}copyBits(e,t){let n=0;for(;n<e-7;n+=8)this.writeBits(8,t.readBits(8));let r=e-n;r>0&&this.writeBits(r,t.readBits(r))}readAlignedByte(){if(this.pos%8!=0)throw Error(`Bitstream is not byte-aligned.`);let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let t=new e(this.bytes);return t.pos=this.pos,t}};
34
+ /*!
35
+ * Copyright (c) 2026-present, Vanilagy and contributors
36
+ *
37
+ * This Source Code Form is subject to the terms of the Mozilla Public
38
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
39
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
40
+ */
41
+ const kt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],At=[-1,1,2,3,4,5,6,8],jt=[1,2,3,4,6,7,17,19,20,21,22],Mt=e=>{if(!e||e.byteLength<2)throw TypeError(`AAC description must be at least 2 bytes long.`);let t=new N(e),n=Nt(t),{frequencyIndex:r,sampleRate:i}=Pt(t),a=t.readBits(4),o=null;a>=1&&a<=7&&(o=At[a]);let s=n,c=!1,l=i;(n===5||n===29)&&(c=n===29,l=Pt(t).sampleRate,s=Nt(t),s===22&&t.skipBits(4));let u=1024,d=null;if(jt.includes(s)&&(u=t.readBits(1)?960:1024,a===0&&(t.readBits(1)&&t.skipBits(14),t.skipBits(1),d=Ht(t),o=Ut(d))),n!==5&&n!==29)for(;t.getBitsLeft()>15;){let e=t.pos;if(t.readBits(11)!==695)t.pos=e+1;else{Nt(t)===5&&t.readBits(1)&&(l=Pt(t).sampleRate,t.getBitsLeft()>11&&t.readBits(11)===1352&&(c=!!t.readBits(1)));break}}return o!==null&&o>1&&(c=!1),{objectType:n,coreObjectType:s,frequencyIndex:r,channelConfiguration:a,coreSampleRate:i,outputSampleRate:l,outputNumberOfChannels:c&&o===1?2:o,frameLength:u,programConfigElement:d}},Nt=e=>{let t=e.readBits(5);return t===31?32+e.readBits(6):t},Pt=e=>{let t=e.readBits(4);return t===15?{frequencyIndex:t,sampleRate:e.readBits(24)}:{frequencyIndex:t,sampleRate:t<kt.length?kt[t]:null}},Ft=e=>{let t=e.objectType===5||e.objectType===29,n=e.objectType===29,r=t?e.outputSampleRate/2:e.outputSampleRate,i=n?1:e.outputNumberOfChannels,a=e.programConfigElement?0:At.indexOf(i);if(a===-1)throw TypeError(`Unsupported number of channels: ${e.outputNumberOfChannels}`);let o=16;e.objectType>=32&&(o+=6),Rt(r)===15&&(o+=24),t&&(o+=9,Rt(e.outputSampleRate)===15&&(o+=24));let s=Math.ceil(o/8)+(e.programConfigElement?zt(e.programConfigElement):0),c=new Uint8Array(s),l=new N(c);return It(l,e.objectType),Lt(l,r),l.writeBits(4,a),t&&(Lt(l,e.outputSampleRate),It(l,2)),l.writeBits(3,0),e.programConfigElement&&Bt(l,e.programConfigElement),c.subarray(0,Math.ceil(l.pos/8))},It=(e,t)=>{t<32?e.writeBits(5,t):(e.writeBits(5,31),e.writeBits(6,t-32))},Lt=(e,t)=>{let n=Rt(t);e.writeBits(4,n),n===15&&e.writeBits(24,t)},Rt=e=>{let t=kt.indexOf(e);return t===-1?15:t},zt=e=>64+e.comment.byteLength,Bt=(e,t)=>{e.writeBits(4,t.elementInstanceTag),e.writeBits(2,t.objectType),e.writeBits(4,t.samplingFrequencyIndex),e.writeBits(4,t.frontElements.length),e.writeBits(4,t.sideElements.length),e.writeBits(4,t.backElements.length),e.writeBits(2,t.lfeElementTags.length),e.writeBits(3,t.assocDataElementTags.length),e.writeBits(4,t.ccElements.length),e.writeBits(1,+(t.monoMixdownElementNumber!==null)),t.monoMixdownElementNumber!==null&&e.writeBits(4,t.monoMixdownElementNumber),e.writeBits(1,+(t.stereoMixdownElementNumber!==null)),t.stereoMixdownElementNumber!==null&&e.writeBits(4,t.stereoMixdownElementNumber),e.writeBits(1,+(t.matrixMixdown!==null)),t.matrixMixdown&&(e.writeBits(2,t.matrixMixdown.index),e.writeBits(1,+t.matrixMixdown.pseudoSurroundEnabled));for(let n of[...t.frontElements,...t.sideElements,...t.backElements])e.writeBits(1,+n.isCpe),e.writeBits(4,n.tagSelect);for(let n of[...t.lfeElementTags,...t.assocDataElementTags])e.writeBits(4,n);for(let n of t.ccElements)e.writeBits(1,+n.isIndependentlySwitched),e.writeBits(4,n.tagSelect);e.pos=8*Math.ceil(e.pos/8),e.writeBits(8,t.comment.byteLength),e.bytes.set(t.comment,e.pos/8),e.pos+=8*t.comment.byteLength},Vt=e=>{let t=new N(e);if(t.readBits(3)!==5)return null;let n=Ht(t),r=t.pos/8;if(r>e.byteLength)throw Error(`Invalid ADTS frame: its program config element extends past the end of the frame.`);return{programConfigElement:n,size:r}},Ht=e=>{let t=e.readBits(4),n=e.readBits(2),r=e.readBits(4),i=e.readBits(4),a=e.readBits(4),o=e.readBits(4),s=e.readBits(2),c=e.readBits(3),l=e.readBits(4),u=e.readBits(1)?e.readBits(4):null,d=e.readBits(1)?e.readBits(4):null,f=e.readBits(1)?{index:e.readBits(2),pseudoSurroundEnabled:!!e.readBits(1)}:null,p=t=>Array.from({length:t},()=>({isCpe:!!e.readBits(1),tagSelect:e.readBits(4)})),m=p(i),h=p(a),g=p(o),_=Array.from({length:s},()=>e.readBits(4)),v=Array.from({length:c},()=>e.readBits(4)),y=Array.from({length:l},()=>({isIndependentlySwitched:!!e.readBits(1),tagSelect:e.readBits(4)}));e.pos=8*Math.ceil(e.pos/8);let b=e.readBits(8),x=e.bytes.slice(e.pos/8,e.pos/8+b);return e.pos+=8*b,{elementInstanceTag:t,objectType:n,samplingFrequencyIndex:r,frontElements:m,sideElements:h,backElements:g,lfeElementTags:_,assocDataElementTags:v,ccElements:y,monoMixdownElementNumber:u,stereoMixdownElementNumber:d,matrixMixdown:f,comment:x}},Ut=e=>[...e.frontElements,...e.sideElements,...e.backElements].reduce((e,t)=>e+(t.isCpe?2:1),e.lfeElementTags.length),Wt=[44100,48e3,32e3],Gt=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],Kt=(e,t,n,r,i)=>t===0?0:t===1?Math.floor(144*n/(r<<e))+i:t===2?Math.floor(144*n/r)+i:(Math.floor(12*n/r)+i)*4,qt=(e,t,n,r)=>t===0?0:t===1?144*n/(r<<e):t===2?144*n/r:12*n/r*4,Jt=(e,t)=>e===3?t===3?21:36:t===3?13:21,Yt=(e,t)=>{
42
+ /*!
43
+ * Copyright (c) 2026-present, Vanilagy and contributors
44
+ *
45
+ * This Source Code Form is subject to the terms of the Mozilla Public
46
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
47
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
48
+ */
49
+ let n=e>>>24,r=e>>>16&255,i=e>>>8&255,a=e&255;if(n!==255&&r!==255&&i!==255&&a!==255)return{header:null,bytesAdvanced:4};if(n!==255||(r&224)!=224)return{header:null,bytesAdvanced:1};let o=0,s=0;r&16?o=r&8?0:1:(o=1,s=1);let c=r>>3&3,l=r>>1&3,u=i>>4&15,d=i>>2&3;if(c===1||d===3)return{header:null,bytesAdvanced:1};let f=i>>1&1,p=a>>6&3,m=a>>4&3,h=a>>3&1,g=a>>2&1,_=a&3,v=Gt[o*16*4+l*16+u];if(v===-1)return{header:null,bytesAdvanced:1};let y=v*1e3,b=Wt[d]>>o+s,x=Kt(o,l,y,b,f);if(t!==null&&t<x)return{header:null,bytesAdvanced:1};let S;return S=c===3?l===3?384:1152:l===3?384:l===2?1152:576,{header:{totalSize:x,mpegVersionId:c,lowSamplingFrequency:o,layer:l,bitrate:y,frequencyIndex:d,sampleRate:b,channel:p,modeExtension:m,copyright:h,original:g,emphasis:_,audioSamplesInFrame:S},bytesAdvanced:1}},Xt=e=>{let t=2130706432,n=0;for(;t!==0;)n>>=1,n|=e&t,t>>=8;return n};var Zt;(function(e){e[e.FrameCount=1]=`FrameCount`,e[e.FileSize=2]=`FileSize`,e[e.Toc=4]=`Toc`,e[e.Quality=8]=`Quality`})(Zt||={});const Qt=e=>e===3?1:2,$t=[48e3,44100,32e3],en=[24e3,22050,16e3],tn=`Mediabunny v1.66.0`
50
+ /*!
51
+ * Copyright (c) 2026-present, Vanilagy and contributors
52
+ *
53
+ * This Source Code Form is subject to the terms of the Mozilla Public
54
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
55
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
56
+ */
57
+ /*!
58
+ * Copyright (c) 2026-present, Vanilagy and contributors
59
+ *
60
+ * This Source Code Form is subject to the terms of the Mozilla Public
61
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
62
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
63
+ */
64
+ /*!
65
+ * Copyright (c) 2026-present, Vanilagy and contributors
66
+ *
67
+ * This Source Code Form is subject to the terms of the Mozilla Public
68
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
69
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
70
+ */
71
+ ;
72
+ /*!
73
+ * Copyright (c) 2026-present, Vanilagy and contributors
74
+ *
75
+ * This Source Code Form is subject to the terms of the Mozilla Public
76
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
77
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
78
+ */
79
+ var P;(function(e){e[e.NON_IDR_SLICE=1]=`NON_IDR_SLICE`,e[e.SLICE_DPA=2]=`SLICE_DPA`,e[e.SLICE_DPB=3]=`SLICE_DPB`,e[e.SLICE_DPC=4]=`SLICE_DPC`,e[e.IDR=5]=`IDR`,e[e.SEI=6]=`SEI`,e[e.SPS=7]=`SPS`,e[e.PPS=8]=`PPS`,e[e.AUD=9]=`AUD`,e[e.SPS_EXT=13]=`SPS_EXT`})(P||={});var F;(function(e){e[e.RASL_N=8]=`RASL_N`,e[e.RASL_R=9]=`RASL_R`,e[e.BLA_W_LP=16]=`BLA_W_LP`,e[e.RSV_IRAP_VCL23=23]=`RSV_IRAP_VCL23`,e[e.VPS_NUT=32]=`VPS_NUT`,e[e.SPS_NUT=33]=`SPS_NUT`,e[e.PPS_NUT=34]=`PPS_NUT`,e[e.AUD_NUT=35]=`AUD_NUT`,e[e.PREFIX_SEI_NUT=39]=`PREFIX_SEI_NUT`,e[e.SUFFIX_SEI_NUT=40]=`SUFFIX_SEI_NUT`})(F||={});const nn=function*(e){let t=0,n=-1;for(;t<e.length-2;){let r=e.indexOf(0,t);if(r===-1||r>=e.length-2)break;t=r;let i=0;t+3<e.length&&e[t+1]===0&&e[t+2]===0&&e[t+3]===1?i=4:e[t+1]===0&&e[t+2]===1&&(i=3),i===0?t++:(n!==-1&&t>n&&(yield{offset:n,length:t-n}),n=t+i,t=n)}n!==-1&&n<e.length&&(yield{offset:n,length:e.length-n})},rn=function*(e,n){let r=0,i=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;r+n<=e.length;){let e;n===1?e=i.getUint8(r):n===2?e=i.getUint16(r,!1):n===3?e=Ce(i,r,!1):(t(n===4),e=i.getUint32(r,!1)),r+=n,yield{offset:r,length:e},r+=e}},an=(e,t)=>{if(t.description){let n=(b(t.description)[4]&3)+1;return rn(e,n)}return nn(e)},on=e=>e&31,sn=e=>{let t=new Uint8Array(e.length),n=e.length,r=0;for(let i=0;i<n;i++)i+2<n&&e[i]===0&&e[i+1]===0&&e[i+2]===3?(t[r++]=0,t[r++]=0,i+=2):t[r++]=e[i];return t.subarray(0,r)},cn=e=>{let t=[],n=0;for(let r of e)n===2&&r<=3&&(t.push(3),n=0),t.push(r),n=r===0?n+1:0;return new Uint8Array(t)},ln=new Uint8Array([0,0,0,1]),un=e=>{let t=e.reduce((e,t)=>e+ln.byteLength+t.byteLength,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(ln,r),r+=ln.byteLength,n.set(t,r),r+=t.byteLength;return n},dn=(e,t)=>{let n=e.reduce((e,n)=>e+t+n.byteLength,0),r=new Uint8Array(n),i=0;for(let n of e){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(i,n.byteLength);break;case 2:e.setUint16(i,n.byteLength,!1);break;case 3:Te(e,i,n.byteLength,!1);break;case 4:e.setUint32(i,n.byteLength,!1)}i+=t,r.set(n,i),i+=n.byteLength}return r},fn=(e,t)=>{if(t.description){let n=(b(t.description)[4]&3)+1;return dn(e,n)}return un(e)},pn=e=>{try{let t=[],n=[],r=[];for(let i of nn(e)){let a=e.subarray(i.offset,i.offset+i.length),o=on(a[0]);o===P.SPS&&t.length<31?t.push(a):o===P.PPS&&n.length<255?n.push(a):o===P.SPS_EXT&&r.length<255&&r.push(a)}if(t.length===0||n.length===0)return null;let i=t[0],a=vn(i);if(!a)return null;let o=gn(a.profileIdc);return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:n,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return M._error(`Error building AVC Decoder Configuration Record:`,e),null}},mn=e=>{let n=[];n.push(e.configurationVersion),n.push(e.avcProfileIndication),n.push(e.profileCompatibility),n.push(e.avcLevelIndication),n.push(252|e.lengthSizeMinusOne&3),n.push(224|e.sequenceParameterSets.length&31);for(let t of e.sequenceParameterSets){let e=t.byteLength;n.push(e>>8),n.push(e&255);for(let r=0;r<e;r++)n.push(t[r])}n.push(e.pictureParameterSets.length);for(let t of e.pictureParameterSets){let e=t.byteLength;n.push(e>>8),n.push(e&255);for(let r=0;r<e;r++)n.push(t[r])}if(gn(e.avcProfileIndication)&&e.chromaFormat!==null){t(e.bitDepthLumaMinus8!==null),t(e.bitDepthChromaMinus8!==null),t(e.sequenceParameterSetExt!==null),n.push(252|e.chromaFormat&3),n.push(248|e.bitDepthLumaMinus8&7),n.push(248|e.bitDepthChromaMinus8&7),n.push(e.sequenceParameterSetExt.length);for(let t of e.sequenceParameterSetExt){let e=t.byteLength;n.push(e>>8),n.push(e&255);for(let r=0;r<e;r++)n.push(t[r])}}return new Uint8Array(n)},hn=e=>{try{let t=x(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=t.getUint8(n++),o=t.getUint8(n++),s=t.getUint8(n++)&3,c=t.getUint8(n++)&31,l=[];for(let r=0;r<c;r++){let r=t.getUint16(n,!1);n+=2,l.push(e.subarray(n,n+r)),n+=r}let u=t.getUint8(n++),d=[];for(let r=0;r<u;r++){let r=t.getUint16(n,!1);n+=2,d.push(e.subarray(n,n+r)),n+=r}let f={configurationVersion:r,avcProfileIndication:i,profileCompatibility:a,avcLevelIndication:o,lengthSizeMinusOne:s,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if(gn(i)&&n+4<=e.length){let r=t.getUint8(n++)&3,i=t.getUint8(n++)&7,a=t.getUint8(n++)&7,o=t.getUint8(n++);f.chromaFormat=r,f.bitDepthLumaMinus8=i,f.bitDepthChromaMinus8=a;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}f.sequenceParameterSetExt=s}return f}catch(e){return M._error(`Error deserializing AVC Decoder Configuration Record:`,e),null}},gn=e=>e!==66&&e!==77&&e!==88,_n={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}},vn=e=>{try{let n=sn(e),r=new N(n);if(r.skipBits(1),r.skipBits(2),r.readBits(5)!==7)return null;let i=r.readAlignedByte(),a=r.readAlignedByte(),o=r.readAlignedByte();_(r);let s=1,c=0,l=0,u=0;if((i===100||i===110||i===122||i===244||i===44||i===83||i===86||i===118||i===128||i===138||i===139||i===134||i===135||i===144)&&(s=_(r),s===3&&(u=r.readBits(1)),c=_(r),l=_(r),r.skipBits(1),r.readBits(1))){for(let e=0;e<(s===3?12:8);e++)if(r.readBits(1)){let t=e<6?16:64,n=8,i=8;for(let e=0;e<t;e++){if(i!==0){let e=y(r);i=(n+e+256)%256}n=i===0?n:i}}}_(r);let d=_(r);if(d===0)_(r);else if(d===1){r.skipBits(1),y(r),y(r);let e=_(r);for(let t=0;t<e;t++)y(r)}let f=_(r);r.skipBits(1);let p=_(r),h=_(r),g=r.readBits(1);g||r.skipBits(1);let v=16*(p+1),b=16*(2-g)*(h+1),x=v,S=b;if(r.skipBits(1),r.readBits(1)){let e=_(r),t=_(r),n=_(r),i=_(r),a,o;if((u===0?s:0)===0)a=1,o=2-g;else{let e=s===3?1:2,t=s===1?2:1;a=e,o=t*(2-g)}x-=a*(e+t),S-=o*(n+i)}if(x<=0||S<=0)return null;let C=2,w=2,ee=2,T=0,te={num:1,den:1},E=null,ne=null,re=null,ie=null,ae=r.pos;if(r.readBits(1)){if(r.readBits(1)){let e=r.readBits(8);if(e===255)te={num:r.readBits(16),den:r.readBits(16)};else{let t=_n[e];t&&(te=t)}}r.readBits(1)&&r.skipBits(1),r.readBits(1)&&(r.skipBits(3),T=r.readBits(1),r.readBits(1)&&(C=r.readBits(8),w=r.readBits(8),ee=r.readBits(8))),r.readBits(1)&&(_(r),_(r)),r.readBits(1)&&(r.skipBits(32),r.skipBits(32),r.skipBits(1));let e=r.readBits(1);e&&yn(r);let t=r.readBits(1);t&&yn(r),(e||t)&&r.skipBits(1),r.skipBits(1),re=r.pos,ie=r.readBits(1),ie&&(r.skipBits(1),_(r),_(r),_(r),_(r),E=Math.min(_(r),16),ne=Math.min(_(r),16))}if(E===null){t(ne===null);let e=a&16;if((i===44||i===86||i===100||i===110||i===122||i===244)&&e)E=0,ne=0;else{let t=p+1,n=h+1,r=(2-g)*n,a=o===11&&e&&(i===66||i===77||i===88),s=Vl.find(e=>e.level>=(a?10:o))??m(Vl),c=Math.min(Math.floor(s.maxDpbMbs/(t*r)),16);E=c,ne=Math.min(Math.max(c,f),16)}}return t(ne!==null),{emulationUnpreventedBytes:n,profileIdc:i,constraintFlags:a,levelIdc:o,frameMbsOnlyFlag:g,chromaFormatIdc:s,bitDepthLumaMinus8:c,bitDepthChromaMinus8:l,codedWidth:v,codedHeight:b,displayWidth:x,displayHeight:S,pixelAspectRatio:te,colourPrimaries:C,matrixCoefficients:ee,transferCharacteristics:w,fullRangeFlag:T,numReorderFrames:E,maxDecFrameBuffering:ne,vuiParametersFlagBitOffset:ae,bitstreamRestrictionFlagBitOffset:re,bitstreamRestrictionFlag:ie}}catch(e){return M._error(`Error parsing AVC SPS:`,e),null}},yn=e=>{let t=_(e);e.skipBits(4),e.skipBits(4);for(let n=0;n<=t;n++)_(e),_(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},bn=e=>{t(e.bitstreamRestrictionFlag!==1);let n=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),r=new N(e.emulationUnpreventedBytes),i=new N(n);e.bitstreamRestrictionFlag===null?(i.copyBits(e.vuiParametersFlagBitOffset,r),i.writeBits(1,1),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0)):(t(e.bitstreamRestrictionFlagBitOffset!==null),i.copyBits(e.bitstreamRestrictionFlagBitOffset,r)),i.writeBits(1,1),i.writeBits(1,1),v(i,2),v(i,1),v(i,16),v(i,16),v(i,e.numReorderFrames),v(i,e.maxDecFrameBuffering),i.writeBits(1,1),i.writeBits((8-i.pos%8)%8,0);let a=i.pos/8;return t(Number.isInteger(a)),cn(n.subarray(0,a))},xn=(e,t)=>{if(t.description){let n=(b(t.description)[21]&3)+1;return dn(e,n)}return un(e)},Sn=(e,t)=>{if(t.description){let n=(b(t.description)[21]&3)+1;return rn(e,n)}return nn(e)},Cn=e=>e>>1&63,wn=e=>{try{let t=new N(sn(e));t.skipBits(16),t.readBits(4);let n=t.readBits(3),r=t.readBits(1),{general_profile_space:i,general_tier_flag:a,general_profile_idc:o,general_profile_compatibility_flags:s,general_constraint_indicator_flags:c,general_level_idc:l}=En(t,n);_(t);let u=_(t),d=0;u===3&&(d=t.readBits(1));let f=_(t),p=_(t),m=f,h=p;if(t.readBits(1)){let e=_(t),n=_(t),r=_(t),i=_(t),a=1,o=1,s=d===0?u:0;s===1?(a=2,o=2):s===2&&(a=2,o=1),m-=(e+n)*a,h-=(r+i)*o}if(m<=0||h<=0)return null;let g=_(t),v=_(t),y=_(t),b=t.readBits(1)?0:n,x=0;for(let e=b;e<=n;e++)_(t),x=_(t),_(t);_(t),_(t),_(t),_(t),_(t),_(t),t.readBits(1)&&t.readBits(1)&&Dn(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),_(t),_(t),t.skipBits(1));let S=_(t);if(On(t,S),t.readBits(1)){let e=_(t);for(let n=0;n<e;n++)t.skipBits(y+4),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let C=2,w=2,ee=2,T=0,te=0,E={num:1,den:1};if(t.readBits(1)){let e=An(t,n);E=e.pixelAspectRatio,C=e.colourPrimaries,w=e.transferCharacteristics,ee=e.matrixCoefficients,T=e.fullRangeFlag,te=e.minSpatialSegmentationIdc}return{displayWidth:m,displayHeight:h,pixelAspectRatio:E,colourPrimaries:C,transferCharacteristics:w,matrixCoefficients:ee,fullRangeFlag:T,maxDecFrameBuffering:Math.min(x+1,16),spsMaxSubLayersMinus1:n,spsTemporalIdNestingFlag:r,generalProfileSpace:i,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:s,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:g,bitDepthChromaMinus8:v,minSpatialSegmentationIdc:te}}catch(e){return M._error(`Error parsing HEVC SPS:`,e),null}},Tn=e=>{try{let t=[],n=[],r=[],i=[],a=[],o=65535;for(let s of nn(e)){let c=e.subarray(s.offset,s.offset+s.length),l=Cn(c[0]);l===F.VPS_NUT&&t.length<o?t.push(c):l===F.SPS_NUT&&n.length<o?n.push(c):l===F.PPS_NUT&&r.length<o?r.push(c):l===F.PREFIX_SEI_NUT&&i.length<o?i.push(c):l===F.SUFFIX_SEI_NUT&&a.length<o&&a.push(c)}if(n.length===0||r.length===0)return null;let s=wn(n[0]);if(!s)return null;let c=0;if(r.length>0){let e=r[0],t=new N(sn(e));t.skipBits(16),_(t),_(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),_(t),_(t),y(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&_(t),y(t),y(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);let n=t.readBits(1),i=t.readBits(1);c=!n&&!i?0:n&&!i?2:!n&&i?3:0}let l=[...t.length?[{arrayCompleteness:1,nalUnitType:F.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:F.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:F.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:0,nalUnitType:F.PREFIX_SEI_NUT,nalUnits:i}]:[],...a.length?[{arrayCompleteness:0,nalUnitType:F.SUFFIX_SEI_NUT,nalUnits:a}]:[]];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:c,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:l}}catch(e){return M._error(`Error building HEVC Decoder Configuration Record:`,e),null}},En=(e,t)=>{let n=e.readBits(2),r=e.readBits(1),i=e.readBits(5),a=0;for(let t=0;t<32;t++)a=a<<1|e.readBits(1);let o=/* @__PURE__ */ new Uint8Array(6);for(let t=0;t<6;t++)o[t]=e.readBits(8);let s=e.readBits(8),c=[],l=[];for(let n=0;n<t;n++)c.push(e.readBits(1)),l.push(e.readBits(1));if(t>0)for(let n=t;n<8;n++)e.skipBits(2);for(let n=0;n<t;n++)c[n]&&e.skipBits(88),l[n]&&e.skipBits(8);return{general_profile_space:n,general_tier_flag:r,general_profile_idc:i,general_profile_compatibility_flags:a,general_constraint_indicator_flags:o,general_level_idc:s}},Dn=e=>{for(let t=0;t<4;t++)for(let n=0;n<(t===3?2:6);n++)if(!e.readBits(1))_(e);else{let n=Math.min(64,1<<4+(t<<1));t>1&&y(e);for(let t=0;t<n;t++)y(e)}},On=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=kn(e,r,t,n)},kn=(e,t,n,r)=>{let i=0,a=0,o=0;if(t!==0&&(a=e.readBits(1)),a){o=t===n?t-(_(e)+1):t-1,e.readBits(1),_(e);let a=r[o]??0;for(let t=0;t<=a;t++)(e.readBits(1)||e.readBits(1))&&i++}else{let t=_(e),n=_(e);for(let n=0;n<t;n++)_(e),e.readBits(1);for(let t=0;t<n;t++)_(e),e.readBits(1);i=t+n}return i},An=(e,t)=>{let n=2,r=2,i=2,a=0,o=0,s={num:1,den:1};if(e.readBits(1)){let t=e.readBits(8);if(t===255)s={num:e.readBits(16),den:e.readBits(16)};else{let e=_n[t];e&&(s=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),a=e.readBits(1),e.readBits(1)&&(n=e.readBits(8),r=e.readBits(8),i=e.readBits(8))),e.readBits(1)&&(_(e),_(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(_(e),_(e),_(e),_(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&_(e),e.readBits(1)&&jn(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=_(e),_(e),_(e),_(e),_(e)),{pixelAspectRatio:s,colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:a,minSpatialSegmentationIdc:o}},jn=(e,t,n)=>{let r=!1,i=!1,a=!1;t&&(r=e.readBits(1)===1,i=e.readBits(1)===1,(r||i)&&(a=e.readBits(1)===1,a&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),a&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let t=0;t<=n;t++){let t=e.readBits(1)===1,n=!0;t||(n=e.readBits(1)===1);let o=!1;n?_(e):o=e.readBits(1)===1;let s=1;o||(s=_(e)+1),r&&Mn(e,s,a),i&&Mn(e,s,a)}},Mn=(e,t,n)=>{for(let r=0;r<t;r++)_(e),_(e),n&&(_(e),_(e)),e.readBits(1)},Nn=e=>{let t=[];t.push(e.configurationVersion),t.push((e.generalProfileSpace&3)<<6|(e.generalTierFlag&1)<<5|e.generalProfileIdc&31),t.push(e.generalProfileCompatibilityFlags>>>24&255),t.push(e.generalProfileCompatibilityFlags>>>16&255),t.push(e.generalProfileCompatibilityFlags>>>8&255),t.push(e.generalProfileCompatibilityFlags&255),t.push(...e.generalConstraintIndicatorFlags),t.push(e.generalLevelIdc&255),t.push(240|e.minSpatialSegmentationIdc>>8&15),t.push(e.minSpatialSegmentationIdc&255),t.push(252|e.parallelismType&3),t.push(252|e.chromaFormatIdc&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.avgFrameRate>>8&255),t.push(e.avgFrameRate&255),t.push((e.constantFrameRate&3)<<6|(e.numTemporalLayers&7)<<3|(e.temporalIdNested&1)<<2|e.lengthSizeMinusOne&3),t.push(e.arrays.length&255);for(let n of e.arrays){t.push((n.arrayCompleteness&1)<<7|n.nalUnitType&63),t.push(n.nalUnits.length>>8&255),t.push(n.nalUnits.length&255);for(let e of n.nalUnits){t.push(e.length>>8&255),t.push(e.length&255);for(let n=0;n<e.length;n++)t.push(e[n])}}return new Uint8Array(t)},Pn=e=>{try{let t=x(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=i>>6&3,o=i>>5&1,s=i&31,c=t.getUint32(n,!1);n+=4;let l=e.subarray(n,n+6);n+=6;let u=t.getUint8(n++),d=(t.getUint8(n++)&15)<<8|t.getUint8(n++),f=t.getUint8(n++)&3,p=t.getUint8(n++)&3,m=t.getUint8(n++)&7,h=t.getUint8(n++)&7,g=t.getUint16(n,!1);n+=2;let _=t.getUint8(n++),v=_>>6&3,y=_>>3&7,b=_>>2&1,S=_&3,C=t.getUint8(n++),w=[];for(let r=0;r<C;r++){let r=t.getUint8(n++),i=r>>7&1,a=r&63,o=t.getUint16(n,!1);n+=2;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}w.push({arrayCompleteness:i,nalUnitType:a,nalUnits:s})}return{configurationVersion:r,generalProfileSpace:a,generalTierFlag:o,generalProfileIdc:s,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:u,minSpatialSegmentationIdc:d,parallelismType:f,chromaFormatIdc:p,bitDepthLumaMinus8:m,bitDepthChromaMinus8:h,avgFrameRate:g,constantFrameRate:v,numTemporalLayers:y,temporalIdNested:b,lengthSizeMinusOne:S,arrays:w}}catch(e){return M._error(`Error deserializing HEVC Decoder Configuration Record:`,e),null}};var Fn;(function(e){e[e.audAllowed=0]=`audAllowed`,e[e.beforeFirstVcl=1]=`beforeFirstVcl`,e[e.afterFirstVcl=2]=`afterFirstVcl`,e[e.eoBitstreamAllowed=3]=`eoBitstreamAllowed`,e[e.noMoreDataAllowed=4]=`noMoreDataAllowed`})(Fn||={});const In=(e,t)=>{let n=/* @__PURE__ */ new Set,r=Fn.audAllowed;for(let i of Sn(e,t)){if(r===Fn.noMoreDataAllowed){n.add(i.offset);continue}let t=Cn(e[i.offset]);if(r===Fn.eoBitstreamAllowed&&t!==37){n.add(i.offset);continue}let a=!1;t===35?r>Fn.audAllowed?a=!0:r=Fn.beforeFirstVcl:t<=31?r>Fn.afterFirstVcl?a=!0:r=Fn.afterFirstVcl:t===36?r===Fn.afterFirstVcl?r=Fn.eoBitstreamAllowed:a=!0:t===37?r<Fn.afterFirstVcl?a=!0:r=Fn.noMoreDataAllowed:t===32||t===33||t===34||t===39||t>=41&&t<=44||t>=48&&t<=55?r>Fn.beforeFirstVcl?a=!0:r=Fn.beforeFirstVcl:(t===38||t===40||t>=45&&t<=47||t>=56&&t<=63)&&r<Fn.afterFirstVcl&&(a=!0),a&&n.add(i.offset)}if(n.size===0)return null;let i=[];for(let r of Sn(e,t))n.has(r.offset)||i.push(e.subarray(r.offset,r.offset+r.length));return xn(i,t)},Ln={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},Rn=e=>{let t=new N(e);if(t.readBits(2)!==2)return null;let n=t.readBits(1),r=(t.readBits(1)<<1)+n;if(r===3&&t.skipBits(1),t.readBits(1)===1||t.readBits(1)!==0||(t.skipBits(2),t.readBits(24)!==4817730))return null;let i=8;r>=2&&(i=t.readBits(1)?12:10);let a=t.readBits(3),o=0,s=0;if(a!==7){if(s=t.readBits(1),r===1||r===3){let e=t.readBits(1),n=t.readBits(1);o=!e&&!n?3:e&&!n?2:1,t.skipBits(1)}else o=1}else o=3,s=1,(r===1||r===3)&&t.skipBits(1);let c=t.readBits(16),l=t.readBits(16),u=(c+1)*(l+1),d=m(Ul).level;for(let e of Ul)if(u<=e.maxPictureSize){d=e.level;break}let f=Ln[a],p=f?.colourPrimaries??2,h=f?.transferCharacteristics??2,g=f?.matrixCoefficients??2;return{profile:r,level:d,bitDepth:i,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:p,transferCharacteristics:h,matrixCoefficients:g}},zn=e=>e.colourPrimaries!==2||e.transferCharacteristics!==2||e.matrixCoefficients!==2,Bn=function*(e){let n=new N(e),r=()=>{let e=0;for(let t=0;t<8;t++){let r=n.readAlignedByte();if(e+=(r&127)*2**(t*7),!(r&128))break;if(t===7&&r&128)return null}return e>2**32-1?null:e};for(;n.getBitsLeft()>=8;){n.skipBits(1);let i=n.readBits(4),a=n.readBits(1),o=n.readBits(1);n.skipBits(1),a&&n.skipBits(8);let s;if(o){let e=r();if(e===null)return;s=e}else s=Math.floor(n.getBitsLeft()/8);t(n.pos%8==0),yield{type:i,data:e.subarray(n.pos/8,n.pos/8+s)},n.skipBits(s*8)}},Vn=e=>{for(let{type:t,data:n}of Bn(e)){if(t!==1)continue;let e=new N(n),r=e.readBits(3);e.readBits(1);let i=e.readBits(1),a=0,o=0,s=0;if(i)a=e.readBits(5);else{let t=e.readBits(1),n=0;if(t){if(e.skipBits(32),e.skipBits(32),e.readBits(1)){let t=0;for(;t<32&&!e.readBits(1);)t++;t<32&&e.skipBits(t)}n=e.readBits(1),n&&(s=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5))}let r=e.readBits(1),i=e.readBits(5);for(let t=0;t<=i;t++){e.skipBits(12);let i=e.readBits(5);if(t===0&&(a=i),i>7){let n=e.readBits(1);t===0&&(o=n)}if(n&&e.readBits(1)){let t=s+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}r&&e.readBits(1)&&e.skipBits(4)}}let c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);let d=l+1;e.skipBits(d);let f=0;if(f=i?0:e.readBits(1),f&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!i){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);let t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let n=e.readBits(1),r=0;r=n?2:e.readBits(1),r>0&&(e.readBits(1)||e.skipBits(1)),t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);let p=e.readBits(1),m=8;r===2&&p?m=e.readBits(1)?12:10:r<=2&&(m=p?10:8);let h=0;r!==1&&(h=e.readBits(1));let g=2,_=2,v=2;e.readBits(1)&&(g=e.readBits(8),_=e.readBits(8),v=e.readBits(8));let y=0,b=1,x=1,S=0;return h?y=e.readBits(1):g===1&&_===13&&v===0?(y=1,b=0,x=0):(y=e.readBits(1),r===0?(b=1,x=1):r===1?(b=0,x=0):m===12?(b=e.readBits(1),x=b?e.readBits(1):0):(b=1,x=0),b&&x&&(S=e.readBits(2))),{profile:r,level:a,tier:o,bitDepth:m,monochrome:h,chromaSubsamplingX:b,chromaSubsamplingY:x,chromaSamplePosition:S,videoFullRangeFlag:y,colourPrimaries:g,transferCharacteristics:_,matrixCoefficients:v}}return null},Hn=e=>e.colourPrimaries!==2||e.transferCharacteristics!==2||e.matrixCoefficients!==2,Un=e=>{if(e.length<28)return null;let t=x(e);return t.getUint32(4)!==1768124518||t.getUint16(8)<20?null:{fullRange:!1,colourPrimaries:t.getUint8(22),transferCharacteristics:t.getUint8(23),matrixCoefficients:t.getUint8(24)}},Wn=e=>{if(e.byteLength<19)throw Error(`Invalid Opus identification header: too short.`);let t=x(e),n=t.getUint8(9),r=t.getUint16(10,!0),i=t.getUint32(12,!0),a=t.getInt16(16,!0),o=t.getUint8(18),s=null;return o&&(s=e.subarray(19)),{outputChannelCount:n,preSkip:r,inputSampleRate:i,outputGain:a,channelMappingFamily:o,channelMappingTable:s}},Gn=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],Kn=e=>{let t=e[0]>>3,n=e[0]&3,r;return r=n===0?1:n===1||n===2?2:e[1]&63,{durationInSamples:Gn[t]*r}},qn=e=>{if(e.length<7)throw Error(`Setup header is too short.`);if(e[0]!==5)throw Error(`Wrong packet type in Setup header.`);if(String.fromCharCode(...e.slice(1,7))!==`vorbis`)throw Error(`Invalid packet signature in Setup header.`);let t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e[t-1-r];let r=new N(n),i=0;for(;r.getBitsLeft()>97;)if(r.readBits(1)===1){i=r.pos;break}if(i===0)throw Error(`Invalid Setup header: framing bit not found.`);let a=0,o=!1,s=0;for(;r.getBitsLeft()>=97;){let e=r.pos,t=r.readBits(8),n=r.readBits(16),i=r.readBits(16);if(t>63||n!==0||i!==0){r.pos=e;break}if(r.skipBits(1),a++,a>64)break;r.clone().readBits(6)+1===a&&(o=!0,s=a)}if(!o)throw Error(`Invalid Setup header: mode header not found.`);if(s>63)throw Error(`Unsupported mode count: ${s}.`);let c=s;r.pos=0,r.skipBits(i);let l=Array(c).fill(0);for(let e=c-1;e>=0;e--)r.skipBits(40),l[e]=r.readBits(1);return{modeBlockflags:l}},Jn=(e,n,r)=>{switch(e){case`avc`:for(let e of an(r,n)){let t=r[e.offset],n=on(t);if(n>=P.NON_IDR_SLICE&&n<=P.SLICE_DPC)return`delta`;if(n===P.IDR)return`key`;if(n===P.SEI&&!qe()){let t=r.subarray(e.offset,e.offset+e.length),n=sn(t),i=1;do{let e=0;for(;;){let t=n[i++];if(t===void 0||(e+=t,t<255))break}let t=0;for(;;){let e=n[i++];if(e===void 0||(t+=e,e<255))break}if(e===6){let e=new N(n);e.pos=8*i;let t=-1;try{t=_(e)}catch{}let r=e.readBits(1);if(t===0&&r===1)return`key`}i+=t}while(i<n.length-1)}}return`delta`;case`hevc`:for(let e of Sn(r,n)){let t=Cn(r[e.offset]);if(t<F.BLA_W_LP)return`delta`;if(t<=F.RSV_IRAP_VCL23)return`key`}return`delta`;case`vp8`:return r[0]&1?`delta`:`key`;case`vp9`:{let e=new N(r);if(e.readBits(2)!==2)return null;let t=e.readBits(1);return(e.readBits(1)<<1)+t===3&&e.skipBits(1),e.readBits(1)?null:e.readBits(1)===0?`key`:`delta`}case`av1`:{let e=!1;for(let{type:t,data:n}of Bn(r))if(t===1){let t=new N(n);t.skipBits(4),e=!!t.readBits(1)}else if(t===3||t===6||t===7){if(e)return`key`;let t=new N(n);if(t.readBits(1))return null;let r=t.readBits(2),i=t.readBits(1);return r===0&&i===1?`key`:`delta`}return null}case`prores`:return`key`;default:k(e),t(!1)}},Yn=(e,t)=>{if(e===`vp8`)return t[0]>>4&1;if(e===`vp9`){let e=e=>{let t=new N(e);t.skipBits(2);let n=t.readBits(1),r=t.readBits(1);return n===1&&r===1&&t.skipBits(1),t.readBits(1)===1||(t.skipBits(1),t.readBits(1)===1)},n=t[t.length-1];if((n&224)==192){let r=(n&7)+1,i=(n>>3&3)+1,a=t.length-(2+r*i);if(t[a]===n){let n=0,o=0;for(let s=0;s<r;s++){let r=0;for(let e=0;e<i;e++)r+=t[a+1+s*i+e]*2**(8*e);e(t.subarray(o,o+r))&&n++,o+=r}return n}}return+!!e(t)}return 1},Xn=(e,t)=>e===`truehd`?(t.byteLength>=8?x(t).getUint32(4):null)===4168249274?`key`:`delta`:`key`;var Zn;(function(e){e[e.STREAMINFO=0]=`STREAMINFO`,e[e.VORBIS_COMMENT=4]=`VORBIS_COMMENT`,e[e.PICTURE=6]=`PICTURE`})(Zn||={});const Qn=(e,t)=>{let n=x(e),r=0;if(e.length<4)return;let i=n.getUint32(r,!0);r+=4;let a=w.decode(e.subarray(r,r+i));if(r+=i,i>0&&(t.raw??={},t.raw.vendor??=a),r+4>e.length)return;let o=n.getUint32(r,!0);r+=4;for(let i=0;i<o&&!(r+4>e.length);i++){let i=n.getUint32(r,!0);r+=4;let a=w.decode(e.subarray(r,r+i));r+=i;let o=a.indexOf(`=`);if(o===-1)continue;let s=a.slice(0,o).toUpperCase(),c=a.slice(o+1);switch(t.raw??={},Array.isArray(t.raw[s])?t.raw[s].push(c):typeof t.raw[s]==`string`?t.raw[s]=[t.raw[s],c]:t.raw[s]??=c,s){case`TITLE`:t.title??=c;break;case`DESCRIPTION`:t.description??=c;break;case`ARTIST`:t.artist??=c;break;case`ALBUM`:t.album??=c;break;case`ALBUMARTIST`:t.albumArtist??=c;break;case`COMMENT`:t.comment??=c;break;case`LYRICS`:t.lyrics??=c;break;case`TRACKNUMBER`:{let e=c.split(`/`),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.trackNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??=r)}break;case`TRACKTOTAL`:{let e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??=e)}break;case`DISCNUMBER`:{let e=c.split(`/`),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.discNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.discsTotal??=r)}break;case`DISCTOTAL`:{let e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.discsTotal??=e)}break;case`DATE`:{let e=St(c);e&&(t.date??=e)}break;case`BPM`:{let e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.beatsPerMinute??=e)}break;case`GENRE`:t.genre??=c;break;case`METADATA_BLOCK_PICTURE`:try{let e=it(c),n=x(e),r=n.getUint32(0,!1),i=n.getUint32(4,!1),a=w.decode(e.subarray(8,8+i)),o=n.getUint32(8+i,!1),s=w.decode(e.subarray(12+i,12+i+o)),l=n.getUint32(i+o+28),u=e.subarray(i+o+32,i+o+32+l);t.images??=[],t.images.push({data:u,mimeType:a,kind:r===3?`coverFront`:r===4?`coverBack`:`unknown`,name:void 0,description:s||void 0})}catch{}}}},$n=(e,t,n)=>{let r=[e],i=T.encode(tn),a=new Uint8Array(4+i.length),o=new DataView(a.buffer);o.setUint32(0,i.length,!0),a.set(i,4),r.push(a);let s=[],c=(e,t)=>{let n=`${e}=${t}`,i=T.encode(n);a=new Uint8Array(4+i.length),o=new DataView(a.buffer),o.setUint32(0,i.length,!0),a.set(i,4),r.push(a),s.push(e)};for(let{key:e,value:r}of nt(t))switch(e){case`title`:c(`TITLE`,r);break;case`description`:c(`DESCRIPTION`,r);break;case`artist`:c(`ARTIST`,r);break;case`album`:c(`ALBUM`,r);break;case`albumArtist`:c(`ALBUMARTIST`,r);break;case`genre`:c(`GENRE`,r);break;case`date`:c(`DATE`,r.toISOString().slice(0,10));break;case`comment`:c(`COMMENT`,r);break;case`lyrics`:c(`LYRICS`,r);break;case`trackNumber`:c(`TRACKNUMBER`,r.toString());break;case`tracksTotal`:c(`TRACKTOTAL`,r.toString());break;case`discNumber`:c(`DISCNUMBER`,r.toString());break;case`discsTotal`:c(`DISCTOTAL`,r.toString());break;case`beatsPerMinute`:c(`BPM`,r.toString());break;case`images`:if(!n)break;for(let e of r){let t=e.kind===`coverFront`?3:e.kind===`coverBack`?4:0,n=new Uint8Array(e.mimeType.length);for(let t=0;t<e.mimeType.length;t++)n[t]=e.mimeType.charCodeAt(t);let r=T.encode(e.description??``),i=new Uint8Array(8+n.length+4+r.length+16+4+e.data.length),a=x(i);a.setUint32(0,t,!1),a.setUint32(4,n.length,!1),i.set(n,8),a.setUint32(8+n.length,r.length,!1),i.set(r,12+n.length),a.setUint32(28+n.length+r.length,e.data.length,!1),i.set(e.data,32+n.length+r.length),c(`METADATA_BLOCK_PICTURE`,at(i))}break;case`raw`:break;case`creationTime`:break;default:k(e)}if(t.raw)for(let e in t.raw){let r=t.raw[e]??t.raw[e.toLowerCase()];if(!(e===`vendor`||r==null||s.includes(e))&&!(e===`METADATA_BLOCK_PICTURE`&&!n&&(t.images?.length??0)>0)){if(typeof r==`string`)c(e,r);else if(Array.isArray(r)&&r.every(e=>typeof e==`string`))for(let t of r)c(e,t)}}let l=/* @__PURE__ */ new Uint8Array(4);x(l).setUint32(0,s.length,!0),r.splice(2,0,l);let u=r.reduce((e,t)=>e+t.length,0),d=new Uint8Array(u),f=0;for(let e of r)d.set(e,f),f+=e.length;return d},er=[2,1,2,3,3,4,4,5],tr=e=>{if(e.length<7||e[0]!==11||e[1]!==119)return null;let t=new N(e);t.skipBits(16),t.skipBits(16);let n=t.readBits(2);if(n===3)return null;let r=t.readBits(6),i=t.readBits(5);if(i>8)return null;let a=t.readBits(3),o=t.readBits(3);return o&1&&o!==1&&t.skipBits(2),o&4&&t.skipBits(2),o===2&&t.skipBits(2),{fscod:n,bsid:i,bsmod:a,acmod:o,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},nr=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,576,384,418,576,448,486,672,448,488,672,512,556,768,512,558,768,640,696,960,640,698,960,768,834,1152,768,836,1152,896,974,1344,896,976,1344,1024,1114,1536,1024,1116,1536,1280,1392,1920,1280,1394,1920,1536,1670,2304,1536,1672,2304,1792,1950,2688,1792,1952,2688,2048,2228,3072,2048,2230,3072,2304,2506,3456,2304,2508,3456,2560,2786,3840,2560,2788,3840];new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);const rr=[1,2,3,6],ir=e=>{if(e.length<6||e[0]!==11||e[1]!==119)return null;let t=new N(e);t.skipBits(16);let n=t.readBits(2);if(t.skipBits(3),n!==0&&n!==2)return null;let r=t.readBits(11),i=t.readBits(2),a=0,o;i===3?(a=t.readBits(2),o=3):o=t.readBits(2);let s=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;let u=rr[o],d;d=i<3?$t[i]/1e3:en[a]/1e3;let f=Math.round((r+1)*d/(u*16)),p=0,m=0,h=2*(r+1);for(;h+2<=e.length&&(t.seekToByte(h),t.readBits(16)===2935&&t.readBits(2)===1);){t.skipBits(3);let e=t.readBits(11);t.skipBits(4);let n=t.readBits(3);if(t.skipBits(11),t.readBits(1)&&t.skipBits(8),n===0&&(t.skipBits(5),t.readBits(1)&&t.skipBits(8)),t.readBits(1)){let e=t.readBits(16);for(let t=0;t<8;t++)e&1<<10-t&&(m|=1<<t);e&2&&(m|=256)}p++,h+=2*(e+1)}return{dataRate:f,substreams:[{fscod:i,fscod2:a,bsid:l,bsmod:0,acmod:s,lfeon:c,numDepSub:p,chanLoc:m}]}},ar=e=>{let t=[],n=0;for(;n<e.length;){if(n+6>e.length||e[n]!==11||e[n+1]!==119)return null;let r=e[n+2]>>6,i=(e[n+2]&7)<<8|e[n+3],a=e[n+4]>>6==3?3:e[n+4]>>4&3,o=e[n+5]>>3,s=2*(i+1);if(o<=10||n+s>e.length)return null;if(r===1){let e=m(t);if(!e)return null;e.size+=s}else t.push({offset:n,size:s,blockCount:rr[a]});n+=s}return t},or=e=>{if(e.length<2)return null;let t=new N(e),n=t.readBits(13),r=t.readBits(3),i=[];for(let n=0;n<=r&&!(Math.ceil(t.pos/8)+3>e.length);n++){let e=t.readBits(2),n=t.readBits(5);t.skipBits(1),t.skipBits(1);let r=t.readBits(3),a=t.readBits(3),o=t.readBits(1);t.skipBits(3);let s=t.readBits(4),c=0;s>0?c=t.readBits(9):t.skipBits(1),i.push({fscod:e,fscod2:null,bsid:n,bsmod:r,acmod:a,lfeon:o,numDepSub:s,chanLoc:c})}return i.length===0?null:{dataRate:n,substreams:i}},sr=e=>{let n=e.substreams[0];return t(n),n.fscod<3?$t[n.fscod]:n.fscod2!==null&&n.fscod2<3?en[n.fscod2]:null},cr=e=>{let n=e.substreams[0];t(n);let r=er[n.acmod]+n.lfeon;if(n.numDepSub>0){let e=[2,2,1,1,2,2,2,1,1];for(let t=0;t<9;t++)n.chanLoc&1<<t&&(r+=e[t])}return r},lr=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],ur=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],dr=[16,16,20,20,0,24,24,0],fr=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],pr=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],mr=[32e3,44100,48e3,0],hr=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],gr=[512,1024,2048,4096],_r=e=>{let t=yr(e),n=x(e),r=t?Math.ceil(t.frameSize/4)*4:0,i=null;for(;r+4<=e.length&&n.getUint32(r)===1683496997;){let t=br(e.subarray(r));if(!t)break;i??=t,r+=t.frameSize}if(t)return{frameSize:i?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:i!==null};if(!i?.asset)return null;let{asset:a}=i;return{frameSize:r,sampleRate:a.sampleRate,numberOfChannels:a.numberOfChannels,sampleCount:a.sampleCount,channelLayout:a.channelLayout,pcmResolution:a.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},vr=e=>{let t=_r(e);return t?.core?t.hasExtensions?`dtsh`:`dtsc`:null},yr=e=>{if(e.length<18||e[0]!==127||e[1]!==254||e[2]!==128||e[3]!==1)return null;let t=new N(e);if(t.skipBits(32),t.skipBits(1),t.readBits(5)!==31)return null;let n=t.readBits(1),r=t.readBits(7)+1;if(r%8!=0)return null;let i=t.readBits(14)+1;if(i<96)return null;let a=t.readBits(6);if(a>=fr.length)return null;let o=lr[t.readBits(4)];if(o===0)return null;let s=ur[t.readBits(5)];if(t.readBits(1)!==0)return null;t.skipBits(4);let c=t.readBits(3),l=t.readBits(1);t.skipBits(1);let u=t.readBits(2);if(u===3)return null;t.skipBits(1),n&&t.skipBits(16),t.skipBits(7);let d=dr[t.readBits(3)];if(d===0)return null;let f=u!==0;return{frameSize:i,sampleRate:o,numberOfChannels:fr[a]+ +!!f,sampleCount:r*32,channelLayout:pr[a]|(f?8:0),amode:a,lfePresent:f,bitRate:s,pcmResolution:d,extAudioId:l?c:null}},br=e=>{if(e.length<10||e[0]!==100||e[1]!==88||e[2]!==32||e[3]!==37)return null;let t=new N(e);t.skipBits(32),t.skipBits(8);let n=t.readBits(2),r=t.readBits(1),i=8+4*r,a=16+4*r;t.skipBits(i);let o=t.readBits(a)+1,s={frameSize:o,asset:null};if(!t.readBits(1))return s;let c=mr[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);let u=t.readBits(3)+1,d=t.readBits(3)+1,f=[];for(let e=0;e<u;e++)f.push(t.readBits(n+1));for(let e of f)t.skipBits(8*Ie(e));if(t.readBits(1)){t.skipBits(2);let e=t.readBits(2)+1<<2,n=t.readBits(2)+1;t.skipBits(n*e)}for(let e=0;e<d;e++)t.skipBits(a);t.skipBits(9),t.skipBits(3),t.readBits(1)&&t.skipBits(4),t.readBits(1)&&t.skipBits(24),t.readBits(1)&&t.skipBits(8*(t.readBits(10)+1));let p=t.readBits(5)+1,m=hr[t.readBits(4)],h=t.readBits(8)+1,g=0;if(t.readBits(1)&&(h>2&&t.skipBits(1),h>6&&t.skipBits(1),t.readBits(1))){let e=t.readBits(2)+1<<2;g=t.readBits(e)}return c===0||t.getBitsLeft()<0?s:{frameSize:o,asset:{sampleRate:m,numberOfChannels:h,sampleCount:Math.round(l*m/c),channelLayout:g,pcmResolution:p}}},xr=e=>{if(e.length<20)return null;let t=x(e),n=t.getUint32(0);if(n===0)return null;let r=new N(e);r.seekToByte(13);let i=r.readBits(2);r.skipBits(5);let a=r.readBits(1),o=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);let s=r.readBits(16),c=null;return s===0?o<fr.length&&(c=fr[o]+a):c=wr(s),{sampleRate:n,maxBitrate:t.getUint32(4),avgBitrate:t.getUint32(8),pcmSampleDepth:e[12],sampleCount:gr[i],channelLayout:s,numberOfChannels:c}},Sr={0:2,2:4,6:3},Cr=e=>{let t=/* @__PURE__ */ new Uint8Array(20),n=x(t);n.setUint32(0,e.sampleRate),n.setUint32(4,e.bitRate),n.setUint32(8,e.bitRate),t[12]=e.pcmResolution;let r=0;if(e.core&&!e.hasExtensions){let{extAudioId:t}=e.core;r=t===null?1:Sr[t]??0}let i=new N(t);return i.seekToByte(13),i.writeBits(2,Math.max(gr.indexOf(e.sampleCount),0)),i.writeBits(5,r),i.writeBits(1,+!!e.core?.lfePresent),i.writeBits(6,e.core?.amode??0),i.writeBits(14,e.core?e.core.frameSize-1:0),i.writeBits(1,0),i.writeBits(3,0),i.writeBits(16,e.channelLayout),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(5,0),t},wr=e=>Ie(e)+Ie(e&44646),Tr=/<(?:(\d{2,}):)?(\d{2}):(\d{2}).(\d{3})>/g,Er=/(?:(\d{2,}):)?(\d{2}):(\d{2}).(\d{3})/,Dr=e=>{
80
+ /*!
81
+ * Copyright (c) 2026-present, Vanilagy and contributors
82
+ *
83
+ * This Source Code Form is subject to the terms of the Mozilla Public
84
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
85
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
86
+ */
87
+ let t=Er.exec(e);if(!t)throw Error(`Expected match.`);return 36e5*Number(t[1]||`0`)+6e4*Number(t[2])+1e3*Number(t[3])+Number(t[4])},Or=e=>{let t=Math.round(1e3*e),n=Math.floor(t/36e5),r=Math.floor(t%36e5/6e4),i=Math.floor(t%6e4/1e3),a=t%1e3;return n.toString().padStart(2,`0`)+`:`+r.toString().padStart(2,`0`)+`:`+i.toString().padStart(2,`0`)+`.`+a.toString().padStart(3,`0`)},kr=e=>{
88
+ /*!
89
+ * Copyright (c) 2026-present, Vanilagy and contributors
90
+ *
91
+ * This Source Code Form is subject to the terms of the Mozilla Public
92
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
93
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
94
+ */
95
+ let t=8191,n=e>>2,r=4096,i=0,a=12,o=0;for(n<0&&(n=-n,i=128),n+=33,n>t&&(n=t);(n&r)!==r&&a>=5;)r>>=1,a--;return o=n>>a-4&15,~(i|a-5<<4|o)&255},Ar=e=>{let t=0,n=0,r=~e;r&128&&(r&=-129,t=-1),n=((r&240)>>4)+5;let i=(1<<n|(r&15)<<n-4|1<<n-5)-33;return(t===0?i:-i)<<2},jr=e=>{let t=4095,n=2048,r=0,i=11,a=0,o=e>>3;for(o<0?o=-o-1:r=128,o>t&&(o=t);(o&n)!==n&&i>=5;)n>>=1,i--;return a=o>>(i===4?1:i-4)&15,(r|i-4<<4|a)^85},Mr=e=>{let t=0,n=0,r=e^85;r&128&&(r&=-129,t=-1),n=((r&240)>>4)+4;let i=0;return i=n===4?r<<1|1:1<<n|(r&15)<<n-4|1<<n-5,(t===0?-i:i)<<3};
96
+ /*!
97
+ * Copyright (c) 2026-present, Vanilagy and contributors
98
+ *
99
+ * This Source Code Form is subject to the terms of the Mozilla Public
100
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
101
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
102
+ */
103
+ var Nr=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},Pr=(function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var r,i=0;function a(){for(;r=t.stack.pop();)try{if(!r.async&&i===1)return i=0,t.stack.push(r),Promise.resolve().then(a);if(r.dispose){var e=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(e).then(a,function(e){return n(e),a()})}else i|=1}catch(e){n(e)}if(i===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return a()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r});st();let Fr=-1/0,Ir=-1/0,Lr=null;typeof FinalizationRegistry<`u`&&(Lr=new FinalizationRegistry(e=>{let t=performance.now();e.type===`video`?(t-Fr>=1e3&&(M._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.`),Fr=t),typeof VideoFrame<`u`&&e.data instanceof VideoFrame&&e.data.close()):(t-Ir>=1e3&&(M._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.`),Ir=t),typeof AudioData<`u`&&e.data instanceof AudioData&&e.data.close())}));var Rr=class{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}};const zr=[`I420`,`I420P10`,`I420P12`,`I420A`,`I420AP10`,`I420AP12`,`I422`,`I422P10`,`I422P12`,`I422A`,`I422AP10`,`I422AP12`,`I444`,`I444P10`,`I444P12`,`I444A`,`I444AP10`,`I444AP12`,`NV12`,`RGBA`,`RGBX`,`BGRA`,`BGRX`],Br=new Set(zr);var Vr=class e{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(ze*this.timestamp)}get microsecondDuration(){return Math.trunc(ze*this.duration)}get hasAlpha(){return this.format&&this.format.includes(`A`)}constructor(t,n){if(this._closed=!1,t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.format===void 0||!Br.has(n.format))throw TypeError(`init.format must be one of: `+zr.join(`, `));if(!Number.isInteger(n.codedWidth)||n.codedWidth<=0)throw TypeError(`init.codedWidth must be a positive integer.`);if(!Number.isInteger(n.codedHeight)||n.codedHeight<=0)throw TypeError(`init.codedHeight must be a positive integer.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(n.flip!==void 0&&typeof n.flip!=`boolean`)throw TypeError(`init.flip, when provided, must be a boolean.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(n.layout!==void 0){if(!Array.isArray(n.layout))throw TypeError(`init.layout, when provided, must be an array.`);for(let e of n.layout){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`Each entry in init.layout must be an object.`);if(!Number.isInteger(e.offset)||e.offset<0)throw TypeError(`plane.offset must be a non-negative integer.`);if(!Number.isInteger(e.stride)||e.stride<0)throw TypeError(`plane.stride must be a non-negative integer.`)}let e=$r(n.format).length;if(n.layout.length!==e)throw TypeError(`init.layout must have ${e} entries for format ${n.format}.`)}if(n.visibleRect!==void 0&&Xr(n.visibleRect),n.displayWidth!==void 0&&(!Number.isInteger(n.displayWidth)||n.displayWidth<=0))throw TypeError(`init.displayWidth, when provided, must be a positive integer.`);if(n.displayHeight!==void 0&&(!Number.isInteger(n.displayHeight)||n.displayHeight<=0))throw TypeError(`init.displayHeight, when provided, must be a positive integer.`);if(n.displayWidth!==void 0!=(n.displayHeight!==void 0))throw TypeError(`init.displayWidth and init.displayHeight must be either both provided or both omitted.`);this.format=n.format,this.rotation=n.rotation??0,this.flip=n.flip??!1,this.timestamp=n.timestamp,this.duration=n.duration??0;let e=n.layout??Qr(n.format,n.codedWidth,n.codedHeight),r=n.colorSpace??null;r===null&&(r=this.format===`RGBA`||this.format===`RGBX`||this.format===`BGRA`||this.format===`BGRX`?{primaries:`bt709`,transfer:`iec61966-2-1`,matrix:`rgb`,fullRange:!0}:{primaries:`bt709`,transfer:`bt709`,matrix:`bt709`,fullRange:!1}),this.visibleRect={left:n.visibleRect?.left??0,top:n.visibleRect?.top??0,width:n.visibleRect?.width??n.codedWidth,height:n.visibleRect?.height??n.codedHeight},n.displayWidth===void 0?(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height):(this.squarePixelWidth=this.rotation%180==0?n.displayWidth:n.displayHeight,this.squarePixelHeight=this.rotation%180==0?n.displayHeight:n.displayWidth),this._data=n._doNotCopy?b(t):b(t).slice(),this._layout=e,this.colorSpace=new Kr(r)}else if(typeof VideoFrame<`u`&&t instanceof VideoFrame){if(t.codedWidth===0)throw TypeError(`data must not be a closed VideoFrame.`);if(n?.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(n?.flip!==void 0&&typeof n.flip!=`boolean`)throw TypeError(`init.flip, when provided, must be a boolean.`);if(n?.timestamp!==void 0&&!Number.isFinite(n?.timestamp))throw TypeError(`init.timestamp, when provided, must be a number.`);if(n?.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);n?.visibleRect!==void 0&&Xr(n.visibleRect),this._data=t,this._layout=null,this.format=t.format,this.visibleRect={left:t.visibleRect?.x??0,top:t.visibleRect?.y??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},this.rotation=n?.rotation??0,this.flip=n?.flip??!1,this.squarePixelWidth=t.displayWidth,this.squarePixelHeight=t.displayHeight,this.timestamp=n?.timestamp??t.timestamp/1e6,this.duration=n?.duration??(t.duration??0)/1e6;let{primaries:e,transfer:r,matrix:i,fullRange:a}=t.colorSpace;this.colorSpace=new Kr({primaries:e!==null&&e in E?e:null,transfer:r!==null&&r in re?r:null,matrix:i!==null&&i in ae?i:null,fullRange:a})}else if(typeof HTMLImageElement<`u`&&t instanceof HTMLImageElement||typeof SVGImageElement<`u`&&t instanceof SVGImageElement||typeof ImageBitmap<`u`&&t instanceof ImageBitmap||typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement||typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&t instanceof OffscreenCanvas){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(n.flip!==void 0&&typeof n.flip!=`boolean`)throw TypeError(`init.flip, when provided, must be a boolean.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(n.visibleRect!==void 0&&Xr(n.visibleRect),typeof VideoFrame<`u`)return new e(new VideoFrame(t,{timestamp:Math.trunc(n.timestamp*ze),duration:Math.trunc((n.duration??0)*ze)||void 0,visibleRect:n.visibleRect&&{x:n.visibleRect.left,y:n.visibleRect.top,width:n.visibleRect.width,height:n.visibleRect.height}}),n);let r=0,i=0;if(`naturalWidth`in t?(r=t.naturalWidth,i=t.naturalHeight):`videoWidth`in t?(r=t.videoWidth,i=t.videoHeight):`width`in t&&(r=Number(t.width),i=Number(t.height)),!r||!i)throw TypeError(`Could not determine dimensions.`);let a=n.visibleRect??{left:0,top:0,width:r,height:i},o=new OffscreenCanvas(a.width,a.height),s=o.getContext(`2d`,{alpha:Ge(),willReadFrequently:!0});if(!s)throw Error(`OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.`);s.drawImage(t,-a.left,-a.top),this._data=o,this._layout=null,this.format=`RGBX`,this.visibleRect={left:0,top:0,width:a.width,height:a.height},this.squarePixelWidth=a.width,this.squarePixelHeight=a.height,this.rotation=n.rotation??0,this.flip=n.flip??!1,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=new Kr({matrix:`rgb`,primaries:`bt709`,transfer:`iec61966-2-1`,fullRange:!0})}else if(t instanceof Rr){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(n.flip!==void 0&&typeof n.flip!=`boolean`)throw TypeError(`init.flip, when provided, must be a boolean.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(this.format=t.getFormat(),this.format!==null&&!zr.includes(this.format))throw TypeError(`getFormat() must return a VideoSamplePixelFormat or null.`);if(this.visibleRect={left:0,top:0,width:t.getCodedWidth(),height:t.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw TypeError(`getCodedWidth() must return a positive integer.`);if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw TypeError(`getCodedHeight() must return a positive integer.`);if(this.squarePixelWidth=t.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw TypeError(`getSquarePixelWidth() must return a positive integer.`);if(this.squarePixelHeight=t.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw TypeError(`getSquarePixelHeight() must return a positive integer.`);this.rotation=n.rotation??0,this.flip=n.flip??!1,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=t.getColorSpace(),this._data=t,t._referenceCount++}else throw TypeError(`Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.`);this.encodeOptions=n?.encodeOptions??{},this.pixelAspectRatio=pt({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Lr?.register(this,{type:`video`,data:this._data},this)}clone(){if(this._closed)throw Error(`VideoSample is closed.`);return t(this._data!==null),this._data instanceof Rr?new e(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):qr(this._data)?new e(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(t(this._layout),new e(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,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new e(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||=(Lr?.unregister(this),this._data instanceof Rr?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):qr(this._data)?this._data.close():this._data=null,!0)}allocationSize(e={}){if(Zr(e),this._closed)throw Error(`VideoSample is closed.`);if((e.format??this.format)==null)throw Error(`Cannot get allocation size when format is null.`);return qr(this._data)?this._data.allocationSize(e):ei(this,e).allocationSize}async copyTo(n,r={}){if(!ue(n))throw TypeError(`destination must be an ArrayBuffer or an ArrayBuffer view.`);if(Zr(r),this._closed)throw Error(`VideoSample is closed.`);if((r.format??this.format)==null)throw Error(`Cannot copy video sample data when format is null.`);if(t(this._data!==null),qr(this._data))return this._data.copyTo(n,r);if(r.format&&![`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(this.format)&&[`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(r.format)){if(this._data instanceof Rr){let t={stack:[],error:void 0,hasError:!1};try{let i=Nr(t,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip},r.colorSpace??`srgb`),!1);if(!(i instanceof e))throw TypeError(`toRgbSample() must return a VideoSample.`);if(![`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(i.format))throw Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${i.format}' instead.`);return await i.copyTo(n,r)}catch(e){t.error=e,t.hasError=!0}finally{Pr(t)}}else{if(typeof VideoFrame>`u`)throw Error(`For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.`);let e=this.toVideoFrame();try{return await e.copyTo(n,r)}finally{e.close()}}}let i=ei(this,r);t(this.format);let a=b(n);if(a.byteLength<i.allocationSize)throw TypeError(`Destination buffer too small. Required: ${i.allocationSize}, Available: ${a.byteLength}`);let o=$r(this.format),s;if(this._data instanceof Rr){let e=this._data.getDataPlanes();if(j(e)&&(e=await e),!Array.isArray(e)||e.some(e=>!(e.data instanceof Uint8Array)||!Number.isInteger(e.stride)||e.stride<0))throw TypeError(`getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.`);s=e}else if(this._data instanceof Uint8Array)t(this._layout),t(this._layout.length===o.length),s=this._layout.map((e,t)=>{let n=Math.ceil((this.visibleRect.top+this.visibleRect.height)/o[t].heightDivisor);return{data:this._data.subarray(e.offset,e.offset+e.stride*n),stride:e.stride}});else{let e=this._data.getContext(`2d`);t(e);let n=e.getImageData(0,0,this.codedWidth,this.codedHeight);s=[{data:b(n.data),stride:4*this.codedWidth}]}let c=[],l=o.length;for(let e=0;e<l;e++){let t=i.computedLayouts[e],n=s[e].stride,r=s[e].data,o=t.sourceTop*n;o+=t.sourceLeftBytes;let l=t.destinationOffset,u=t.sourceWidthBytes,d={offset:l,stride:t.destinationStride};for(let e=0;e<t.sourceHeight;e++){if(o+u>r.byteLength)throw Error(`Source buffer OOB read.`);if(l+u>a.byteLength)throw Error(`Destination buffer OOB write.`);let e=r.subarray(o,o+u);a.set(e,l),o+=n,l+=t.destinationStride}c.push(d)}if(r.format!==void 0){let e=this.format.startsWith(`RGB`)!==r.format.startsWith(`RGB`),t=this.format.includes(`X`)&&r.format.includes(`A`);if(e||t){let n=i.computedLayouts[0];for(let r=0;r<n.sourceHeight;r++){let i=n.destinationOffset+r*n.destinationStride,o=i+n.sourceWidthBytes;for(let n=i;n<o;n+=4){if(e){let e=a[n],t=a[n+2];a[n]=t,a[n+2]=e}t&&(a[n+3]=255)}}}}return c}toVideoFrame(){if(this._closed)throw Error(`VideoSample is closed.`);if(t(this._data!==null),this._data instanceof Rr){if(this.format===null)throw Error(`Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.`);let e=this._data.getDataPlanes();if(j(e))throw Error(`Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.`);let t=e.reduce((e,t)=>e+t.data.byteLength,0),n=new Uint8Array(t),r=0,i=[];for(let t of e)n.set(t.data,r),i.push(r),r+=t.data.byteLength;return new VideoFrame(n,{format:this.format,layout:e.map((e,t)=>({offset:i[t],stride:e.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return qr(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(t(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.visibleRect.left+this.visibleRect.width,codedHeight:this.visibleRect.top+this.visibleRect.height,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:{x:this.visibleRect.left,y:this.visibleRect.top,width:this.visibleRect.width,height:this.visibleRect.height},displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,n,r,i,a,o,s,c){let l=0,u=0,d=this.displayWidth,f=this.displayHeight,p=0,m=0,h=this.displayWidth,g=this.displayHeight;if(a===void 0?(p=t,m=n,r!==void 0&&(h=r,g=i)):(l=t,u=n,d=r,f=i,p=a,m=o,s===void 0?(h=d,g=f):(h=s,g=c)),!(typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<`u`&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError(`context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.`);if(!Number.isFinite(l))throw TypeError(`sx must be a number.`);if(!Number.isFinite(u))throw TypeError(`sy must be a number.`);if(!Number.isFinite(d)||d<0)throw TypeError(`sWidth must be a non-negative number.`);if(!Number.isFinite(f)||f<0)throw TypeError(`sHeight must be a non-negative number.`);if(!Number.isFinite(p))throw TypeError(`dx must be a number.`);if(!Number.isFinite(m))throw TypeError(`dy must be a number.`);if(!Number.isFinite(h)||h<0)throw TypeError(`dWidth must be a non-negative number.`);if(!Number.isFinite(g)||g<0)throw TypeError(`dHeight must be a non-negative number.`);if(this._closed)throw Error(`VideoSample is closed.`);({sx:l,sy:u,sWidth:d,sHeight:f}=this._unmapSourceRegion(l,u,d,f,this.rotation,this.flip));let _=this.toCanvasImageSource();e.save();let v=p+h/2,y=m+g/2;e.translate(v,y),this.flip&&e.scale(-1,1),e.rotate(this.rotation*Math.PI/180);let b=this.rotation%180==0?1:h/g;e.scale(1/b,b),e.drawImage(_,l,u,d,f,-h/2,-g/2,h,g),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<`u`&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError(`context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit must be 'fill', 'contain', or 'cover'.`);if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`options.rotation, when provided, must be 0, 90, 180, or 270.`);if(t.flip!==void 0&&typeof t.flip!=`boolean`)throw TypeError(`options.flip, when provided, must be a boolean.`);t.crop!==void 0&&Yr(t.crop,`options.`);let n=e.canvas.width,r=e.canvas.height,i=t.rotation??this.rotation,a=t.flip??this.flip,[o,s]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],c=t.crop;c&&=Jr(c,o,s);let l,u,d,f,{sx:p,sy:m,sWidth:h,sHeight:g}=this._unmapSourceRegion(c?.left??0,c?.top??0,c?.width??o,c?.height??s,i,a);if(t.fit===`fill`)l=0,u=0,d=n,f=r;else{let[e,i]=c?[c.width,c.height]:[o,s],a=t.fit===`contain`?Math.min(n/e,r/i):Math.max(n/e,r/i);d=e*a,f=i*a,l=(n-d)/2,u=(r-f)/2}let _=this.toCanvasImageSource();e.save();let v=i%180==0?1:d/f;e.translate(n/2,r/2),a&&e.scale(-1,1),e.rotate(i*Math.PI/180),e.scale(1/v,v),e.translate(-n/2,-r/2),e.drawImage(_,p,m,h,g,l,u,d,f),e.restore()}_unmapSourceRegion(e,t,n,r,i,a){return a&&(e=(i%180==0?this.squarePixelWidth:this.squarePixelHeight)-e-n),i===90?[e,t,n,r]=[t,this.squarePixelHeight-e-n,r,n]:i===180?[e,t]=[this.squarePixelWidth-e-n,this.squarePixelHeight-t-r]:i===270&&([e,t,n,r]=[this.squarePixelWidth-t-r,e,r,n]),{sx:e,sy:t,sWidth:n,sHeight:r}}_drawWithFitAndMipmapping(e,t,n){let r=e.width,i=e.height,[a,o]=n.rotation%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],s=n.crop?n.crop.width:a,c=n.crop?n.crop.height:o,l=0;2*r<s&&2*i<c&&(l=Math.floor(Math.log2(Math.min(s/r,c/i))));let u=r*2**l,d=i*2**l,{canvas:f,context:p,isNew:m}=l>0?Gr(u,d):{canvas:e,context:t,isNew:n.targetIsFresh};p.imageSmoothingQuality=`high`,n.fillBlack?(p.fillStyle=`black`,p.fillRect(0,0,u,d)):m||p.clearRect(0,0,u,d),this.drawWithFit(p,{fit:n.fit,rotation:n.rotation,flip:n.flip,crop:n.crop}),p.globalCompositeOperation=`copy`;for(let e=l;e>1;e--){let t=r*2**e,n=i*2**e;p.drawImage(f,0,0,t,n,0,0,t/2,n/2)}p.globalCompositeOperation=`source-over`,l>0&&(t.imageSmoothingQuality=`high`,t.globalCompositeOperation=`copy`,t.drawImage(f,0,0,2*r,2*i,0,0,r,i),t.globalCompositeOperation=`source-over`)}toCanvasImageSource(){if(this._closed)throw Error(`VideoSample is closed.`);if(t(this._data!==null),this._data instanceof Rr||this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}async transform(t){if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw TypeError(`options.width, when provided, must be a positive integer.`);if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw TypeError(`options.height, when provided, must be a positive integer.`);if(t.roundDimensionsTo!==void 0&&(!Number.isInteger(t.roundDimensionsTo)||t.roundDimensionsTo<=0))throw TypeError(`options.roundDimensionsTo, when provided, must be a positive integer.`);if(t.fit!==void 0&&![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.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 TypeError(`When both options.width and options.height are provided, options.fit must also be provided.`);if(t.rotate!==void 0&&![0,90,180,270].includes(t.rotate))throw TypeError(`options.rotate, when provided, must be 0, 90, 180 or 270.`);if(t.flip!==void 0&&typeof t.flip!=`boolean`)throw TypeError(`options.flip, when provided, must be a boolean.`);if(t.crop!==void 0&&Yr(t.crop,`options.`),t.alpha!==void 0&&![`keep`,`discard`].includes(t.alpha))throw TypeError(`options.alpha, when provided, must be 'keep' or 'discard'.`);let{rotation:n,flip:r}=p(this.rotation,this.flip,t.rotate??0,t.flip??!1),[i,a]=n%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=t.crop;o&&=Jr(o,i,a);let s=o?o.width:i,c=o?o.height:a,l=s/c,u,d;t.width!==void 0&&t.height===void 0?(u=t.width,d=u/l):t.width===void 0&&t.height!==void 0?(d=t.height,u=d*l):t.width!==void 0&&t.height!==void 0?(u=t.width,d=t.height):(u=s,d=c),u=je(u,t.roundDimensionsTo??1),d=je(d,t.roundDimensionsTo??1);let f={width:u,height:d,fit:t.fit??`fill`,rotation:n,flip:r,crop:o??{left:0,top:0,width:i,height:a},alpha:t.alpha??`keep`};for(let e of Hr){let t=e(this,f);if(j(t)&&(t=await t),t!==null)return t}let{canvas:m,context:h,isNew:g}=Gr(f.width,f.height);return this._drawWithFitAndMipmapping(m,h,{fit:f.fit,rotation:f.rotation,flip:f.flip,crop:f.crop,targetIsFresh:g,fillBlack:f.alpha===`discard`}),new e(m,{timestamp:this.timestamp,duration:this.duration,rotation:0,flip:!1,encodeOptions:this.encodeOptions})}setRotation(e){if(![0,90,180,270].includes(e))throw TypeError(`newRotation must be 0, 90, 180, or 270.`);this.rotation=e}setFlip(e){if(typeof e!=`boolean`)throw TypeError(`newFlip must be a boolean.`);this.flip=e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError(`newTimestamp must be a number.`);this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw TypeError(`newDuration must be a non-negative number.`);this.duration=e}setEncodeOptions(e){if(!e||typeof e!=`object`)throw TypeError(`newEncodeOptions must be an object.`);this.encodeOptions=e}[Symbol.dispose](){this.close()}};const Hr=[],Ur=[];let Wr=0;const Gr=(e,t)=>{for(let n of Ur)if(n.canvas.width===e&&n.canvas.height===t)return n.age=Wr++,{canvas:n.canvas,context:n.context,isNew:!1};let n;if(typeof OffscreenCanvas<`u`)n=new OffscreenCanvas(e,t);else{if(typeof window>`u`||typeof document>`u`)throw Error(`Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().`);n=document.createElement(`canvas`),n.width=e,n.height=t}let r=n.getContext(`2d`,{alpha:!0,willReadFrequently:!1});if(!r)throw Error(`The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.`);return Ur.length>=3&&Ur.splice(ft(Ur,e=>e.age),1),Ur.push({canvas:n,context:r,age:Wr++}),{canvas:n,context:r,isNew:!0}};var Kr=class{constructor(e){if(e!==void 0){if(!e||typeof e!=`object`)throw TypeError(`init.colorSpace, when provided, must be an object.`);let t=Object.keys(E);if(e.primaries!=null&&!t.includes(e.primaries))throw TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(`, `)}.`);let n=Object.keys(re);if(e.transfer!=null&&!n.includes(e.transfer))throw TypeError(`init.colorSpace.transfer, when provided, must be one of ${n.join(`, `)}.`);let r=Object.keys(ae);if(e.matrix!=null&&!r.includes(e.matrix))throw TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(`, `)}.`);if(e.fullRange!=null&&typeof e.fullRange!=`boolean`)throw 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}}};const qr=e=>typeof VideoFrame<`u`&&e instanceof VideoFrame,Jr=(e,n,r)=>{let i=Math.min(e.left,n),a=Math.min(e.top,r),o=Math.min(e.width,n-i),s=Math.min(e.height,r-a);return t(o>=0),t(s>=0),{left:i,top:a,width:o,height:s}},Yr=(e,t)=>{if(!e||typeof e!=`object`)throw TypeError(t+`crop, when provided, must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw TypeError(t+`crop.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw TypeError(t+`crop.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw TypeError(t+`crop.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw TypeError(t+`crop.height must be a non-negative integer.`)},Xr=e=>{if(mt(e,`init.visibleRect`),e.width===0||e.height===0)throw TypeError(`init.visibleRect must not be empty.`)},Zr=e=>{if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.colorSpace!==void 0&&![`display-p3`,`srgb`].includes(e.colorSpace))throw TypeError(`options.colorSpace, when provided, must be 'display-p3' or 'srgb'.`);if(e.format!==void 0&&typeof e.format!=`string`)throw TypeError(`options.format, when provided, must be a string.`);if(e.layout!==void 0){if(!Array.isArray(e.layout))throw TypeError(`options.layout, when provided, must be an array.`);for(let t of e.layout){if(!t||typeof t!=`object`)throw TypeError(`Each entry in options.layout must be an object.`);if(!Number.isInteger(t.offset)||t.offset<0)throw TypeError(`plane.offset must be a non-negative integer.`);if(!Number.isInteger(t.stride)||t.stride<0)throw TypeError(`plane.stride must be a non-negative integer.`)}}if(e.rect!==void 0){if(!e.rect||typeof e.rect!=`object`)throw TypeError(`options.rect, when provided, must be an object.`);if(e.rect.x!==void 0&&(!Number.isInteger(e.rect.x)||e.rect.x<0))throw TypeError(`options.rect.x, when provided, must be a non-negative integer.`);if(e.rect.y!==void 0&&(!Number.isInteger(e.rect.y)||e.rect.y<0))throw TypeError(`options.rect.y, when provided, must be a non-negative integer.`);if(e.rect.width!==void 0&&(!Number.isInteger(e.rect.width)||e.rect.width<0))throw TypeError(`options.rect.width, when provided, must be a non-negative integer.`);if(e.rect.height!==void 0&&(!Number.isInteger(e.rect.height)||e.rect.height<0))throw TypeError(`options.rect.height, when provided, must be a non-negative integer.`)}},Qr=(e,t,n)=>{let r=$r(e),i=[],a=0;for(let e of r){let r=Math.ceil(t/e.widthDivisor),o=Math.ceil(n/e.heightDivisor),s=r*e.sampleBytes,c=s*o;i.push({offset:a,stride:s}),a+=c}return i},$r=e=>{let n=(e,t,n,r,i)=>{let a=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:n,heightDivisor:r},{sampleBytes:t,widthDivisor:n,heightDivisor:r}];return i&&a.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),a};switch(e){case`I420`:return n(1,1,2,2,!1);case`I420P10`:case`I420P12`:return n(2,2,2,2,!1);case`I420A`:return n(1,1,2,2,!0);case`I420AP10`:case`I420AP12`:return n(2,2,2,2,!0);case`I422`:return n(1,1,2,1,!1);case`I422P10`:case`I422P12`:return n(2,2,2,1,!1);case`I422A`:return n(1,1,2,1,!0);case`I422AP10`:case`I422AP12`:return n(2,2,2,1,!0);case`I444`:return n(1,1,1,1,!1);case`I444P10`:case`I444P12`:return n(2,2,1,1,!1);case`I444A`:return n(1,1,1,1,!0);case`I444AP10`:case`I444AP12`:return n(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:k(e),t(!1)}},ei=(e,t)=>{let n={x:e.visibleRect.left,y:e.visibleRect.top,width:e.visibleRect.width,height:e.visibleRect.height},r=t.rect,i=ti(n,r,e.visibleRect.left+e.visibleRect.width,e.visibleRect.top+e.visibleRect.height,e.format),a=t.layout,o;if(!t.format||t.format===e.format)o=e.format;else if([`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(t.format))o=t.format;else throw Error(`NotSupportedError: Invalid destination format.`);return ri(i,o,a)},ti=(e,t,n,r,i)=>{let a={...e};if(t!==void 0){if(!t.width||!t.height)throw TypeError(`visibleRect dimensions cannot be zero.`);if((t.x||0)+(t.width||0)>n)throw TypeError(`visibleRect exceeds codedWidth.`);if((t.y||0)+(t.height||0)>r)throw TypeError(`visibleRect exceeds codedHeight.`);a.x=t.x||0,a.y=t.y||0,a.width=t.width||0,a.height=t.height||0}if(!ni(i,a))throw TypeError(`visibleRect alignment is invalid for the format.`);return a},ni=(e,t)=>{if(e===null)return!0;let n=$r(e);for(let e=0;e<n.length;e++){let r=n[e],i=r.widthDivisor,a=r.heightDivisor;if((t.x||0)%i!==0||(t.y||0)%a!==0)return!1}return!0},ri=(e,t,n)=>{let r=$r(t),i=r.length;if(n!==void 0&&n.length!==i)throw TypeError(`Layout must have ${i} planes.`);let a=0,o=[],s=[];for(let t=0;t<i;t++){let i=r[t],c=i.sampleBytes,l=i.widthDivisor,u=i.heightDivisor,d={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(d.sourceTop=Math.ceil(Math.trunc(e.y||0)/u),d.sourceHeight=Math.ceil(Math.trunc(e.height||0)/u),d.sourceLeftBytes=Math.floor(Math.trunc(e.x||0)/l)*c,d.sourceWidthBytes=Math.ceil(Math.trunc(e.width||0)/l)*c,n!==void 0){let e=n[t];if(e.stride<d.sourceWidthBytes)throw TypeError(`Stride for plane ${t} is too small.`);d.destinationOffset=e.offset,d.destinationStride=e.stride}else d.destinationOffset=a,d.destinationStride=d.sourceWidthBytes;let f=d.destinationStride*d.sourceHeight+d.destinationOffset;if(f>4294967295)throw TypeError(`Allocation size exceeds limit.`);s.push(f),a=Math.max(a,f);for(let e=0;e<t;e++){let n=o[e];if(!(s[t]<=n.destinationOffset||s[e]<=d.destinationOffset))throw TypeError(`Planes overlap.`)}o.push(d)}return{allocationSize:a,computedLayouts:o}},ii=/* @__PURE__ */ new Set([`f32`,`f32-planar`,`s16`,`s16-planar`,`s32`,`s32-planar`,`u8`,`u8-planar`]);var ai=class{constructor(){this._referenceCount=0}},oi=class e{get microsecondTimestamp(){return Math.trunc(ze*this.timestamp)}get microsecondDuration(){return Math.trunc(ze*this.duration)}constructor(e){if(this._closed=!1,di(e)){if(e.format===null)throw 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 instanceof ai){if(this.format=e.getFormat(),!ii.has(this.format))throw TypeError(`getFormat() must return an AudioSampleFormat.`);if(this.sampleRate=e.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw TypeError(`getSampleRate() must return a positive integer.`);if(this.numberOfFrames=e.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw TypeError(`getNumberOfFrames() must return a non-negative integer.`);if(this.numberOfChannels=e.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw TypeError(`getNumberOfChannels() must return a positive integer.`);if(this.timestamp=e.getTimestamp(),!Number.isFinite(this.timestamp))throw TypeError(`getTimestamp() must return a finite number.`);this.duration=this.numberOfFrames/this.sampleRate,this._data=e,e._referenceCount++}else{if(!e||typeof e!=`object`)throw TypeError(`Invalid AudioDataInit: must be an object.`);if(!ii.has(e.format))throw TypeError(`Invalid AudioDataInit: invalid format.`);if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw TypeError(`Invalid AudioDataInit: sampleRate must be > 0.`);if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels<=0)throw TypeError(`Invalid AudioDataInit: numberOfChannels must be an integer > 0.`);if(!Number.isFinite(e?.timestamp))throw TypeError(`init.timestamp must be a number.`);let t=e.data.byteLength/(si(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw TypeError(`Invalid AudioDataInit: data size is not a multiple of frame size.`);this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let n;if(e.data instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e.data instanceof SharedArrayBuffer)n=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))n=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw TypeError(`Invalid AudioDataInit: data is not a BufferSource.`);let r=this.numberOfFrames*this.numberOfChannels*si(this.format);if(n.byteLength<r)throw TypeError(`Invalid AudioDataInit: insufficient data size.`);this._data=e._doNotCopy?n:n.slice()}Lr?.register(this,{type:`audio`,data:this._data},this)}allocationSize(e){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw TypeError(`planeIndex must be a non-negative integer.`);if(e.format!==void 0&&!ii.has(e.format))throw TypeError(`Invalid format.`);if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw TypeError(`frameOffset must be a non-negative integer.`);if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw TypeError(`frameCount must be a non-negative integer.`);if(this._closed)throw Error(`AudioSample is closed.`);let t=e.format??this.format,n=e.frameOffset??0;if(n>0&&n>=this.numberOfFrames)throw RangeError(`frameOffset out of range`);let r=e.frameCount===void 0?this.numberOfFrames-n:e.frameCount;if(r>this.numberOfFrames-n)throw RangeError(`frameCount out of range`);let i=si(t),a=ci(t);if(a&&e.planeIndex>=this.numberOfChannels||!a&&e.planeIndex!==0)throw RangeError(`planeIndex out of range`);return(a?r:r*this.numberOfChannels)*i}copyTo(e,n){if(!ue(e))throw TypeError(`destination must be an ArrayBuffer or an ArrayBuffer view.`);if(!n||typeof n!=`object`)throw TypeError(`options must be an object.`);if(!Number.isInteger(n.planeIndex)||n.planeIndex<0)throw TypeError(`planeIndex must be a non-negative integer.`);if(n.format!==void 0&&!ii.has(n.format))throw TypeError(`Invalid format.`);if(n.frameOffset!==void 0&&(!Number.isInteger(n.frameOffset)||n.frameOffset<0))throw TypeError(`frameOffset must be a non-negative integer.`);if(n.frameCount!==void 0&&(!Number.isInteger(n.frameCount)||n.frameCount<0))throw TypeError(`frameCount must be a non-negative integer.`);if(this._closed)throw Error(`AudioSample is closed.`);let{format:r,frameCount:i,frameOffset:a}=n,{planeIndex:o}=n,s=this.format,c=r??this.format;if(!c)throw Error(`Destination format not determined`);let l=this.numberOfFrames,u=this.numberOfChannels,d=a??0;if(d>0&&d>=l)throw RangeError(`frameOffset out of range`);let f=i===void 0?l-d:i;if(f>l-d)throw RangeError(`frameCount out of range`);let p=si(c),m=ci(c);if(m&&o>=u||!m&&o!==0)throw RangeError(`planeIndex out of range`);let h=(m?f:f*u)*p;if(e.byteLength<h)throw RangeError(`Destination buffer is too small`);let g=x(e),_=ui(c);if(di(this._data)){if(Ue()&&u>2&&c!==s){pi(this._data,g,s,c,u,o,d,f);return}try{this._data.copyTo(e,{planeIndex:o,frameOffset:d,frameCount:f,format:c});return}catch(e){if(c===`f32-planar`)throw e;s=`f32-planar`}}let v=li(s),y=si(s),b=ci(s),S;if(this._data instanceof ai){let e=e=>{let t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw TypeError(`getDataPlane() must return a Uint8Array.`);let n=l*y*(b?1:u);if(t.byteLength!==n)throw TypeError(`Data plane ${e} has invalid size. Expected exactly ${n} bytes, got ${t.byteLength} bytes.`);return t};if(b){if(m)S=e(o),o=0;else{S=new Uint8Array(l*y*u);for(let t=0;t<u;t++){let n=e(t);S.set(n,t*l*y)}}}else S=e(0)}else if(this._data instanceof Uint8Array)S=this._data;else if(t(s===`f32-planar`),m)S=new Uint8Array(this._data.allocationSize({format:`f32-planar`,planeIndex:o})),this._data.copyTo(S,{format:`f32-planar`,planeIndex:o}),o=0;else{S=new Uint8Array(this._data.allocationSize({format:`f32-planar`,planeIndex:0})*u);for(let e=0;e<u;e++)this._data.copyTo(S.subarray(e*l*y,(e+1)*l*y),{format:`f32-planar`,planeIndex:e})}let C=x(S);for(let e=0;e<f;e++)if(m){let t=e*p,n;n=b?(o*l+(e+d))*y:((e+d)*u+o)*y,_(g,t,v(C,n))}else for(let t=0;t<u;t++){let n=(e*u+t)*p,r;r=b?(t*l+(e+d))*y:((e+d)*u+t)*y,_(g,n,v(C,r))}}clone(){if(this._closed)throw Error(`AudioSample is closed.`);if(this._data instanceof ai){let t=new e(this._data);return t.setTimestamp(this.timestamp),t}if(di(this._data)){let t=new e(this._data.clone());return t.setTimestamp(this.timestamp),t}return new e({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data,_doNotCopy:!0})}trim(t,n=this.numberOfFrames){if(!Number.isInteger(t)||t<0)throw TypeError(`startFrame must be a non-negative integer.`);if(!Number.isInteger(n)||n<0)throw TypeError(`endFrame must be a non-negative integer.`);if(t>this.numberOfFrames)throw RangeError(`startFrame out of range.`);if(n>this.numberOfFrames)throw RangeError(`endFrame out of range.`);if(n<t)throw RangeError(`endFrame must not be less than startFrame.`);if(this._closed)throw Error(`AudioSample is closed.`);let r=n-t,i=si(this.format),a;if(ci(this.format)){let e=r*i;if(a=new Uint8Array(e*this.numberOfChannels),r>0)for(let n=0;n<this.numberOfChannels;n++)this.copyTo(a.subarray(n*e,(n+1)*e),{planeIndex:n,format:this.format,frameOffset:t,frameCount:r})}else a=new Uint8Array(r*this.numberOfChannels*i),r>0&&this.copyTo(a,{planeIndex:0,format:this.format,frameOffset:t,frameCount:r});return new e({data:a,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+t/this.sampleRate,_doNotCopy:!0})}close(){this._closed||=(Lr?.unregister(this),this._data instanceof ai?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):di(this._data)?this._data.close():this._data=/* @__PURE__ */ new Uint8Array,!0)}toAudioData(){if(this._closed)throw Error(`AudioSample is closed.`);return this._data instanceof ai?this._createAudioDataFromData():di(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():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:this._data.slice()})}_createAudioDataFromData(){if(ci(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(t,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}{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})}}toAudioBuffer(){if(this._closed)throw Error(`AudioSample is closed.`);let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:`f32-planar`})/4);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(t,{planeIndex:n,format:`f32-planar`}),e.copyToChannel(t,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError(`newTimestamp must be a number.`);this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(t,n){if(!(t instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let r=t.numberOfChannels,i=t.sampleRate,a=t.length,o=Math.floor(24e4/r),s=0,c=a;for(;c>0;){let a=Math.min(o,c),l=new Float32Array(r*a);for(let e=0;e<r;e++)t.copyFromChannel(l.subarray(e*a,(e+1)*a),e,s);yield new e({format:`f32-planar`,sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:n+s/i,data:l,_doNotCopy:!0}),s+=a,c-=a}}static fromAudioBuffer(t,n){if(!(t instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let r=t.numberOfChannels,i=t.sampleRate,a=t.length,o=Math.floor(24e4/r),s=0,c=a,l=[];for(;c>0;){let a=Math.min(o,c),u=new Float32Array(r*a);for(let e=0;e<r;e++)t.copyFromChannel(u.subarray(e*a,(e+1)*a),e,s);let d=new e({format:`f32-planar`,sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:n+s/i,data:u,_doNotCopy:!0});l.push(d),s+=a,c-=a}return l}};const si=e=>{switch(e){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 Error(`Unknown AudioSampleFormat`)}},ci=e=>{switch(e){case`u8-planar`:case`s16-planar`:case`s32-planar`:case`f32-planar`:return!0;default:return!1}},li=e=>{switch(e){case`u8`:case`u8-planar`:return(e,t)=>(e.getUint8(t)-128)/128;case`s16`:case`s16-planar`:return(e,t)=>e.getInt16(t,!0)/32768;case`s32`:case`s32-planar`:return(e,t)=>e.getInt32(t,!0)/2147483648;case`f32`:case`f32-planar`:return(e,t)=>e.getFloat32(t,!0)}},ui=e=>{switch(e){case`u8`:case`u8-planar`:return(e,t,n)=>e.setUint8(t,A(Math.round(n*128)+128,0,255));case`s16`:case`s16-planar`:return(e,t,n)=>e.setInt16(t,A(Math.round(n*32768),-32768,32767),!0);case`s32`:case`s32-planar`:return(e,t,n)=>e.setInt32(t,A(Math.round(n*2147483648),-2147483648,2147483647),!0);case`f32`:case`f32-planar`:return(e,t,n)=>e.setFloat32(t,n,!0)}},di=e=>typeof AudioData<`u`&&e instanceof AudioData,fi=e=>{switch(e){case`u8-planar`:return`u8`;case`s16-planar`:return`s16`;case`s32-planar`:return`s32`;case`f32-planar`:return`f32`;default:return e}},pi=(e,t,n,r,i,a,o,s)=>{let c=li(n),l=ui(r),u=si(n),d=si(r),f=ci(n);if(ci(r)){if(f){let r=new ArrayBuffer(s*u),i=x(r);e.copyTo(r,{planeIndex:a,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=e*u;l(t,e*d,c(i,n))}}else{let r=new ArrayBuffer(s*i*u),f=x(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=(e*i+a)*u;l(t,e*d,c(f,n))}}}else if(f){let r=s*u,a=new ArrayBuffer(r),f=x(a);for(let r=0;r<i;r++){e.copyTo(a,{planeIndex:r,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=e*u;l(t,(e*i+r)*d,c(f,n))}}}else{let r=new ArrayBuffer(s*i*u),a=x(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++)for(let n=0;n<i;n++){let r=e*i+n,o=r*u;l(t,r*d,c(a,o))}}},mi=(e,t)=>{let n=e.allocationSize({format:t,planeIndex:0}),r=new ArrayBuffer(n);return e.copyTo(r,{format:t,planeIndex:0}),new oi({data:r,format:t,numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,timestamp:e.timestamp,duration:e.duration,_doNotCopy:!0})},hi=/* @__PURE__ */ new Map,gi=/* @__PURE__ */ new Map,_i=e=>{
104
+ /*!
105
+ * Copyright (c) 2026-present, Vanilagy and contributors
106
+ *
107
+ * This Source Code Form is subject to the terms of the Mozilla Public
108
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
109
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
110
+ */
111
+ if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!Fl.includes(e.codec))throw TypeError(`Invalid video codec '${e.codec}'. Must be one of: ${Fl.join(`, `)}.`);let t=e.bitrate;if(e.quality===void 0&&t===void 0)throw TypeError(`config.quality must be provided.`);if(e.quality!==void 0&&t!==void 0)throw TypeError(`config.quality and config.bitrate cannot both be provided.`);if(e.quality!==void 0&&!(e.quality instanceof I))throw TypeError(`config.quality, when provided, must be a Quality.`);if(t!==void 0&&!(t instanceof I)&&(!Number.isInteger(t)||t<=0))throw TypeError(`config.bitrate, when provided, must be a positive integer or a quality.`);if(e.keyFrameInterval!==void 0&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError(`config.keyFrameInterval, when provided, must be a non-negative number.`);if(e.sizeChangeBehavior!==void 0&&![`deny`,`passThrough`,`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior))throw TypeError(`config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.`);if(e.transform!==void 0){if(typeof e.transform!=`object`||!e.transform)throw TypeError(`config.transform, when provided, must be an object.`);if(e.transform.width!==void 0&&(!Number.isInteger(e.transform.width)||e.transform.width<=0))throw TypeError(`config.transform.width, when provided, must be a positive integer.`);if(e.transform.height!==void 0&&(!Number.isInteger(e.transform.height)||e.transform.height<=0))throw TypeError(`config.transform.height, when provided, must be a positive integer.`);if(e.transform.fit!==void 0&&![`fill`,`contain`,`cover`].includes(e.transform.fit))throw TypeError(`config.transform.fit, when provided, must be one of "fill", "contain", or "cover".`);if(e.transform.width!==void 0&&e.transform.height!==void 0&&e.transform.fit===void 0&&![`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior))throw TypeError(`When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.`);if(e.transform.fit!==void 0&&[`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior)&&e.transform.fit!==e.sizeChangeBehavior)throw TypeError(`config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.`);if(e.transform.rotate!==void 0&&![0,90,180,270].includes(e.transform.rotate))throw TypeError(`config.transform.rotate, when provided, must be 0, 90, 180 or 270.`);if(e.transform.flip!==void 0&&typeof e.transform.flip!=`boolean`)throw TypeError(`config.transform.flip, when provided, must be a boolean.`);if(e.transform.crop!==void 0&&Yr(e.transform.crop,`config.transform.`),e.transform.alpha!==void 0&&![`keep`,`discard`].includes(e.transform.alpha))throw TypeError(`config.transform.alpha, when provided, must be 'keep' or 'discard'.`);if(e.transform.process!==void 0&&typeof e.transform.process!=`function`)throw TypeError(`config.transform.process, when provided, must be a function.`);if(e.transform.frameRate!==void 0&&(!Number.isFinite(e.transform.frameRate)||e.transform.frameRate<=0))throw TypeError(`config.transform.frameRate, when provided, must be a finite positive number.`);if(e.transform.force!==void 0&&typeof e.transform.force!=`boolean`)throw TypeError(`config.transform.force, when provided, must be a boolean.`)}if(e.onEncodedPacket!==void 0&&typeof e.onEncodedPacket!=`function`)throw TypeError(`config.onEncodedPacket, when provided, must be a function.`);if(e.onEncoderConfig!==void 0&&typeof e.onEncoderConfig!=`function`)throw TypeError(`config.onEncoderConfig, when provided, must be a function.`);if(e.onEncodedSample!==void 0&&typeof e.onEncodedSample!=`function`)throw TypeError(`config.onEncodedSample, when provided, must be a function.`);vi(e.codec,e)},vi=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`Encoding options must be an object.`);if(t.alpha!==void 0&&![`discard`,`keep`].includes(t.alpha))throw TypeError(`options.alpha, when provided, must be 'discard' or 'keep'.`);let n=t.bitrateMode;if(n!==void 0&&![`constant`,`variable`].includes(n))throw TypeError(`bitrateMode, when provided, must be 'constant' or 'variable'.`);if(t.latencyMode!==void 0&&![`quality`,`realtime`].includes(t.latencyMode))throw TypeError(`latencyMode, when provided, must be 'quality' or 'realtime'.`);if(t.fullCodecString!==void 0&&typeof t.fullCodecString!=`string`)throw TypeError(`fullCodecString, when provided, must be a string.`);if(t.fullCodecString!==void 0&&su(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`);if(t.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(t.hardwareAcceleration))throw TypeError(`hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(t.scalabilityMode!==void 0&&typeof t.scalabilityMode!=`string`)throw TypeError(`scalabilityMode, when provided, must be a string.`);if(t.contentHint!==void 0&&typeof t.contentHint!=`string`)throw TypeError(`contentHint, when provided, must be a string.`)},yi=e=>{let n=e.bitrateMode,r=e.quality._toVideoRateControl(e.codec,e.width,e.height,n),i=(t,n,r)=>({codec:e.fullCodecString??Jl(e.codec,e.width,e.height,r,e.alpha===`keep`),width:e.width,height:e.height,displayWidth:e.squarePixelWidth,displayHeight:e.squarePixelHeight,bitrate:t,bitrateMode:n,alpha:e.alpha??`discard`,framerate:e.framerate,latencyMode:e.latencyMode,hardwareAcceleration:e.hardwareAcceleration,scalabilityMode:e.scalabilityMode,contentHint:e.contentHint,...cu(e.codec)}),a=[];return r.quantizer!==null&&a.push({config:i(void 0,`quantizer`,r.bitrate),quantizer:r.quantizer}),r.bitrateMode!==`quantizer`&&a.push({config:i(r.bitrate,r.bitrateMode,r.bitrate),quantizer:null}),t(a.length>0),a},bi=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!Rl.includes(e.codec))throw TypeError(`Invalid audio codec '${e.codec}'. Must be one of: ${Rl.join(`, `)}.`);let t=e.bitrate;if(e.quality===void 0&&t===void 0&&!(Il.includes(e.codec)||e.codec===`flac`||e.codec===`truehd`))throw TypeError(`config.quality must be provided for compressed audio codecs.`);if(e.quality!==void 0&&t!==void 0)throw TypeError(`config.quality and config.bitrate cannot both be provided.`);if(e.quality!==void 0&&!(e.quality instanceof I))throw TypeError(`config.quality, when provided, must be a Quality.`);if(t!==void 0&&!(t instanceof I)&&(!Number.isInteger(t)||t<=0))throw TypeError(`config.bitrate, when provided, must be a positive integer or a quality.`);if(e.transform!==void 0){if(typeof e.transform!=`object`||!e.transform)throw TypeError(`config.transform, when provided, must be an object.`);if(e.transform.numberOfChannels!==void 0&&(!Number.isInteger(e.transform.numberOfChannels)||e.transform.numberOfChannels<=0))throw TypeError(`config.transform.numberOfChannels, when provided, must be a positive integer.`);if(e.transform.sampleRate!==void 0&&(!Number.isInteger(e.transform.sampleRate)||e.transform.sampleRate<=0))throw TypeError(`config.transform.sampleRate, when provided, must be a positive integer.`);if(e.transform.sampleFormat!==void 0&&![`u8`,`s16`,`s32`,`f32`].includes(e.transform.sampleFormat))throw TypeError(`config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.`);if(e.transform.process!==void 0&&typeof e.transform.process!=`function`)throw TypeError(`config.transform.process, when provided, must be a function.`)}if(e.onEncodedPacket!==void 0&&typeof e.onEncodedPacket!=`function`)throw TypeError(`config.onEncodedPacket, when provided, must be a function.`);if(e.onEncoderConfig!==void 0&&typeof e.onEncoderConfig!=`function`)throw TypeError(`config.onEncoderConfig, when provided, must be a function.`);if(e.onEncodedSample!==void 0&&typeof e.onEncodedSample!=`function`)throw TypeError(`config.onEncodedSample, when provided, must be a function.`);xi(e.codec,e)},xi=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`Encoding options must be an object.`);let n=t.bitrateMode;if(n!==void 0&&![`constant`,`variable`].includes(n))throw TypeError(`bitrateMode, when provided, must be 'constant' or 'variable'.`);if(t.fullCodecString!==void 0&&typeof t.fullCodecString!=`string`)throw TypeError(`fullCodecString, when provided, must be a string.`);if(t.fullCodecString!==void 0&&su(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`)},Si=e=>{let t=e.bitrateMode;return{codec:e.fullCodecString??$l(e.codec),numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,bitrate:e.quality?._toAudioBitrate(e.codec,e.numberOfChannels),bitrateMode:e.quality?._bitrateMode??t,...lu(e.codec)}};var I=class{constructor(e){if((typeof e==`number`||typeof e==`string`)&&(e={quality:e}),!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.bitrateMode!==void 0&&![`constant`,`variable`].includes(e.bitrateMode))throw TypeError(`options.bitrateMode, when provided, must be 'constant' or 'variable'.`);if(`quality`in e){if(typeof e.quality==`string`?!Object.prototype.hasOwnProperty.call(Ci,e.quality):typeof e.quality!=`number`||Number.isNaN(e.quality))throw TypeError(`options.quality must be a number, or one of 'very-low', 'low', 'medium', 'high' or 'very-high'.`);if(e.preferBitrate!==void 0&&typeof e.preferBitrate!=`boolean`)throw TypeError(`options.preferBitrate, when provided, must be a boolean.`);if(`bitrate`in e||`quantizer`in e)throw TypeError(`options.quality cannot be combined with options.bitrate or options.quantizer.`);this._quality=typeof e.quality==`string`?Ci[e.quality]:e.quality,this._preferBitrate=e.preferBitrate??!1,this._bitrate=void 0,this._quantizer=void 0}else{if(e.bitrate!==void 0&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`options.bitrate, when provided, must be a positive integer.`);if(e.quantizer!==void 0&&(!Number.isInteger(e.quantizer)||e.quantizer<0))throw TypeError(`options.quantizer, when provided, must be a non-negative integer.`);if(e.bitrate===void 0&&e.quantizer===void 0)throw TypeError(`At least one of options.bitrate or options.quantizer must be set.`);if(`preferBitrate`in e)throw TypeError(`options.preferBitrate can only be combined with options.quality.`);this._quality=void 0,this._preferBitrate=!1,this._bitrate=e.bitrate,this._quantizer=e.quantizer}this._bitrateMode=e.bitrateMode}_toVideoRateControl(e,n,r,i){let a=wi[e],o=null,s=this._bitrateMode??i??`variable`;if(this._quantizer!==void 0){if(!a){if(this._bitrate===void 0)throw Error(`Codec '${e}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else if(this._quantizer<a.min||this._quantizer>a.max){if(this._bitrate===void 0)throw Error(`Quantizer ${this._quantizer} is out of range for codec '${e}'; must be between ${a.min} and ${a.max}.`)}else o=this._quantizer,this._bitrate===void 0&&(s=`quantizer`)}else this._bitrate===void 0&&a&&!this._preferBitrate&&(t(this._quality!==void 0),o=A(Math.round(Oe(a.worst,a.best,this._quality)),a.min,a.max));let c;if(this._bitrate!==void 0)c=this._bitrate;else{let i=this._quality;i===void 0&&(t(o!==null&&a),i=A((o-a.worst)/(a.best-a.worst),0,1)),c=Ei(e,n,r,Ti(i))}return{quantizer:o,bitrate:c,bitrateMode:s}}_toVideoBitrate(e,n,r){return this._bitrate===void 0?(t(this._quality!==void 0),Ei(e,n,r,Ti(this._quality))):this._bitrate}_toAudioBitrate(e,t){if(Il.includes(e)||e===`flac`||e===`truehd`)return;if(this._bitrate!==void 0)return this._bitrate;if(this._quality===void 0)throw Error(`This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.`);let n=Ti(this._quality),r={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[e];if(!r)throw Error(`Unhandled codec: ${e}`);let i=r*n;return(e===`opus`||e===`vorbis`)&&(i*=t/2),e===`aac`?i=[96e3,128e3,16e4,192e3].reduce((e,t)=>Math.abs(t-i)<Math.abs(e-i)?t:e):e===`opus`||e===`vorbis`?i=Math.max(6e3,i):e===`mp3`&&(i=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((e,t)=>Math.abs(t-i)<Math.abs(e-i)?t:e)),Math.round(i/1e3)*1e3}};const Ci={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},wi={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:(Ye()??1/0)<145?{min:0,max:63,worst:52,best:20}:{min:0,max:255,worst:208,best:80},av1:{min:0,max:255,worst:208,best:80}},Ti=e=>.3*Math.exp(2.5538*e),Ei=(e,t,n,r)=>{let i=t*n,a=3e6,o=a*(i/2073600)**.95*{avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:22e7/a}[e]*r;return Math.ceil(o/1e3)*1e3},Di=(e,n)=>{if(e===`avc`)return{avc:{quantizer:n}};if(e===`hevc`)return{hevc:{quantizer:n}};if(e===`vp9`)return{vp9:{quantizer:n}};if(e===`av1`)return{av1:{quantizer:n}};t(!1)},Oi=async(e,t={})=>{let{width:n=1280,height:r=720,quality:i,bitrate:a,frameRate:o,...s}=t;if(!Fl.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`width must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`height must be a positive integer.`);if(i!==void 0&&!(i instanceof I))throw TypeError(`quality, when provided, must be a Quality.`);if(i!==void 0&&a!==void 0)throw TypeError(`quality and bitrate cannot both be provided.`);if(a!==void 0&&!(a instanceof I)&&(!Number.isInteger(a)||a<=0))throw TypeError(`bitrate must be a positive integer or a quality.`);if(o!==void 0&&(!Number.isFinite(o)||o<=0))throw TypeError(`frameRate, when provided, must be a finite positive number.`);vi(e,s);let c=Ai(i,a)??new I(`medium`),l;try{l=yi({codec:e,width:n,height:r,quality:c,framerate:o,...s,alpha:`discard`})}catch{return!1}let u=JSON.stringify(l),d=hi.get(u);if(d)return d;let f=(async()=>{for(let{config:t}of l)if(Fi.some(n=>n.supports(e,t)))return!0;if(typeof VideoEncoder>`u`||(n%2==1||r%2==1)&&(e===`avc`||e===`hevc`))return!1;for(let{config:t,quantizer:i}of l){try{if(!(await VideoEncoder.isConfigSupported(t)).supported)continue}catch{continue}if(!Ge()||await new Promise(async a=>{let o=new VideoEncoder({output:()=>{},error:()=>a(!1)});try{o.configure(t);let s=new Uint8Array(n*r*4),c=new VideoFrame(s,{format:`RGBA`,codedWidth:n,codedHeight:r,timestamp:0});o.encode(c,i===null?void 0:Di(e,i)),c.close(),await o.flush(),a(!0)}catch{a(!1)}finally{o.state!==`closed`&&o.close()}}))return!0}return!1})();return hi.set(u,f),f},ki=async(e,t={})=>{let{numberOfChannels:n=2,sampleRate:r=48e3,quality:i,bitrate:a,...o}=t;if(!Rl.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`numberOfChannels must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`sampleRate must be a positive integer.`);if(i!==void 0&&!(i instanceof I))throw TypeError(`quality, when provided, must be a Quality.`);if(i!==void 0&&a!==void 0)throw TypeError(`quality and bitrate cannot both be provided.`);if(a!==void 0&&!(a instanceof I)&&(!Number.isInteger(a)||a<=0))throw TypeError(`bitrate must be a positive integer.`);xi(e,o);let s=Ai(i,a)??new I(`medium`),c=Si({codec:e,numberOfChannels:n,sampleRate:r,quality:s,...o}),l=JSON.stringify(c),u=gi.get(l);if(u)return u;let d=(async()=>{if(Ii.some(t=>t.supports(e,c))||Il.includes(e))return!0;if(typeof AudioEncoder>`u`)return!1;try{return(await AudioEncoder.isConfigSupported(c)).supported===!0}catch{return!1}})();return gi.set(l,d),d},Ai=(e,t)=>{if(e!==void 0)return e;if(t!==void 0)return t instanceof I?t:new I({bitrate:t})},ji=async(e=Rl,t)=>{let n=await Promise.all(e.map(e=>ki(e,t)));return e.filter((e,t)=>n[t])},Mi=async(e,t)=>{for(let n of e)if(await Oi(n,t))return n;return null},Ni=[],Pi=[],Fi=[],Ii=[],Li=/* #__PURE__ */ new Uint8Array
112
+ /*!
113
+ * Copyright (c) 2026-present, Vanilagy and contributors
114
+ *
115
+ * This Source Code Form is subject to the terms of the Mozilla Public
116
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
117
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
118
+ */
119
+ /*!
120
+ * Copyright (c) 2026-present, Vanilagy and contributors
121
+ *
122
+ * This Source Code Form is subject to the terms of the Mozilla Public
123
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
124
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
125
+ */
126
+ ;var L=class e{constructor(e,t,n,r,i=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=r,this.sequenceNumber=i,e===Li&&a===void 0)throw Error(`Internal error: byteLength must be explicitly provided when constructing metadata-only packets.`);if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==`key`&&t!==`delta`)throw TypeError(`type must be either "key" or "delta".`);if(!Number.isFinite(n))throw TypeError(`timestamp must be a number.`);if(!Number.isFinite(r)||r<0)throw TypeError(`duration must be a non-negative number.`);if(!Number.isFinite(i))throw TypeError(`sequenceNumber must be a number.`);if(!Number.isInteger(a)||a<0)throw TypeError(`byteLength must be a non-negative integer.`);if(o!==void 0&&(typeof o!=`object`||!o))throw TypeError(`sideData, when provided, must be an object.`);if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw TypeError(`sideData.alpha, when provided, must be a Uint8Array.`);if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw TypeError(`sideData.alphaByteLength, when provided, must be a non-negative integer.`);this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Li}get microsecondTimestamp(){return Math.trunc(ze*this.timestamp)}get microsecondDuration(){return Math.trunc(ze*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`EncodedVideoChunk is not available in this environment.`);return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw TypeError(`This packet does not contain alpha side data.`);if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`EncodedVideoChunk is not available in this environment.`);return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to an audio chunk.`);if(typeof EncodedAudioChunk>`u`)throw Error(`EncodedAudioChunk is not available in this environment.`);return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(t,n){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw TypeError(`chunk must be an EncodedVideoChunk or EncodedAudioChunk.`);let r=new Uint8Array(t.byteLength);return t.copyTo(r),new e(r,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,n)}clone(t){if(t!==void 0&&(typeof t!=`object`||!t))throw TypeError(`options, when provided, must be an object.`);if(t?.data!==void 0&&!(t.data instanceof Uint8Array))throw TypeError(`options.data, when provided, must be a Uint8Array.`);if(t?.type!==void 0&&t.type!==`key`&&t.type!==`delta`)throw TypeError(`options.type, when provided, must be either "key" or "delta".`);if(t?.timestamp!==void 0&&!Number.isFinite(t.timestamp))throw TypeError(`options.timestamp, when provided, must be a number.`);if(t?.duration!==void 0&&!Number.isFinite(t.duration))throw TypeError(`options.duration, when provided, must be a number.`);if(t?.sequenceNumber!==void 0&&!Number.isFinite(t.sequenceNumber))throw TypeError(`options.sequenceNumber, when provided, must be a number.`);if(t?.sideData!==void 0&&(typeof t.sideData!=`object`||t.sideData===null))throw TypeError(`options.sideData, when provided, must be an object.`);return new e(t?.data??this.data,t?.type??this.type,t?.timestamp??this.timestamp,t?.duration??this.duration,t?.sequenceNumber??this.sequenceNumber,t?.data?.byteLength??this.byteLength,t?.sideData??this.sideData)}},Ri=class{constructor(e){
127
+ /*!
128
+ * Copyright (c) 2026-present, Vanilagy and contributors
129
+ *
130
+ * This Source Code Form is subject to the terms of the Mozilla Public
131
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
132
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
133
+ */
134
+ this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,this.bufferStartFrame=0,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels}doChannelMixerSetup(){t(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,n=this.targetNumberOfChannels;this.channelMixer=e===1&&n===2?(t,n)=>t[n*e]:e===1&&n===4?(t,n,r)=>t[n*e]*+(r<2):e===1&&n===6?(t,n,r)=>t[n*e]*+(r===2):e===2&&n===1?(t,n)=>{let r=n*e;return .5*(t[r]+t[r+1])}:e===2&&n===4||e===2&&n===6?(t,n,r)=>r<2?t[n*e+r]:0:e===4&&n===1?(t,n)=>{let r=n*e;return .25*(t[r]+t[r+1]+t[r+2]+t[r+3])}:e===4&&n===2?(t,n,r)=>{let i=n*e;return .5*(t[i+r]+t[i+r+2])}:e===4&&n===6?(t,n,r)=>{let i=n*e;return r<2?t[i+r]:r===2||r===3?0:t[i+r-2]}:e===6&&n===1?(t,n)=>{let r=n*e;return Math.SQRT1_2*(t[r]+t[r+1])+t[r+2]+.5*(t[r+4]+t[r+5])}:e===6&&n===2?(t,n,r)=>{let i=n*e;return t[i+r]+Math.SQRT1_2*(t[i+2]+t[i+r+4])}:e===6&&n===4?(t,n,r)=>{let i=n*e;return r<2?t[i+r]+Math.SQRT1_2*t[i+2]:t[i+r+2]}:(t,n,r)=>r<e?t[n*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){if(this.sourceSampleRate===null){this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp;let t=Math.ceil(this.targetSampleRate/this.sourceSampleRate);this.bufferCapacityInFrames=this.bufferSizeInFrames+t,this.outputBuffer=new Float32Array(this.bufferCapacityInFrames*this.targetNumberOfChannels),this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()}t(this.startTime!==null);let n=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(n);let r=e.allocationSize({planeIndex:0,format:`f32`}),i=new Float32Array(this.tempSourceBuffer.buffer,0,r/4);e.copyTo(i,{planeIndex:0,format:`f32`});let a=Math.round((e.timestamp-this.startTime)*this.sourceSampleRate),o=a+e.numberOfFrames,s=Math.floor((a-1)*this.targetSampleRate/this.sourceSampleRate)+1,c=Math.ceil(o*this.targetSampleRate/this.sourceSampleRate);for(let n=s;n<c;n++){if(n<this.bufferStartFrame)continue;for(;n>=this.bufferStartFrame+this.bufferCapacityInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let r=n-this.bufferStartFrame;t(r<this.bufferCapacityInFrames);let o=n*this.sourceSampleRate/this.targetSampleRate-a,s=Math.floor(o),c=Math.ceil(o),l=o-s;for(let t=0;t<this.targetNumberOfChannels;t++){let n=0,a=0;s>=0&&s<e.numberOfFrames&&(n=this.channelMixer(i,s,t)),c>=0&&c<e.numberOfFrames&&(a=this.channelMixer(i,c,t));let o=n+l*(a-n),u=r*this.targetNumberOfChannels+t;this.outputBuffer[u]+=o}this.maxWrittenFrame=this.maxWrittenFrame===null?r:Math.max(this.maxWrittenFrame,r)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;t(this.startTime!==null);let e=Math.min(this.maxWrittenFrame+1,this.bufferSizeInFrames)*this.targetNumberOfChannels,n=new Float32Array(e);n.set(this.outputBuffer.subarray(0,e));let r=new oi({format:`f32`,sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:n,_doNotCopy:!0});await this.onSample(r),this.outputBuffer.copyWithin(0,this.bufferSizeInSamples),this.outputBuffer.fill(0,this.outputBuffer.length-this.bufferSizeInSamples),this.maxWrittenFrame=this.maxWrittenFrame>=this.bufferSizeInFrames?this.maxWrittenFrame-this.bufferSizeInFrames:null}async finalize(){for(;this.maxWrittenFrame!==null;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames}},zi=class{constructor(e){
135
+ /*!
136
+ * Copyright (c) 2026-present, Vanilagy and contributors
137
+ *
138
+ * This Source Code Form is subject to the terms of the Mozilla Public
139
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
140
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
141
+ */
142
+ this.input=e}dispose(){}};
143
+ /*!
144
+ * Copyright (c) 2026-present, Vanilagy and contributors
145
+ *
146
+ * This Source Code Form is subject to the terms of the Mozilla Public
147
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
148
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
149
+ */
150
+ const Bi=2082844800,Vi=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isQuickTime?`quicktime`:`mp4`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},Hi=e=>{if(e.length<24)throw Error(`Invalid pssh box: too small.`);let t=x(e),n=0,r=t.getUint8(n);n+=1,n+=3;let i=pe(e.subarray(n,n+16));n+=16;let a=null;if(r>0){let r=t.getUint32(n);if(n+=4,n+16*r+4>e.length)throw Error(`Invalid pssh box: key ID count exceeds box size.`);if(r>0){a=[];for(let t=0;t<r;t++)a.push(pe(e.subarray(n,n+16))),n+=16}}let o=t.getUint32(n);return n+=4,{systemId:i,keyIds:a,data:e.slice(n,n+o)}},Ui=(e,t)=>{if(e.systemId!==t.systemId||!ot(e.data,t.data))return!1;let n=e.keyIds,r=t.keyIds;return!n||!r?n===r:n.length===r.length&&n.every((e,t)=>e===r[t])},Wi=/* @__PURE__ */ new Uint32Array(256),Gi=/* @__PURE__ */ new Uint32Array(256),Ki=/* @__PURE__ */ new Uint32Array(256),qi=/* @__PURE__ */ new Uint32Array(256),Ji=/* @__PURE__ */ new Uint32Array(256),Yi=/* @__PURE__ */ new Uint32Array(256),Xi=/* @__PURE__ */ new Uint32Array(10)
151
+ /*!
152
+ * Copyright (c) 2026-present, Vanilagy and contributors
153
+ *
154
+ * This Source Code Form is subject to the terms of the Mozilla Public
155
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
156
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
157
+ */
158
+ ;let Zi=!1;const Qi=()=>{let e=/* @__PURE__ */ new Uint8Array(256),t=/* @__PURE__ */ new Uint8Array(256),n=/* @__PURE__ */ new Uint8Array(256);for(let e=0,r=1;e<256;e++)n[e]=r,t[r]=e,r=r^r<<1^(r&128?283:0);let r=(e,r)=>e&&r?n[(t[e]+t[r])%255]:0;e[0]=99;for(let r=1;r<256;r++){let i=n[255-t[r]],a=i^i<<1^i<<2^i<<3^i<<4;a=a>>>8^a&255^99,e[r]=a}for(let t=0;t<256;t++){let n=e[t],i=e.indexOf(t);Wi[t]=n<<24|n<<16|n<<8|n,Yi[t]=i<<24|i<<16|i<<8|i;let a=r(i,14),o=r(i,9),s=r(i,13),c=r(i,11),l=a<<24|o<<16|s<<8|c;Gi[t]=l,Ki[t]=l>>>8|l<<24,qi[t]=l>>>16|l<<16,Ji[t]=l>>>24|l<<8}let i=1;for(let e=0;e<10;e++)Xi[e]=i<<24,i=i<<1^(i&128?283:0);Zi=!0};var $i=class{constructor(){this.roundkey=/* @__PURE__ */ new Uint32Array(44),this.iv=new Uint32Array(16/Uint32Array.BYTES_PER_ELEMENT),this.in=/* @__PURE__ */ new Uint8Array(16),this.out=/* @__PURE__ */ new Uint8Array(16),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:n}){t(e.byteLength===16),t(n.byteLength===16),Zi||Qi();let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=new DataView(n.buffer,n.byteOffset,n.byteLength);this.roundkey[0]=r.getUint32(0,!1),this.roundkey[1]=r.getUint32(4,!1),this.roundkey[2]=r.getUint32(8,!1),this.roundkey[3]=r.getUint32(12,!1),this.iv[0]=i.getUint32(0,!1),this.iv[1]=i.getUint32(4,!1),this.iv[2]=i.getUint32(8,!1),this.iv[3]=i.getUint32(12,!1);for(let e=4;e<44;e+=4){let t=this.roundkey[e-1];this.roundkey[e]=this.roundkey[e-4]^Wi[t>>>16&255]&4278190080^Wi[t>>>8&255]&16711680^Wi[t>>>0&255]&65280^Wi[t>>>24&255]&255^Xi[e/4-1],this.roundkey[e+1]=this.roundkey[e-3]^this.roundkey[e],this.roundkey[e+2]=this.roundkey[e-2]^this.roundkey[e+1],this.roundkey[e+3]=this.roundkey[e-1]^this.roundkey[e+2]}for(let e=0,t=40;e<t;e+=4,t-=4)for(let n=0;n<4;n++){let r=this.roundkey[e+n];this.roundkey[e+n]=this.roundkey[t+n],this.roundkey[t+n]=r}for(let e=4;e<40;e+=4)for(let t=0;t<4;t++){let n=this.roundkey[e+t];this.roundkey[e+t]=Gi[Wi[n>>>24&255]&255]^Ki[Wi[n>>>16&255]&255]^qi[Wi[n>>>8&255]&255]^Ji[Wi[n>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],n=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3],i=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),s=this.inView.getUint32(12,!1),c,l,u,d;for(let i=1;i<10;i++){let a=i*4;c=Gi[e>>>24]^Ki[r>>>16&255]^qi[n>>>8&255]^Ji[t&255]^this.roundkey[a],l=Gi[t>>>24]^Ki[e>>>16&255]^qi[r>>>8&255]^Ji[n&255]^this.roundkey[a+1],u=Gi[n>>>24]^Ki[t>>>16&255]^qi[e>>>8&255]^Ji[r&255]^this.roundkey[a+2],d=Gi[r>>>24]^Ki[n>>>16&255]^qi[t>>>8&255]^Ji[e&255]^this.roundkey[a+3],e=c,t=l,n=u,r=d}let f=Yi[e>>>24&255]&4278190080^Yi[r>>>16&255]&16711680^Yi[n>>>8&255]&65280^Yi[t>>>0&255]&255^this.roundkey[40],p=Yi[t>>>24&255]&4278190080^Yi[e>>>16&255]&16711680^Yi[r>>>8&255]&65280^Yi[n>>>0&255]&255^this.roundkey[41],m=Yi[n>>>24&255]&4278190080^Yi[t>>>16&255]&16711680^Yi[e>>>8&255]&65280^Yi[r>>>0&255]&255^this.roundkey[42],h=Yi[r>>>24&255]&4278190080^Yi[n>>>16&255]&16711680^Yi[t>>>8&255]&65280^Yi[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,f^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,h^this.iv[3],!1),this.iv[0]=i,this.iv[1]=a,this.iv[2]=o,this.iv[3]=s}};const ea=(e,t,n)=>{let r=!1,i=!1,a=0,o=2**16,s=new $i,c=()=>{i||(i=!0,n())};return new ReadableStream({pull:async n=>{try{r||=(s.init(await t()),!0);let i=o+16,l=e.requestSliceRange(a,0,i);if(j(l)&&(l=await l),!l||l.length===0)throw Error(`Invalid ciphertext.`);let u=l.length;if(u%16!=0)throw Error(`Invalid ciphertext.`);let d=u===i?u-16:u,f=V(l,d),p=new Uint8Array(d);for(let e=0;e<d;e+=16)s.in.set(f.subarray(e,e+16)),s.decrypt(),p.set(s.out,e);if(d<u)n.enqueue(p),a+=d;else{let e=p[d-1];if(e===0||e>16)throw Error(`Invalid PKCS#7 padding. Incorrect key or corrupted data.`);let t=p.subarray(0,d-e);n.enqueue(t),n.close(),c()}}catch(e){throw c(),e}},cancel:()=>{c()}})},ta=[2,1,1,2,2,2,2,1,1,2,2,1,1]
159
+ /*!
160
+ * Copyright (c) 2026-present, Vanilagy and contributors
161
+ *
162
+ * This Source Code Form is subject to the terms of the Mozilla Public
163
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
164
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
165
+ */
166
+ ;var na=class e extends zi{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.idToTrack=/* @__PURE__ */ new Map,this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.movieMatrix=a,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=/* @__PURE__ */ new Map,this.psshBoxes=[],this.currentFragment=null,this.isReadingTraf=!1,this.currentFragmentTrackState=null,this.lastReadFragment=null,this.fragmentSummaries=/* @__PURE__ */ new Map,this.decryptionKeyCache=/* @__PURE__ */ new Map,this.boxNestingDepth=0,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return Vi({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>e.info?.type===`video`),hasAudio:this.tracks.some(e=>e.info?.type===`audio`),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0,n=!1,r=!1;for(;;){let t=this.reader.requestSliceRange(e,8,16);if(j(t)&&(t=await t),!t)break;let i=e,a=al(t);if(!a)break;if((a.name===`ftyp`||a.name===`styp`)&&t.remainingLength>=4){let e=G(t,4);this.isQuickTime=e===`qt `}else if(a.name===`moov`){let e=this.reader.requestSlice(t.filePos,a.contentSize);if(j(e)&&(e=await e),!e)break;if(this.moovSlice=e,this.readContiguousBoxes(this.moovSlice),this.movieTimescale===-1)throw Error(`Invalid moov box: missing mvhd box.`);for(let e of this.tracks){let t=e.editListPreviousSegmentDurations/this.movieTimescale;e.editListOffset-=Math.round(t*e.timescale)}n=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>i+a.totalSize,r=!0;break}else if(a.name===`moof`){if(!this.input._initInput)throw Error(`"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.`);await this.copyMetadataFromInitInput(this.input._initInput),n=!1,r=!0;break}e=i+a.totalSize}if(!r&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),n){t(this.reader.fileSize!==null);let e=this.reader.requestSlice(this.reader.fileSize-4,4);j(e)&&(e=await e),t(e);let n=W(e),r=this.reader.fileSize-n;if(r>=0&&r<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(r,8,16);if(j(e)&&(e=await e),e){let t=al(e);if(t&&t.name===`mfra`){let n=this.reader.requestSlice(e.filePos,t.contentSize);j(n)&&(n=await n),n&&this.readContiguousBoxes(n)}}}}for(let e of this.tracks){let t=e.fragmentLookupTable;t.sort((e,t)=>e.timestamp-t.timestamp);let n=0;for(let e of t)(n===0||e.timestamp!==t[n-1].timestamp)&&(t[n++]=e);t.length=n}})()}async copyMetadataFromInitInput(n){let r=await n._getDemuxer();if(r.constructor!==e)throw Error(`Init input must match the input's format.`);await r.readMetadata(),this.movieTimescale=r.movieTimescale,this.movieDurationInTimescale=r.movieDurationInTimescale,this.movieMatrix=r.movieMatrix,this.metadataTags=r.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=r.fragmentTrackDefaults,this.psshBoxes=r.psshBoxes;for(let e of r.tracks){let n={id:e.id,demuxer:this,trackBacking:null,disposition:e.disposition,timescale:e.timescale,durationInMediaTimescale:e.durationInMediaTimescale,durationInMovieTimescale:e.durationInMovieTimescale,matrix:e.matrix,internalCodecId:e.internalCodecId,name:e.name,languageCode:e.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],fragmentPositionCache:[],editListPreviousSegmentDurations:e.editListPreviousSegmentDurations,editListOffset:e.editListOffset,encryptionInfo:e.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:e.maxBitrate,avgBitrate:e.avgBitrate,info:e.info};e.trackBacking&&(t(n.info),n.info.type===`video`&&n.info.width!==-1?(n.trackBacking=new ia(n),this.tracks.push(n),this.idToTrack.set(n.id,n)):n.info.type===`audio`&&n.info.numberOfChannels!==-1&&(n.trackBacking=new aa(n),this.tracks.push(n),this.idToTrack.set(n.id,n)))}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let n={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],sampleCount:0,cumulativeSampleSizes:null,keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],sortedCompositionTimeOffsets:null};if(e.sampleTable=n,e.sampleTableByteOffset===null)return n;t(this.moovSlice);let r=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e;try{this.traverseBox(r)}catch(t){throw e.sampleTable=null,t}finally{this.currentTrack=null}let i=m(n.sampleTimingEntries),a=D(n.sampleToChunk,n.chunkOffsets.length-1,e=>e.startChunkIndex),o=n.sampleToChunk[a];if(n.sampleCount=Math.min(n.sampleCount,i?i.startIndex+i.count:0,o?o.startSampleIndex+(n.chunkOffsets.length-o.startChunkIndex)*o.samplesPerChunk:0),_a(n.sampleTimingEntries,n.sampleCount),_a(n.sampleCompositionTimeOffsets,n.sampleCount),e.info?.type===`audio`&&e.info.codec&&Il.includes(e.info.codec)&&n.sampleCompositionTimeOffsets.length===0&&n.sampleTimingEntries.length>0){t(e.info?.type===`audio`);let r=ou(e.info.codec),i=[],a=[];for(let t=0;t<n.sampleToChunk.length;t++){let o=n.sampleToChunk[t],s=n.sampleToChunk[t+1],c=Math.min(s?s.startChunkIndex:1/0,n.chunkOffsets.length)-o.startChunkIndex,l=a.length;for(let t=0;t<c;t++){let s=o.startSampleIndex+t*o.samplesPerChunk,c=s+o.samplesPerChunk,l=D(n.sampleTimingEntries,s,e=>e.startIndex),u=n.sampleTimingEntries[l],d=D(n.sampleTimingEntries,c,e=>e.startIndex),f=n.sampleTimingEntries[d],p=u.startDecodeTimestamp+(s-u.startIndex)*u.delta,h=f.startDecodeTimestamp+(c-f.startIndex)*f.delta-p,g=m(i);g&&g.delta===h?g.count++:i.push({startIndex:a.length,startDecodeTimestamp:p,count:1,delta:h});let _=Math.round(h*e.info.sampleRate/e.timescale)*r.sampleSize*e.info.numberOfChannels;a.push(_)}o.startSampleIndex=l,o.samplesPerChunk=1}n.sampleTimingEntries=i,n.sampleSizes=a,n.sampleCount=a.length}if(n.sampleCompositionTimeOffsets.length>0){let e=n.sampleCompositionTimeOffsets,t=m(e),r=t.startIndex+t.count;r<n.sampleCount&&e.push({startIndex:r,count:n.sampleCount-r,offset:0,startTimestamp:-1,lastTimestamp:-1,maxLastTimestamp:-1});let i=e.filter(e=>e.count>0),a=n.sampleTimingEntries,o=0,s=e=>{for(;o+1<a.length&&a[o+1].startIndex<=e;)o++;let t=a[o];return t.startDecodeTimestamp+(e-t.startIndex)*t.delta};for(let e of i){let t=e.startIndex+e.count-1;e.startTimestamp=s(e.startIndex)+e.offset,e.lastTimestamp=s(t)+e.offset}i.sort((e,t)=>e.startTimestamp-t.startTimestamp||e.startIndex-t.startIndex);let c=-1/0;for(let e of i)c=Math.max(c,e.lastTimestamp),e.maxLastTimestamp=c;n.sortedCompositionTimeOffsets=i}if(n.sampleSizes.length>1){n.cumulativeSampleSizes=[0];for(let e=0;e<n.sampleSizes.length;e++)n.cumulativeSampleSizes.push(n.cumulativeSampleSizes[e]+n.sampleSizes[e])}return n}readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment.promise;let n=(async()=>{let n=this.reader.requestSliceRange(e,8,16);j(n)&&(n=await n),t(n);let r=al(n);t(r?.name===`moof`);let i=this.reader.requestSlice(e,r.totalSize);if(j(i)&&(i=await i),!i)return null;this.traverseBox(i);let a=this.currentFragment;t(a&&a.moofOffset===e),this.currentFragment=null,this.fragmentSummaries.set(e,{moofSize:a.moofSize,trackIds:new Set(a.trackData.keys())});for(let[,e]of a.trackData){let n=e.track,{fragmentPositionCache:r}=n;if(!e.startTimestampIsFinal){let i=ge(n.fragmentLookupTable,a.moofOffset,e=>e.moofOffset),o=n.fragmentLookupTable[i];if(o&&e.trunSampleCounts.length>=o.trunNumber&&e.trunSampleCounts[o.trunNumber-1]>=o.sampleNumber){let n=0;for(let t=1;t<o.trunNumber;t++)n+=e.trunSampleCounts[t-1];n+=o.sampleNumber-1;let r=e.samples[n];t(r);let i=o.timestamp-r.presentationTimestamp;ma(e,i)}else{let t=D(r,a.moofOffset-1,e=>e.moofOffset);if(t!==-1){let n=r[t];ma(e,n.endDecodeTimestamp)}else{let t=m(this.getSampleTableForTrack(n).sampleTimingEntries);if(t){let{startDecodeTimestamp:n,count:r,delta:i}=t;ma(e,n+r*i)}}}e.startTimestampIsFinal=!0}let i=D(r,e.startTimestamp,e=>e.startTimestamp),o=r[i],s=r[i+1];if((!o||o.moofOffset<a.moofOffset)&&(!s||s.moofOffset>a.moofOffset)&&r.splice(i+1,0,{moofOffset:a.moofOffset,startTimestamp:e.startTimestamp,endDecodeTimestamp:e.endDecodeTimestamp,hasKeyFrame:e.firstKeyFrameTimestamp!==null}),e.encryptionAuxInfo&&n.encryptionInfo){let t=await ya(this.reader,n.encryptionInfo,e.encryptionAuxInfo);for(let n=0;n<Math.min(e.samples.length,t.length);n++){let r=t[n];e.samples[n].encryption=r}}}return a})();return this.lastReadFragment={moofOffset:e,promise:n},n.catch(()=>{this.lastReadFragment?.promise===n&&(this.lastReadFragment=null)}),n}readContiguousBoxes(e){if(this.boxNestingDepth===64)throw Error(`Invalid file: boxes are nested too deeply.`);let t=e.filePos;this.boxNestingDepth++;try{for(;e.filePos-t<=e.length-8&&this.traverseBox(e););}finally{this.boxNestingDepth--}}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8;){let t=e.filePos,n=al(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=t+n.totalSize}}traverseBox(e){let n=e.filePos,r=al(e);if(!r)return!1;let i=e.filePos,o=n+r.totalSize;switch(r.name){case`mdia`:case`minf`:case`dinf`:case`mfra`:case`edts`:case`sinf`:case`schi`:this.readContiguousBoxes(e.slice(i,r.contentSize));break;case`mvhd`:{let t=H(e);e.skip(3);let n;if(t===1?(n=$c(e),e.skip(8),this.movieTimescale=W(e),this.movieDurationInTimescale=$c(e)):(n=W(e),e.skip(4),this.movieTimescale=W(e),this.movieDurationInTimescale=W(e)),n!==0&&(this.metadataTags.creationTime=/* @__PURE__ */ new Date(1e3*(n-Bi))),this.movieTimescale===0)throw Error(`Invalid mvhd box: timescale must not be 0.`);e.skip(16),this.movieMatrix=ha(e)}break;case`trak`:{if(this.currentFragment||this.currentTrack)break;let t={id:-1,demuxer:this,trackBacking:null,disposition:{...Dt,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,matrix:a,internalCodecId:null,name:null,languageCode:`und`,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:null,avgBitrate:null};this.currentTrack=t,this.readContiguousBoxes(e.slice(i,r.contentSize)),t.id!==-1&&t.timescale!==-1&&t.info!==null&&t.sampleTableByteOffset!==-1&&(t.info.type===`video`&&t.info.width!==-1?(t.trackBacking=new ia(t),this.tracks.push(t),this.idToTrack.set(t.id,t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new aa(t),this.tracks.push(t),this.idToTrack.set(t.id,t))),this.currentTrack=null}break;case`tkhd`:{let t=this.currentTrack;if(!t||this.currentFragment)break;let n=H(e),r=!!(Kc(e)&1);if(t.disposition.default=r,n===0)e.skip(8),t.id=W(e),e.skip(4),t.durationInMovieTimescale=W(e);else if(n===1)e.skip(16),t.id=W(e),e.skip(4),t.durationInMovieTimescale=$c(e);else throw Error(`Incorrect track header version ${n}.`);e.skip(16);let i=ha(e);t.matrix=f(i,this.movieMatrix)}break;case`elst`:{let t=this.currentTrack;if(!t)break;let n=H(e);e.skip(3);let r=!1,i=0,a=W(e);for(let o=0;o<a;o++){let a=n===1?$c(e):W(e),o=n===1?el(e):Xc(e),s=ol(e);if(r){M._warn(`Unsupported edit list: multiple edits are not currently supported. Only using first edit.`);break}if(o===-1)i+=a;else{if(s!==1){M._warn(`Unsupported edit list entry: media rate must be 1.`);break}t.editListPreviousSegmentDurations=i,t.editListOffset=o,r=!0}}}break;case`mdhd`:{let t=this.currentTrack;if(!t)break;let n=H(e);if(e.skip(3),n===0?(e.skip(8),t.timescale=W(e),t.durationInMediaTimescale=W(e)):n===1&&(e.skip(16),t.timescale=W(e),t.durationInMediaTimescale=$c(e)),t.durationInMediaTimescale===2**(n===1?64:32)-1&&(t.durationInMediaTimescale=-1),t.timescale===0)throw Error(`Invalid mdhd box: timescale must not be 0.`);let r=U(e);if(r>0){t.languageCode=``;for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(r&31))+t.languageCode,r>>=5;Re(t.languageCode)||(t.languageCode=`und`)}}break;case`hdlr`:{let t=this.currentTrack;if(!t)break;e.skip(8);let n=G(e,4);n===`vide`?t.info={type:`video`,width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...le},avcType:null,avcCodecInfo:null,hevcType:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:n===`soun`&&(t.info={type:`audio`,numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case`stbl`:{let t=this.currentTrack;if(!t)break;t.sampleTableByteOffset=n,this.readContiguousBoxes(e.slice(i,r.contentSize))}break;case`stsd`:{let t=this.currentTrack;if(!t||t.info===null||t.sampleTable)break;let n=H(e);e.skip(3);let r=W(e);for(let i=0;i<r;i++){let r=e.filePos,i=al(e);if(!i)break;t.internalCodecId=i.name;let a=i.name.toLowerCase();if(t.info.type===`video`){e.skip(24),t.info.width=U(e),t.info.height=U(e),t.info.squarePixelWidth=t.info.width,t.info.squarePixelHeight=t.info.height,e.skip(50),t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));let n=a===`encv`?t.frmaCodecString:a;t.frmaCodecString=null,n===`avc1`||n===`avc3`?(t.info.codec=`avc`,t.info.avcType=n===`avc1`?1:3):n===`hvc1`||n===`hev1`?(t.info.codec=`hevc`,t.info.hevcType=n):n===`vp08`?t.info.codec=`vp8`:n===`vp09`?t.info.codec=`vp9`:n===`av01`?t.info.codec=`av1`:Gl.includes(a)?(t.info.codec=`prores`,t.info.proresFormat=a):n===null?M._warn(`Unknown encrypted video codec due to missing frma box.`):M._warn(`Unsupported video codec (sample entry type '${i.name}').`)}else{e.skip(8);let o=U(e);e.skip(6);let s=U(e),c=U(e);e.skip(4);let l=W(e)/65536,u=null;n===0&&o>0&&(o===1?(e.skip(4),c=8*W(e),e.skip(8)):o===2&&(e.skip(4),l=rl(e),s=W(e),e.skip(4),c=W(e),u=W(e),e.skip(8))),t.info.numberOfChannels=s,t.info.sampleRate=l||t.timescale,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));let d=a===`enca`?t.frmaCodecString:a;if(t.frmaCodecString=null,d!==`mp4a`){if(d===`.mp3`)t.info.codec=`mp3`;else if(d===`opus`)t.info.codec=`opus`,t.info.sampleRate=ru;else if(d===`flac`)t.info.codec=`flac`;else if(d===`ulaw`)t.info.codec=`ulaw`;else if(d===`alaw`)t.info.codec=`alaw`;else if(d===`ac-3`)t.info.codec=`ac3`;else if(d===`ec-3`)t.info.codec=`eac3`;else if(Kl.includes(d))t.info.codec=`dts`,t.info.dtsFormat=d;else if(d===`mlpa`)t.info.codec=`truehd`;else if(d===`twos`)c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=t.info.pcmLittleEndian?`pcm-s16`:`pcm-s16be`:(M._warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null);else if(d===`sowt`)c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=`pcm-s16`:(M._warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null);else if(d===`raw `)t.info.codec=`pcm-u8`;else if(d===`in24`)t.info.codec=t.info.pcmLittleEndian?`pcm-s24`:`pcm-s24be`;else if(d===`in32`)t.info.codec=t.info.pcmLittleEndian?`pcm-s32`:`pcm-s32be`;else if(d===`fl32`)t.info.codec=t.info.pcmLittleEndian?`pcm-f32`:`pcm-f32be`;else if(d===`fl64`)t.info.codec=t.info.pcmLittleEndian?`pcm-f64`:`pcm-f64be`;else if(d===`ipcm`){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?e===16?t.info.codec=`pcm-s16`:e===24?t.info.codec=`pcm-s24`:e===32?t.info.codec=`pcm-s32`:(M._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null):e===16?t.info.codec=`pcm-s16be`:e===24?t.info.codec=`pcm-s24be`:e===32?t.info.codec=`pcm-s32be`:(M._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if(d===`fpcm`){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?e===32?t.info.codec=`pcm-f32`:e===64?t.info.codec=`pcm-f64`:(M._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):e===32?t.info.codec=`pcm-f32be`:e===64?t.info.codec=`pcm-f64be`:(M._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if(d===`lpcm`&&u!==null){let e=c+7>>3,n=!!(u&1),r=!!(u&2),i=u&4?-1:0;c>0&&c<=64&&(n?c===32?t.info.codec=r?`pcm-f32be`:`pcm-f32`:c===64&&(t.info.codec=r?`pcm-f64be`:`pcm-f64`):i&1<<e-1?e===1?t.info.codec=`pcm-s8`:e===2?t.info.codec=r?`pcm-s16be`:`pcm-s16`:e===3?t.info.codec=r?`pcm-s24be`:`pcm-s24`:e===4&&(t.info.codec=r?`pcm-s32be`:`pcm-s32`):e===1&&(t.info.codec=`pcm-u8`)),t.info.codec===null&&M._warn(`Unsupported PCM format.`)}else d===null?M._warn(`Unknown encrypted audio codec due to missing frma box.`):M._warn(`Unsupported audio codec (sample entry type '${i.name}').`)}}e.filePos=r+i.totalSize}}break;case`frma`:{let t=this.currentTrack;if(!t)break;t.frmaCodecString=G(e,4).toLowerCase()}break;case`schm`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=G(e,4);n===`cenc`||n===`cens`||n===`cbcs`?t.encryptionInfo={scheme:n,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:M._warn(`Unsupported encryption scheme '${n}'.`)}break;case`tenc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=H(e);e.skip(3),e.skip(1);let r=H(e);if(n>0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=r&15):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=H(e)!==0,t.encryptionInfo.defaultPerSampleIvSize=H(e),t.encryptionInfo.defaultKid=pe(V(e,16)),t.encryptionInfo.defaultPerSampleIvSize>16)throw Error(`Invalid tenc box: IV size must not exceed 16 bytes.`);if(t.encryptionInfo.defaultIsProtected&&t.encryptionInfo.defaultPerSampleIvSize===0){let n=H(e);if(n>16)throw Error(`Invalid tenc box: IV size must not exceed 16 bytes.`);let r=/* @__PURE__ */ new Uint8Array(16);r.set(V(e,n),0),t.encryptionInfo.defaultConstantIv=r}}break;case`avcC`:{let t=this.currentTrack;if(!t||t.info?.type!==`video`||r.contentSize===0)break;t.info.codecDescription=V(e,r.contentSize);let n=hn(t.info.codecDescription)?.sequenceParameterSets[0],i=n&&vn(n);i&&ga(t,i.pixelAspectRatio)}break;case`hvcC`:{let t=this.currentTrack;if(!t||t.info?.type!==`video`||r.contentSize===0)break;t.info.codecDescription=V(e,r.contentSize);let n=Pn(t.info.codecDescription)?.arrays.find(e=>e.nalUnitType===F.SPS_NUT)?.nalUnits[0],i=n&&wn(n);i&&ga(t,i.pixelAspectRatio)}break;case`vpcC`:{let t=this.currentTrack;if(!t||t.info?.type!==`video`)break;e.skip(4);let n=H(e),r=H(e),i=H(e),a=i>>4,o=i>>1&7,s=i&1,c=H(e),l=H(e),u=H(e);t.info.vp9CodecInfo={profile:n,level:r,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:c,transferCharacteristics:l,matrixCoefficients:u}}break;case`av1C`:{let t=this.currentTrack;if(!t||t.info?.type!==`video`)break;e.skip(1);let n=H(e),i=n>>5,a=n&31,o=H(e),s=o>>7,c=o>>6&1,l=o>>5&1,u=o>>4&1,d=o>>3&1,f=o>>2&1,p=o&3,m=i===2&&c?l?12:10:c?10:8;e.skip(1);let h=V(e,r.contentSize-4),g=Vn(h);t.info.av1CodecInfo={profile:i,level:a,tier:s,bitDepth:m,monochrome:u,chromaSubsamplingX:d,chromaSubsamplingY:f,chromaSamplePosition:p,videoFullRangeFlag:g?.videoFullRangeFlag??0,colourPrimaries:g?.colourPrimaries??2,transferCharacteristics:g?.transferCharacteristics??2,matrixCoefficients:g?.matrixCoefficients??2}}break;case`colr`:{let t=this.currentTrack;if(!t||t.info?.type!==`video`)break;let n=G(e,4);if(n!==`nclx`&&n!==`nclc`)break;let r=U(e),i=U(e),a=U(e),o;n===`nclx`&&(o=!!(H(e)&128)),t.info.colorSpace={primaries:ne[r],transfer:ie[i],matrix:oe[a],fullRange:o}}break;case`pasp`:{let t=this.currentTrack;if(!t||t.info?.type!==`video`)break;let n=W(e),r=W(e);n>0&&r>0&&(t.info.squarePixelWidth=t.info.width,t.info.squarePixelHeight=t.info.height,n>r?t.info.squarePixelWidth=Math.round(t.info.width*n/r):t.info.squarePixelHeight=Math.round(t.info.height*r/n))}break;case`btrt`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=W(e),r=W(e);t.maxBitrate=n>0?n:null,t.avgBitrate=r>0?r:null}break;case`wave`:this.readContiguousBoxes(e.slice(i,r.contentSize));break;case`esds`:{let t=this.currentTrack;if(!t||t.info?.type!==`audio`)break;e.skip(4);let{objectTypeIndication:n,decoderSpecificInfo:r}=ll(e);if(n===64||n===103?(t.info.codec=`aac`,t.info.aacCodecInfo={isMpeg2:n===103,objectType:null}):n===105||n===107?t.info.codec=`mp3`:n===221?t.info.codec=`vorbis`:n===169?t.info.codec=`dts`:M._warn(`Unsupported audio codec (objectTypeIndication ${n}) - discarding track.`),r&&(t.info.codecDescription=r,t.info.codec===`aac`)){let e=Mt(t.info.codecDescription);e.outputNumberOfChannels!==null&&(t.info.numberOfChannels=e.outputNumberOfChannels),e.outputSampleRate!==null&&(t.info.sampleRate=e.outputSampleRate)}}break;case`enda`:{let t=this.currentTrack;if(!t||t.info?.type!==`audio`)break;t.info.pcmLittleEndian=!!(U(e)&255)}break;case`pcmC`:{let t=this.currentTrack;if(!t||t.info?.type!==`audio`)break;e.skip(4);let n=H(e);t.info.pcmLittleEndian=!!(n&1),t.info.pcmSampleSize=H(e)}break;case`srat`:{let t=this.currentTrack;if(!t||t.info?.type!==`audio`)break;e.skip(4),t.info.sampleRate=W(e)}break;case`dOps`:{let t=this.currentTrack;if(!t||t.info?.type!==`audio`)break;e.skip(1);let n=H(e),i=U(e),a=W(e),o=qc(e),s=H(e),c=s===0?/* @__PURE__ */ new Uint8Array:V(e,r.contentSize-11),l=new Uint8Array(19+c.byteLength),u=new DataView(l.buffer);u.setUint32(0,1332770163,!1),u.setUint32(4,1214603620,!1),u.setUint8(8,1),u.setUint8(9,n),u.setUint16(10,i,!0),u.setUint32(12,a,!0),u.setInt16(16,o,!0),u.setUint8(18,s),l.set(c,19),t.info.codecDescription=l,t.info.numberOfChannels=n}break;case`dfLa`:{let t=this.currentTrack;if(!t||t.info?.type!==`audio`)break;e.skip(4);let n=e.filePos;for(;e.filePos<o;){let n=H(e),r=Kc(e);if((n&127)===Zn.STREAMINFO){e.skip(10);let n=W(e),r=n>>>12,i=(n>>9&7)+1;t.info.sampleRate=r,t.info.numberOfChannels=i,e.skip(20)}else e.skip(r);if(n&128)break}let r=e.filePos;e.filePos=n;let i=V(e,r-n),a=new Uint8Array(4+i.byteLength);new DataView(a.buffer).setUint32(0,1716281667,!1),a.set(i,4),t.info.codecDescription=a}break;case`dac3`:{let t=this.currentTrack;if(!t||t.info?.type!==`audio`)break;let n=new N(V(e,3)),r=n.readBits(2);n.skipBits(8);let i=n.readBits(3),a=n.readBits(1);r<3&&(t.info.sampleRate=$t[r]),t.info.numberOfChannels=er[i]+a}break;case`dec3`:{let t=this.currentTrack;if(!t||t.info?.type!==`audio`)break;let n=V(e,r.contentSize),i=or(n);if(!i){M._warn(`Invalid dec3 box contents, ignoring.`);break}let a=sr(i);a!==null&&(t.info.sampleRate=a),t.info.numberOfChannels=cr(i)}break;case`ddts`:{let t=this.currentTrack;if(!t||t.info?.type!==`audio`)break;let n=V(e,Math.min(r.contentSize,20)),i=xr(n);if(!i){M._warn(`Invalid ddts box contents, ignoring.`);break}t.info.sampleRate=i.sampleRate,i.numberOfChannels!==null&&(t.info.numberOfChannels=i.numberOfChannels)}break;case`dmlp`:{let t=this.currentTrack;if(!t||t.info?.type!==`audio`)break;let n=W(e),r=n>>>28;if(r===15){M._warn(`Invalid dmlp box contents, ignoring.`);break}t.info.sampleRate=(r&8?44100:48e3)<<(r&7);let i=n>>>15&31,a=n&8191||i,o=0;for(let e=0;e<ta.length;e++)a&1<<e&&(o+=ta[e]);t.info.numberOfChannels=o}break;case`stts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=W(e),r=0,i=0;for(let a=0;a<n;a++){let n=W(e),a=W(e);t.sampleTable.sampleTimingEntries.push({startIndex:r,startDecodeTimestamp:i,count:n,delta:a}),r+=n,i+=n*a}}break;case`ctts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=W(e),r=0;for(let i=0;i<n;i++){let n=W(e),i=Xc(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:r,count:n,offset:i,startTimestamp:-1,lastTimestamp:-1,maxLastTimestamp:-1}),r+=n}}break;case`stsz`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=W(e),r=W(e);if(n===0)for(let n=0;n<r;n++){let n=W(e);t.sampleTable.sampleSizes.push(n)}else t.sampleTable.sampleSizes.push(n);t.sampleTable.sampleCount=r}break;case`stz2`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),e.skip(3);let n=H(e),r=W(e);if(n!==4&&n!==8&&n!==16)throw Error(`Invalid stz2 box: unsupported field size ${n}.`);let i=new N(V(e,Math.ceil(r*n/8)));for(let e=0;e<r;e++){let e=i.readBits(n);t.sampleTable.sampleSizes.push(e)}t.sampleTable.sampleCount=r}break;case`stss`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];let n=W(e);for(let r=0;r<n;r++){let n=W(e)-1;t.sampleTable.keySampleIndices.push(n)}t.sampleTable.keySampleIndices.sort((e,t)=>e-t),t.sampleTable.keySampleIndices[0]!==0&&t.sampleTable.keySampleIndices.unshift(0)}break;case`stsc`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=W(e),r=0;for(let i=0;i<n;i++){let n=W(e)-1,i=W(e),a=W(e),o=m(t.sampleTable.sampleToChunk);o&&n<=o.startChunkIndex?r++:t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:n,samplesPerChunk:i,sampleDescriptionIndex:a})}r>0&&M._warn(`Skipped ${r} invalid stsc entries whose chunk indices weren't strictly increasing.`);let i=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)if(t.sampleTable.sampleToChunk[e].startSampleIndex=i,e<t.sampleTable.sampleToChunk.length-1){let n=t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex;i+=n*t.sampleTable.sampleToChunk[e].samplesPerChunk}}break;case`stco`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=W(e);for(let r=0;r<n;r++){let n=W(e);t.sampleTable.chunkOffsets.push(n)}}break;case`co64`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=W(e);for(let r=0;r<n;r++){let n=$c(e);t.sampleTable.chunkOffsets.push(n)}}break;case`mvex`:this.isFragmented=!0,this.readContiguousBoxes(e.slice(i,r.contentSize));break;case`mehd`:{let t=H(e);e.skip(3);let n=t===1?$c(e):W(e);this.movieDurationInTimescale=n}break;case`trex`:{e.skip(4);let t=W(e),n=W(e),r=W(e),i=W(e),a=W(e);this.fragmentTrackDefaults.set(t,{trackId:t,defaultSampleDescriptionIndex:n,defaultSampleDuration:r,defaultSampleSize:i,defaultSampleFlags:a})}break;case`tfra`:{let t=H(e);e.skip(3);let n=W(e),r=this.idToTrack.get(n);if(!r)break;let i=W(e),a=(i&48)>>4,o=(i&12)>>2,s=i&3,c=[H,U,Kc,W],l=c[a],u=c[o],d=c[s],f=W(e);for(let n=0;n<f;n++){let n=t===1?$c(e):W(e),i=t===1?$c(e):W(e);l(e);let a=u(e),o=d(e);a>=1&&o>=1&&r.fragmentLookupTable.push({timestamp:n,moofOffset:i,trunNumber:a,sampleNumber:o})}}break;case`moof`:if(this.currentFragment)break;this.currentFragment={moofOffset:n,moofSize:r.totalSize,implicitBaseDataOffset:n,trackData:/* @__PURE__ */ new Map,psshBoxes:[],sampleCount:0};try{this.readContiguousBoxes(e.slice(i,r.contentSize))}catch(e){throw this.currentFragment=null,e}finally{this.currentTrack=null,this.currentFragmentTrackState=null}break;case`traf`:{if(!this.currentFragment||this.isReadingTraf)break;this.isReadingTraf=!0;try{this.readContiguousBoxes(e.slice(i,r.contentSize))}finally{this.isReadingTraf=!1}let n=this.currentFragmentTrackState;if(this.currentFragmentTrackState=null,this.currentTrack){t(n);let e=this.currentFragment.trackData.get(this.currentTrack.id);cond:if(e){if(e.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break cond}e.presentationTimestamps=e.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let t=0;t<e.presentationTimestamps.length;t++){let n=e.presentationTimestamps[t],r=e.samples[n.sampleIndex];e.firstKeyFrameTimestamp===null&&r.isKeyFrame&&(e.firstKeyFrameTimestamp=r.presentationTimestamp),t<e.presentationTimestamps.length-1&&(r.duration=e.presentationTimestamps[t+1].presentationTimestamp-n.presentationTimestamp)}let t=e.samples[e.presentationTimestamps[0].sampleIndex],r=e.samples[m(e.presentationTimestamps).sampleIndex];e.startTimestamp=t.presentationTimestamp,e.endTimestamp=r.presentationTimestamp+r.duration,e.endDecodeTimestamp=n.currentTimestamp,n.startTimestamp!==null&&(ma(e,n.startTimestamp),e.startTimestampIsFinal=!0),n.encryptionAuxInfo&&!e.samples[0].encryption&&(e.encryptionAuxInfo=n.encryptionAuxInfo)}this.currentTrack=null}}break;case`pssh`:{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let t=Hi(V(e,r.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(t):this.currentTrack||this.psshBoxes.push(t)}break;case`tfhd`:{if(!this.currentFragment||!this.isReadingTraf||this.currentFragmentTrackState)break;e.skip(1);let t=Kc(e),n=!!(t&1),r=!!(t&2),i=!!(t&8),a=!!(t&16),o=!!(t&32),s=!!(t&65536),c=!!(t&131072),l=W(e),u=this.fragmentTrackDefaults.get(l),d={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:u?.defaultSampleDescriptionIndex??null,defaultSampleDuration:u?.defaultSampleDuration??null,defaultSampleSize:u?.defaultSampleSize??null,defaultSampleFlags:u?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null,currentOffset:null,currentTimestamp:0};this.currentFragmentTrackState=d,n?d.baseDataOffset=$c(e):c&&(d.baseDataOffset=this.currentFragment.moofOffset),r&&(d.sampleDescriptionIndex=W(e)),i&&(d.defaultSampleDuration=W(e)),a&&(d.defaultSampleSize=W(e)),o&&(d.defaultSampleFlags=W(e)),s&&(d.defaultSampleDuration=0);let f=this.idToTrack.get(l);if(!f)break;if(this.currentFragment.trackData.has(l)){M._warn(`Multiple traf boxes for track ${l} in the same moof box; ignoring the samples of all but the first.`);break}this.currentTrack=f}break;case`tfdt`:{if(!this.currentFragmentTrackState)break;let t=H(e);e.skip(3);let n=t===0?W(e):$c(e);this.currentFragmentTrackState.startTimestamp=n}break;case`trun`:{let t=this.currentFragmentTrackState;if(!t||!this.currentFragment)break;let n=this.currentTrack;e.skip(1);let r=Kc(e),i=!!(r&1),a=!!(r&4),o=!!(r&256),s=!!(r&512),c=!!(r&1024),l=!!(r&2048),u=W(e),{defaultSampleDuration:d,defaultSampleSize:f,defaultSampleFlags:p}=t;if(u>0&&(!o&&d===null||!s&&f===null||!c&&p===null))throw Error(`Invalid trun box: sample values are missing and there are no defaults.`);if(this.currentFragment.sampleCount+=u,this.currentFragment.sampleCount>2**20)throw Error(`Too many (> 2^20) samples in fragment.`);let m=null;i&&(m=Xc(e));let h=null;a&&(h=W(e));let g=m===null?t.currentOffset??t.baseDataOffset:t.baseDataOffset+m,_=null;n&&(_=this.currentFragment.trackData.get(n.id)??null,_||(_={track:n,startTimestamp:0,endTimestamp:0,endDecodeTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,trunSampleCounts:[],encryptionAuxInfo:null},this.currentFragment.trackData.set(n.id,_)),_.trunSampleCounts.push(u));for(let n=0;n<u;n++){let r;r=o?W(e):d;let i;i=s?W(e):f;let a;a=c?W(e):p,n===0&&h!==null&&(a=h);let u=0;l&&(u=Xc(e)),_?.samples.push({presentationTimestamp:t.currentTimestamp+u,duration:r,byteOffset:g,byteSize:i,isKeyFrame:!(a&65536),encryption:null}),g+=i,t.currentTimestamp+=r}t.currentOffset=g,this.currentFragment.implicitBaseDataOffset=g}break;case`saiz`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;if(e.skip(1),Kc(e)&1){let n=G(e,4),r=W(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let n=H(e),r=W(e),i=null;n===0&&r>0&&(i=V(e,r));let a=va(t,this.currentFragmentTrackState);a.defaultSampleInfoSize=n,a.sampleSizes=i,a.sampleCount=r}break;case`saio`:{let n=this.currentTrack;if(!n||!n.encryptionInfo)break;let r=H(e);if(Kc(e)&1){let t=G(e,4),r=W(e);if(t!==n.encryptionInfo.scheme||r!==0)break}let i=W(e);if(i===0)break;i>1&&M._warn(`Multiple saio entries are not supported; using the first offset only.`);let a=r===0?W(e):Number($c(e));this.currentFragment&&(t(this.currentFragmentTrackState),a+=this.currentFragmentTrackState.baseDataOffset);let o=va(n,this.currentFragmentTrackState);o.offset=a}break;case`senc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=this.currentFragment?.trackData.get(t.id);if(!n)break;e.skip(1);let r=!!(Kc(e)&2),i=W(e),a=t.encryptionInfo.defaultPerSampleIvSize;if(a===null)throw Error(`Invalid file: encrypted track is missing its tenc box.`);for(let o=0;o<Math.min(i,n.samples.length);o++){let i=/* @__PURE__ */ new Uint8Array(16);if(a>0)i.set(V(e,a),0);else if(t.encryptionInfo.defaultConstantIv)i.set(t.encryptionInfo.defaultConstantIv,0);else throw Error(`Invalid file: encrypted sample has no IV.`);let s=null;if(r){let t=U(e);s=[];for(let n=0;n<t;n++){let t=U(e),n=W(e);s.push({clearLen:t,protectedLen:n})}}let c=n.samples[o];c.encryption={iv:i,subsamples:s}}}break;case`udta`:{let t=this.iterateContiguousBoxes(e.slice(i,r.contentSize));for(let{boxInfo:e,slice:n}of t){if(e.name!==`meta`&&!this.currentTrack){let t=n.filePos;this.metadataTags.raw??={},e.name[0]===`©`?this.metadataTags.raw[e.name]??=ul(n):this.metadataTags.raw[e.name]??=V(n,e.contentSize),n.filePos=t}switch(e.name){case`meta`:n.skip(-e.headerSize),this.traverseBox(n);break;case`©nam`:this.currentTrack?this.currentTrack.name=ul(n):this.metadataTags.title??=ul(n);break;case`name`:this.currentTrack?this.currentTrack.name=w.decode(V(n,e.contentSize)):this.metadataTags.title??=ul(n);break;case`©des`:this.currentTrack||(this.metadataTags.description??=ul(n));break;case`©ART`:this.currentTrack||(this.metadataTags.artist??=ul(n));break;case`©alb`:this.currentTrack||(this.metadataTags.album??=ul(n));break;case`albr`:this.currentTrack||(this.metadataTags.albumArtist??=ul(n));break;case`©gen`:this.currentTrack||(this.metadataTags.genre??=ul(n));break;case`©day`:if(!this.currentTrack){let e=St(ul(n));e&&(this.metadataTags.date??=e)}break;case`©cmt`:this.currentTrack||(this.metadataTags.comment??=ul(n));break;case`©lyr`:this.currentTrack||(this.metadataTags.lyrics??=ul(n))}}}break;case`meta`:{if(this.currentTrack)break;let t=W(e)!==0;this.currentMetadataKeys=/* @__PURE__ */ new Map,t?this.readContiguousBoxes(e.slice(i,r.contentSize)):this.readContiguousBoxes(e.slice(i+4,r.contentSize-4)),this.currentMetadataKeys=null}break;case`keys`:{if(!this.currentMetadataKeys)break;e.skip(4);let t=W(e);for(let n=0;n<t;n++){let t=W(e);if(t<8)throw Error(`Invalid keys box: key size must be at least 8.`);e.skip(4);let r=w.decode(V(e,t-8));this.currentMetadataKeys.set(n+1,r)}}break;case`ilst`:{if(!this.currentMetadataKeys)break;let t=this.iterateContiguousBoxes(e.slice(i,r.contentSize));for(let{boxInfo:e,slice:n}of t){let t=e.name,r=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(r)&&(t=this.currentMetadataKeys.get(r));let i=dl(n);switch(this.metadataTags.raw??={},this.metadataTags.raw[t]??=i,t){case`©nam`:case`titl`:case`com.apple.quicktime.title`:case`title`:typeof i==`string`&&(this.metadataTags.title??=i);break;case`©des`:case`desc`:case`dscp`:case`com.apple.quicktime.description`:case`description`:typeof i==`string`&&(this.metadataTags.description??=i);break;case`©ART`:case`com.apple.quicktime.artist`:case`artist`:typeof i==`string`&&(this.metadataTags.artist??=i);break;case`©alb`:case`albm`:case`com.apple.quicktime.album`:case`album`:typeof i==`string`&&(this.metadataTags.album??=i);break;case`aART`:case`album_artist`:typeof i==`string`&&(this.metadataTags.albumArtist??=i);break;case`©cmt`:case`com.apple.quicktime.comment`:case`comment`:typeof i==`string`&&(this.metadataTags.comment??=i);break;case`©gen`:case`gnre`:case`com.apple.quicktime.genre`:case`genre`:typeof i==`string`&&(this.metadataTags.genre??=i);break;case`©lyr`:case`lyrics`:typeof i==`string`&&(this.metadataTags.lyrics??=i);break;case`©day`:case`rldt`:case`com.apple.quicktime.creationdate`:case`date`:if(typeof i==`string`){let e=St(i);e&&(this.metadataTags.date??=e)}break;case`tmpo`:if(i instanceof Uint8Array&&i.length>=2){let e=x(i).getInt16(0,!1);e>0&&(this.metadataTags.beatsPerMinute??=e)}break;case`covr`:case`com.apple.quicktime.artwork`:i instanceof wt?(this.metadataTags.images??=[],this.metadataTags.images.push({data:i.data,kind:`coverFront`,mimeType:i.mimeType})):i instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:i,kind:`coverFront`,mimeType:`image/*`}));break;case`track`:if(typeof i==`string`){let e=i.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`trkn`:if(i instanceof Uint8Array&&i.length>=6){let e=x(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),n>0&&(this.metadataTags.tracksTotal??=n)}break;case`disc`:case`disk`:if(i instanceof Uint8Array&&i.length>=6){let e=x(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),n>0&&(this.metadataTags.discsTotal??=n)}}}}}return e.filePos=o,!0}},ra=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=/* @__PURE__ */ new WeakMap,this.packetToFragmentLocation=/* @__PURE__ */ new WeakMap,this.nextEac3Frames=/* @__PURE__ */ new WeakMap}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),n=0;for(let r of e.tracks)if(r.trackBacking.getType()===t&&n++,r===this.internalTrack)break;return n}getCodec(){throw 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}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return this.internalTrack.maxBitrate}getAverageBitrate(){return this.internalTrack.avgBitrate}async getDurationFromMetadata(){let e=this.internalTrack;return e.durationInMediaTimescale<=0||e.demuxer.isFragmented&&e.demuxer.getSampleTableForTrack(e).sampleCount>0?null:(t(e.trackBacking),((await e.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+e.durationInMediaTimescale/e.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.fetchFirstFragmentedPacket(!1,e)}mapTimestampIntoTimescale(e){return Ae(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=oa(r,n),a=await this.fetchPacketForSampleIndex(i,t,n);if(!this.internalTrack.demuxer.isFragmented)return a;let o=await this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=D(t.presentationTimestamps,n,e=>e.presentationTimestamp);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t);return!a||!o?a??o:a.timestamp>o.timestamp?a:o}async getNextPacket(e,t){let n=this.nextEac3Frames.get(e);if(n)return n;let r=this.packetToSampleIndex.get(e);if(r!==void 0){let e=await this.fetchPacketForSampleIndex(r+1,t);return e||!this.internalTrack.demuxer.isFragmented?e:this.fetchFirstFragmentedPacket(!1,t)}let i=this.packetToFragmentLocation.get(e);if(i===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(i.fragment,e=>{if(e===i.fragment){let t=e.trackData.get(this.internalTrack.id);if(i.sampleIndex+1<t.samples.length)return{sampleIndex:i.sampleIndex+1,correctSampleFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=sa(r,n),a=await this.fetchPacketForSampleIndex(i,t,n);if(!this.internalTrack.demuxer.isFragmented)return a;let o=await this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=be(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=n);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t,!0);return!a||!o?a??o:a.timestamp>o.timestamp?a:o}async getNextKeyPacket(e,n){let r=this.nextEac3Frames.get(e);if(r)return r;let i=this.packetToSampleIndex.get(e);if(i!==void 0){let e=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),t=pa(e,i),r=await this.fetchPacketForSampleIndex(t,n);return r||!this.internalTrack.demuxer.isFragmented?r:this.fetchFirstFragmentedPacket(!0,n)}let a=this.packetToFragmentLocation.get(e);if(a===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(a.fragment,e=>{if(e===a.fragment){let t=e.trackData.get(this.internalTrack.id);for(let e=a.sampleIndex+1;e<t.samples.length;e++)if(t.samples[e].isKeyFrame)return{sampleIndex:e,correctSampleFound:!0}}else{let n=e.trackData.get(this.internalTrack.id);if(n&&n.firstKeyFrameTimestamp!==null){let e=n.samples.findIndex(e=>e.isKeyFrame);return t(e!==-1),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,n)}fetchFirstFragmentedPacket(e,t){return this.performFragmentedLookup(null,t=>{let n=t.trackData.get(this.internalTrack.id)?.samples.findIndex(t=>!e||t.isKeyFrame)??-1;return{sampleIndex:n,correctSampleFound:n!==-1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t,n=-1/0){if(e===-1)return null;let r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=ca(r,e);if(!i)return null;let a;if(t.metadataOnly&&this.internalTrack.info?.codec!==`eac3`)a=Li;else{let t=this.internalTrack.demuxer.reader.requestSlice(i.sampleOffset,i.sampleSize);if(j(t)&&(t=await t),!t)return null;if(a=V(t,i.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){let n=await ya(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<n.length&&(t=n[e])}t??=ba(this.internalTrack.encryptionInfo),t&&(a=await xa(this.internalTrack,t,a,null))}}let o=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,s=i.duration/this.internalTrack.timescale,c=new L(a,i.isKeyFrame?`key`:`delta`,o,s,e,i.sampleSize);return this.internalTrack.info?.codec===`eac3`?this.splitEac3Sample(c,t,n,this.packetToSampleIndex,e):(this.packetToSampleIndex.set(c,e),c)}async fetchPacketInFragment(e,n,r,i){if(n===-1)return null;let a=e.trackData.get(this.internalTrack.id).samples[n];t(a);let o;if(r.metadataOnly&&this.internalTrack.info?.codec!==`eac3`)o=Li;else{let t=this.internalTrack.demuxer.reader.requestSlice(a.byteOffset,a.byteSize);if(j(t)&&(t=await t),!t)return null;if(o=V(t,a.byteSize),this.internalTrack.encryptionInfo){let t=a.encryption??ba(this.internalTrack.encryptionInfo);t&&(o=await xa(this.internalTrack,t,o,e))}}let s=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=a.duration/this.internalTrack.timescale,l=new L(o,a.isKeyFrame?`key`:`delta`,s,c,e.moofOffset+n,a.byteSize);return this.internalTrack.info?.codec===`eac3`?this.splitEac3Sample(l,r,i,this.packetToFragmentLocation,{fragment:e,sampleIndex:n}):(this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:n}),l)}async performFragmentedLookup(e,t,n,r,i,a=!1){let{demuxer:o,fragmentLookupTable:s,fragmentPositionCache:c}=this.internalTrack,l=null,u=-1;if(e){let{sampleIndex:r,correctSampleFound:a}=t(e);if(a)return this.fetchPacketInFragment(e,r,i,n);r!==-1&&(l=e,u=r)}let d=D(s,n,e=>e.timestamp),f=D(c,n,e=>e.startTimestamp),p=1/0;for(;;){for(;d!==-1&&s[d].moofOffset>=p;)d--;for(;f!==-1&&(c[f].moofOffset>=p||a&&!c[f].hasKeyFrame);)f--;let m=Math.max(s[d]?.moofOffset??0,c[f]?.moofOffset??0)||null,h,g=null;e?m===null||e.moofOffset>=m?(h=e.moofOffset+e.moofSize,g=e):h=m:h=m??0;let _=g?g.moofOffset:h;for(;h<p;){if(g){let e=g.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break;g=null}let e=o.fragmentSummaries.get(h);if(e&&!e.trackIds.has(this.internalTrack.id)){h+=e.moofSize;continue}let a=o.reader.requestSliceRange(h,8,16);if(j(a)&&(a=await a),!a)break;let s=h,c=al(a);if(!c)break;if(c.name===`moof`){if(g=await o.readFragment(s),!g)break;let{sampleIndex:e,correctSampleFound:r}=t(g);if(r)return this.fetchPacketInFragment(g,e,i,n);e!==-1&&(l=g,u=e)}h=s+c.totalSize}if(m===null||l&&l.moofOffset>=m)break;p=_,e=null}return l?this.fetchPacketInFragment(l,u,i,n):null}splitEac3Sample(e,n,r,i,a){let o=this.internalTrack.info;t(o?.type===`audio`);let s=ar(e.data)??[{offset:0,size:e.data.byteLength,blockCount:6}],c=(r-this.internalTrack.editListOffset)/this.internalTrack.timescale,l=null,u=null,d=0;for(let t=0;t<s.length;t++){let r=s[t],f=e.timestamp+256*d/o.sampleRate,p=s.length===1?e.duration:256*r.blockCount/o.sampleRate,m=new L(n.metadataOnly?Li:e.data.subarray(r.offset,r.offset+r.size),`key`,f,p,8*e.sequenceNumber+t,r.size);i.set(m,a),u&&this.nextEac3Frames.set(u,m),(t===0||f<=c)&&(l=m),u=m,d+=r.blockCount}return t(l),l}},ia=class extends ra{constructor(e){super(e),this.decoderConfigPromise=null}getType(){return`video`}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}getTransformationMatrix(){return[...this.internalTrack.matrix]}async getColorSpace(){let e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}async canBeTransparent(){return this.internalTrack.info.codec===`prores`&&(this.internalTrack.info.proresFormat===`ap4h`||this.internalTrack.info.proresFormat===`ap4x`)}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`avc`&&!this.internalTrack.info.codecDescription){let e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&pn(e.data)}else if(this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription){let e=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&Tn(e.data)}else if(this.internalTrack.info.codec===`vp9`&&(!this.internalTrack.info.vp9CodecInfo||!zn(this.internalTrack.info.vp9CodecInfo))){let e=await this.getFirstPacket({}),t=e&&Rn(e.data);t&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??t,videoFullRangeFlag:t.videoFullRangeFlag,colourPrimaries:t.colourPrimaries,transferCharacteristics:t.transferCharacteristics,matrixCoefficients:t.matrixCoefficients})}else if(this.internalTrack.info.codec===`av1`&&(!this.internalTrack.info.av1CodecInfo||!Hn(this.internalTrack.info.av1CodecInfo))){let e=await this.getFirstPacket({}),t=e&&Vn(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else if(this.internalTrack.info.codec===`prores`&&!this.internalTrack.info.proresCodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=e&&Un(e.data)}if(!se(this.internalTrack.info.colorSpace)){let e=Ql(this.internalTrack.info);this.internalTrack.info.colorSpace.primaries??=e.primaries,this.internalTrack.info.colorSpace.transfer??=e.transfer,this.internalTrack.info.colorSpace.matrix??=e.matrix,this.internalTrack.info.colorSpace.fullRange??=e.fullRange}let e={codec:Zl(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}},aa=class extends ra{constructor(e){super(e),this.decoderConfigPromise=null}getType(){return`audio`}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.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`dts`&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&vr(e.data)}return{codec:eu(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}};const oa=(e,t)=>{if(e.sortedCompositionTimeOffsets)return la(e,t,!1);{let n=D(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(n===-1)return-1;let r=e.sampleTimingEntries[n];return r.delta===0?r.startIndex+r.count-1:r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},sa=(e,t)=>{if(!e.keySampleIndices)return oa(e,t);if(e.sortedCompositionTimeOffsets)return la(e,t,!0);{let n=oa(e,t),r=D(e.keySampleIndices,n,e=>e);return e.keySampleIndices[r]??-1}},ca=(e,t)=>{if(t>=e.sampleCount)return null;let n=D(e.sampleTimingEntries,t,e=>e.startIndex),r=e.sampleTimingEntries[n],i=r.startDecodeTimestamp+(t-r.startIndex)*r.delta,a=D(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[a];o&&t-o.startIndex<o.count&&(i+=o.offset);let s=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],c=D(e.sampleToChunk,t,e=>e.startSampleIndex),l=e.sampleToChunk[c],u=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),d=e.chunkOffsets[u],f=l.startSampleIndex+(u-l.startChunkIndex)*l.samplesPerChunk,p=d;e.sampleSizes.length===1?p+=s*(t-f):p+=e.cumulativeSampleSizes[t]-e.cumulativeSampleSizes[f];let m=r.delta;if(e.sortedCompositionTimeOffsets){let n=ua(e,t,i);n!==null&&(m=n-i)}return{presentationTimestamp:i,duration:m,sampleOffset:p,sampleSize:s,chunkOffset:d,isKeyFrame:!e.keySampleIndices||ge(e.keySampleIndices,t,e=>e)!==-1}},la=(e,t,n)=>{let r=e.sortedCompositionTimeOffsets,i=-1,a=-1/0,o=D(r,t,e=>e.startTimestamp);for(let s=o;s>=0;s--){let o=r[s];if(o.maxLastTimestamp<a)break;let c=o.lastTimestamp<=t?o.startIndex+o.count-1:da(e,o,(e,n)=>n>t)-1;if(n){let t=D(e.keySampleIndices,c,e=>e);c=e.keySampleIndices[t]??-1}if(c<o.startIndex)continue;let l=fa(e,c)+o.offset;(l>a||l===a&&c>i)&&(i=c,a=l)}return i},ua=(e,t,n)=>{let r=e.sortedCompositionTimeOffsets,i=D(r,n,e=>e.startTimestamp),a=r[i+1]?.startTimestamp??null;for(let o=i;o>=0;o--){let i=r[o];if(i.maxLastTimestamp<n)break;let s=da(e,i,(e,r)=>r>n||r===n&&e>t);if(s===i.startIndex+i.count)continue;let c=fa(e,s)+i.offset;(a===null||c<a)&&(a=c)}return a},da=(e,t,n)=>{let r=t.startIndex,i=t.startIndex+t.count;for(;r<i;){let a=Math.floor((r+i)/2);n(a,fa(e,a)+t.offset)?i=a:r=a+1}return r},fa=(e,t)=>{let n=D(e.sampleTimingEntries,t,e=>e.startIndex),r=e.sampleTimingEntries[n];return r.startDecodeTimestamp+(t-r.startIndex)*r.delta},pa=(e,t)=>{if(!e.keySampleIndices)return t+1;let n=D(e.keySampleIndices,t,e=>e);return e.keySampleIndices[n+1]??-1},ma=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t,e.endDecodeTimestamp+=t;for(let n of e.samples)n.presentationTimestamp+=t;for(let n of e.presentationTimestamps)n.presentationTimestamp+=t},ha=e=>[ol(e),ol(e),sl(e),ol(e),ol(e),sl(e),ol(e),ol(e),sl(e)],ga=(e,t)=>{let n=e.info;if(n.type!==`video`)return;let{num:r,den:i}=t;r>0&&i>0&&r!==i&&(r>i?(n.squarePixelWidth=Math.round(n.width*r/i),n.squarePixelHeight=n.height):(n.squarePixelWidth=n.width,n.squarePixelHeight=Math.round(n.height*i/r)))},_a=(e,t)=>{for(;e.length>0&&m(e).startIndex>=t;)e.pop();let n=m(e);n&&(n.count=Math.min(n.count,t-n.startIndex))},va=(e,t)=>t?t.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:e.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},ya=async(e,n,r)=>{if(r.resolved)return r.resolved;if(r.offset===null||r.sampleCount===0)throw Error(`Incomplete saiz/saio info; cannot resolve encryption data.`);let i=0;if(r.defaultSampleInfoSize>0)i=r.defaultSampleInfoSize*r.sampleCount;else{t(r.sampleSizes);for(let e=0;e<r.sampleCount;e++)i+=r.sampleSizes[e]}let a=e.requestSlice(r.offset,i);if(j(a)&&(a=await a),!a)throw Error(`Failed to read auxiliary encryption info.`);let o=n.defaultPerSampleIvSize;if(o===null)throw Error(`Invalid file: encrypted track is missing its tenc box.`);let s=[];for(let e=0;e<r.sampleCount;e++){let t=r.defaultSampleInfoSize>0?r.defaultSampleInfoSize:r.sampleSizes[e],i=/* @__PURE__ */ new Uint8Array(16);if(o>0)i.set(V(a,o),0);else if(n.defaultConstantIv)i.set(n.defaultConstantIv,0);else throw Error(`Invalid file: encrypted sample has no IV.`);let c=null;if(t>o){let e=U(a);c=[];for(let t=0;t<e;t++){let e=U(a),t=W(a);c.push({clearLen:e,protectedLen:t})}}s.push({iv:i,subsamples:c})}return r.resolved=s,s},ba=e=>e.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,xa=async(e,n,r,i)=>{t(e.encryptionInfo);let a=e.encryptionInfo;if(a.defaultKid===null)throw Error(`Invalid file: encrypted track is missing its tenc box.`);let o=a.defaultKid,s,c=e.demuxer.decryptionKeyCache.get(o);if(c)s=await c;else{if(!e.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw Error(`Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.`);let t=(async()=>{let t=e.demuxer.psshBoxes;if(i){t=[...t,...i.psshBoxes].filter(e=>e.keyIds===null||e.keyIds.includes(o));for(let e=0;e<t.length-1;e++)for(let n=e+1;n<t.length;n++)Ui(t[e],t[n])&&(t.splice(n,1),n--)}let n=await e.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:o,psshBoxes:t});if(!(typeof n==`string`&&n.length===32&&fe.test(n)||n instanceof Uint8Array&&n.byteLength===16))throw TypeError(`resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.`);return n instanceof Uint8Array?n:me(n)})();e.demuxer.decryptionKeyCache.set(o,t),s=await t}return a.scheme===`cenc`||a.scheme===`cens`?Sa(s,a,n,r):Ca(s,a,n,r)},Sa=async(e,n,r,i)=>{let a=/* @__PURE__ */ new Uint8Array(16);a.set(r.iv,0);let o=await crypto.subtle.importKey(`raw`,e,{name:`AES-CTR`},!1,[`decrypt`]),s=async e=>{let t=await crypto.subtle.decrypt({name:`AES-CTR`,counter:a,length:64},o,e);return new Uint8Array(t)};if(!r.subsamples)return s(i);t(n.defaultCryptByteBlock!==null&&n.defaultSkipByteBlock!==null);let c=wa(r.subsamples,n.defaultCryptByteBlock,n.defaultSkipByteBlock,i.length),l=0;for(let e of c)for(let t of e.perSubsample)l+=t.length;let u=new Uint8Array(l),d=0;for(let e of c)for(let t of e.perSubsample)u.set(i.subarray(t.offset,t.offset+t.length),d),d+=t.length;let f=await s(u),p=new Uint8Array(i),m=0;for(let e of c)for(let t of e.perSubsample)p.set(f.subarray(m,m+t.length),t.offset),m+=t.length;return p},Ca=(e,n,r,i)=>{let a=new $i;a.init({key:e,iv:r.iv});let o=n.defaultCryptByteBlock,s=n.defaultSkipByteBlock;if(t(o!==null&&s!==null),!r.subsamples){let e=new Uint8Array(i),t=Math.floor(i.length/16);for(let n=0;n<t;n++){let t=n*16;a.in.set(i.subarray(t,t+16)),a.decrypt(),e.set(a.out,t)}return e}if(o===0&&s===0)throw Error(`cbcs with subsamples requires pattern encryption.`);let c=new Uint8Array(i),l=wa(r.subsamples,o,s,i.length),u=new DataView(r.iv.buffer,r.iv.byteOffset,16);for(let e of l){a.iv[0]=u.getUint32(0,!1),a.iv[1]=u.getUint32(4,!1),a.iv[2]=u.getUint32(8,!1),a.iv[3]=u.getUint32(12,!1);for(let t of e.perSubsample){let e=t.length/16;for(let n=0;n<e;n++){let e=t.offset+n*16;a.in.set(i.subarray(e,e+16)),a.decrypt(),c.set(a.out,e)}}}return c},wa=(e,t,n,r)=>{let i=[],a=t!==0||n!==0,o=0;for(let s of e){if(o+s.clearLen+s.protectedLen>r)throw Error(`Invalid encryption info: subsamples exceed the sample size.`);o+=s.clearLen;let e=[];if(!a)s.protectedLen>0&&e.push({offset:o,length:s.protectedLen}),o+=s.protectedLen;else{let r=s.protectedLen,i=o;for(;r>0&&!(r<16*t);){let a=16*t;e.push({offset:i,length:a}),i+=a,r-=a;let o=Math.min(16*n,r);i+=o,r-=o}o+=s.protectedLen}i.push({perSubsample:e})}return i};
167
+ /*!
168
+ * Copyright (c) 2026-present, Vanilagy and contributors
169
+ *
170
+ * This Source Code Form is subject to the terms of the Mozilla Public
171
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
172
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
173
+ */
174
+ var Ta=class{constructor(e){this.value=e}},Ea=class{constructor(e){this.value=e}},Da=class{constructor(e){this.value=e}},Oa=class{constructor(e){this.value=e}},R;(function(e){e[e.EBML=440786851]=`EBML`,e[e.EBMLVersion=17030]=`EBMLVersion`,e[e.EBMLReadVersion=17143]=`EBMLReadVersion`,e[e.EBMLMaxIDLength=17138]=`EBMLMaxIDLength`,e[e.EBMLMaxSizeLength=17139]=`EBMLMaxSizeLength`,e[e.DocType=17026]=`DocType`,e[e.DocTypeVersion=17031]=`DocTypeVersion`,e[e.DocTypeReadVersion=17029]=`DocTypeReadVersion`,e[e.Void=236]=`Void`,e[e.Segment=408125543]=`Segment`,e[e.SeekHead=290298740]=`SeekHead`,e[e.Seek=19899]=`Seek`,e[e.SeekID=21419]=`SeekID`,e[e.SeekPosition=21420]=`SeekPosition`,e[e.Duration=17545]=`Duration`,e[e.Info=357149030]=`Info`,e[e.TimestampScale=2807729]=`TimestampScale`,e[e.DateUTC=17505]=`DateUTC`,e[e.Title=31657]=`Title`,e[e.MuxingApp=19840]=`MuxingApp`,e[e.WritingApp=22337]=`WritingApp`,e[e.Tracks=374648427]=`Tracks`,e[e.TrackEntry=174]=`TrackEntry`,e[e.TrackNumber=215]=`TrackNumber`,e[e.TrackUID=29637]=`TrackUID`,e[e.TrackType=131]=`TrackType`,e[e.FlagEnabled=185]=`FlagEnabled`,e[e.FlagDefault=136]=`FlagDefault`,e[e.FlagForced=21930]=`FlagForced`,e[e.FlagOriginal=21934]=`FlagOriginal`,e[e.FlagHearingImpaired=21931]=`FlagHearingImpaired`,e[e.FlagVisualImpaired=21932]=`FlagVisualImpaired`,e[e.FlagCommentary=21935]=`FlagCommentary`,e[e.FlagLacing=156]=`FlagLacing`,e[e.MaxBlockAdditionID=21998]=`MaxBlockAdditionID`,e[e.Name=21358]=`Name`,e[e.Language=2274716]=`Language`,e[e.LanguageBCP47=2274717]=`LanguageBCP47`,e[e.CodecID=134]=`CodecID`,e[e.CodecPrivate=25506]=`CodecPrivate`,e[e.CodecDelay=22186]=`CodecDelay`,e[e.SeekPreRoll=22203]=`SeekPreRoll`,e[e.DefaultDuration=2352003]=`DefaultDuration`,e[e.Video=224]=`Video`,e[e.PixelWidth=176]=`PixelWidth`,e[e.PixelHeight=186]=`PixelHeight`,e[e.DisplayWidth=21680]=`DisplayWidth`,e[e.DisplayHeight=21690]=`DisplayHeight`,e[e.DisplayUnit=21682]=`DisplayUnit`,e[e.StereoMode=21432]=`StereoMode`,e[e.AlphaMode=21440]=`AlphaMode`,e[e.Audio=225]=`Audio`,e[e.SamplingFrequency=181]=`SamplingFrequency`,e[e.OutputSamplingFrequency=30901]=`OutputSamplingFrequency`,e[e.Channels=159]=`Channels`,e[e.BitDepth=25188]=`BitDepth`,e[e.SimpleBlock=163]=`SimpleBlock`,e[e.BlockGroup=160]=`BlockGroup`,e[e.Block=161]=`Block`,e[e.BlockAdditions=30113]=`BlockAdditions`,e[e.BlockMore=166]=`BlockMore`,e[e.BlockAdditional=165]=`BlockAdditional`,e[e.BlockAddID=238]=`BlockAddID`,e[e.BlockDuration=155]=`BlockDuration`,e[e.ReferenceBlock=251]=`ReferenceBlock`,e[e.Cluster=524531317]=`Cluster`,e[e.Timestamp=231]=`Timestamp`,e[e.Cues=475249515]=`Cues`,e[e.CuePoint=187]=`CuePoint`,e[e.CueTime=179]=`CueTime`,e[e.CueTrackPositions=183]=`CueTrackPositions`,e[e.CueTrack=247]=`CueTrack`,e[e.CueClusterPosition=241]=`CueClusterPosition`,e[e.CueRelativePosition=240]=`CueRelativePosition`,e[e.Colour=21936]=`Colour`,e[e.MatrixCoefficients=21937]=`MatrixCoefficients`,e[e.TransferCharacteristics=21946]=`TransferCharacteristics`,e[e.Primaries=21947]=`Primaries`,e[e.Range=21945]=`Range`,e[e.Projection=30320]=`Projection`,e[e.ProjectionType=30321]=`ProjectionType`,e[e.ProjectionPoseYaw=30323]=`ProjectionPoseYaw`,e[e.ProjectionPosePitch=30324]=`ProjectionPosePitch`,e[e.ProjectionPoseRoll=30325]=`ProjectionPoseRoll`,e[e.Attachments=423732329]=`Attachments`,e[e.AttachedFile=24999]=`AttachedFile`,e[e.FileDescription=18046]=`FileDescription`,e[e.FileName=18030]=`FileName`,e[e.FileMediaType=18016]=`FileMediaType`,e[e.FileData=18012]=`FileData`,e[e.FileUID=18094]=`FileUID`,e[e.Chapters=272869232]=`Chapters`,e[e.Tags=307544935]=`Tags`,e[e.Tag=29555]=`Tag`,e[e.Targets=25536]=`Targets`,e[e.TargetTypeValue=26826]=`TargetTypeValue`,e[e.TargetType=25546]=`TargetType`,e[e.TagTrackUID=25541]=`TagTrackUID`,e[e.TagEditionUID=25545]=`TagEditionUID`,e[e.TagChapterUID=25540]=`TagChapterUID`,e[e.TagAttachmentUID=25542]=`TagAttachmentUID`,e[e.SimpleTag=26568]=`SimpleTag`,e[e.TagName=17827]=`TagName`,e[e.TagLanguage=17530]=`TagLanguage`,e[e.TagString=17543]=`TagString`,e[e.TagBinary=17541]=`TagBinary`,e[e.ContentEncodings=28032]=`ContentEncodings`,e[e.ContentEncoding=25152]=`ContentEncoding`,e[e.ContentEncodingOrder=20529]=`ContentEncodingOrder`,e[e.ContentEncodingScope=20530]=`ContentEncodingScope`,e[e.ContentCompression=20532]=`ContentCompression`,e[e.ContentCompAlgo=16980]=`ContentCompAlgo`,e[e.ContentCompSettings=16981]=`ContentCompSettings`,e[e.ContentEncryption=20533]=`ContentEncryption`})(R||={});const ka=[R.EBML,R.Segment],Aa=[R.SeekHead,R.Info,R.Cluster,R.Tracks,R.Cues,R.Attachments,R.Chapters,R.Tags],ja=[...ka,...Aa],Ma=e=>e<256?1:e<65536?2:e<1<<24?3:e<2**32?4:e<2**40?5:6,Na=e=>e<1n<<8n?1:e<1n<<16n?2:e<1n<<24n?3:e<1n<<32n?4:e<1n<<40n?5:e<1n<<48n?6:e<1n<<56n?7:8,Pa=e=>e>=-64&&e<64?1:e>=-8192&&e<8192?2:e>=-1048576&&e<1<<20?3:e>=-134217728&&e<1<<27?4:e>=-(2**34)&&e<2**34?5:6,Fa=e=>{if(e<127)return 1;if(e<16383)return 2;if(e<(1<<21)-1)return 3;if(e<(1<<28)-1)return 4;if(e<2**35-1)return 5;if(e<2**42-1)return 6;throw Error(`EBML varint size not supported `+e)};var Ia=class{constructor(e){this.writer=e,this.helper=/* @__PURE__ */ new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */ new WeakMap,this.dataOffsets=/* @__PURE__ */ new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,t=Ma(e)){let n=0;switch(t){case 6:this.helperView.setUint8(n++,e/2**40|0);case 5:this.helperView.setUint8(n++,e/2**32|0);case 4:this.helperView.setUint8(n++,e>>24);case 3:this.helperView.setUint8(n++,e>>16);case 2:this.helperView.setUint8(n++,e>>8);case 1:this.helperView.setUint8(n++,e);break;default:throw Error(`Bad unsigned int size `+t)}this.writer.write(this.helper.subarray(0,n))}writeUnsignedBigInt(e,t=Na(e)){let n=0;for(let r=t-1;r>=0;r--)this.helperView.setUint8(n++,Number(e>>BigInt(r*8)&255n));this.writer.write(this.helper.subarray(0,n))}writeSignedInt(e,t=Pa(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=Fa(e)){if(e>=2**(7*t)-1)throw Error(`EBML variable-size integer ${e} doesn't fit into ${t} bytes.`);let n=0;switch(t){case 1:this.helperView.setUint8(n++,128|e);break;case 2:this.helperView.setUint8(n++,64|e>>8),this.helperView.setUint8(n++,e);break;case 3:this.helperView.setUint8(n++,32|e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 4:this.helperView.setUint8(n++,16|e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 5:this.helperView.setUint8(n++,8|e/2**32&7),this.helperView.setUint8(n++,e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 6:this.helperView.setUint8(n++,4|e/2**40&3),this.helperView.setUint8(n++,e/2**32|0),this.helperView.setUint8(n++,e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;default:throw Error(`Bad EBML varint size `+t)}this.writer.write(this.helper.subarray(0,n))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split(``).map(e=>e.charCodeAt(0))))}writeEBML(e){if(e!==null){if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(let t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){if(e.size===void 0)this.writeVarInt(La(e.data)),this.dataOffsets.set(e,this.writer.getPos()),this.writeEBML(e.data);else{let t=this.writer.getPos(),n=e.size===-1?1:e.size;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+n);let r=this.writer.getPos();if(this.dataOffsets.set(e,r),this.writeEBML(e.data),e.size!==-1){let e=this.writer.getPos()-r,i=this.writer.getPos();this.writer.seek(t),this.writeVarInt(e,n),this.writer.seek(i)}}}else if(typeof e.data==`number`){let t=e.size??Ma(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data==`bigint`){let t=e.size??Na(e.data);this.writeVarInt(t),this.writeUnsignedBigInt(e.data,t)}else if(typeof e.data==`string`)this.writeVarInt(e.data.length),this.writeAsciiString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof Ta)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof Ea)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof Da){let t=e.size??Pa(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof Oa){let t=T.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else k(e.data)}}};const La=e=>{if(e===null)return 0;if(e instanceof Uint8Array)return e.byteLength;if(Array.isArray(e))return e.reduce((e,t)=>e+La(t),0);let n,r;return Array.isArray(e.data)?(n=La(e.data),r=e.size===void 0?Fa(n):e.size===-1?1:e.size):typeof e.data==`number`?(n=e.size??Ma(e.data),r=Fa(n)):typeof e.data==`bigint`?(n=e.size??Na(e.data),r=Fa(n)):typeof e.data==`string`?(n=e.data.length,r=Fa(n)):e.data instanceof Uint8Array?(n=e.data.byteLength,r=e.size??Fa(n)):e.data instanceof Ta?(n=4,r=1):e.data instanceof Ea?(n=8,r=1):e.data instanceof Da?(n=e.size??Pa(e.data.value),r=Fa(n)):(t(e.data instanceof Oa),n=T.encode(e.data.value).length,r=Fa(n)),Ma(e.id)+r+n},Ra=Date.UTC(2001,0,1),za=e=>{if(e.remainingLength<1)return null;let t=H(e);if(e.skip(-1),t===0)return null;let n=1,r=128;for(;(t&r)===0;)n++,r>>=1;return e.remainingLength<n?null:n},Ba=e=>{if(e.remainingLength<1)return null;let t=H(e);if(t===0)return null;let n=1,r=128;for(;(t&r)===0;)n++,r>>=1;if(e.remainingLength<n-1)return null;let i=t&r-1;for(let t=1;t<n;t++)i*=256,i+=H(e);return i},z=(e,t)=>{if(t>8)throw Error(`Bad unsigned int size `+t);let n=0;for(let r=0;r<t;r++)n*=256,n+=H(e);return n},Va=(e,t)=>{if(t>8)throw Error(`Bad unsigned int size `+t);let n=0n;for(let r=0;r<t;r++)n<<=8n,n+=BigInt(H(e));return n},Ha=(e,t)=>t===0?0n:BigInt.asIntN(8*t,Va(e,t)),Ua=e=>{let t=za(e);return t===null||e.remainingLength<t?null:z(e,t)},Wa=e=>{let t=e.filePos,n=Ba(e);if(n===null)return null;if(n!==2**(7*(e.filePos-t))-1)return n},Ga=e=>{t(e.remainingLength>=2);let n=Ua(e);if(n===null)return null;let r=Wa(e);return r===null?null:{id:n,size:r}},Ka=(e,t)=>{let n=V(e,t),r=``;for(let e=0;e<t&&n[e]!==0;e++)r+=String.fromCharCode(n[e]);return r},qa=(e,t)=>{let n=V(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return w.decode(n.subarray(0,r))},Ja=(e,t)=>{if(t===0)return 0;if(t!==4&&t!==8)throw Error(`Bad float size `+t);return t===4?nl(e):rl(e)},Ya=async(e,t,n,r)=>{let i=new Set(n),a=t;for(;r===null||a<r;){let t=e.requestSliceRange(a,2,16);if(j(t)&&(t=await t),!t)break;let n=Ga(t);if(!n)break;if(i.has(n.id))return{pos:a,found:!0};Qa(n.size),a=t.filePos+n.size}return{pos:r!==null&&r>a?r:a,found:!1}},Xa=async(e,t,n,r)=>{let i=2**16,a=new Set(n),o=t;for(;o<r;){let t=e.requestSliceRange(o,0,Math.min(i,r-o));if(j(t)&&(t=await t),!t||t.length===0)break;let n=Math.max(t.length-8,1);for(let e=0;e<n;e++){t.filePos=o;let e=Ua(t);if(e!==null&&a.has(e))return o;o++}}return null},Za={avc:`V_MPEG4/ISO/AVC`,hevc:`V_MPEGH/ISO/HEVC`,vp8:`V_VP8`,vp9:`V_VP9`,av1:`V_AV1`,prores:`V_PRORES`,aac:`A_AAC`,mp3:`A_MPEG/L3`,opus:`A_OPUS`,vorbis:`A_VORBIS`,flac:`A_FLAC`,ac3:`A_AC3`,eac3:`A_EAC3`,dts:`A_DTS`,truehd:`A_TRUEHD`,"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 Qa(e){if(e===void 0)throw Error(`Undefined element size is used in a place where it is not supported.`)}
175
+ /*!
176
+ * Copyright (c) 2026-present, Vanilagy and contributors
177
+ *
178
+ * This Source Code Form is subject to the terms of the Mozilla Public
179
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
180
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
181
+ */
182
+ const $a=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isWebM?`webm`:`x-matroska`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings.filter(Boolean))];t+=`; codecs="${n.join(`, `)}"`}return t};
183
+ /*!
184
+ * Copyright (c) 2026-present, Vanilagy and contributors
185
+ *
186
+ * This Source Code Form is subject to the terms of the Mozilla Public
187
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
188
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
189
+ */
190
+ var eo;(function(e){e[e.None=0]=`None`,e[e.Xiph=1]=`Xiph`,e[e.FixedSize=2]=`FixedSize`,e[e.Ebml=3]=`Ebml`})(eo||={});var to;(function(e){e[e.Block=1]=`Block`,e[e.Private=2]=`Private`,e[e.Next=4]=`Next`})(to||={});var no;(function(e){e[e.Zlib=0]=`Zlib`,e[e.Bzlib=1]=`Bzlib`,e[e.lzo1x=2]=`lzo1x`,e[e.HeaderStripping=3]=`HeaderStripping`})(no||={});const ro=[{id:R.SeekHead,flag:`seekHeadSeen`},{id:R.Info,flag:`infoSeen`},{id:R.Tracks,flag:`tracksSeen`},{id:R.Cues,flag:`cuesSeen`}],io=10*2**20;var ao=class extends zi{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.currentProjection=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.claimedSeekTargets=/* @__PURE__ */ new Set,this.elementNestingDepth=0,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(e=>e.trackBacking))}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return $a({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>e.info?.type===`video`)),hasAudio:this.segments.some(e=>e.tracks.some(e=>e.info?.type===`audio`)),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let e of this.segments)e.metadataTagsPromise||=this.reader.fileSize===null?Promise.resolve():this.loadSegmentMetadata(e),await e.metadataTagsPromise;let e={};for(let t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,16);if(j(t)&&(t=await t),!t)break;let n=Ga(t);if(!n)break;let r=n.id,i=n.size,a=t.filePos;if(r===R.EBML){Qa(i);let e=this.reader.requestSlice(a,i);if(j(e)&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===R.Segment){if(await this.readSegment(a,i),i===void 0||this.reader.fileSize===null)break}else if(r===R.Cluster){if(this.reader.fileSize===null)break;i===void 0&&(i=(await Ya(this.reader,a,ja,this.reader.fileSize)).pos-a);let e=m(this.segments);e&&(e.elementEndPos=a+i)}Qa(i),e=a+i}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],idToTrack:/* @__PURE__ */ new Map,cuePoints:[],dataStartPos:e,elementEndPos:t===void 0?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,clusterSummaries:/* @__PURE__ */ new Map,metadataTags:{},metadataTagsPromise:null},this.segments.push(this.currentSegment);let n=e,r=/* @__PURE__ */ new Set;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let t=this.reader.requestSliceRange(n,2,16);if(j(t)&&(t=await t),!t)break;let i=n,a=Ga(t);if(!a||!Aa.includes(a.id)&&a.id!==R.Void){let e=await Xa(this.reader,i+1,Aa,Math.min(this.currentSegment.elementEndPos??1/0,i+io));if(e){n=e;continue}break}let{id:o,size:s}=a,c=t.filePos,l=ro.findIndex(e=>e.id===o);if(l!==-1){let t=ro[l].flag;this.currentSegment[t]=!0,o===R.SeekHead&&r.add(i-e),Qa(s);let n=this.reader.requestSlice(c,s);j(n)&&(n=await n),n&&this.readContiguousElements(n)}else if(o===R.Tags||o===R.Attachments){o===R.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Qa(s);let e=this.reader.requestSlice(c,s);j(e)&&(e=await e),e&&this.readContiguousElements(e)}else if(o===R.Cluster){this.currentSegment.clusterSeekStartPos=i;break}if(s===void 0)break;n=c+s}if(this.reader.fileSize!==null)for(let t=0;t<this.currentSegment.seekEntries.length;t++){let n=this.currentSegment.seekEntries[t];if(n.id!==R.SeekHead||r.has(n.segmentPosition)||(r.add(n.segmentPosition),!this.claimSeekTarget(e+n.segmentPosition)))continue;let i=this.reader.requestSliceRange(e+n.segmentPosition,2,16);if(j(i)&&(i=await i),!i)continue;let a=Ga(i);if(!a||a.id!==R.SeekHead)continue;let{size:o}=a;Qa(o);let s=this.reader.requestSlice(i.filePos,o);j(s)&&(s=await s),s&&this.readContiguousElements(s)}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),this.reader.fileSize!==null)for(let t of this.currentSegment.seekEntries){let n=ro.find(e=>e.id===t.id);if(!n||this.currentSegment[n.flag]||!this.claimSeekTarget(e+t.segmentPosition))continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,16);if(j(r)&&(r=await r),!r)continue;let i=Ga(r);if(!i)continue;let{id:a,size:o}=i;if(a!==n.id)continue;Qa(o),this.currentSegment[n.flag]=!0;let s=this.reader.requestSlice(r.filePos,o);j(s)&&(s=await s),s&&this.readContiguousElements(s)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3);for(let e of this.currentSegment.tracks)e.defaultDurationNs!==null&&(e.defaultDuration=this.currentSegment.timestampFactor*e.defaultDurationNs/1e9),e.codecDelay=Math.round(this.currentSegment.timestampFactor*e.codecDelayNs/1e9);for(let e of this.currentSegment.cuePoints){let t=this.currentSegment.idToTrack.get(e.trackId);t&&t.cuePoints.push(e)}for(let e of this.currentSegment.tracks){let t=e.cuePoints;t.sort((e,t)=>e.time-t.time);let n=0;for(let e of t)(n===0||e.time!==t[n-1].time)&&(t[n++]=e);t.length=n}let i=null,a=-1/0;for(let e of this.currentSegment.tracks)e.cuePoints.length>a&&(a=e.cuePoints.length,i=e);for(let e of this.currentSegment.tracks)e.cuePoints.length===0&&(e.cuePoints=i.cuePoints);this.currentSegment=null}async readCluster(e,n){if(n.lastReadCluster?.elementStartPos===e)return n.lastReadCluster;let r=this.reader.requestSliceRange(e,2,16);j(r)&&(r=await r),t(r);let i=e,a=Ga(r);t(a);let o=a.id;t(o===R.Cluster);let s=a.size,c=r.filePos;s===void 0&&(s=(await Ya(this.reader,c,ja,n.elementEndPos)).pos-c);let l=this.reader.requestSliceRange(c,0,s);j(l)&&(l=await l);let u={segment:n,elementStartPos:i,elementEndPos:c+s,dataStartPos:c,timestamp:-1,trackData:/* @__PURE__ */ new Map};if(l){this.currentCluster=u;try{u.elementEndPos=this.readContiguousElements(l,ja)}finally{this.currentCluster=null,this.currentBlock=null}}for(let[,e]of u.trackData){let n=e.track;t(e.blocks.length>0);let r=!1;for(let t=0;t<e.blocks.length;t++){let n=e.blocks[t];n.timestamp+=u.timestamp,r||=n.lacing!==eo.None}e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let t=0;t<e.presentationTimestamps.length;t++){let r=e.presentationTimestamps[t],i=e.blocks[r.blockIndex];t<e.presentationTimestamps.length-1?i.duration=e.presentationTimestamps[t+1].timestamp-i.timestamp:i.duration===0&&n.defaultDuration!=null&&i.lacing===eo.None&&(i.duration=Math.round(n.defaultDuration))}if(r&&(e.blocks=this.expandLacedBlocks(e.blocks,n),e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp)),n.info?.type===`audio`&&n.info.codec){let t=Bl.includes(n.info.codec);for(let r of e.blocks)(r.decoded||!t)&&(r.isKeyFrame=Xn(n.info.codec,r.data)===`key`)}let a=e.presentationTimestamps.find(t=>e.blocks[t.blockIndex].isKeyFrame);a&&(e.firstKeyFrameTimestamp=a.timestamp);let o=e.blocks[e.presentationTimestamps[0].blockIndex],s=e.blocks[m(e.presentationTimestamps).blockIndex];e.startTimestamp=o.timestamp,e.endTimestamp=s.timestamp+s.duration;let c=D(n.clusterPositionCache,e.startTimestamp,e=>e.startTimestamp),l=n.clusterPositionCache[c],d=n.clusterPositionCache[c+1];(!l||l.elementStartPos<i)&&(!d||d.elementStartPos>i)&&n.clusterPositionCache.splice(c+1,0,{elementStartPos:u.elementStartPos,startTimestamp:e.startTimestamp,hasKeyFrame:e.firstKeyFrameTimestamp!==null})}return n.lastReadCluster=u,n.clusterSummaries.set(e,{elementEndPos:u.elementEndPos,trackIds:new Set(u.trackData.keys())}),u}getTrackDataInCluster(e,t){let n=e.trackData.get(t);if(!n){let r=e.segment.idToTrack.get(t);if(!r)return null;n={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,n)}return n}expandLacedBlocks(e,n){let r=[];for(let i of e){if(i.lacing===eo.None){r.push(i);continue}let e=Uc.tempFromBytes(i.data);if(e.length===0)throw Error(`Invalid laced block: no data.`);let a=[],o=H(e)+1;switch(i.lacing){case eo.Xiph:{let t=0;for(let n=0;n<o-1;n++){let n=0;for(;e.bufferPos<e.length;){let r=H(e);if(n+=r,r<255){a.push(n),t+=n;break}}}a.push(e.length-(e.bufferPos+t))}break;case eo.FixedSize:{let t=e.length-1,n=Math.floor(t/o);for(let e=0;e<o;e++)a.push(n)}break;case eo.Ebml:{if(o===1){a.push(e.length-e.bufferPos);break}let t=Ba(e);if(t===null)throw Error(`Invalid EBML lacing: bad frame size.`);let n=t;a.push(n);let r=n;for(let t=1;t<o-1;t++){let t=e.bufferPos,i=Ba(e);if(i===null)throw Error(`Invalid EBML lacing: bad frame size.`);let o=i-((1<<(e.bufferPos-t)*7-1)-1);n+=o,a.push(n),r+=n}a.push(e.length-(e.bufferPos+r))}break;default:t(!1)}if(a.length!==o||a.some(e=>e<=0))throw Error(`Invalid block lacing: frame sizes don't match the block.`);let s=i.duration||Math.round(o*(n.defaultDuration??0));for(let t=0;t<o;t++){let n=a[t],c=V(e,n),l=Math.floor(s*t/o),u=Math.floor(s*(t+1)/o);r.push({timestamp:i.timestamp+l,duration:u-l,isKeyFrame:i.isKeyFrame,data:c,lacing:eo.None,decoded:i.decoded,postProcessed:!1,mainAdditional:i.mainAdditional})}}return r}async loadSegmentMetadata(e){for(let n of e.seekEntries){if((n.id!==R.Tags||e.tagsSeen)&&(n.id!==R.Attachments||e.attachmentsSeen)||!this.claimSeekTarget(e.dataStartPos+n.segmentPosition))continue;let r=this.reader.requestSliceRange(e.dataStartPos+n.segmentPosition,2,16);if(j(r)&&(r=await r),!r)continue;let i=Ga(r);if(!i||i.id!==n.id)continue;let{size:a}=i;Qa(a);let o=this.reader.requestSlice(r.filePos,a);if(j(o)&&(o=await o),o){t(!this.currentSegment),this.currentSegment=e;try{this.readContiguousElements(o)}finally{this.currentSegment=null}}n.id===R.Tags?e.tagsSeen=!0:n.id===R.Attachments&&(e.attachmentsSeen=!0)}}claimSeekTarget(e){return!this.claimedSeekTargets.has(e)&&(this.claimedSeekTargets.add(e),!0)}readContiguousElements(e,t){if(this.elementNestingDepth===64)throw Error(`Invalid file: elements are nested too deeply.`);this.elementNestingDepth++;try{for(;e.remainingLength>=2;){let n=e.filePos;if(!this.traverseElement(e,t))return n}return e.filePos}finally{this.elementNestingDepth--}}traverseElement(e,r){let a=Ga(e);if(!a||r&&r.includes(a.id))return!1;let{id:o,size:s}=a,c=e.filePos;if(Qa(s),c+s>e.end)return!1;switch(o){case R.DocType:this.isWebM=Ka(e,s)===`webm`;break;case R.Seek:{if(!this.currentSegment)break;let t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(c,s)),(t.id===-1||t.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case R.SeekID:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=z(e,s)}break;case R.SeekPosition:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=z(e,s)}break;case R.TimestampScale:{if(!this.currentSegment)break;let t=s===0?1e6:z(e,s);if(t===0)throw Error(`Invalid TimestampScale element: must not be 0.`);this.currentSegment.timestampScale=t,this.currentSegment.timestampFactor=1e9/t}break;case R.Duration:if(!this.currentSegment)break;this.currentSegment.duration=Ja(e,s);break;case R.DateUTC:{if(!this.currentSegment)break;let t=Ha(e,s);this.currentSegment.metadataTags.creationTime=new Date(Ra+Number(t/1000000n))}break;case R.Title:if(!this.currentSegment)break;this.currentSegment.metadataTags.title??=qa(e,s);break;case R.TrackEntry:if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...Dt,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,codecDelay:0,codecDelayNs:0,name:null,languageCode:`eng`,hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(c,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(e=>e.data?.type!==`decompress`||e.scope!==to.Block||e.data.algorithm!==no.HeaderStripping)&&(M._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentSegment.idToTrack.has(this.currentTrack.id)&&(M._warn(`Track #${this.currentTrack.id} is defined more than once; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let e=this.currentTrack.codecId.indexOf(`/`),t=e===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if(this.currentTrack.info.type===`video`&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height;let e=this.currentTrack.info.displayWidth,n=this.currentTrack.info.displayHeight,r=this.currentTrack.info.stereoMode;if(e!==null&&[1,8,9,11].includes(r)&&(e*=2),n!==null&&[2,3,6,7].includes(r)&&(n*=2),this.currentTrack.info.displayUnit===0&&(e??=this.currentTrack.info.width,n??=this.currentTrack.info.height),this.currentTrack.info.displayUnit!==4&&e!==null&&n!==null){let t=e*this.currentTrack.info.height,r=n*this.currentTrack.info.width;t>0&&r>0&&(t>r?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*t/r):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*r/t))}if(this.currentTrack.codecId===Za.avc)this.currentTrack.info.codec=`avc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===Za.hevc)this.currentTrack.info.codec=`hevc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===Za.vp8)this.currentTrack.info.codec=`vp8`;else if(t===Za.vp9)this.currentTrack.info.codec=`vp9`;else if(t===Za.av1)this.currentTrack.info.codec=`av1`;else if(t===Za.prores){let e=this.currentTrack.codecPrivate?w.decode(this.currentTrack.codecPrivate):``;Gl.includes(e)&&(this.currentTrack.info.codec=`prores`,this.currentTrack.info.proresFormat=e)}let i=this.currentTrack;this.currentTrack.trackBacking=new so(i),this.currentSegment.tracks.push(this.currentTrack),this.currentSegment.idToTrack.set(this.currentTrack.id,this.currentTrack)}else if(this.currentTrack.info.type===`audio`){if(this.currentTrack.info.outputSampleRate!==null&&(this.currentTrack.info.sampleRate=this.currentTrack.info.outputSampleRate),t===Za.aac){if(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.codecPrivate&&this.currentTrack.codecId!==Za.aac){let e=this.currentTrack.codecId.split(`/`)[2]??``,t=[`MAIN`,`LC`,`SSR`,`LTP`].indexOf(e)+1;if(t===0)throw Error(`Unknown Matroska AAC codec ID '${this.currentTrack.codecId}'.`);let n=this.currentTrack.codecId.endsWith(`/SBR`);n&&this.currentTrack.info.outputSampleRate===null&&(this.currentTrack.info.sampleRate*=2),this.currentTrack.info.codecDescription=Ft({objectType:n?5:t,outputSampleRate:this.currentTrack.info.sampleRate,outputNumberOfChannels:this.currentTrack.info.numberOfChannels,programConfigElement:null})}}else this.currentTrack.codecId===Za.mp3?this.currentTrack.info.codec=`mp3`:t===Za.opus?(this.currentTrack.info.codec=`opus`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=ru):t===Za.vorbis?(this.currentTrack.info.codec=`vorbis`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Za.flac?(this.currentTrack.info.codec=`flac`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Za.ac3?(this.currentTrack.info.codec=`ac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Za.eac3?(this.currentTrack.info.codec=`eac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Za.dts?(this.currentTrack.info.codec=`dts`,this.currentTrack.codecId===`A_DTS/EXPRESS`?this.currentTrack.info.dtsFormat=`dtse`:this.currentTrack.codecId===`A_DTS/LOSSLESS`&&(this.currentTrack.info.dtsFormat=`dtsl`)):t===Za.truehd?this.currentTrack.info.codec=`truehd`: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 e=this.currentTrack;this.currentTrack.trackBacking=new co(e),this.currentSegment.tracks.push(this.currentTrack),this.currentSegment.idToTrack.set(this.currentTrack.id,this.currentTrack)}}this.currentTrack=null;break;case R.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=z(e,s);break;case R.TrackType:{if(!this.currentTrack)break;let t=z(e,s);t===1?this.currentTrack.info={type:`video`,width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:0,stereoMode:0,squarePixelWidth:-1,squarePixelHeight:-1,horizontalScale:1,verticalScale:1,rotation:0,codec:null,codecDescription:null,colorSpace:{...le},alphaMode:!1,proresFormat:null}:t===2&&(this.currentTrack.info={type:`audio`,numberOfChannels:1,sampleRate:8e3,outputSampleRate:null,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case R.FlagEnabled:if(!this.currentTrack)break;s===0||z(e,s)||(this.currentTrack=null);break;case R.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=s===0||!!z(e,s);break;case R.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!z(e,s);break;case R.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!z(e,s);break;case R.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!z(e,s);break;case R.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!z(e,s);break;case R.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!z(e,s);break;case R.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Ka(e,s);break;case R.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=V(e,s);break;case R.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=z(e,s);break;case R.CodecDelay:if(!this.currentTrack)break;this.currentTrack.codecDelayNs=z(e,s);break;case R.Name:if(!this.currentTrack)break;this.currentTrack.name=qa(e,s);break;case R.Language:if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=s===0?`eng`:Ka(e,s),Re(this.currentTrack.languageCode)||(this.currentTrack.languageCode=`und`);break;case R.LanguageBCP47:{if(!this.currentTrack)break;let t=Ka(e,s).split(`-`)[0];t?this.currentTrack.languageCode=t:this.currentTrack.languageCode=`und`,this.currentTrack.hasLanguageBcp47=!0}break;case R.Video:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(c,s));break;case R.PixelWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.width=z(e,s);break;case R.PixelHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.height=z(e,s);break;case R.DisplayWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayWidth=z(e,s);break;case R.DisplayHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayHeight=z(e,s);break;case R.DisplayUnit:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayUnit=z(e,s);break;case R.StereoMode:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.stereoMode=z(e,s);break;case R.AlphaMode:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.alphaMode=z(e,s)===1;break;case R.Colour:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(c,s));break;case R.MatrixCoefficients:{if(this.currentTrack?.info?.type!==`video`)break;let t=s===0?2:z(e,s),n=oe[t];this.currentTrack.info.colorSpace.matrix=n}break;case R.Range:{if(this.currentTrack?.info?.type!==`video`)break;let t=z(e,s);this.currentTrack.info.colorSpace.fullRange=t===1||t===2?t===2:void 0}break;case R.TransferCharacteristics:{if(this.currentTrack?.info?.type!==`video`)break;let t=s===0?2:z(e,s),n=ie[t];this.currentTrack.info.colorSpace.transfer=n}break;case R.Primaries:{if(this.currentTrack?.info?.type!==`video`)break;let t=s===0?2:z(e,s),n=ne[t];this.currentTrack.info.colorSpace.primaries=n}break;case R.Projection:{if(this.currentTrack?.info?.type!==`video`)break;let t=this.currentTrack.info,r={type:0,yaw:0,pitch:0,roll:0};if(this.currentProjection=r,this.readContiguousElements(e.slice(c,s)),this.currentProjection=null,r.type!==0)break;let a=e=>{try{return Math.round(Math.cos(i(e)*n))}catch{return 1}};t.horizontalScale=a(r.yaw),t.verticalScale=a(r.pitch);try{t.rotation=i(-r.roll)}catch{}}break;case R.ProjectionType:if(!this.currentProjection)break;this.currentProjection.type=z(e,s);break;case R.ProjectionPoseYaw:if(!this.currentProjection)break;this.currentProjection.yaw=Ja(e,s);break;case R.ProjectionPosePitch:if(!this.currentProjection)break;this.currentProjection.pitch=Ja(e,s);break;case R.ProjectionPoseRoll:if(!this.currentProjection)break;this.currentProjection.roll=Ja(e,s);break;case R.Audio:if(this.currentTrack?.info?.type!==`audio`)break;this.readContiguousElements(e.slice(c,s));break;case R.SamplingFrequency:{if(this.currentTrack?.info?.type!==`audio`)break;let t=s===0?8e3:Ja(e,s);if(!(t>0)||!Number.isFinite(t))throw Error(`Invalid SamplingFrequency element: must be a positive, finite number.`);this.currentTrack.info.sampleRate=t}break;case R.OutputSamplingFrequency:{if(this.currentTrack?.info?.type!==`audio`)break;let t=Ja(e,s);if(!(t>0)||!Number.isFinite(t))throw Error(`Invalid OutputSamplingFrequency element: must be a positive, finite number.`);this.currentTrack.info.outputSampleRate=t}break;case R.Channels:{if(this.currentTrack?.info?.type!==`audio`)break;let t=s===0?1:z(e,s);if(t===0)throw Error(`Invalid Channels element: must not be 0.`);this.currentTrack.info.numberOfChannels=t}break;case R.BitDepth:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.bitDepth=z(e,s);break;case R.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(c,s)),this.currentCueTime=null;break;case R.CueTime:this.currentCueTime=z(e,s);break;case R.CueTrackPositions:{if(this.currentCueTime===null||!this.currentSegment)break;let t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(c,s)),(t.trackId===-1||t.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case R.CueTrack:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=z(e,s)}break;case R.CueClusterPosition:{let n=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!n)break;t(this.currentSegment),n.clusterPosition=this.currentSegment.dataStartPos+z(e,s)}break;case R.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=z(e,s);break;case R.SimpleBlock:{if(!this.currentCluster)break;let t=e.slice(c,s),n=Ba(t);if(n===null||t.remainingLength<3)break;let r=this.getTrackDataInCluster(this.currentCluster,n);if(!r)break;let i=qc(t),a=H(t),o=a>>1&3,l=!!(a&128),u=V(t,t.remainingLength),d=r.track.decodingInstructions.length>0;r.blocks.push({timestamp:i,duration:0,isKeyFrame:l,data:u,lacing:o,decoded:!d,postProcessed:!1,mainAdditional:null})}break;case R.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(c,s)),this.currentBlock=null;break;case R.Block:{if(!this.currentCluster)break;let t=e.slice(c,s),n=Ba(t);if(n===null||t.remainingLength<3)break;let r=this.getTrackDataInCluster(this.currentCluster,n);if(!r)break;let i=qc(t),a=H(t)>>1&3,o=V(t,t.remainingLength),l=r.track.decodingInstructions.length>0;this.currentBlock={timestamp:i,duration:0,isKeyFrame:!0,data:o,lacing:a,decoded:!l,postProcessed:!1,mainAdditional:null},r.blocks.push(this.currentBlock)}break;case R.BlockAdditions:this.readContiguousElements(e.slice(c,s));break;case R.BlockMore:{let t=this.currentBlock;if(!t)break;let n={addId:1,data:null};this.currentBlockAdditional=n,this.readContiguousElements(e.slice(c,s)),n.data&&n.addId===1&&(t.mainAdditional=n.data),this.currentBlockAdditional=null}break;case R.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=V(e,s);break;case R.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=s===0?1:z(e,s);break;case R.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=z(e,s);break;case R.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case R.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(c,s));break;case R.Targets:this.readContiguousElements(e.slice(c,s));break;case R.TargetTypeValue:(s===0?50:z(e,s))!==50&&(this.currentTagTargetIsMovie=!1);break;case R.TagTrackUID:case R.TagEditionUID:case R.TagChapterUID:case R.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case R.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(c,s));break;case R.TagName:this.currentSimpleTagName=qa(e,s);break;case R.TagString:{if(!this.currentSimpleTagName)break;let t=qa(e,s);this.processTagValue(this.currentSimpleTagName,t)}break;case R.TagBinary:{if(!this.currentSimpleTagName)break;let t=V(e,s);this.processTagValue(this.currentSimpleTagName,t)}break;case R.AttachedFile:{if(!this.currentSegment||this.currentAttachedFile)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(c,s));let t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??={},t.raw[this.currentAttachedFile.fileUid.toString()]=new Tt(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 e=this.currentAttachedFile.fileName,n=`unknown`;if(e){let t=e.toLowerCase();t.startsWith(`cover.`)?n=`coverFront`:t.startsWith(`back.`)&&(n=`coverBack`)}t.images??=[],t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:n,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case R.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=Va(e,s);break;case R.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=qa(e,s);break;case R.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Ka(e,s);break;case R.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=V(e,s);break;case R.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=qa(e,s);break;case R.ContentEncodings:{let t=this.currentTrack;if(!t)break;this.readContiguousElements(e.slice(c,s)),t.decodingInstructions.sort((e,t)=>t.order-e.order)}break;case R.ContentEncoding:{let t=this.currentTrack;if(!t)break;let n={order:0,scope:to.Block,data:null};this.currentDecodingInstruction=n,this.readContiguousElements(e.slice(c,s)),n.data&&t.decodingInstructions.push(n),this.currentDecodingInstruction=null}break;case R.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=z(e,s);break;case R.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=s===0?to.Block:z(e,s);break;case R.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decompress`,algorithm:no.Zlib,settings:null},this.readContiguousElements(e.slice(c,s));break;case R.ContentCompAlgo:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.algorithm=z(e,s);break;case R.ContentCompSettings:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.settings=V(e,s);break;case R.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decrypt`}}return e.filePos=c+s,!0}decodeBlockData(e,n){t(e.decodingInstructions.length>0);let r=n;for(let n of e.decodingInstructions)if(t(n.data),n.data.type===`decompress`)switch(n.data.algorithm){case no.HeaderStripping:if(n.data.settings&&n.data.settings.length>0){let e=n.data.settings,t=new Uint8Array(e.length+r.length);t.set(e,0),t.set(r,e.length),r=t}}return r}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=t,typeof t==`string`)switch(e.toLowerCase()){case`title`:n.title??=t;break;case`description`:n.description??=t;break;case`artist`:n.artist??=t;break;case`album`:n.album??=t;break;case`album_artist`:n.albumArtist??=t;break;case`genre`:n.genre??=t;break;case`bpm`:{let e=Number.parseInt(t,10);Number.isInteger(e)&&e>0&&(n.beatsPerMinute??=e)}break;case`comment`:n.comment??=t;break;case`lyrics`:n.lyrics??=t;break;case`date`:{let e=St(t);e&&(n.date??=e)}break;case`track_number`:case`part_number`:{let e=t.split(`/`),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(n.trackNumber??=r),i&&Number.isInteger(i)&&i>0&&(n.tracksTotal??=i)}break;case`disc_number`:case`disc`:{let e=t.split(`/`),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(n.discNumber??=r),i&&Number.isInteger(i)&&i>0&&(n.discsTotal??=i)}}}getDurationFromMetadata(e){if(e.duration<=0)return null;let t=Math.min(...e.tracks.map(e=>e.codecDelay));return(e.duration-t)/e.timestampFactor}},oo=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=/* @__PURE__ */ new WeakMap}getNumber(){let e=this.internalTrack.demuxer,n=this.internalTrack.trackBacking.getType(),r=0;for(let t of e.segments)for(let e of t.tracks)if(e.trackBacking.getType()===n&&r++,e===this.internalTrack)return r;t(!1)}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Ae(e*this.internalTrack.segment.timestampFactor)+this.internalTrack.codecDelay}async getPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let r=D(t.presentationTimestamps,n,e=>e.timestamp);return{blockIndex:r===-1?-1:t.presentationTimestamps[r].blockIndex,correctBlockFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw Error(`Packet was not created from this track.`);return this.performClusterLookup(n.cluster,e=>{if(e===n.cluster){let t=e.trackData.get(this.internalTrack.id);if(n.blockIndex+1<t.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let r=be(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=n);return{blockIndex:r===-1?-1:t.presentationTimestamps[r].blockIndex,correctBlockFound:r!==-1&&n<t.endTimestamp}},n,n,t,!0)}async getNextKeyPacket(e,n){let r=this.packetToClusterLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performClusterLookup(r.cluster,e=>{if(e===r.cluster){let t=e.trackData.get(this.internalTrack.id);for(let e=r.blockIndex+1;e<t.blocks.length;e++)if(t.blocks[e].isKeyFrame)return{blockIndex:e,correctBlockFound:!0}}else{let n=e.trackData.get(this.internalTrack.id);if(n&&n.firstKeyFrameTimestamp!==null){let e=n.blocks.findIndex(e=>e.isKeyFrame);return t(e!==-1),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,n)}async fetchPacketInCluster(e,n,r){if(n===-1)return null;let i=e.trackData.get(this.internalTrack.id).blocks[n];if(t(i),i.decoded||=(i.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,i.data),!0),!i.postProcessed){if(this.internalTrack.info?.codec===`prores`&&!(i.data.length>=8&&i.data[4]===105&&i.data[5]===99&&i.data[6]===112&&i.data[7]===102)){let e=new Uint8Array(i.data.length+8);x(e).setUint32(0,e.length,!1),e[4]=105,e[5]=99,e[6]=112,e[7]=102,e.set(i.data,8),i.data=e}i.postProcessed=!0}let a=r.metadataOnly?Li:i.data,{codecDelay:o,segment:s}=this.internalTrack,c=(i.timestamp-o)/s.timestampFactor,l=i.duration/s.timestampFactor,u={};i.mainAdditional&&this.internalTrack.info?.type===`video`&&this.internalTrack.info.alphaMode&&(u.alpha=r.metadataOnly?Li:i.mainAdditional,u.alphaByteLength=i.mainAdditional.byteLength);let d=new L(a,i.isKeyFrame?`key`:`delta`,c,l,e.dataStartPos+n,i.data.byteLength,u);return this.packetToClusterLocation.set(d,{cluster:e,blockIndex:n}),d}async performClusterLookup(e,n,r,i,a,o=!1){let{demuxer:s,segment:c,cuePoints:l,clusterPositionCache:u}=this.internalTrack,d=null,f=-1;if(e){let{blockIndex:t,correctBlockFound:r}=n(e);if(r)return this.fetchPacketInCluster(e,t,a);t!==-1&&(d=e,f=t)}let p=D(l,r,e=>e.time),m=D(u,r,e=>e.startTimestamp),h=1/0;for(;;){for(;p!==-1&&l[p].clusterPosition>=h;)p--;for(;m!==-1&&(u[m].elementStartPos>=h||o&&!u[m].hasKeyFrame);)m--;let r=Math.max(l[p]?.clusterPosition??0,u[m]?.elementStartPos??0)||null,g,_=null;e?r===null||e.elementStartPos>=r?(g=e.elementEndPos,_=e):g=r:g=r??c.clusterSeekStartPos;let v=_?_.elementStartPos:g;for(;(c.elementEndPos===null||g<=c.elementEndPos-2)&&g<h;){if(_){let e=_.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>i)break;_=null}let e=c.clusterSummaries.get(g);if(e&&!e.trackIds.has(this.internalTrack.id)){g=e.elementEndPos;continue}let r=s.reader.requestSliceRange(g,2,16);if(j(r)&&(r=await r),!r)break;let o=g,l=Ga(r);if(c.elementEndPos===null&&l&&ka.includes(l.id)){c.elementEndPos=o;break}if(!l||!Aa.includes(l.id)&&l.id!==R.Void){let e=await Xa(s.reader,o+1,Aa,Math.min(c.elementEndPos??1/0,o+io));if(e){g=e;continue}break}let u=l.id,p=l.size,m=r.filePos;if(u===R.Cluster){_=await s.readCluster(o,c),p=_.elementEndPos-m;let{blockIndex:e,correctBlockFound:t}=n(_);if(t)return this.fetchPacketInCluster(_,e,a);e!==-1&&(d=_,f=e)}p===void 0&&(t(u!==R.Cluster),p=(await Ya(s.reader,m,ja,c.elementEndPos)).pos-m),g=m+p}if(r===null||d&&d.elementStartPos>=r)break;h=v,e=null}return d?this.fetchPacketInCluster(d,f,a):null}},so=class extends oo{constructor(e){super(e),this.decoderConfigPromise=null}getType(){return`video`}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}getTransformationMatrix(){let e=this.internalTrack.info,t=f(d(e.horizontalScale,e.verticalScale),l(e.rotation));return o(t,e.width,e.height)}async getColorSpace(){let e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}async canBeTransparent(){return this.internalTrack.info.alphaMode||this.internalTrack.info.codec===`prores`&&(this.internalTrack.info.proresFormat===`ap4h`||this.internalTrack.info.proresFormat===`ap4x`)}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=this.internalTrack.codecPrivate,t=this.internalTrack.info.codec===`av1`&&e?Vn(e.subarray(4)):null,n=null;(this.internalTrack.info.codec===`vp9`||this.internalTrack.info.codec===`av1`&&!t||this.internalTrack.info.codec===`prores`||this.internalTrack.info.codec===`avc`&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription)&&(n=await this.getFirstPacket({})),this.internalTrack.info.codec===`av1`&&n&&(t=Vn(n.data));let r={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`&&n?pn(n.data):null,hevcType:`hev1`,hevcCodecInfo:this.internalTrack.info.codec===`hevc`&&n?Tn(n.data):null,vp9CodecInfo:this.internalTrack.info.codec===`vp9`&&n?Rn(n.data):null,av1CodecInfo:t,proresCodecInfo:this.internalTrack.info.codec===`prores`&&n?Un(n.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!se(this.internalTrack.info.colorSpace)){let e=Ql(r);this.internalTrack.info.colorSpace.primaries??=e.primaries,this.internalTrack.info.colorSpace.transfer??=e.transfer,this.internalTrack.info.colorSpace.matrix??=e.matrix,this.internalTrack.info.colorSpace.fullRange??=e.fullRange}let i={codec:Zl(r),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(i.displayAspectWidth=this.internalTrack.info.squarePixelWidth,i.displayAspectHeight=this.internalTrack.info.squarePixelHeight),i})():null}},co=class extends oo{constructor(e){super(e),this.decoderConfigPromise=null}getType(){return`audio`}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.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`dts`&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&vr(e.data)}return{codec:eu({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}},lo
191
+ /*!
192
+ * Copyright (c) 2026-present, Vanilagy and contributors
193
+ *
194
+ * This Source Code Form is subject to the terms of the Mozilla Public
195
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
196
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
197
+ */
198
+ ;(function(e){e[e.Unsynchronisation=128]=`Unsynchronisation`,e[e.ExtendedHeader=64]=`ExtendedHeader`,e[e.ExperimentalIndicator=32]=`ExperimentalIndicator`,e[e.Footer=16]=`Footer`})(lo||={});var uo;(function(e){e[e.ISO_8859_1=0]=`ISO_8859_1`,e[e.UTF_16_WITH_BOM=1]=`UTF_16_WITH_BOM`,e[e.UTF_16_BE_NO_BOM=2]=`UTF_16_BE_NO_BOM`,e[e.UTF_8=3]=`UTF_8`})(uo||={});const fo=/* @__PURE__ */ `Blues.Classic rock.Country.Dance.Disco.Funk.Grunge.Hip-hop.Jazz.Metal.New age.Oldies.Other.Pop.Rhythm and blues.Rap.Reggae.Rock.Techno.Industrial.Alternative.Ska.Death metal.Pranks.Soundtrack.Euro-techno.Ambient.Trip-hop.Vocal.Jazz & funk.Fusion.Trance.Classical.Instrumental.Acid.House.Game.Sound clip.Gospel.Noise.Alternative rock.Bass.Soul.Punk.Space.Meditative.Instrumental pop.Instrumental rock.Ethnic.Gothic.Darkwave.Techno-industrial.Electronic.Pop-folk.Eurodance.Dream.Southern rock.Comedy.Cult.Gangsta.Top 40.Christian rap.Pop/funk.Jungle music.Native US.Cabaret.New wave.Psychedelic.Rave.Showtunes.Trailer.Lo-fi.Tribal.Acid punk.Acid jazz.Polka.Retro.Musical.Rock 'n' roll.Hard rock.Folk.Folk rock.National folk.Swing.Fast fusion.Bebop.Latin.Revival.Celtic.Bluegrass.Avantgarde.Gothic rock.Progressive rock.Psychedelic rock.Symphonic rock.Slow rock.Big band.Chorus.Easy listening.Acoustic.Humour.Speech.Chanson.Opera.Chamber music.Sonata.Symphony.Booty bass.Primus.Porn groove.Satire.Slow jam.Club.Tango.Samba.Folklore.Ballad.Power ballad.Rhythmic Soul.Freestyle.Duet.Punk rock.Drum solo.A cappella.Euro-house.Dance hall.Goa music.Drum & bass.Club-house.Hardcore techno.Terror.Indie.Britpop.Negerpunk.Polsk punk.Beat.Christian gangsta rap.Heavy metal.Black metal.Crossover.Contemporary Christian.Christian rock.Merengue.Salsa.Thrash metal.Anime.Jpop.Synthpop.Christmas.Art rock.Baroque.Bhangra.Big beat.Breakbeat.Chillout.Downtempo.Dub.EBM.Eclectic.Electro.Electroclash.Emo.Experimental.Garage.Global.IDM.Illbient.Industro-Goth.Jam Band.Krautrock.Leftfield.Lounge.Math rock.New romantic.Nu-breakz.Post-punk.Post-rock.Psytrance.Shoegaze.Space rock.Trop rock.World music.Neoclassical.Audiobook.Audio theatre.Neue Deutsche Welle.Podcast.Indie rock.G-Funk.Dubstep.Garage rock.Psybient`.split(`.`),po=(e,t)=>{let n=e.filePos;t.raw??={},t.raw.TAG??=V(e,125),e.filePos=n;let r=mo(e,30);r&&(t.title??=r);let i=mo(e,30);i&&(t.artist??=i);let a=mo(e,30);a&&(t.album??=a);let o=mo(e,4),s=Number.parseInt(o,10);Number.isInteger(s)&&s>0&&(t.date??=bt(s));let c=V(e,30),l;if(c[28]===0&&c[29]!==0){let n=c[29];n>0&&(t.trackNumber??=n),e.skip(-30),l=mo(e,28),e.skip(2)}else e.skip(-30),l=mo(e,30);l&&(t.comment??=l);let u=H(e);u<fo.length&&(t.genre??=fo[u])},mo=(e,t)=>{let n=V(e,t),r=tt(n.indexOf(0),n.length),i=n.subarray(0,r),a=``;for(let e=0;e<i.length;e++)a+=String.fromCharCode(i[e]);return a.trimEnd()},ho=async(e,t)=>{let n=t;for(;;){let t=e.requestSlice(n,10);if(j(t)&&(t=await t),!t)return n;let r=go(t);if(!r)return n;n=t.filePos+r.size}},go=e=>{let t=e.filePos,n=G(e,3),r=H(e),i=H(e),a=H(e),o=W(e);if(n!==`ID3`||r===255||i===255||o&2155905152)return e.filePos=t,null;let s=Xt(o);return r===4&&a&lo.Footer&&(s+=10),{majorVersion:r,revision:i,flags:a,size:s}},_o=(e,t,n)=>{if(![2,3,4].includes(t.majorVersion)){M._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}if(t.majorVersion===2&&t.flags&lo.ExtendedHeader){M._warn(`Skipping compressed ID3v2.2 tag`);return}let r=t.majorVersion===4&&t.flags&lo.Footer?t.size-10:t.size,i=new vo(t,V(e,r));if(t.flags&lo.Unsynchronisation&&t.majorVersion<=3&&i.ununsynchronizeAll(),t.flags&lo.ExtendedHeader){if(i.bytes.length<4)return;let e=i.readU32();t.majorVersion===3?i.pos+=e:i.pos+=Xt(e)-4}let a=null,o=null;for(;i.pos<=i.bytes.length-i.frameHeaderSize();){let e=i.readId3V2Frame();if(!e)break;let r=Math.min(i.pos+e.size,i.bytes.length),s=r,c=!1,l=!1,u=!1,d=!1,f=!1;if(t.majorVersion===3?(c=!!(e.flags&64),l=!!(e.flags&128),d=!!(e.flags&32)):t.majorVersion===4&&(d=!!(e.flags&64),c=!!(e.flags&4),l=!!(e.flags&8),u=!!(e.flags&2)||!!(t.flags&lo.Unsynchronisation),f=!!(e.flags&1)),c){M._warn(`Skipping encrypted ID3v2 frame ${e.id}`),i.pos=r;continue}if(l){M._warn(`Skipping compressed ID3v2 frame ${e.id}`),i.pos=r;continue}d&&(i.pos+=1),f&&(i.pos+=4),u&&(s=i.ununsynchronizeRegion(i.pos,s));let p=i.pos,m=t=>{if(s-i.pos<t)throw Error(`Invalid ID3v2 ${e.id} frame: too short.`)};if(n.raw??={},e.id===`TXXX`||e.id===`TXX`){let t=n.raw[e.id]??={};m(1);let r=i.readId3V2TextEncoding(),a=i.readId3V2Text(r,s),o=i.readId3V2Text(r,s);t[a]??=o}else if(e.id[0]===`T`)n.raw[e.id]??=i.readId3V2EncodingAndText(s);else{let t=i.readBytes(s-i.pos),r=n.raw[e.id];r instanceof Uint8Array?n.raw[e.id]=[r,t]:Array.isArray(r)?r.push(t):n.raw[e.id]??=t}switch(i.pos=p,e.id){case`TIT2`:case`TT2`:n.title??=i.readId3V2EncodingAndText(s);break;case`TIT3`:case`TT3`:n.description??=i.readId3V2EncodingAndText(s);break;case`TPE1`:case`TP1`:n.artist??=i.readId3V2EncodingAndText(s);break;case`TALB`:case`TAL`:n.album??=i.readId3V2EncodingAndText(s);break;case`TPE2`:case`TP2`:n.albumArtist??=i.readId3V2EncodingAndText(s);break;case`TRCK`:case`TRK`:{let e=i.readId3V2EncodingAndText(s).split(`/`),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.trackNumber??=t),r&&Number.isInteger(r)&&r>0&&(n.tracksTotal??=r)}break;case`TPOS`:case`TPA`:{let e=i.readId3V2EncodingAndText(s).split(`/`),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.discNumber??=t),r&&Number.isInteger(r)&&r>0&&(n.discsTotal??=r)}break;case`TCON`:case`TCO`:{let e=i.readId3V2EncodingAndText(s),t=/^\((\d+)\)/.exec(e);if(t){let e=Number.parseInt(t[1]);if(fo[e]!==void 0){n.genre??=fo[e];break}}if(t=/^\d+$/.exec(e),t){let e=Number.parseInt(t[0]);if(fo[e]!==void 0){n.genre??=fo[e];break}}n.genre??=e}break;case`TDRC`:{let e=St(i.readId3V2EncodingAndText(s));e&&(n.date??=e)}break;case`TYER`:case`TYE`:{let e=i.readId3V2EncodingAndText(s),t=Number.parseInt(e,10);Number.isInteger(t)&&(a??=t)}break;case`TDAT`:case`TDA`:o??=i.readId3V2EncodingAndText(s);break;case`TBPM`:case`TBP`:{let e=i.readId3V2EncodingAndText(s),t=Number.parseInt(e,10);Number.isInteger(t)&&t>0&&(n.beatsPerMinute??=t)}break;case`USLT`:case`ULT`:{m(4);let e=i.readId3V2TextEncoding();i.pos+=3,i.readId3V2Text(e,s),n.lyrics??=i.readId3V2Text(e,s)}break;case`COMM`:case`COM`:{m(4);let e=i.readId3V2TextEncoding();i.pos+=3,i.readId3V2Text(e,s)===``&&(n.comment??=i.readId3V2Text(e,s))}break;case`APIC`:case`PIC`:{m(1);let e=i.readId3V2TextEncoding(),r;if(t.majorVersion===2){m(3);let e=i.readAscii(3);r=e===`PNG`?`image/png`:e===`JPG`?`image/jpeg`:`image/*`}else r=i.readId3V2Text(uo.ISO_8859_1,s);m(1);let a=i.readU8(),o=i.readId3V2Text(e,s).trimEnd(),c=s-i.pos;if(c>=0){let e=i.readBytes(c);n.images||=[],n.images.push({data:e,mimeType:r,kind:a===3?`coverFront`:a===4?`coverBack`:`unknown`,description:o})}}break;default:i.pos+=e.size}i.pos=r}if(a!==null){let e=bt(a),t=/^(0[1-9]|[12]\d|3[01])(0[1-9]|1[0-2])$/.exec(o??``);if(t){let n=Number(t[1]),r=bt(a,Number(t[2])-1,n);r.getUTCDate()===n&&(e=r)}Number.isNaN(e.getTime())||(n.date??=e)}};var vo=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.ownsBytes=!1,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=new Uint8Array(this.bytes.length),t=0;for(let n=0;n<this.bytes.length;n++){let r=this.bytes[n];e[t++]=r,r===255&&n!==this.bytes.length-1&&this.bytes[n+1]===0&&n++}this.bytes=e.subarray(0,t),this.view=x(this.bytes)}ununsynchronizeRegion(e,t){this.ownsBytes||=(this.bytes=this.bytes.slice(),this.view=x(this.bytes),!0);let n=e;for(let r=e;r<t;r++){let e=this.bytes[r];this.bytes[n++]=e,e===255&&r!==t-1&&this.bytes[r+1]===0&&r++}return n}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+2);return this.pos+=3,e*256+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t=``;for(let n=0;n<e;n++)t+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);return e===`\0\0\0`?null:{id:e,size:this.readU24(),flags:0}}{let e=this.readAscii(4);if(e===`\0\0\0\0`)return null;let t=this.readU32(),n=!(t&2155905152),r=this.header.majorVersion===4&&n?Xt(t):t,i=this.readU16(),a=this.pos,o=e=>{let t=a+e;if(t>this.bytes.length)return!1;if(t<=this.bytes.length-this.frameHeaderSize()){this.pos=t;let e=this.readAscii(4);if(e!==`\0\0\0\0`&&!/[0-9A-Z]{4}/.test(e))return!1}return!0};if(n&&!o(r)){let e=this.header.majorVersion===4?t:Xt(t);o(e)&&(r=e)}return this.pos=a,{id:e,size:r,flags:i}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let n=this.pos,r=this.readBytes(t-this.pos);switch(e){case uo.ISO_8859_1:{let e=``;for(let t=0;t<r.length;t++){let i=r[t];if(i===0){this.pos=n+t+1;break}e+=String.fromCharCode(i)}return e}case uo.UTF_16_WITH_BOM:if(r[0]===255&&r[1]===254){let e=new C(`utf-16le`),t=tt(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}if(r[0]===254&&r[1]===255){let e=new C(`utf-16be`),t=tt(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}if(r[0]===0&&r[1]===0)return this.pos=n+2,``;{let e=tt(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),w.decode(r.subarray(0,e))}case uo.UTF_16_BE_NO_BOM:{let e=new C(`utf-16be`),t=tt(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(0,t))}case uo.UTF_8:{let e=tt(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),w.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return``;let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}};
199
+ /*!
200
+ * Copyright (c) 2026-present, Vanilagy and contributors
201
+ *
202
+ * This Source Code Form is subject to the terms of the Mozilla Public
203
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
204
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
205
+ */
206
+ const yo=async(e,t,n,r)=>{let i=t;for(;;){let a=await bo(e,i,t+n,r);if(!a)return null;let{header:o}=a,s=Jt(o.mpegVersionId,o.channel),c=e.requestSlice(a.startPos+s,4);if(j(c)&&(c=await c),c){let e=W(c);if(e===1483304551||e===1231971951)return a}let l=a.startPos+o.totalSize;if(l===e.fileSize)return a;if(l+128===e.fileSize){let t=e.requestSlice(l,3);if(j(t)&&(t=await t),t&&G(t,3)===`TAG`)return a}let u=await bo(e,l,l+4);if(u&&u.header.channel===o.channel&&u.header.sampleRate===o.sampleRate)return a;i=a.startPos+1}},bo=async(e,t,n,r=null)=>{let i=2**16,a=t;for(;n===null||a<n;){let t=n===null?i:Math.min(i,n-a),o=e.requestSliceRange(a,4,t);if(j(o)&&(o=await o),!o||o.length<4)break;for(;o.remainingLength>=4;){let t=o.filePos,n=W(o),i=e.fileSize===null?null:e.fileSize-a,s=Yt(n,i);if(s.header&&(!r||s.header.sampleRate===r.sampleRate&&s.header.mpegVersionId===r.mpegVersionId&&s.header.layer===r.layer&&Qt(s.header.channel)===Qt(r.channel)))return{header:s.header,startPos:a};o.filePos=t+s.bytesAdvanced,a=o.filePos}}return null}
207
+ /*!
208
+ * Copyright (c) 2026-present, Vanilagy and contributors
209
+ *
210
+ * This Source Code Form is subject to the terms of the Mozilla Public
211
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
212
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
213
+ */
214
+ ;var xo=class extends zi{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.xingFrameHeader=null,this.xingFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new de,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.primingDelay=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw Error(`No valid MP3 frame found.`);this.trackBackings=[new So(this)]})()}async advanceReader(){let e;if(this.lastLoadedPos===0){let t=await ho(this.reader,0);e=await yo(this.reader,t,4096,null)}else if(e=await bo(this.reader,this.lastLoadedPos,this.lastLoadedPos+2,this.firstFrameHeader),!e){if(this.firstFrameHeader){let e=this.reader.requestSlice(this.lastLoadedPos,5);if(j(e)&&(e=await e),e)for(let t=0;t<2;t++){e.filePos=this.lastLoadedPos+t;let{header:n}=Yt(W(e),null);if(n&&n.sampleRate!==this.firstFrameHeader.sampleRate){M._warn(`The sample rate changes mid-stream (from ${this.firstFrameHeader.sampleRate} Hz to ${n.sampleRate} Hz), which isn't properly supported or handled by Mediabunny.`),this.lastSampleLoaded=!0;return}}}let t=await ho(this.reader,this.lastLoadedPos+1);e=await yo(this.reader,t,2**16,this.firstFrameHeader)}if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let n=Jt(t.mpegVersionId,t.channel),r=this.reader.requestSlice(e.startPos+n,4);if(j(r)&&(r=await r),r){let i=W(r);if(i===1483304551||i===1231971951){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let r=this.reader.requestSlice(e.startPos+n+4,8);if(j(r)&&(r=await r),r){let a=V(r,8),o=x(a),s=o.getUint32(0,!1);this.xingData={isVbr:i===1483304551,frameCount:s&Zt.FrameCount?o.getUint32(4,!1):null};let c=e.startPos+n+8+(s&Zt.FrameCount?4:0)+(s&Zt.FileSize?4:0)+(s&Zt.Toc?100:0)+(s&Zt.Quality?4:0);if(!this.firstFrameHeader&&c+24<=e.startPos+t.totalSize){let e=this.reader.requestSlice(c,24);if(j(e)&&(e=await e),e){let t=V(e,24),n=String.fromCharCode(...t.subarray(0,4));(n===`LAME`||n===`Lavf`||n===`Lavc`)&&(this.primingDelay=(t[21]<<4|t[22]>>4)+529,this.nextTimestampInSamples=-this.primingDelay)}}}}return}}let i=t.layer===1?this.reader.requestSlice(e.startPos+4+32,18):null;if(j(i)&&(i=await i),i){let n=W(i),r=U(i);if(n===1447187017&&r===1){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){i.skip(8);let e=W(i);this.xingData={isVbr:!0,frameCount:e}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);let a=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,o={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:a,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(o),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return`audio/mpeg`}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,n=!1;for(;;){let t=this.reader.requestSlice(e,10);if(j(t)&&(t=await t),!t)break;let r=go(t);if(!r)break;n=!0;let i=this.reader.requestSlice(t.filePos,r.size);if(j(i)&&(i=await i),!i)break;_o(i,r,this.metadataTags),e=t.filePos+r.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=128){let e=this.reader.requestSlice(this.reader.fileSize-128,128);j(e)&&(e=await e),t(e),G(e,3)===`TAG`&&po(e,this.metadataTags)}return this.metadataTags}finally{e()}}},So=class{constructor(e){this.demuxer=e}getType(){return`audio`}getNumber(){return 1}getTimeResolution(){return t(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.demuxer;if(t(e.firstFrameHeader!==null),t(e.firstFrameHeaderPos!==null),e.xingData&&e.xingData.frameCount!==null)return(e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame-e.primingDelay)/e.firstFrameHeader.sampleRate;if(!e.xingData?.isVbr&&e.reader.fileSize!==null){let n=e.reader.fileSize;if(n-e.firstFrameHeaderPos>=128){let r=e.reader.requestSlice(n-128,3);j(r)&&(r=await r),t(r),G(r,3)===`TAG`&&(n-=128)}if(n-e.firstFrameHeaderPos>=32){let r=e.reader.requestSlice(n-32,32);if(j(r)&&(r=await r),t(r),G(r,8)===`APETAGEX`){r.skip(4);let t=Yc(r);r.skip(4);let i=!!(Yc(r)&1<<31);if(n-=t+(i?32:0),n<e.firstFrameHeaderPos)throw Error(`Invalid APE tag size.`)}}let r=qt(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate),i=(n-e.firstFrameHeaderPos)/r;return(Math.round(i)*e.firstFrameHeader.audioSamplesInFrame-e.primingDelay)/e.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return`und`}getCodec(){return`mp3`}getInternalCodecId(){return null}getNumberOfChannels(){return t(this.demuxer.firstFrameHeader),Qt(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return t(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...Dt}}async getDecoderConfig(){return t(this.demuxer.firstFrameHeader),{codec:`mp3`,numberOfChannels:Qt(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=Li;else{let e=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(j(e)&&(e=await e),!e)return null;r=V(e,n.dataSize)}return new L(r,`key`,n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=ge(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(n===-1)throw Error(`Packet was not created from this track.`);let r=n+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=this.getSampleRate(),r=Ae(e*n)/n;for(;;){let e=D(this.demuxer.loadedSamples,r,e=>e.timestamp);if(e===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||e>=0&&e+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(e,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};
215
+ /*!
216
+ * Copyright (c) 2026-present, Vanilagy and contributors
217
+ *
218
+ * This Source Code Form is subject to the terms of the Mozilla Public
219
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
220
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
221
+ */
222
+ const Co=/* @__PURE__ */ new Uint32Array(256);for(let e=0;e<256;e++){let t=e<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^79764919:t<<1;Co[e]=t>>>0|0}const wo=e=>{let t=x(e),n=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let t=0;t<e.length;t++){let n=e[t];r=(r<<8^Co[r>>>24^n])>>>0}return t.setUint32(22,n,!0),r},To=(e,n,r)=>{let i=0,a=null;if(e.length>0){if(n.codec===`vorbis`){t(n.vorbisInfo);let o=n.vorbisInfo.modeBlockflags.length,s=(1<<Fe(o-1))-1<<1,c=(e[0]&s)>>1;if(c>=n.vorbisInfo.modeBlockflags.length)throw Error(`Invalid mode number.`);let l=r??n.vorbisInfo.blocksizes[0],u=n.vorbisInfo.modeBlockflags[c];if(a=n.vorbisInfo.blocksizes[u],u===1){let t=(s|1)+1,r=e[0]&t?1:0;l=n.vorbisInfo.blocksizes[r]}i=l+a>>2}else n.codec===`opus`&&(i=Kn(e).durationInSamples)}return{durationInSamples:i,vorbisBlockSize:a}},Eo=e=>{let t=`audio/ogg`;if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},Do=65307,Oo=e=>{
223
+ /*!
224
+ * Copyright (c) 2026-present, Vanilagy and contributors
225
+ *
226
+ * This Source Code Form is subject to the terms of the Mozilla Public
227
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
228
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
229
+ */
230
+ let t=e.filePos;if(Yc(e)!==1399285583)return null;e.skip(1);let n=H(e),r=tl(e),i=Yc(e),a=Yc(e),o=Yc(e),s=H(e);if(s===0||e.remainingLength<s)return null;let c=new Uint8Array(s);for(let t=0;t<s;t++)c[t]=H(e);let l=27+s,u=c.reduce((e,t)=>e+t,0);return{headerStartPos:t,totalSize:l+u,dataStartPos:t+l,dataSize:u,headerType:n,granulePosition:r,serialNumber:i,sequenceNumber:a,checksum:o,lacingValues:c}},ko=(e,t,n)=>{for(;e.filePos<t-3;){let t=Yc(e),r=t&255,i=t>>>8&255,a=t>>>16&255,o=t>>>24&255;if(r===79||i===79||a===79||o===79){if(e.skip(-4),t===1399285583){if(n===void 0||e.filePos+18>e.end)return!0;e.skip(14);let t=Yc(e);if(e.skip(-18),t===n)return!0}e.skip(1)}}return!1}
231
+ /*!
232
+ * Copyright (c) 2026-present, Vanilagy and contributors
233
+ *
234
+ * This Source Code Form is subject to the terms of the Mozilla Public
235
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
236
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
237
+ */
238
+ ;var Ao=class extends zi{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,27,282);if(j(t)&&(t=await t),!t)break;let n=Oo(t);if(!n||!(n.headerType&2))break;if(this.bitstreams.length===64)throw Error(`Too many (> 64) logical bitstreams.`);this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let e of this.bitstreams){let t=await this.readPacket(e.bosPage,0);t&&(t.data.byteLength>=30&&t.data[0]===1&&t.data[1]===118&&t.data[2]===111&&t.data[3]===114&&t.data[4]===98&&t.data[5]===105&&t.data[6]===115?await this.readVorbisMetadata(t,e):t.data.byteLength>=19&&t.data[0]===79&&t.data[1]===112&&t.data[2]===117&&t.data[3]===115&&t.data[4]===72&&t.data[5]===101&&t.data[6]===97&&t.data[7]===100&&await this.readOpusMetadata(t,e),e.codecInfo.codec!==null&&this.trackBackings.push(new jo(e,this)))}})()}async readVorbisMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let r=await this.readPacket(n.startPage,n.startSegmentIndex);if(!r||(n=await this.findNextPacketStart(r),!n))return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i||r.data[0]!==3||i.data[0]!==5)return;let a=x(e.data),o=a.getUint8(11),s=a.getUint32(12,!0);if(o===0||s===0)throw Error(`Invalid Vorbis identification header: channel count and sample rate must not be 0.`);let c=[],l=e=>{for(;c.push(Math.min(255,e)),!(e<255);)e-=255};l(e.data.length),l(r.data.length);let u=new Uint8Array(1+c.length+e.data.length+r.data.length+i.data.length);u[0]=2,u.set(c,1),u.set(e.data,1+c.length),u.set(r.data,1+c.length+e.data.length),u.set(i.data,1+c.length+e.data.length+r.data.length),t.codecInfo.codec=`vorbis`,t.description=u,t.lastMetadataPacket=i,t.numberOfChannels=o,t.sampleRate=s;let d=a.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(d&15),1<<(d>>4)],modeBlockflags:qn(i.data).modeBlockflags},Qn(r.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let r=await this.readPacket(n.startPage,n.startSegmentIndex);if(!r)return;t.codecInfo.codec=`opus`,t.description=e.data,t.lastMetadataPacket=r;let i=Wn(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=ru,t.codecInfo.opusInfo={preSkip:i.preSkip},Qn(r.data.subarray(8),this.metadataTags)}async readPacket(e,n){t(n<e.lacingValues.length);let r=0;for(let t=0;t<n;t++)r+=e.lacingValues[t];let i=e,a=r,o=n,s=[];outer:for(;;){let t=this.reader.requestSlice(i.dataStartPos,i.dataSize);if(j(t)&&(t=await t),!t)return null;let n=V(t,i.dataSize);for(;;){if(o===i.lacingValues.length){s.push(n.subarray(r,a));break}let e=i.lacingValues[o];if(a+=e,e<255){s.push(n.subarray(r,a));break outer}o++}let c=i.headerStartPos+i.totalSize;for(;;){let t=this.reader.requestSliceRange(c,27,282);if(j(t)&&(t=await t),!t)return null;let n=Oo(t);if(!n)return null;if(i=n,i.serialNumber===e.serialNumber)break;c=i.headerStartPos+i.totalSize}r=0,a=0,o=0}let c=s.reduce((e,t)=>e+t.length,0);if(c===0)throw Error(`Invalid Ogg stream: empty packets are only allowed at the very end of a stream.`);let l=new Uint8Array(c),u=0;for(let e=0;e<s.length;e++){let t=s[e];l.set(t,u),u+=t.length}return{data:l,endPage:i,endSegmentIndex:o}}async findNextPacketStart(e){let t=e.endPage,n=e.endSegmentIndex+1;if(n===t.lacingValues.length){if(t.headerType&4)return null;let e=t.headerStartPos+t.totalSize;for(;;){let r=this.reader.requestSliceRange(e,27,282);if(j(r)&&(r=await r),!r)return null;let i=Oo(r);if(!i)return null;if(i.serialNumber===t.serialNumber){t=i,n=0;break}e=i.headerStartPos+i.totalSize}}return t.headerType&4&&n===t.lacingValues.length-1&&t.lacingValues[n]===0?null:{startPage:t,startSegmentIndex:n}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackings.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return Eo({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},jo=class{constructor(e,n){this.bitstream=e,this.demuxer=n,this.encodedPacketToMetadata=/* @__PURE__ */ new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new de,this.firstTimestampInSamplesPromise=null;let r=e.codecInfo.codec;t(r),r===`vorbis`?this.internalSampleRate=e.sampleRate:r===`opus`?this.internalSampleRate=ru:(k(r),t(!1))}getType(){return`audio`}getNumber(){let e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return t(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return t(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...Dt,primary:!1}}granulePositionToTimestampInSamples(e){let n=this.bitstream.codecInfo.codec;if(t(n),n===`vorbis`)return e;if(n===`opus`)return t(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip;k(n),t(!1)}createEncodedPacketFromOggPacket(e,t,n){if(!e)return null;let{durationInSamples:r,vorbisBlockSize:i}=To(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new L(n.metadataOnly?Li:e.data,`key`,t.timestampInSamples/this.internalSampleRate,r/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:r,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:i}),a}getFirstTimestampInSamples(){return this.firstTimestampInSamplesPromise??=(async()=>{let e=this.granulePositionToTimestampInSamples(0);t(this.bitstream.lastMetadataPacket);let n=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!n)return e;let r=null,i=0,a=null,o=null;for(;n;){let e=await this.demuxer.readPacket(n.startPage,n.startSegmentIndex);if(!e||(r??=e.endPage,e.endPage.headerStartPos!==r.headerStartPos))break;let{durationInSamples:t,vorbisBlockSize:s}=To(e.data,this.bitstream.codecInfo,o);i+=t,a??=t,o=s,n=await this.demuxer.findNextPacketStart(e)}if(!r)return e;t(a!==null);let s=r.granulePosition-i;if(r.granulePosition!==-1&&!(r.headerType&4))return e+s;let c=this.bitstream.codecInfo.codec;t(c);let l;return c===`vorbis`?l=-a:c===`opus`?l=0:(k(c),t(!1)),e+Math.max(s,l)})()}async getFirstPacket(e){t(this.bitstream.lastMetadataPacket);let n=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!n)return null;let r=await this.getFirstTimestampInSamples(),i=await this.demuxer.readPacket(n.startPage,n.startSegmentIndex);return this.createEncodedPacketFromOggPacket(i,{timestampInSamples:r,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let n=this.encodedPacketToMetadata.get(e);if(!n)throw Error(`Packet was not created from this track.`);let r=await this.demuxer.findNextPacketStart(n.packet);if(!r)return null;let i=n.timestampInSamples+n.durationInSamples,a=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:i,vorbisLastBlocksize:n.vorbisBlockSize},t)}async getPacket(e,n){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,n);let r=Ae(e*this.internalSampleRate),i=await this.getFirstTimestampInSamples();if(r===i)return this.getFirstPacket(n);if(r<i)return null;t(this.bitstream.lastMetadataPacket);let a=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!a)return null;let o=a.startPage,s=this.demuxer.reader.fileSize,c=[o];outer:for(;o.headerStartPos+o.totalSize<s;){let e=o.headerStartPos,t=Math.floor((e+s)/2),n=t;for(;;){let e=Math.min(n+Do,s-27),i=this.demuxer.reader.requestSlice(n,Math.max(e-n,0));if(j(i)&&(i=await i),!i||!ko(i,e,this.bitstream.serialNumber)){if(s<=t+27)break outer;s=t+27;continue outer}let a=i.filePos,l=this.demuxer.reader.requestSliceRange(a,27,282);j(l)&&(l=await l);let u=l&&Oo(l);if(!u||u.serialNumber!==this.bitstream.serialNumber)n=a+4;else if(u.granulePosition===-1)n=u.headerStartPos+u.totalSize;else{this.granulePositionToTimestampInSamples(u.granulePosition)>r||u.headerStartPos+u.totalSize>this.demuxer.reader.fileSize?s=u.headerStartPos:(o=u,c.push(u));continue outer}}}let l=a.startPage;for(let e of c){if(e.granulePosition===o.granulePosition)break;(!l||e.headerStartPos>l.headerStartPos)&&(l=e)}let u=l,d=[u];for(;u.serialNumber!==this.bitstream.serialNumber||u.granulePosition!==o.granulePosition;){let e=u.headerStartPos+u.totalSize,t=this.demuxer.reader.requestSliceRange(e,27,282);j(t)&&(t=await t);let n=t&&Oo(t);if(!n){u=o,d.push(o);break}u=n,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}let f=null,p,m,h=u,g=0;if(u.headerStartPos===a.startPage.headerStartPos)p=i,m=!0,f=0;else{t(u.granulePosition!==-1),p=0,m=!1;for(let e=u.lacingValues.length-1;e>=0;e--)if(u.lacingValues[e]<255){f=e+1;break}if(f===null)throw Error(`Invalid page with granule position: no packets end on this page.`);g=f-1;let e={data:Li,endPage:h,endSegmentIndex:g},n=await this.demuxer.findNextPacketStart(e);if(n){let e=No(d,u,f);t(e);let r=Mo(d,e.page,e.segmentIndex);r?(u=r.page,f=r.segmentIndex):(u=n.startPage,f=n.startSegmentIndex,p=this.granulePositionToTimestampInSamples(h.granulePosition),m=!0)}else for(;;){let e=No(d,u,f);if(!e)break;let t=Mo(d,e.page,e.segmentIndex);if(!t)break;if(u=t.page,f=t.segmentIndex,e.page.headerStartPos!==h.headerStartPos){h=e.page,g=e.segmentIndex;break}}}let _=null,v=null;for(;u!==null;){t(f!==null);let e=await this.demuxer.readPacket(u,f);if(!e)break;if(!(u.headerStartPos===a.startPage.headerStartPos&&f<a.startSegmentIndex)){let i=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:p,vorbisLastBlocksize:v?.vorbisBlockSize??null},n);t(i);let a=this.encodedPacketToMetadata.get(i);if(t(a),!m&&e.endPage.headerStartPos===h.headerStartPos&&e.endSegmentIndex===g?(p=this.granulePositionToTimestampInSamples(h.granulePosition),m=!0,i=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:p-a.durationInSamples,vorbisLastBlocksize:v?.vorbisBlockSize??null},n),t(i),a=this.encodedPacketToMetadata.get(i),t(a)):p+=a.durationInSamples,_=i,v=a,m&&(p>r||a.timestampInSamples===r))break}let i=await this.demuxer.findNextPacketStart(e);if(!i)break;u=i.startPage,f=i.startSegmentIndex}return _}async getPacketSequential(e,n){let r=await this.sequentialScanMutex.acquire();try{let r=Ae(e*this.internalSampleRate);e=r/this.internalSampleRate;let i=D(this.sequentialScanCache,r,e=>e.timestampInSamples),a;if(i!==-1){let e=this.sequentialScanCache[i];a=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},n)}else if(a=await this.getFirstPacket(n),a&&a.timestamp>e)return null;let o=0;for(;a&&a.timestamp<e;){let r=await this.getNextPacket(a,n);if(!r||r.timestamp>e)break;if(a=r,o++,o===100){o=0;let e=this.encodedPacketToMetadata.get(a);t(e),this.sequentialScanCache.length>0&&t(m(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return a}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};const Mo=(e,n,r)=>{let i=n,a=r;outer:for(;;){for(a--;a>=0;a--)if(i.lacingValues[a]<255){a++;break outer}if(t(a===-1),!(i.headerType&1)){a=0;break}let n=ye(e,e=>e.headerStartPos<i.headerStartPos);if(!n)return null;i=n,a=i.lacingValues.length}if(t(a!==-1),a===i.lacingValues.length){let n=e[e.indexOf(i)+1];t(n),i=n,a=0}return{page:i,segmentIndex:a}},No=(e,t,n)=>{if(n>0)return{page:t,segmentIndex:n-1};let r=ye(e,e=>e.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};
239
+ /*!
240
+ * Copyright (c) 2026-present, Vanilagy and contributors
241
+ *
242
+ * This Source Code Form is subject to the terms of the Mozilla Public
243
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
244
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
245
+ */
246
+ var Po;(function(e){e[e.PCM=1]=`PCM`,e[e.IEEE_FLOAT=3]=`IEEE_FLOAT`,e[e.ALAW=6]=`ALAW`,e[e.MULAW=7]=`MULAW`,e[e.EXTENSIBLE=65534]=`EXTENSIBLE`})(Po||={});var Fo=class extends zi{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.dataSizeCapped=!1,this.dataSizeIsPlaceholder=!1,this.audioInfo=null,this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);j(e)&&(e=await e),t(e);let n=G(e,4),r=n!==`RIFX`,i=n===`RF64`,a=Jc(e,r),o=!i&&a===0,s=i||o||a===4294967295?this.reader.fileSize:Math.min(a+8,this.reader.fileSize??1/0);if(G(e,4)!==`WAVE`)throw Error(`Invalid WAVE file - wrong format`);let c=0,l=null,u=e.filePos;for(;s===null||u<s;){let e=this.reader.requestSlice(u,8);if(j(e)&&(e=await e),!e)break;let t=G(e,4),n=Jc(e,r),a=e.filePos;if(i&&c===0&&t!==`ds64`)throw Error(`Invalid RF64 file: First chunk must be "ds64".`);if(t===`fmt `)await this.parseFmtChunk(a,n,r);else if(t===`data`){if(l??=n,(o&&l===0||!i&&l===4294967295)&&(l=2**53-1,n=l),this.dataSizeIsPlaceholder=l===2**53-1,i&&(n=l),this.dataStart=e.filePos,this.dataSize=Math.max(Math.min(l,(s??1/0)-this.dataStart),0),this.reader.fileSize===null)break}else if(t===`ds64`){let e=this.reader.requestSlice(a,n);if(j(e)&&(e=await e),!e)break;if(n<16)throw Error(`Invalid RF64 file: "ds64" chunk is too small.`);let t=Math.min(Qc(e,r),2**53-1);l=Math.min(Qc(e,r),2**53-1),o=t===0,s=o?this.reader.fileSize:Math.min(t+8,this.reader.fileSize??1/0)}else t===`LIST`?await this.parseListChunk(a,n,r):(t===`ID3 `||t===`id3 `)&&await this.parseId3Chunk(a,n);u=a+n+(n&1),c++}if(!this.audioInfo)throw Error(`Invalid WAVE file - missing "fmt " chunk`);if(this.dataStart===-1)throw Error(`Invalid WAVE file - missing "data" chunk`);let d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.maybeCapDataSize(),this.trackBackings.push(new Lo(this))})()}async parseFmtChunk(e,t,n){let r=this.reader.requestSlice(e,t);if(j(r)&&(r=await r),!r)return;if(t<14)throw Error(`Invalid WAVE file - "fmt " chunk is too small`);let i=Gc(r,n),a=Gc(r,n),o=Jc(r,n);r.skip(4);let s=Gc(r,n);if(a===0||o===0||s===0)throw Error(`Invalid WAVE file - channel count, sample rate and block align must be positive`);let c;if(c=t<16?8:Gc(r,n),t>=18&&i!==357){let e=Gc(r,n),a=t-18;if(Math.min(a,e)>=22&&i===Po.EXTENSIBLE){r.skip(6);let e=V(r,16);i=e[0]|e[1]<<8}}if((i===Po.MULAW||i===Po.ALAW)&&(c=8),i!==Po.PCM&&i!==Po.IEEE_FLOAT&&i!==Po.ALAW&&i!==Po.MULAW)throw Error(`Unsupported WAVE codec (format tag ${i}). Only integer/float PCM, A-law, and μ-law are supported.`);if(i===Po.PCM&&![8,16,24,32].includes(c))throw Error(`Unsupported WAVE PCM bit depth (${c}). Only 8, 16, 24, and 32 bits are supported.`);if(i===Po.IEEE_FLOAT&&![32,64].includes(c))throw Error(`Unsupported WAVE float bit depth (${c}). Only 32 and 64 bits are supported.`);this.audioInfo={format:i,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:s}}async parseListChunk(e,t,n){if(t<4)return;let r=this.reader.requestSlice(e,t);if(j(r)&&(r=await r),!r)return;let i=G(r,4);if(i!==`INFO`&&i!==`INF0`)return;let a=r.filePos;for(;a<=e+t-8;){r.filePos=a;let e=G(r,4),t=Jc(r,n);if(t>r.remainingLength)break;let i=V(r,t),o=i.indexOf(0),s=i.subarray(0,o===-1?i.length:o),c;try{c=ee.decode(s)}catch{c=``;for(let e of s)c+=String.fromCharCode(e)}switch(this.metadataTags.raw??={},this.metadataTags.raw[e]=c,e){case`INAM`:case`TITL`:this.metadataTags.title??=c;break;case`TIT3`:this.metadataTags.description??=c;break;case`IART`:this.metadataTags.artist??=c;break;case`IPRD`:this.metadataTags.album??=c;break;case`IPRT`:case`ITRK`:case`TRCK`:{let e=c.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`ICRD`:{let e=St(c);e&&(this.metadataTags.date??=e)}break;case`YEAR`:{let e=Number.parseInt(c,10),t=bt(e);e>0&&!Number.isNaN(t.getTime())&&(this.metadataTags.date??=t)}break;case`IGNR`:case`GENR`:this.metadataTags.genre??=c;break;case`ICMT`:case`CMNT`:case`COMM`:this.metadataTags.comment??=c}a+=8+t+(t&1)}}async parseId3Chunk(e,t){if(t<10)return;let n=this.reader.requestSlice(e,t);if(j(n)&&(n=await n),!n)return;let r=go(n);if(r){let i=t-10;if(r.size=Math.min(r.size,i),r.size>0){let t=n.slice(e+10,r.size);_o(t,r,this.metadataTags)}}}getCodec(){if(t(this.audioInfo),this.audioInfo.format===Po.MULAW)return`ulaw`;if(this.audioInfo.format===Po.ALAW)return`alaw`;if(this.audioInfo.format===Po.PCM){if(this.audioInfo.sampleSizeInBytes===1)return`pcm-u8`;if(this.audioInfo.sampleSizeInBytes===2)return`pcm-s16`;if(this.audioInfo.sampleSizeInBytes===3)return`pcm-s24`;if(this.audioInfo.sampleSizeInBytes===4)return`pcm-s32`}if(this.audioInfo.format===Po.IEEE_FLOAT){if(this.audioInfo.sampleSizeInBytes===4)return`pcm-f32`;if(this.audioInfo.sampleSizeInBytes===8)return`pcm-f64`}t(!1)}maybeCapDataSize(){if(t(this.audioInfo),this.dataSizeCapped)return;let e=this.reader.fileSize;e!==null&&(this.dataSize=Math.min(this.dataSize,Ne(e-this.dataStart,this.audioInfo.blockSizeInBytes)),this.dataSizeCapped=!0)}async getMimeType(){return`audio/wav`}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}};const Io=2048;var Lo=class{constructor(e){this.demuxer=e}getType(){return`audio`}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(t(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return t(this.demuxer.dataSize!==-1),this.demuxer.maybeCapDataSize(),this.demuxer.dataSizeIsPlaceholder&&!this.demuxer.dataSizeCapped?null:this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...Dt}}async getPacketAtIndex(e,n){t(e>=0),t(this.demuxer.audioInfo);let r=this.demuxer.audioInfo.blockSizeInBytes;this.demuxer.maybeCapDataSize();let i=this.demuxer.reader.fileSize,a=e*Io*r;if(a>=this.demuxer.dataSize)return null;let o=Math.min(Io*r,this.demuxer.dataSize-a);if(i===null){let r=this.demuxer.reader.requestSlice(this.demuxer.dataStart+a,o);if(j(r)&&(r=await r),!r)return t(this.demuxer.reader.fileSize!==null),this.getPacketAtIndex(e,n)}let s;if(n.metadataOnly)s=Li;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+a,o);j(e)&&(e=await e),t(e),s=V(e,o)}let c=e*Io/this.demuxer.audioInfo.sampleRate,l=o/r/this.demuxer.audioInfo.sampleRate;return new L(s,`key`,c,l,e,o)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,n){t(this.demuxer.audioInfo);let r=Math.floor(Math.min(Ae(e*this.demuxer.audioInfo.sampleRate)/Io,(this.demuxer.dataSize-1)/(Io*this.demuxer.audioInfo.blockSizeInBytes)));return r<0?null:await this.getPacketAtIndex(r,n)||this.getPacket(e,n)}getNextPacket(e,n){t(this.demuxer.audioInfo);let r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Io);return this.getPacketAtIndex(r+1,n)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}
247
+ /*!
248
+ * Copyright (c) 2026-present, Vanilagy and contributors
249
+ *
250
+ * This Source Code Form is subject to the terms of the Mozilla Public
251
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
252
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
253
+ */
254
+ ;const Ro=async(e,t,n,r)=>{let i=(e,t)=>e.objectType===t.objectType&&e.samplingFrequencyIndex===t.samplingFrequencyIndex&&e.channelConfiguration===t.channelConfiguration,a=e.requestSliceRange(t,7,n+9);if(j(a)&&(a=await a),!a)return null;for(let o=t;o<Math.min(t+n,a.end);o++){if(a.filePos=o,H(a)!==255)continue;a.filePos=o;let t=zo(a);if(!t||r&&!i(t,r))continue;let n=o+t.frameLength;if(n===e.fileSize)return t;let s=e.requestSliceRange(n,7,9);j(s)&&(s=await s);let c=s&&zo(s);if(c&&i(t,c))return t}return null},zo=e=>{let t=e.filePos;if(e.remainingLength<7)return null;let n=new N(V(e,7));if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let r=n.readBits(1),i=n.readBits(2)+1,a=n.readBits(4);if(a>=kt.length)return null;n.skipBits(1);let o=n.readBits(3);n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let s=n.readBits(13);n.skipBits(11);let c=n.readBits(2)+1;if(c!==1)return null;let l=null;if(r===0){if(e.remainingLength<2)return null;l=U(e)}return s<e.filePos-t?null:{objectType:i,samplingFrequencyIndex:a,channelConfiguration:o,frameLength:s,numberOfAacFrames:c,crcCheck:l,startPos:t}},Bo=1024
255
+ /*!
256
+ * Copyright (c) 2026-present, Vanilagy and contributors
257
+ *
258
+ * This Source Code Form is subject to the terms of the Mozilla Public
259
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
260
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
261
+ */
262
+ ;var Vo=class extends zi{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.numberOfChannels=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new de,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();let e=this.firstFrameHeader;if(t(e),e.channelConfiguration===0){let t=e.crcCheck===null?7:9,n=this.reader.requestSlice(e.startPos+t,e.frameLength-t);if(j(n)&&(n=await n),!n)throw Error(`Invalid ADTS file: the first frame is cut off.`);let r=Vt(V(n,e.frameLength-t));if(!r)throw Error(`Invalid ADTS file: frames with channel configuration 0 must begin with a program config element.`);this.numberOfChannels=Ut(r.programConfigElement)}else this.numberOfChannels=At[e.channelConfiguration];this.trackBackings=[new Ho(this)]})()}async advanceReader(){let e;if(this.lastLoadedPos===0){let t=await ho(this.reader,0);e=await Ro(this.reader,t,4096,null)}else{let n=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(j(n)&&(n=await n),e=n&&zo(n),!e){t(this.firstFrameHeader);let n=await ho(this.reader,this.lastLoadedPos);e=await Ro(this.reader,n,2**16,this.firstFrameHeader)}}if(!e||this.reader.fileSize!==null&&e.startPos+e.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader??=e;let n=kt[this.firstFrameHeader.samplingFrequencyIndex];if(t(n!==void 0),e.samplingFrequencyIndex!==this.firstFrameHeader.samplingFrequencyIndex){M._warn(`The sample rate changes mid-stream (from ${n} Hz to ${kt[e.samplingFrequencyIndex]} Hz), which isn't properly supported or handled by Mediabunny.`),this.lastSampleLoaded=!0;return}let r={timestamp:this.nextTimestampInSamples/n,duration:Bo/n,dataStart:e.startPos,dataSize:e.frameLength};this.loadedSamples.push(r),this.nextTimestampInSamples+=Bo,this.lastLoadedPos=e.startPos+e.frameLength}async getMimeType(){return`audio/aac`}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,10);if(j(t)&&(t=await t),!t)break;let n=go(t);if(!n)break;let r=this.reader.requestSlice(t.filePos,n.size);if(j(r)&&(r=await r),!r)break;_o(r,n,this.metadataTags),e=t.filePos+n.size}return this.metadataTags}finally{e()}}},Ho=class{constructor(e){this.demuxer=e}getType(){return`audio`}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return`und`}getCodec(){return`aac`}getInternalCodecId(){return t(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){return t(this.demuxer.numberOfChannels!==null),this.demuxer.numberOfChannels}getSampleRate(){t(this.demuxer.firstFrameHeader);let e=kt[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return t(e!==void 0),e}getDisposition(){return{...Dt}}async getDecoderConfig(){return t(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=Li;else{let e=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(j(e)&&(e=await e),!e)return null;r=V(e,n.dataSize)}return new L(r,`key`,n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=ge(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(n===-1)throw Error(`Packet was not created from this track.`);let r=n+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=this.getSampleRate(),r=Ae(e*n)/n;for(;;){let e=D(this.demuxer.loadedSamples,r,e=>e.timestamp);if(e===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||e>=0&&e+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(e,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};
263
+ /*!
264
+ * Copyright (c) 2026-present, Vanilagy and contributors
265
+ *
266
+ * This Source Code Form is subject to the terms of the Mozilla Public
267
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
268
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
269
+ */
270
+ const Uo=e=>e===0?null:e===1?192:e>=2&&e<=5?144*2**e:e===6?`uncommon-u8`:e===7?`uncommon-u16`:e>=8&&e<=15?2**e:null,Wo=(e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return`uncommon-u8`;case 13:return`uncommon-u16`;case 14:return`uncommon-u16-10`;default:return null}},Go=e=>{let t=0,n=new N(V(e,1));for(;n.readBits(1)===1;)t++;if(t===0)return n.readBits(7);let r=[],i=t-1,a=new N(V(e,i)),o=8-t-1;for(let e=0;e<o;e++)r.unshift(n.readBits(1));for(let e=0;e<i;e++)for(let e=0;e<8;e++){let t=a.readBits(1);e<2||r.unshift(t)}return r.reduce((e,t,n)=>e+t*2**n,0)},Ko=(e,n)=>{if(n===`uncommon-u16`)return U(e)+1;if(n===`uncommon-u8`)return H(e)+1;if(typeof n==`number`)return n;k(n),t(!1)},qo=(e,t)=>t===`uncommon-u16`?U(e):t===`uncommon-u16-10`?U(e)*10:t===`uncommon-u8`?1e3*H(e):typeof t==`number`?t:null,Jo=e=>{let t=0;for(let n of e){t^=n;for(let e=0;e<8;e++)t&128?t=t<<1^7:t<<=1,t&=255}return t};
271
+ /*!
272
+ * Copyright (c) 2026-present, Vanilagy and contributors
273
+ *
274
+ * This Source Code Form is subject to the terms of the Mozilla Public
275
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
276
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
277
+ */
278
+ var Yo=class extends zi{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.trackBacking=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new de,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),t(this.trackBacking),[this.trackBacking]}async getMimeType(){return`audio/flac`}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let n=this.reader.requestSlice(e,10);if(j(n)&&(n=await n),!n)break;let r=go(n);if(!r)break;let i=this.reader.requestSlice(n.filePos,r.size);j(i)&&(i=await i),t(i),_o(i,r,this.metadataTags),e=n.filePos+r.size}for(e+=4;this.reader.fileSize===null||e<this.reader.fileSize;){let n=this.reader.requestSlice(e,4);if(j(n)&&(n=await n),e+=4,n===null)throw Error(`Metadata block at position ${e} is too small! Corrupted file.`);t(n);let r=H(n),i=Kc(n),a=!!(r&128);switch(r&127){case Zn.STREAMINFO:{if(i<34)throw Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let t=this.reader.requestSlice(e,i);if(j(t)&&(t=await t),t===null)throw Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let n=V(t,34),r=new N(n),a=r.readBits(16),o=r.readBits(16),s=r.readBits(24),c=r.readBits(24),l=r.readBits(20);if(l===0)throw Error(`Invalid StreamInfo block: sample rate is 0. Corrupted file.`);let u=r.readBits(3)+1;r.readBits(5);let d=r.readBits(36);r.skipBits(128);let f=/* @__PURE__ */ new Uint8Array(42);f.set(new Uint8Array([102,76,97,67]),0),f.set(new Uint8Array([128,0,0,34]),4),f.set(n,8),this.audioInfo={numberOfChannels:u,sampleRate:l,totalSamples:d,minimumBlockSize:a,maximumBlockSize:o,minimumFrameSize:s,maximumFrameSize:c,description:f},this.trackBacking=new Xo(this);break}case Zn.VORBIS_COMMENT:{let t=this.reader.requestSlice(e,i);if(j(t)&&(t=await t),!t)throw Error(`Vorbis comment block at position ${e} exceeds the file. Corrupted file.`);Qn(V(t,i),this.metadataTags);break}case Zn.PICTURE:{let t=this.reader.requestSlice(e,i);if(j(t)&&(t=await t),!t)throw Error(`Picture block at position ${e} exceeds the file. Corrupted file.`);try{let e=W(t),n=W(t),r=w.decode(V(t,n)),i=W(t),a=w.decode(V(t,i));t.skip(16);let o=W(t),s=V(t,o);this.metadataTags.images??=[],this.metadataTags.images.push({data:s,mimeType:r,kind:e===3?`coverFront`:e===4?`coverBack`:`unknown`,description:a})}catch{}break}}if(e+=i,a)break}if(this.lastLoadedPos=e,!this.audioInfo)throw Error(`Missing STREAMINFO metadata block! Corrupted FLAC file.`)})()}async readNextFlacFrame(e){t(this.audioInfo);let n=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+16+2,r=this.audioInfo.minimumFrameSize||10,i=(this.audioInfo.maximumFrameSize||n)+16,a=await this.reader.requestSliceRange(e,6,i);if(!a)return null;let o=this.readFlacFrameHeader(a);if(!o)return null;for(a.filePos=e+r;;){if(a.filePos>a.end-6)return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:a.end-e,isLastFrame:!0};if(H(a)===255){let t=a.filePos;if(H(a)!==(this.blockingBit===1?249:248)){a.filePos=t;continue}a.skip(-2);let n=a.filePos-e,r=this.readFlacFrameHeader(a);if(!r){a.filePos=t;continue}if(this.blockingBit===0){if(r.num-o.num!==1){a.filePos=t;continue}}else if(r.num-o.num!==o.blockSize){a.filePos=t;continue}return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:n,isLastFrame:!1}}}}readFlacFrameHeader(e){let n=e.filePos,r=new N(V(e,4));if(r.readBits(15)!==32764)return null;let i=r.readBits(1);if(this.blockingBit!==null&&i!==this.blockingBit)return null;let a=Uo(r.readBits(4));if(!a)return null;t(this.audioInfo);let o=Wo(r.readBits(4),this.audioInfo.sampleRate);if(!o||(r.readBits(4),r.readBits(3),r.readBits(1)!==0))return null;let s=H(e);if(e.skip(-1),n+(4+Math.max(Math.clz32(~s<<24),1)+(a===`uncommon-u16`?2:+(a===`uncommon-u8`))+(o===`uncommon-u8`?1:typeof o==`number`?0:2)+1)>e.end)return null;let c=Go(e),l=Ko(e,a),u=qo(e,o);if(u===null||u!==this.audioInfo.sampleRate)return null;let d=e.filePos-n,f=H(e);return e.skip(-d),e.skip(-1),f===Jo(V(e,d))?(this.blockingBit=i,{num:c,blockSize:l,sampleRate:u}):null}async advanceReader(){await this.readMetadata(),t(this.lastLoadedPos!==null),t(this.audioInfo);let e=this.lastLoadedPos,n=await this.readNextFlacFrame(e);if(!n){this.lastSampleLoaded=!0;return}let r=this.loadedSamples[this.loadedSamples.length-1],i={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:n.blockSize,byteOffset:e,byteSize:n.size};this.lastLoadedPos+=n.size,this.loadedSamples.push(i),n.isLastFrame&&(this.lastSampleLoaded=!0)}},Xo=class{constructor(e){this.demuxer=e}getType(){return`audio`}getNumber(){return 1}getCodec(){return`flac`}getInternalCodecId(){return null}getNumberOfChannels(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return`und`}getTimeResolution(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...Dt}}async getDecoderConfig(){return t(this.demuxer.audioInfo),{codec:`flac`,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,n){if(t(this.demuxer.audioInfo),e<0)return null;let r=await this.demuxer.readingMutex.acquire();try{let t=Ae(e*this.demuxer.audioInfo.sampleRate);for(;;){let e=D(this.demuxer.loadedSamples,t,e=>e.blockOffset);if(e===-1){if(this.demuxer.lastSampleLoaded)return null;await this.demuxer.advanceReader();continue}let r=this.demuxer.loadedSamples[e];if(r.blockOffset+r.blockSize<=t){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,n);await this.demuxer.advanceReader()}else return this.getPacketAtIndex(e,n)}}finally{r()}}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&n>=this.demuxer.loadedSamples.length)return null;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,n){let r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(n.metadataOnly)i=Li;else{let e=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(j(e)&&(e=await e),!e)return null;i=V(e,r.byteSize)}t(this.demuxer.audioInfo);let a=r.blockOffset/this.demuxer.audioInfo.sampleRate,o=r.blockSize/this.demuxer.audioInfo.sampleRate;return new L(i,`key`,a,o,e,r.byteSize)}async getFirstPacket(e){let t=await this.demuxer.readingMutex.acquire();try{for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}finally{t()}}};
279
+ /*!
280
+ * Copyright (c) 2026-present, Vanilagy and contributors
281
+ *
282
+ * This Source Code Form is subject to the terms of the Mozilla Public
283
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
284
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
285
+ */
286
+ const Zo=9e4,Qo=2**33,$o=e=>{let t=`video/MP2T`,n=[...new Set(e.filter(Boolean))];return n.length>0&&(t+=`; codecs="${n.join(`, `)}"`),t},es=e=>{let t=60*Zo;return{reference:e>=Qo-t?e-t-Qo:e-t}},ts=(e,t)=>t.reference+ke(e-t.reference,Qo),ns=`PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.`,rs=/* @__PURE__ */ new Set([133,134,162]),is=/* @__PURE__ */ new Set
287
+ /*!
288
+ * Copyright (c) 2026-present, Vanilagy and contributors
289
+ *
290
+ * This Source Code Form is subject to the terms of the Mozilla Public
291
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
292
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
293
+ */
294
+ ;var as=class e extends zi{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.timestampWrapInfo=null,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let n=this.reader.requestSlice(0,205);j(n)&&(n=await n),t(n);let r=V(n,205);if(r[0]===71&&r[188]===71)this.packetOffset=0,this.packetStride=188;else if(r[0]===71&&r[204]===71)this.packetOffset=0,this.packetStride=204;else if(r[4]===71&&r[196]===71)this.packetOffset=4,this.packetStride=192;else throw Error(`Unreachable.`);this.minReferencePointByteDistance=256*this.packetStride;let i=this.packetOffset,a=null,o=!1,s=!1;for(;;){let n=await this.readPacketHeader(i);if(!n)break;if(n.payloadUnitStartIndicator===0||s&&!this.elementaryStreams.some(e=>e.pid===n.pid&&!e.initialized)){i+=this.packetStride;continue}let r=this.elementaryStreams.some(e=>e.pid===n.pid),c=await this.readSection(i,!r,!s);if(!c)break;let l=!1;if(!s&&c.pid!==0&&(a===null||c.pid===a)&&(c.payload[0]!==0||c.payload[1]!==0||c.payload[2]!==1)){let e=new N(c.payload),t=e.readAlignedByte();e.skipBits(8*t),l=e.readBits(8)===2}if(c.pid===0&&!o){let e=new N(c.payload),t=e.readAlignedByte();e.skipBits(8*t),e.skipBits(14);let n=e.readBits(10),r=e.pos+8*n;for(e.skipBits(40);r-e.pos>32;){let t=e.readBits(16);e.skipBits(3);let n=e.readBits(13);if(t!==0){if(a!==null)throw Error(`Only files with a single program are supported.`);a=n}}if(a===null)throw Error(`Program Association Table must link to a Program Map Table.`);o=!0}else if(l){let e=new N(c.payload),t=e.readAlignedByte();e.skipBits(8*t),e.skipBits(12);let n=e.readBits(12),r=e.pos+8*n;e.skipBits(43),e.readBits(13),e.skipBits(6);let i=e.readBits(10),a=e.pos+8*i,o=!1;for(;e.pos<a;){let t=e.readBits(8),n=e.readBits(8),r=e.pos+8*n;if(t===5&&n>=4){let t=e.readBits(32);o||=t===1212435798||t===1212436562}e.pos=r}for(e.pos=a;r-e.pos>32;){let t=e.readBits(8);e.skipBits(3);let n=e.readBits(13);e.skipBits(6);let r=e.readBits(10),i=e.pos+8*r,a=!1,s=!1,c=!1;for(;e.pos<i;){let t=e.readBits(8),n=e.readBits(8),r=e.pos+8*n;if(t===106)a=!0;else if(t===122||t===204)s=!0;else if(t===123)c=!0;else if(t===5&&n>=4){let t=e.readBits(32);c||=(t&4294967040)==1146376960}e.pos=r}let l=null,u=o&&rs.has(t)?130:t;switch(u){case 27:case 36:l={type:`video`,codec:t===27?`avc`:`hevc`,decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:case 130:case 138:{let e;e=u===3||u===4?`mp3`:u===15?`aac`:u===129?`ac3`:u===135?`eac3`:`dts`,l={type:`audio`,codec:e,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:s?l={type:`audio`,codec:`eac3`,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:a?l={type:`audio`,codec:`ac3`,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:c&&(l={type:`audio`,codec:`dts`,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:is.has(t)||(M._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),is.add(t))}l&&this.elementaryStreams.push({demuxer:this,pid:n,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:l,referencePesPackets:[]})}s=!0}else{let n=this.elementaryStreams.find(e=>e.pid===c.pid);outer:if(n&&!n.initialized){if(!os(this,c,!0))throw Error(`Couldn't read first PES packet for Elementary Stream with PID ${n.pid}`);if(n.firstSection=c,n.canBeTrustedWithKeyPackets=c.randomAccessIndicator===1,this.input._initInput){let t=await this.input._initInput._getDemuxer();if(t.constructor!==e)throw Error(`Init input must match the input's format.`);await t.readMetadata();let r=t.elementaryStreams.find(e=>e.pid===c.pid&&e.info.codec===n.info.codec&&e.initialized);if(r){n.info=r.info,n.initialized=!0;break outer}}let r=new ds(n,c.startPos);if(n.info.type===`video`){for(;;){let e=r;if(e.suppliedPacket=null,await r.markNextPacket(),n.info.codec===`avc`){if(!r.suppliedPacket)throw Error(`Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.`);if(n.info.avcCodecInfo=pn(r.suppliedPacket.data),!n.info.avcCodecInfo)continue;let e=n.info.avcCodecInfo.sequenceParameterSets[0];t(e);let i=vn(e);n.info.width=i.displayWidth,n.info.height=i.displayHeight;let a=i.pixelAspectRatio.num,o=i.pixelAspectRatio.den;n.info.squarePixelWidth=n.info.width,n.info.squarePixelHeight=n.info.height,a>0&&o>0&&(a>o?n.info.squarePixelWidth=Math.round(n.info.width*a/o):n.info.squarePixelHeight=Math.round(n.info.height*o/a)),n.info.colorSpace={primaries:ne[i.colourPrimaries],transfer:ie[i.transferCharacteristics],matrix:oe[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},n.info.reorderSize=i.maxDecFrameBuffering;break}if(n.info.codec===`hevc`){if(!r.suppliedPacket)throw Error(`Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.`);if(n.info.hevcCodecInfo=Tn(r.suppliedPacket.data),!n.info.hevcCodecInfo)continue;let e=n.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===F.SPS_NUT).nalUnits[0];t(e);let i=wn(e);n.info.width=i.displayWidth,n.info.height=i.displayHeight;let a=i.pixelAspectRatio.num,o=i.pixelAspectRatio.den;n.info.squarePixelWidth=n.info.width,n.info.squarePixelHeight=n.info.height,a>0&&o>0&&(a>o?n.info.squarePixelWidth=Math.round(n.info.width*a/o):n.info.squarePixelHeight=Math.round(n.info.height*o/a)),n.info.colorSpace={primaries:ne[i.colourPrimaries],transfer:ie[i.transferCharacteristics],matrix:oe[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},n.info.reorderSize=i.maxDecFrameBuffering;break}throw Error(`Unhandled.`)}n.info.decoderConfig={codec:Zl({width:n.info.width,height:n.info.height,codec:n.info.codec,codecDescription:null,colorSpace:n.info.colorSpace,avcType:1,avcCodecInfo:n.info.avcCodecInfo,hevcType:`hev1`,hevcCodecInfo:n.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:n.info.width,codedHeight:n.info.height,colorSpace:n.info.colorSpace},(n.info.width!==n.info.squarePixelWidth||n.info.height!==n.info.squarePixelHeight)&&(n.info.decoderConfig.displayAspectWidth=n.info.squarePixelWidth,n.info.decoderConfig.displayAspectHeight=n.info.squarePixelHeight),n.initialized=!0}else{if(await r.markNextPacket(),!r.suppliedPacket)throw Error(`Couldn't parse first media packet for Elementary Stream with PID ${n.pid}`);if(n.info.codec===`aac`){let e=Uc.tempFromBytes(r.suppliedPacket.data),t=zo(e);if(!t)throw Error(`Invalid AAC audio stream; could not read ADTS frame header from first packet.`);if(n.info.aacCodecInfo={isMpeg2:!1,objectType:t.objectType},t.channelConfiguration===0){let e=t.crcCheck===null?7:9,i=Vt(r.suppliedPacket.data.subarray(e,t.frameLength));if(!i)throw Error(`Invalid AAC audio stream; ADTS frames with channel configuration 0 must begin with a program config element.`);n.info.numberOfChannels=Ut(i.programConfigElement)}else n.info.numberOfChannels=At[t.channelConfiguration];n.info.sampleRate=kt[t.samplingFrequencyIndex]}else if(n.info.codec===`mp3`){let e=W(Uc.tempFromBytes(r.suppliedPacket.data)),t=Yt(e,r.suppliedPacket.data.byteLength);if(!t.header)throw Error(`Invalid MP3 audio stream; could not read frame header from first packet.`);n.info.numberOfChannels=Qt(t.header.channel),n.info.sampleRate=t.header.sampleRate}else if(n.info.codec===`ac3`){let e=tr(r.suppliedPacket.data);if(!e)throw Error(`Invalid AC-3 audio stream; could not read sync frame from first packet.`);if(e.fscod===3)throw Error(`Invalid AC-3 audio stream; reserved sample rate code found in first packet.`);n.info.numberOfChannels=er[e.acmod]+e.lfeon,n.info.sampleRate=$t[e.fscod]}else if(n.info.codec===`eac3`){let e=ir(r.suppliedPacket.data);if(!e)throw Error(`Invalid E-AC-3 audio stream; could not read sync frame from first packet.`);let t=sr(e);if(t===null)throw Error(`Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.`);n.info.numberOfChannels=cr(e),n.info.sampleRate=t}else if(n.info.codec===`dts`){let e=_r(r.suppliedPacket.data);if(!e)throw Error(`Invalid DTS audio stream; could not read frame header from first packet.`);n.info.numberOfChannels=e.numberOfChannels,n.info.sampleRate=e.sampleRate,e.core&&(n.info.dtsFormat=e.hasExtensions?`dtsh`:`dtsc`)}else throw Error(`Unhandled.`);n.info.decoderConfig={codec:eu({codec:n.info.codec,codecDescription:null,aacCodecInfo:n.info.aacCodecInfo,dtsFormat:n.info.dtsFormat}),numberOfChannels:n.info.numberOfChannels,sampleRate:n.info.sampleRate},n.initialized=!0}}}if(s&&this.elementaryStreams.every(e=>e.initialized))break;i+=this.packetStride}if(!s)throw Error(o?`No Program Map Table found in the file.`:`No Program Association Table found in the file.`);for(let e of this.elementaryStreams)e.initialized&&(e.info.type===`video`?this.trackBackingEntries.push(new cs(e)):this.trackBackingEntries.push(new ls(e)))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return $o(e)}async readSection(e,n,r=!1){let i=e,a=e,o=[],s=0,c=null,l=!0,u=0;for(;;){let e=await this.readPacket(a);if(a+=this.packetStride,!e)break;if(!c)t(e.payloadUnitStartIndicator===1),c=e;else{if(e.pid!==c.pid){if(r){l=!1;break}continue}if(e.payloadUnitStartIndicator===1)break}let d=!!(e.adaptationFieldControl&2),f=!!(e.adaptationFieldControl&1),p=0;if(d&&(p=1+e.body[0],e===c&&p>1&&(u=e.body[1]>>6&1)),f&&(p===0?(o.push(e.body),s+=e.body.byteLength):(o.push(e.body.subarray(p)),s+=e.body.byteLength-p)),i=a,!n&&s>=64||ge(this.sectionEndPositions,i,e=>e)!==-1){l=!1;break}}if(l){let e=D(this.sectionEndPositions,i,e=>e);this.sectionEndPositions.splice(e+1,0,i)}if(!c)return null;let d;if(o.length===1)d=o[0];else{let e=o.reduce((e,t)=>e+t.length,0);d=new Uint8Array(e);let t=0;for(let e of o)d.set(e,t),t+=e.length}return{startPos:e,pid:c.pid,payload:d,randomAccessIndicator:u}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(j(t)&&(t=await t),!t)return null;if(H(t)!==71)throw Error(`Invalid TS packet sync byte; the file is likely corrupted.`);let n=U(t);n>>15;let r=n>>14&1;n>>13&1;let i=n&8191,a=H(t);a>>6;let o=a>>4&3;return a&15,{payloadUnitStartIndicator:r,pid:i,adaptationFieldControl:o}}async readPacket(e){let t=this.reader.requestSlice(e,188);if(j(t)&&(t=await t),!t)return null;let n=V(t,188);if(n[0]!==71)throw Error(`Invalid TS packet sync byte; the file is likely corrupted.`);let r=(n[1]<<8)+n[2];r>>15;let i=r>>14&1;r>>13&1;let a=r&8191,o=n[3];o>>6;let s=o>>4&3;return o&15,{payloadUnitStartIndicator:i,pid:a,adaptationFieldControl:s,body:n.subarray(4)}}normalizeTimestamp(e){return this.timestampWrapInfo??=es(e),ts(e,this.timestampWrapInfo)}};const os=(e,t,n)=>{if(t.payload.byteLength<3)return null;let r=new N(t.payload);if(r.readBits(24)!==1)return null;let i=r.readBits(8);if(r.skipBits(16),i===188||i===190||i===191||i===240||i===241||i===255||i===242||i===248)return null;r.skipBits(8);let a=r.readBits(2);r.skipBits(14);let o=null;if(a===2||a===3)o=0,r.skipBits(4),o+=r.readBits(3)*(1<<30),r.skipBits(1),o+=r.readBits(15)*32768,r.skipBits(1),o+=r.readBits(15),o=e.normalizeTimestamp(o);else if(n)throw Error(ns);return{sectionStartPos:t.startPos,pts:o,randomAccessIndicator:t.randomAccessIndicator}};var ss=class e{constructor(e){this.elementaryStream=e,this.packetBuffers=/* @__PURE__ */ new WeakMap,this.packetSectionStarts=/* @__PURE__ */ new WeakMap}getNumber(){let n=this.elementaryStream.demuxer,r=this.elementaryStream.info.type,i=0;for(let a of n.trackBackingEntries)if(a.getType()===r&&i++,t(a instanceof e),a.elementaryStream===this.elementaryStream)break;return i}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...Dt,primary:!1}}getTimeResolution(){return Zo}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,n){let r;return r=this.allPacketsAreKeyPackets()||e.randomAccessIndicator===1?`key`:`delta`,new L(n.metadataOnly?Li:e.data,r,e.pts/Zo,Math.max(t/Zo,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let n=this.elementaryStream.firstSection;t(n);let r=new ds(this.elementaryStream,n.startPos),i=new fs(this,r),a=await i.readNext();if(!a)return null;let o=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(o,i),this.packetSectionStarts.set(o,a.packet.sectionStartPos),o}async getNextPacket(e,n){let r=this.packetBuffers.get(e);if(r){this.packetBuffers.delete(e);let t=await r.readNext();if(!t)return null;let i=this.createEncodedPacket(t.packet,t.duration,n);return this.packetBuffers.set(i,r),this.packetSectionStarts.set(i,t.packet.sectionStartPos),i}let i=this.packetSectionStarts.get(e);if(i===void 0)throw Error(`Packet was not created from this track.`);let a=this.elementaryStream.demuxer,o=i,s=this.getReorderSize(),c=i-a.packetStride;for(;s>0&&c>=a.packetOffset;){let e=await a.readPacketHeader(c);if(t(e),e.pid===this.elementaryStream.pid&&e.payloadUnitStartIndicator===1){let e=await a.readSection(c,!1);t(e);let n=os(a,e,!1);n&&n.pts!==null&&(o=c,s--)}c-=a.packetStride}let l=new ds(this.elementaryStream,o);r=new fs(this,l);let u=e.sequenceNumber;for(;;){let e=await r.readNext();if(!e)return null;if(e.packet.sequenceNumber>u){let t=this.createEncodedPacket(e.packet,e.duration,n);return this.packetBuffers.set(t,r),this.packetSectionStarts.set(t,e.packet.sectionStartPos),t}}}async getNextKeyPacket(e,t){let n=e;for(;;){if(n=await this.getNextPacket(n,t),!n)return null;if(n.type===`key`)return n}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,n,r){let i=Ae(e*Zo),a=this.elementaryStream.demuxer,{reader:o,seekChunkSize:s}=a,c=this.elementaryStream.pid,l=async(e,t)=>{let n=e;for(;n<t;){let e=await a.readPacketHeader(n);if(!e)return null;if(e.pid===c&&e.payloadUnitStartIndicator===1){let e=await a.readSection(n,!1);if(!e)return null;let t=os(a,e,!1);if(t&&t.pts!==null)return t}n+=a.packetStride}return null},u=this.elementaryStream.firstSection;t(u);let d=os(a,u,!0);t(d);let f,p=this.elementaryStream.referencePesPackets,h=D(p,i,e=>e.pts),g=h===-1?null:p[h];if(g&&i-g.pts<45e3)f=g.sectionStartPos;else{let e=0;if(o.fileSize!==null&&i>=d.pts){let t=Math.ceil(o.fileSize/s);if(t>1){let n=0,r=t-1;for(e=n;n<=r;){let t=Math.floor((n+r)/2),o=Ne(t*s,a.packetStride)+d.sectionStartPos,c=await l(o,o+s);c&&c.pts<=i?(e=t,n=t+1):r=t-1}}}f=Ne(e*s,a.packetStride)+d.sectionStartPos}let _=await l(f,o.fileSize??1/0);_||=d;let v=this.getReorderSize(),y=async(e,n)=>{let a=new ds(this.elementaryStream,e),o=new fs(this,a);for(;!((m(o.presentationOrderPackets)?.pts??-1/0)>=i||!await o.readNextPacket()););let s=be(o.presentationOrderPackets,n);if(s===-1)return null;let c=o.presentationOrderPackets[s];o.decodeOrderPackets.splice(0,o.decodeOrderPackets.indexOf(c));let l=await o.readNext();t(l);let u=this.createEncodedPacket(l.packet,l.duration,r);return this.packetBuffers.set(u,o),this.packetSectionStarts.set(u,l.packet.sectionStartPos),u};if(!n||this.allPacketsAreKeyPackets()){outer:for(;;){let e=_.sectionStartPos+a.packetStride;for(;;){let t=await a.readPacketHeader(e);if(!t)break outer;if(t.pid===c&&t.payloadUnitStartIndicator===1){let t=await a.readSection(e,!1);if(t){let e=os(a,t,!1);if(e&&e.pts!==null){if(e.pts>i)break outer;_=e,us(this.elementaryStream,_);break}}}e+=a.packetStride}}outer:for(let e=0;e<v+1;e++){let e=_.sectionStartPos-a.packetStride;for(;e>=d.sectionStartPos;){let t=await a.readPacketHeader(e);if(!t)break outer;if(t.pid===c&&t.payloadUnitStartIndicator===1){let t=await a.readSection(e,!1);if(t){let e=os(a,t,!1);if(e&&e.pts!==null){_=e;break}}}e-=a.packetStride}if(e<d.sectionStartPos)break}return y(_.sectionStartPos,e=>e.pts<=i)}{let e=f,t=null;for(;;){let n=null,r=e<=d.sectionStartPos,u;u=r?d:await l(e,t??o.fileSize??1/0);let f=!1,p=0,m=null;outer:for(;u&&!(t!==null&&u.sectionStartPos>=t);){if(u.pts<=i){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=u.randomAccessIndicator===1;else{for(m??=new ds(this.elementaryStream,u.sectionStartPos);(!m.suppliedPacket||m.suppliedPacket.sectionStartPos<u.sectionStartPos)&&(m.suppliedPacket=null,await m.markNextPacket(),m.suppliedPacket););e=m.suppliedPacket?.sectionStartPos===u.sectionStartPos&&m.suppliedPacket.randomAccessIndicator===1}e&&(n=u)}if(u.pts>i&&(f=!0),f&&(p++,p>v))break;let e=u.sectionStartPos+a.packetStride;for(;;){let t=await a.readPacketHeader(e);if(!t)break outer;if(t.pid===c&&t.payloadUnitStartIndicator===1){let t=await a.readSection(e,!1);if(t){let e=os(a,t,!1);if(e&&e.pts!==null){u=e,us(this.elementaryStream,u);break}}}e+=a.packetStride}}if(n){let e=n;if(p===0)outer:for(let t=0;t<v+1;t++){let t=e.sectionStartPos-a.packetStride;for(;t>=d.sectionStartPos;){let n=await a.readPacketHeader(t);if(!n)break outer;if(n.pid===c&&n.payloadUnitStartIndicator===1){let n=await a.readSection(t,!1);if(n){let t=os(a,n,!1);if(t&&t.pts!==null){e=t;break}}}t-=a.packetStride}if(t<d.sectionStartPos)break}let t=await y(e.sectionStartPos,e=>e.pts<=i&&e.randomAccessIndicator===1);if(t)return t}if(r)return null;t=e,e=Math.max(Ne(e-d.sectionStartPos-s,a.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}},cs=class extends ss{getType(){return`video`}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getTransformationMatrix(){return[...a]}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return t(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},ls=class extends ss{getType(){return`audio`}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return t(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}};const us=(e,t)=>{let n=e.referencePesPackets,r=D(n,t.sectionStartPos,e=>e.sectionStartPos),i=e.demuxer.minReferencePointByteDistance;if(r>=0){let e=n[r];if(t.pts<=e.pts||t.sectionStartPos-e.sectionStartPos<i)return!1}if(r<n.length-1){let e=n[r+1];if(e.pts<t.pts||e.sectionStartPos-t.sectionStartPos<i)return!1}return n.splice(r+1,0,{sectionStartPos:t.sectionStartPos,pts:t.pts,randomAccessIndicator:t.randomAccessIndicator}),!0};var ds=class{constructor(e,t){this.reachedEnd=!1,this.isInPesPacket=!1,this.pesHeaderBytesLeft=0,this.pesDataBytesLeft=0,this.currentPos=0,this.endPos=0,this.scratch=new Uint8Array(2**16),this.scratchStartPos=0,this.pesPackets=[],this.pesPacketDataStartPositions=[],this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.nextTsPacketPos=t}ensureBuffered(e){let t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}async bufferData(e){let n=this.endPos+e;for(;this.endPos<n&&!this.reachedEnd;){let e=this.nextTsPacketPos,n=await this.demuxer.readPacket(e);if(!n){this.reachedEnd=!0;break}if(this.nextTsPacketPos+=this.demuxer.packetStride,n.pid!==this.pid)continue;if(n.payloadUnitStartIndicator===1){this.isInPesPacket=!1;let n=await this.demuxer.readSection(e,!1);t(n);let r=os(this.demuxer,n,!1);if(!r)continue;let i=new N(n.payload);i.skipBits(32);let a=i.readBits(16);i.skipBits(16);let o=i.readBits(8);this.pesHeaderBytesLeft=i.pos/8+o,this.pesDataBytesLeft=a>0?Math.max(6+a-this.pesHeaderBytesLeft,0):1/0,this.isInPesPacket=!0,this.pesPackets.push(r),this.pesPacketDataStartPositions.push(this.endPos)}if(!this.isInPesPacket||!(n.adaptationFieldControl&1))continue;let r=n.body,i=n.adaptationFieldControl&2?1+r[0]:0,a=Math.min(this.pesHeaderBytesLeft,Math.max(r.byteLength-i,0));this.pesHeaderBytesLeft-=a,i+=a;let o=Math.min(r.byteLength,i+this.pesDataBytesLeft);if(o<=i)continue;let s=o-i;this.pesDataBytesLeft-=s;let c=this.endPos-this.scratchStartPos;if(c+s>this.scratch.byteLength){let e=new Uint8Array(2*this.scratch.byteLength);e.set(this.scratch.subarray(0,c)),this.scratch=e}this.scratch.set(r.subarray(i,o),c),this.endPos+=s}}readBytes(e){let t=this.currentPos-this.scratchStartPos;return this.currentPos+=e,this.scratch.subarray(t,t+e)}readU8(){return this.scratch[this.currentPos++-this.scratchStartPos]}seekTo(e){t(e>=this.scratchStartPos),this.currentPos=e}skip(e){this.seekTo(this.currentPos+e)}async markNextPacket(){t(!this.suppliedPacket);let e=this.elementaryStream;if(e.info.type===`video`){let n=e.info.codec,r=1024;if(n!==`avc`&&n!==`hevc`)throw Error(`Unhandled.`);let i=n===`avc`?1:2,a=null,o=!1,s=0;for(;;){let e=this.ensureBuffered(r);if(j(e)&&(e=await e),e===0)break;let t=this.currentPos,c=this.readBytes(e),l=c.byteLength,u=0;for(;u<l;){let e=c.indexOf(0,u);if(e===-1||e>=l)break;u=e;let r=t+u;if(u+3>=l){this.seekTo(r);break}let d=c[u+1],f=c[u+2],p=c[u+3],m=0;if(d===0&&f===0&&p===1?m=4:d===0&&f===1&&(m=3),m===0){u++;continue}let h=r;a??=h;let g=u+m,v=g+i;if(v+1>l){this.seekTo(r);break}let y=c[g],b,x,S,C;if(n===`avc`)b=on(y),x=b===P.NON_IDR_SLICE||b===P.SLICE_DPA||b===P.IDR,S=b===P.SEI||b===P.SPS||b===P.PPS||b===P.AUD,C=b===P.AUD;else{if(b=Cn(y),((y&1)<<5|c[g+1]>>3)>0){u+=m;continue}x=b<=F.RASL_R||b>=F.BLA_W_LP&&b<=21,S=b>=F.VPS_NUT&&b<=35||b===F.PREFIX_SEI_NUT||b>=41&&b<=44||b>=48&&b<=55,C=b===F.AUD_NUT}let w=!1;if(x){let e;if(n===`avc`){let t=new N(c.subarray(v)),n;try{n=_(t)}catch{n=null}if(n===null||t.getBitsLeft()<0){this.seekTo(r);break}e=!o||n<=s,s=n}else e=c[v]>>7==1;e&&(o?w=!0:o=!0)}else S&&o?w=!0:C&&(a=h);if(w){let e=h-a;return this.seekTo(a),this.supplyPacket(e,0)}u+=m}if(e<r)break}if(o){t(a!==null);let e=this.endPos-a;return this.seekTo(a),this.supplyPacket(e,0)}}else{let n=e.info.codec;for(;;){let r=this.ensureBuffered(128);j(r)&&(r=await r);let i=this.currentPos;for(;this.currentPos-i<r;){let r=this.readU8();if(n===`aac`){if(r!==255)continue;this.skip(-1);let t=this.currentPos,n=this.ensureBuffered(9);if(j(n)&&(n=await n),n<9)return;let i=this.readBytes(9),a=zo(Uc.tempFromBytes(i));if(a){this.seekTo(t);let n=this.ensureBuffered(a.frameLength);return j(n)&&(n=await n),this.supplyPacket(n,Bo*Zo/e.info.sampleRate)}this.seekTo(t+1)}else if(n===`mp3`){if(r!==255)continue;this.skip(-1);let t=this.currentPos,n=this.ensureBuffered(4);if(j(n)&&(n=await n),n<4)return;let i=this.readBytes(4),a=x(i).getUint32(0),o=Yt(a,null);if(o.header){this.seekTo(t);let n=this.ensureBuffered(o.header.totalSize);j(n)&&(n=await n);let r=o.header.audioSamplesInFrame*Zo/e.info.sampleRate;return this.supplyPacket(n,r)}this.seekTo(t+1)}else if(n===`ac3`){if(r!==11)continue;this.skip(-1);let n=this.currentPos,i=this.ensureBuffered(5);if(j(i)&&(i=await i),i<5)return;let a=this.readBytes(5);if(a[0]!==11||a[1]!==119){this.seekTo(n+1);continue}let o=a[4]>>6,s=a[4]&63;if(o===3||s>37){this.seekTo(n+1);continue}let c=nr[3*s+o];t(c!==void 0),this.seekTo(n),i=this.ensureBuffered(c),j(i)&&(i=await i);let l=1536*Zo/e.info.sampleRate;return this.supplyPacket(i,l)}else if(n===`eac3`){if(r!==11)continue;this.skip(-1);let t=this.currentPos,n=this.ensureBuffered(5);if(j(n)&&(n=await n),n<5)return;let i=this.readBytes(5);if(i[0]!==11||i[1]!==119){this.seekTo(t+1);continue}let a=(((i[2]&7)<<8|i[3])+1)*2,o=i[4]>>6==3?3:i[4]>>4&3,s=rr[o];for(;;){this.seekTo(t);let e=a+4,n=this.ensureBuffered(e);if(j(n)&&(n=await n),n<e)break;this.seekTo(t+a);let r=this.readBytes(4);if(r[0]!==11||r[1]!==119||r[2]>>6!=1)break;a+=2*(((r[2]&7)<<8|r[3])+1)}this.seekTo(t),n=this.ensureBuffered(a),j(n)&&(n=await n);let c=s*256*Zo/e.info.sampleRate;return this.supplyPacket(n,c)}else if(n===`dts`){if(r!==127&&r!==100)continue;this.skip(-1);let t=this.currentPos,n=this.ensureBuffered(18);if(j(n)&&(n=await n),n<18)return;let i=this.readBytes(18),a=yr(i),o=a?null:br(i);if(!a&&!o){this.seekTo(t+1);continue}if(o&&!o.asset){this.seekTo(t);let e=Math.min(o.frameSize,4096),n=this.ensureBuffered(e);j(n)&&(n=await n),o=br(this.readBytes(n))??o}let s=a?a.frameSize:o.frameSize;if(a){let e=Math.ceil(a.frameSize/4)*4;for(;;){this.seekTo(t);let n=e+10,r=this.ensureBuffered(n);if(j(r)&&(r=await r),r<n)break;this.seekTo(t+e);let i=br(this.readBytes(10));if(!i)break;e+=i.frameSize,s=e}}let c=a?.sampleCount??o.asset?.sampleCount;if(c===void 0){this.seekTo(t+1);continue}this.seekTo(t),n=this.ensureBuffered(s),j(n)&&(n=await n);let l=c*Zo/e.info.sampleRate;return this.supplyPacket(n,l)}else throw Error(`Unhandled.`)}if(r<128)break}}}supplyPacket(e,n){let r=be(this.pesPacketDataStartPositions,e=>e<=this.currentPos);t(r!==-1);let i=this.pesPackets[r],a=this.pesPacketDataStartPositions[r],o;if(this.lastSuppliedPesPacket===i)t(this.nextPts!==null),o=this.nextPts;else{if(i.pts===null)throw Error(ns);o=i.pts,us(this.elementaryStream,i)}this.lastSuppliedPesPacket=i,this.nextPts=o+n;let s=i.sectionStartPos,c=s+(this.currentPos-a),l=this.readBytes(e).slice(),u=i.randomAccessIndicator;if(u===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type===`audio`)u=1;else if(this.elementaryStream.info.decoderConfig){let e=Jn(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,l)===`key`;u=Number(e)}}let d=Math.round(o);this.suppliedPacket={pts:d,intrinsicDuration:Math.round(o+n)-d,data:l,sequenceNumber:c,sectionStartPos:s,randomAccessIndicator:u};let f=this.currentPos-this.scratchStartPos;this.scratch.copyWithin(0,f,this.endPos-this.scratchStartPos),this.scratchStartPos=this.currentPos;let p=be(this.pesPacketDataStartPositions,e=>e<=this.currentPos);this.pesPackets.splice(0,p),this.pesPacketDataStartPositions.splice(0,p)}},fs=class{constructor(e,n){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=n,this.reorderSize=e.getReorderSize(),t(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e),n;for(t!==-1&&t<this.presentationOrderPackets.length-1?(n=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=n):n=e.intrinsicDuration>0?e.intrinsicDuration:t>0?e.pts-this.presentationOrderPackets[t-1].pts:this.lastDuration,this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){let e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:e,duration:n}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket||await this.context.markNextPacket(),e=this.context.suppliedPacket,this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){let e=this.decodeOrderPackets[0];for(t(e);;){let t=this.presentationOrderPackets.indexOf(e);if(t!==-1&&t<=this.presentationOrderPackets.length-2||this.decodeOrderPackets.length>4*(this.reorderSize+1)||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let e=0;for(let t=1;t<this.reorderBuffer.length;t++)this.reorderBuffer[t].pts<this.reorderBuffer[e].pts&&(e=t);let t=this.reorderBuffer[e];this.presentationOrderPackets.push(t),this.reorderBuffer.splice(e,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}};
295
+ /*!
296
+ * Copyright (c) 2026-present, Vanilagy and contributors
297
+ *
298
+ * This Source Code Form is subject to the terms of the Mozilla Public
299
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
300
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
301
+ */
302
+ const ps=`application/vnd.apple.mpegurl`,ms=e=>e.length===0||e.startsWith(`#`)&&!e.startsWith(`#EXT`);var hs=class{constructor(e,t){this._attributes={};let n=``,r=``,i=!1,a=!1,o=!1,s=()=>{if(!n)return;let e=n.trim().toLowerCase();Object.prototype.hasOwnProperty.call(this._attributes,e)&&M._warn(`Duplicate AttributeName "${e}"; using last value`);let a=o||r.startsWith(`0x`)||r.startsWith(`0X`);this._attributes[e]=a&&t?t.substitute(r):r,n=``,r=``,i=!1,o=!1};for(let t=0;t<e.length;t++){let c=e[t];c===`"`?(i&&!a&&r.length===0&&(o=!0),a=!a):c===`=`&&!i&&!a?i=!0:c===`,`&&!a?s():i?r+=c:n+=c}if(a)throw Error(`Invalid M3U8 file; unterminated quoted-string AttributeValue.`);s()}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){let t=this.get(e);if(t===null)return null;let n=Number(t);return Number.isFinite(n)?n:null}merge(e){Object.assign(this._attributes,e._attributes)}};const gs=/^[A-Za-z0-9_-]+$/,_s=/\{\$([A-Za-z0-9_-]+)\}/g,vs=2**26;var ys=class{constructor(e,t){this.playlistPath=e,this.importedVariables=t,this.variables=/* @__PURE__ */ new Map,this.totalSubstitutedLength=0}define(e){let t=new hs(e,this),n=t.get(`name`),r=t.get(`import`),i=t.get(`queryparam`);if([n,r,i].filter(e=>e!==null).length!==1)throw Error(`Invalid #EXT-X-DEFINE tag; exactly one of NAME, IMPORT, or QUERYPARAM must be present.`);if(n!==null){let e=t.get(`value`);if(e===null)throw Error(`Invalid #EXT-X-DEFINE tag; NAME requires VALUE.`);this.set(n,e)}else if(r!==null){let e=this.importedVariables?.get(r);if(e===void 0)throw Error(`Invalid #EXT-X-DEFINE tag; cannot import undefined variable "${r}".`);this.set(r,e)}else if(i!==null){let e=ut(this.playlistPath,i);if(e===null)throw Error(`Invalid #EXT-X-DEFINE tag; query parameter "${i}" is missing.`);this.set(i,e)}}substitute(e){return e.replaceAll(_s,(e,t)=>{let n=this.variables.get(t);if(n===void 0)throw Error(`Invalid M3U8 file; variable "${t}" is referenced before being defined.`);if(this.totalSubstitutedLength+=n.length,this.totalSubstitutedLength>vs)throw Error(`Invalid M3U8 file; variable substitution produces an excessive amount of data.`);return n})}get(e){return this.variables.get(e)}set(e,t){if(!gs.test(e))throw Error(`Invalid #EXT-X-DEFINE tag; invalid variable name "${e}".`);if(this.variables.has(e))throw Error(`Invalid #EXT-X-DEFINE tag; variable "${e}" is already defined.`);this.variables.set(e,t)}},bs=class{constructor(e,t,n){
303
+ /*!
304
+ * Copyright (c) 2026-present, Vanilagy and contributors
305
+ *
306
+ * This Source Code Form is subject to the terms of the Mozilla Public
307
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
308
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
309
+ */
310
+ this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.hasOnlyKeyPackets=!1,this.learnedSegmentTimestampOffset=null,this.segmentMediaOffsets=/* @__PURE__ */ new WeakMap,this.input=e,this.path=t,this.trackDeclarations=n}async getDurationFromMetadata(e){let t=await this.getSegmentAt(1/0,{skipLiveWait:e.skipLiveWait});return t?t.timestamp+await this.getFirstSegmentTimestampOffset()+t.duration:null}async getUnixTimeForTimestamp(e){let t=await this.getSegmentAt(e,{skipLiveWait:!0});if(t??=await this.getFirstSegment({}),!t||t.unixEpochTimestamp===null)return null;let n=e-(t.timestamp+await this.getFirstSegmentTimestampOffset());return t.unixEpochTimestamp+n}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{let e=[];if(this.trackDeclarations){for(let t of this.trackDeclarations)if(t.type===`video`){let n=dt(e,e=>e.getType()===`video`)+1;e.push(new ws(this,t,n))}else if(t.type===`audio`){let n=dt(e,e=>e.getType()===`audio`)+1;e.push(new Ts(this,t,n))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];let t=await this.getInputForSegment(this.firstSegment).getTracks();for(let n of t)if(n.type===`video`){let t=dt(e,e=>e.getType()===`video`)+1;e.push(new ws(this,{type:`video`},t))}else if(n.type===`audio`){let t=dt(e,e=>e.getType()===`audio`)+1;e.push(new Ts(this,{type:`audio`},t))}}return e})()}getMediaOffset(e,t){let n=this.segmentMediaOffsets.get(e);return n||(n=(async()=>{let n=await this.getRawTimestampOffset(t);if(n===null)return e.timestamp;let r=n+await this.getMediaOffsetForDiscontinuity(e.discontinuityNumber),i=this.getTimestampWrapPeriod();if(i<1/0){let n=await xs(t);if(n!==null){let t=n+r;r+=i*Math.round((e.timestamp-t)/i)}}return r})(),this.segmentMediaOffsets.set(e,n),n)}dispose(){for(let e of this.inputCache)e.input.dispose();this.inputCache.length=0}};const xs=async e=>{let t=await e.getTracks(),n=[...t.filter(e=>e.type===`video`),...t.filter(e=>e.type!==`video`)];for(let e of n){let t=await e.getFirstTimestampOrNull();if(t!==null)return t}return null};var Ss=class{constructor(e,t,n){this.packetInfos=/* @__PURE__ */ new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=null,this.segmentedInput=e,this.decl=t,this.number=n}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw Error(`Missing first segment, can't retrieve track.`);let e=this.segmentedInput.firstSegment,t=null;for(;e&&(t=(await this.segmentedInput.getInputForSegment(e).getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number)??null,!t);)e=await this.segmentedInput.getNextSegment(e,{});if(!t)throw Error(`No matching track found in underlying media data.`);this.firstInputTrack=t,this.firstSegment=e})()}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.segmentedInput.hasOnlyKeyPackets||(this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null))}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),t(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,n,r){t(e.sequenceNumber>=0),t(this.segmentedInput.firstSegment);let i=await this.segmentedInput.getMediaOffset(n,r.input),a=n.timestamp-this.segmentedInput.firstSegment.timestamp,o=e.clone({timestamp:Me(e.timestamp+i,await r.getTimeResolution()),sequenceNumber:Math.floor(1e8*a)+e.sequenceNumber});return this.packetInfos.set(o,{segment:n,track:r,sourcePacket:e}),o}async getFirstPacket(e){await this.hydrate(),t(this.firstInputTrack),t(this.firstSegment);let n=this.firstInputTrack,r=this.firstSegment;for(;;){if(n){let t=await n._backing.getFirstPacket(e);if(t)return this.createAdjustedPacket(t,r,n)}if(r=await this.segmentedInput.getNextSegment(r,{skipLiveWait:e.skipLiveWait}),!r)break;n=(await this.segmentedInput.getInputForSegment(r).getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number)??null}return null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}async _getNextInternal(e,t,n){let r=this.packetInfos.get(e);if(!r)throw Error(`Packet was not created from this track.`);let i=n?await r.track._backing.getNextKeyPacket(r.sourcePacket,t):await r.track._backing.getNextPacket(r.sourcePacket,t);if(i)return this.createAdjustedPacket(i,r.segment,r.track);let a=r.segment;for(;;){let e=await this.segmentedInput.getNextSegment(a,{skipLiveWait:t.skipLiveWait});if(!e)return null;let i=(await this.segmentedInput.getInputForSegment(e).getTracks()).find(e=>e.type===r.track.type&&e.number===r.track.number);if(!i){a=e;continue}let o=await i._backing.getFirstPacket(t);if(o&&n&&o.type!==`key`&&(o=await i._backing.getNextKeyPacket(o,t)),!o)a=e;else return this.createAdjustedPacket(o,e,i)}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,n,r){let i=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:n.skipLiveWait});if(i??=await this.segmentedInput.getFirstSegment({}),!i)return null;for(await this.hydrate();i;){let a=this.segmentedInput.getInputForSegment(i),o=(await a.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number);if(!o){i=await this.segmentedInput.getPreviousSegment(i,{skipLiveWait:n.skipLiveWait});continue}let s=await this.segmentedInput.getMediaOffset(i,a),c=this.segmentedInput.learnedSegmentTimestampOffset===null?await o._backing.getFirstPacket({...n,metadataOnly:!0}):null;if(c){let t=c.timestamp+s;this.segmentedInput.learnedSegmentTimestampOffset=t-i.timestamp;let r=e-t;if(r<-i.duration||r>=2*i.duration){let t=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:n.skipLiveWait});if(t!==i){i=t;continue}}}let l=Cs(e,s,await o.getTimeResolution()),u=r?await o._backing.getKeyPacket(l,n):await o._backing.getPacket(l,n);if(!u){i=await this.segmentedInput.getPreviousSegment(i,{skipLiveWait:n.skipLiveWait});continue}let d=r?await o._backing.getPacket(l,{...n,metadataOnly:!0}):u;if(t(d),l>=d.timestamp+d.duration){let t=await this.segmentedInput.getNextSegment(i,{skipLiveWait:n.skipLiveWait});if(t){let a=this.segmentedInput.getInputForSegment(t),o=(await a.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number),s=o?await o._backing.getFirstPacket({...n,metadataOnly:!0}):null;if(s&&r&&s.type!==`key`&&(s=await o._backing.getNextKeyPacket(s,{...n,metadataOnly:!0})),s){let n=await this.segmentedInput.getMediaOffset(t,a),r=Cs(e,n,await o.getTimeResolution());if(s.timestamp<=r){i=t;continue}}}}return this.createAdjustedPacket(u,i,o)}return null}};const Cs=(e,t,n)=>(Math.floor(Ae(n*e))-Math.round(n*t))/n;var ws=class extends Ss{getType(){return`video`}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getTransformationMatrix(){return this.delegate(()=>this.firstInputTrack._backing.getTransformationMatrix())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}},Ts=class extends Ss{getType(){return`audio`}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}
311
+ /*!
312
+ * Copyright (c) 2026-present, Vanilagy and contributors
313
+ *
314
+ * This Source Code Form is subject to the terms of the Mozilla Public
315
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
316
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
317
+ */
318
+ ;(/* @__PURE__ */ e(((e,t)=>{t.exports={}})))(),st();const Es=1/0;var Ds=class extends _t{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,typeof FinalizationRegistry<`u`&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new Vc;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e===void 0&&(await this._read(0,1,0,Es),e=this._getFileSize(),t(e!==void 0)),e})()}async getSize(){if(this._disposed)throw new Vc;let e=await this.getSizeOrNull();if(e===null)throw Error(`Cannot determine the size of an unsized source.`);return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw TypeError(`length, when provided, must be a non-negative integer.`);return new Fs(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit(`read`,{start:e,end:t})}ref(){return new Os(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},Os=class{constructor(e){if(this._freed=!1,e._disposed)throw Error(`Cannot ref a disposed source.`);e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw Error(`Can't get source; ref has already been freed.`);return this._source}get freed(){return this._freed}free(){if(this._freed)throw Error(`Illegal operation: double free on SourceRef.`);let e=this.source;t(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}},ks=class extends Ds{constructor(e,t){if(typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`requestHandler must be a function.`);super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){let t=this.requestHandler(e),n=e=>{if(!(e instanceof Ds||e instanceof Os))throw TypeError(`requestHandler must return or resolve to a Source or SourceRef.`);let t=e instanceof Ds?e.ref():e;return t.source._usedForHls||=this._usedForHls,t};return j(t)?t.then(n):n(t)}};const As=(e,t)=>e.path===t.path;var js=class extends ks{constructor(){super(...arguments),this._root=null,this._rootRequest=null,this._removeRootReadListener=null}_read(e,n,r,i){if(!this._root){if(!this._rootRequest){let e=this._resolveRequest({path:this.rootPath,isRoot:!0}),n=e=>{let t=e instanceof Ds?e.ref():e;return this._root=t,this._rootRequest=null,this._removeRootReadListener=t.source.on(`read`,({start:e,end:t})=>{this._dispatchRead(e,t)}),t};j(e)?this._rootRequest=e.then(n):(n(e),t(this._root))}if(this._rootRequest)return this._rootRequest.then(()=>this._read(e,n,r,i))}let a=this._root.source;return n>(a._getFileSize()??1/0)?null:a._read(e,n,r,i)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?(this._removeRootReadListener(),this._root.free()):this._rootRequest&&this._rootRequest.then(e=>{this._removeRootReadListener(),e.free()}).catch(()=>{})}},Ms=class extends Ds{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw TypeError(`buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.`);super(),this._onreadCalled=!1,this._bytes=b(e),this._view=x(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||=(this._dispatchRead(0,this._bytes.byteLength),!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}};typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}),typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e.close()});var Ns=class extends Ds{constructor(e,t={}){if(!(e instanceof ReadableStream))throw TypeError(`stream must be a ReadableStream.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.handleUnhandledError!==void 0&&typeof t.handleUnhandledError!=`function`)throw TypeError(`options.handleUnhandledError, when provided, must be a function.`);if(t.maxCacheSize!==void 0&&(!ct(t.maxCacheSize)||t.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._cacheMissErrorMessage=`Attempted to read data from an already-evicted part of the cache. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.`,this._stream=e,this._maxCacheSize=t.maxCacheSize??32*2**20,this._handleUnhandledError=t.handleUnhandledError}_getFileSize(){return this._endIndex}_read(e,t){if(this._endIndex!==null&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);let n=D(this._cache,e,e=>e.start),r=n===-1?null:this._cache[n];if(r&&r.start<=e&&t<=r.end)return{bytes:r.bytes,view:r.view,offset:r.start};let i=e,a=[];if(n!==-1)for(let r=n;r<this._cache.length;r++){let n=this._cache[r];if(n.start>=t)break;let o=Math.max(e,n.start);o>i&&this._throwDueToCacheMiss();let s=Math.min(t,n.end);o<s&&(a.push({start:o,bytes:n.bytes.subarray(o-n.start,s-n.start)}),i=s)}if(i===t)return Ps(e,t,a);this._currentIndex>i&&this._throwDueToCacheMiss();let{promise:o,resolve:s,reject:c}=O();return this._pendingSlices.push({start:e,end:t,parts:a,resolve:s,reject:c}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(e=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0;else if(this._handleUnhandledError)this._handleUnhandledError(e);else throw e})),o}_throwDueToCacheMiss(){throw Error(this._cacheMissErrorMessage)}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex<this._targetIndex&&!this._disposed;){let{done:e,value:t}=await this._reader.read();if(e){for(let e of this._pendingSlices)e.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let n=this._currentIndex,r=this._currentIndex+t.byteLength;this._dispatchRead(n,r);for(let e=0;e<this._pendingSlices.length;e++){let i=this._pendingSlices[e],a=Math.max(n,i.start),o=Math.min(r,i.end);a<o&&(i.parts.push({start:a,bytes:t.subarray(a-n,o-n)}),o===i.end&&(i.resolve(Ps(i.start,i.end,i.parts)),this._pendingSlices.splice(e,1),e--))}for(this._cache.push({start:n,end:r,bytes:t,view:x(t),age:0});this._cache.length>0;){let e=this._cache[0];if(this._maxRequestedIndex-e.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){for(let e of this._pendingSlices)e.reject(new Vc);this._pendingSlices.length=0,this._cache.length=0,(this._reader??this._stream).cancel().catch(()=>{})}};const Ps=(e,t,n)=>{let r=new Uint8Array(t-e);for(let t of n)r.set(t.bytes,t.start-e);return{bytes:r,view:x(r),offset:e}};var Fs=class extends Ds{constructor(e,t,n){if(super(),this._ref=null,this._removeReadListener=null,e._disposed)throw Error(`Cannot create a slice of a disposed source.`);this._baseSource=e,this._offset=t,this._length=n??null}_getFileSize(){if(this._length!==null)return this._length;let e=this._baseSource._getFileSize();return e==null?e:Math.max(e-this._offset,0)}_read(e,t,n,r){if(this._length!==null&&t>this._length)return null;let i=this._baseSource._getFileSize(),a=typeof i==`number`&&this._offset+t>i?null:this._baseSource._read(this._offset+e,this._offset+t,this._offset+n,this._offset+r),o=e=>{if(!e){if(this._length!==null){let e=this._offset+this._length;throw Error(`Underlying data too short, expected a length of at least ${e} bytes.`)}return null}return e.offset-=this._offset,e};return j(a)?a.then(o):o(a)}_dispose(){this._ref?.free(),this._removeReadListener?.()}ref(){return this._ref||(this._ref=this._baseSource.ref(),this._removeReadListener=this._baseSource.on(`read`,({start:e,end:t})=>{let n=Math.max(e-this._offset,0),r=Math.min(t-this._offset,this._length??1/0);n<r&&this._dispatchRead(n,r)})),super.ref()}},Is=function(e,t,n){
319
+ /*!
320
+ * Copyright (c) 2026-present, Vanilagy and contributors
321
+ *
322
+ * This Source Code Form is subject to the terms of the Mozilla Public
323
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
324
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
325
+ */
326
+ if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},Ls=(function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var r,i=0;function a(){for(;r=t.stack.pop();)try{if(!r.async&&i===1)return i=0,t.stack.push(r),Promise.resolve().then(a);if(r.dispose){var e=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(e).then(a,function(e){return n(e),a()})}else i|=1}catch(e){n(e)}if(i===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return a()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r});const Rs=/^0[xX][0-9a-fA-F]+$/,zs=/^data:.*;base64,/i,Bs=1e9;var Vs=class extends bs{constructor(e,t,n,r){super(e.input,t,n),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.neverRemovesSegments=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.segmentTimestampOffsetPromise=null,this.rootPath=t,this.demuxer=e,this.nextLines=r}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let e=this.getRemainingWaitTimeMs();e>0&&await ht(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){let e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){let n={stack:[],error:void 0,hasError:!1};try{let r=Is(n,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),i=new Hc(r.source),a=i.requestSliceRange(0,0,64);if(j(a)&&(a=await a),a&&!w.decode(V(a,a.length)).trimStart().startsWith(`#EXTM3U`))throw Error(`Invalid M3U8 file; expected first line to be #EXTM3U.`);let o=await i.requestEntireFile();t(o),e=il(o,o.length,{ignore:ms}),r.source instanceof ks&&(this.rootPath=r.source.rootPath)}catch(e){n.error=e,n.hasError=!0}finally{Ls(n)}}let n=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1&&(this.segments.length===0||this.segments[0].unixEpochTimestamp===this.segments[0].timestamp),r=new ys(this.rootPath,this.demuxer.hasMasterPlaylist?this.demuxer.masterPlaylistVariables:null),i=!1,a=0,o=null,s=null,c=null,l=0,u=0,d=null,f=null,p=null,h=null,g=null,_=m(this.segments)??null,v=e=>{let t=e.indexOf(`@`),n=Number(t===-1?e:e.slice(0,t));if(!Number.isInteger(n)||n<0)throw Error(`Invalid #EXT-X-BYTERANGE length '${e}'.`);let r=null;if(t!==-1&&(r=Number(e.slice(t+1)),!Number.isInteger(r)||r<0))throw Error(`Invalid #EXT-X-BYTERANGE offset '${e}'.`);return{length:n,offset:r}},y=e=>{if(l=e,_&&(t(_.sequenceNumber!==null),_.sequenceNumber<e)){let t=(e-_.sequenceNumber)*_.duration;a=_.timestamp+t,d=_.firstSegment??_,f=_.initSegment,g=_.lastProgramDateTimeSeconds,o=_.unixEpochTimestamp===null?null:_.unixEpochTimestamp+t,_=null}};for(let t=0;t<e.length;t++){let m=e[t];if(i){if(!m.startsWith(`#`)){if(!_){if(s===null)throw Error(`Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.`);let e=c;if(e&&e.method===`AES-128`&&!e.iv){let t=/* @__PURE__ */ new Uint8Array(16),n=x(t);n.setUint32(8,Math.floor(l/2**32)),n.setUint32(12,l),e={...e,iv:t}}let t={path:lt(this.rootPath,r.substitute(m)),offset:h?.offset??0,length:h?.length??null};d&&d.discontinuityNumber!==u&&(d=null);let n={index:this.segments.length,timestamp:a,unixEpochTimestamp:o,discontinuityNumber:u,firstSegment:d,sequenceNumber:l,location:t,duration:s,encryption:e,initSegment:f,lastProgramDateTimeSeconds:g};d??=n,a+=s,o!==null&&(o+=s),this.segments.push(n)}s=null,h===null?p=null:h=null,y(l+1)}if(m.startsWith(`#EXTINF:`)){if(_)continue;let e=m.slice(8),t=e.indexOf(`,`),n=t===-1?e:e.slice(0,t),r=Number(n);if(!Number.isFinite(r)||r<0||r>Bs)throw Error(`Invalid #EXTINF tag duration '${n}'.`);s=r}else if(m.startsWith(`#EXT-X-DEFINE:`))r.define(m.slice(14));else if(m.startsWith(`#EXT-X-MAP:`)){let e=new hs(m.slice(11),r),t=e.get(`uri`);if(!t)throw Error(`Invalid #EXT-X-MAP tag; missing URI attribute.`);let n=e.get(`byterange`),i=null;if(n!==null&&(i=v(n)),i&&i.offset===null)throw Error(`Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.`);if(!_){let e={path:lt(this.rootPath,t),offset:i?.offset??0,length:i?.length??null};if(c?.method===`AES-128`&&!c.iv)throw Error(`IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.`);f={index:-1,timestamp:a,unixEpochTimestamp:o,discontinuityNumber:u,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:c,initSegment:null,lastProgramDateTimeSeconds:g}}}else if(m.startsWith(`#EXT-X-KEY:`)){let e=new hs(m.slice(11),r),t=e.get(`method`);if(t===`NONE`)c=null;else if(t===`AES-128`){let t=e.get(`uri`);if(!t)throw Error(`Invalid #EXT-X-KEY: AES-128 requires a URI attribute.`);let n=null,r=e.get(`iv`);if(r){if(!Rs.test(r))throw Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,`0`),e=e.slice(-32),n=/* @__PURE__ */ new Uint8Array(16);for(let t=0;t<16;t++){let r=2*t;n[t]=parseInt(e.slice(r,r+2),16)}}let i=e.get(`keyformat`)??`identity`;if(i!==`identity`)throw Error(`For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.`);c={method:`AES-128`,keyUri:lt(this.rootPath,t),iv:n,keyFormat:i}}else if(t===`SAMPLE-AES`||t===`SAMPLE-AES-CTR`){let n=e.get(`uri`);if(!n)throw Error(`Invalid #EXT-X-KEY: ${t} requires a URI attribute.`);if((e.get(`keyformat`)??`identity`)===`identity`)throw Error(`For SAMPLE-AES and SAMPLE-AES-CTR encryption, the 'identity' KEYFORMAT is not supported. If you think this format should be supported, please raise an issue.`);let r=null;if(zs.test(n)){let e=n.indexOf(`,`),t=it(n.slice(e+1));if(t.length>=8&&t[4]===112&&t[5]===115&&t[6]===115&&t[7]===104){let e=x(t).getUint32(0);r=Hi(t.subarray(8,Math.min(e,t.length)))}}c={method:t,psshBox:r}}else throw Error(`Unsupported encryption method '${t}'. If you think this method should be supported, please raise an issue.`)}else if(m.startsWith(`#EXT-X-MEDIA-SEQUENCE:`)){let e=m.slice(22),t=Number(e);if(!Number.isSafeInteger(t)||t<0)throw Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);y(t)}else if(m.startsWith(`#EXT-X-BYTERANGE:`)){let e=v(m.slice(17));if(e.offset===null){if(p===null)throw Error(`Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.`);e.offset=p}h=e,p=e.offset+e.length}else if(m.startsWith(`#EXT-X-PROGRAM-DATE-TIME:`)){if(_)continue;let e=m.slice(25),t=Date.parse(e);if(!Number.isFinite(t))continue;let r=t/1e3;if(g===r)continue;if(g===null&&this.segments.length>0){let e=r-a;for(let t of this.segments)t.unixEpochTimestamp=t.timestamp+e,n&&(t.timestamp=t.unixEpochTimestamp)}g=r,o=r,n&&(a=r)}else if(m===`#EXT-X-DISCONTINUITY`)d=null,u++;else if(m.startsWith(`#EXT-X-DISCONTINUITY-SEQUENCE:`)){let e=m.slice(30),t=Number(e);if(!Number.isSafeInteger(t)||t<0)throw Error(`Invalid EXT-X-DISCONTINUITY-SEQUENCE value '${e}'.`);u=t}else if(m.startsWith(`#EXT-X-TARGETDURATION:`)){let e=m.slice(22),t=Number(e);if(!Number.isFinite(t)||t<0||t>Bs)throw Error(`Invalid EXT-X-TARGETDURATION value '${e}'.`);this.refreshInterval=A(t,.5,3600)}else if(m===`#EXT-X-I-FRAMES-ONLY`)this.hasOnlyKeyPackets=!0;else if(m===`#EXT-X-ENDLIST`){this.streamHasEnded=!0;break}else if(m.startsWith(`#EXT-X-PLAYLIST-TYPE:`)){let e=m.slice(21).toLowerCase();e===`vod`&&(this.streamHasEnded=!0),(e===`vod`||e===`event`)&&(this.neverRemovesSegments=!0)}}else{if(m!==`#EXTM3U`)throw Error(`Invalid M3U8 file; expected first line to be #EXTM3U.`);i=!0}}if(!i)throw Error(`Invalid M3U8 file; no #EXTM3U header.`)}async getFirstSegment(){return this.segments.length===0&&!this.streamHasEnded&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){this.segments.length===0&&!this.streamHasEnded&&!(t.skipLiveWait&&this.getRemainingWaitTimeMs()>0)&&await this.runUpdateSegments();let n=e-(this.learnedSegmentTimestampOffset??0),r=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){let e=D(this.segments,n,e=>e.timestamp);if(e===-1)return null;if(e<this.segments.length-1||this.streamHasEnded||r)return this.segments[e];let i=this.segments[e];if(n<i.timestamp+i.duration)return i;await this.runUpdateSegments(),t.skipLiveWait&&(r=!0)}}async getNextSegment(e,n){let r=e.index;t(r!==-1);let i=r+1,a=!!n.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(i<this.segments.length)return this.segments[i];if(this.streamHasEnded||a)return null;await this.runUpdateSegments(),n.skipLiveWait&&(a=!0)}}async getPreviousSegment(e){let n=e.index;return t(n!==-1),this.segments[n-1]??null}getInputForSegment(e){let n=e,r=this.inputCache.find(e=>e.segment===n);if(r)return r.age=this.nextInputCacheAge++,r.input;let i=null;(n.initSegment||n.firstSegment)&&(i=this.getInputForSegment(n.initSegment??n.firstSegment));let a={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(e=>{if(!n.encryption||n.encryption.method!==`SAMPLE-AES`&&n.encryption.method!==`SAMPLE-AES-CTR`||!n.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(e);let t=e.psshBoxes,{psshBox:r}=n.encryption;return(r.keyIds===null||r.keyIds.includes(e.keyId))&&!t.some(e=>Ui(e,r))&&(t=[...t,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:t})})}},o=new zc({source:new js(n.location.path,async e=>{t(e.isRoot);let r={...e,isRoot:!1},i,a=n.location.offset>0||n.location.length!==null;if(!n.encryption||n.encryption.method===`SAMPLE-AES`||n.encryption.method===`SAMPLE-AES-CTR`){if(i=await this.input._getSourceCached(r),a){let e=i.source.slice(n.location.offset,n.location.length??void 0).ref();i.free(),i=e}}else if(n.encryption.method===`AES-128`){let e=n.encryption;t(e.iv);let o=await this.input._getSourceCached(r);if(a){let e=o.source.slice(n.location.offset,n.location.length??void 0).ref();o.free(),o=e}let s=new Hc(o.source);i=new Ns(ea(s,async()=>{let t={stack:[],error:void 0,hasError:!1};try{let n=await new Hc(Is(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},2),!1).source).requestSlice(0,16);if(!n)throw Error(`Invalid AES-128 key; expected at least 16 bytes of data.`);return{key:V(n,16),iv:e.iv}}catch(e){t.error=e,t.hasError=!0}finally{Ls(t)}},()=>{o.free()})).ref()}else t(!1);return i}),formats:this.input._formats.filter(e=>!(e instanceof cc)),initInput:i??void 0,formatOptions:a});if(o._onFormatDetermined=e=>{if((n.encryption?.method===`SAMPLE-AES`||n.encryption?.method===`SAMPLE-AES-CTR`)&&!e._isIsobmff)throw Error(`The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.`)},this.inputCache.push({segment:n,input:o,age:this.nextInputCacheAge++}),this.inputCache.length>4){let e=ft(this.inputCache,e=>e.age);t(e!==-1),this.inputCache.splice(e,1)}return o}async getLiveRefreshInterval(){return!this.streamHasEnded&&this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}getMediaOffsetForDiscontinuity(e){return this.demuxer.getMediaOffsetForDiscontinuity(e)}getFirstSegmentTimestampOffset(){return this.segmentTimestampOffsetPromise??=(async()=>{let e=await this.getFirstSegment();t(e);let n=this.demuxer.getReferenceSegmentedInput();if(this===n)return 0;let r=await n.getFirstSegment();if(r&&(this.listsAllSegments()&&n.listsAllSegments()||e.unixEpochTimestamp===e.timestamp&&r.unixEpochTimestamp===r.timestamp))return 0;let i=this.getInputForSegment(e);if(await this.getRawTimestampOffset(i)===null)return 0;let a=await xs(i);if(a===null)throw Error(`The playlist's first segment contains no media.`);let o=a+await this.getMediaOffset(e,i)-e.timestamp;return this.learnedSegmentTimestampOffset??=o,o})()}listsAllSegments(){return this.segments[0].sequenceNumber===0||this.neverRemovesSegments}async getRawTimestampOffset(e){if((await e.getFormat()).supportsTimestampedMediaData)return 0;let t=(await e.getMetadataTags()).raw?.PRIV;for(let n of gt(t)){if(!(n instanceof Uint8Array)||n.length!==53||w.decode(n.subarray(0,44))!==`com.apple.streaming.transportStreamTimestamp`||n[44]!==0)continue;let t=x(n),r=t.getUint32(45),i=t.getUint32(49);if(r>1)continue;let a=2**32*r+i;return ts(a,es(a))/Zo-await e.getFirstTimestamp()}return null}getTimestampWrapPeriod(){return Qo/Zo}},Hs=class extends zi{constructor(e){
327
+ /*!
328
+ * Copyright (c) 2026-present, Vanilagy and contributors
329
+ *
330
+ * This Source Code Form is subject to the terms of the Mozilla Public
331
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
332
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
333
+ */
334
+ super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0,this.masterPlaylistVariables=null,this.mediaOffsets=/* @__PURE__ */ new Map}readMetadata(){return this.metadataPromise??=(async()=>{t(this.input._rootSource instanceof ks);let e=await this.input._reader.requestEntireFile();t(e);let n=il(e,e.length,{ignore:ms}),{rootPath:r}=this.input._rootSource,i=new ys(r,null),a=[],o=[];for(let e=1;e<n.length;e++){let t=n[e];if(t.startsWith(`#EXT-X-DEFINE:`))i.define(t.slice(14));else if(t.startsWith(`#EXT-X-STREAM-INF:`)){let o=e,s=n[++e];if(s===void 0)throw Error(`Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.`);s=i.substitute(s);let c=lt(r,s),l=new hs(t.slice(18),i);if(l.getAsNumber(`bandwidth`)===null)throw Error(`Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.`);a.push({fullPath:c,attributes:l,lineNumber:o,hasOnlyKeyPackets:!1})}else if(t.startsWith(`#EXT-X-I-FRAME-STREAM-INF:`)){let n=new hs(t.slice(26),i),o=n.get(`uri`);if(o===null)throw Error(`Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.`);if(n.getAsNumber(`bandwidth`)===null)throw Error(`Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.`);let s=lt(r,o);a.push({fullPath:s,attributes:n,lineNumber:e,hasOnlyKeyPackets:!0})}else if(t.startsWith(`#EXT-X-MEDIA:`)){let n=new hs(t.slice(13),i);if(n.get(`type`)===null)throw Error(`Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.`);if(n.get(`group-id`)===null)throw Error(`Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.`);let a=null,s=n.get(`uri`);s!==null&&(a=lt(r,s)),o.push({fullPath:a,attributes:n,lineNumber:e})}else if(t.startsWith(`#EXTINF:`)){let e=new Vs(this,r,null,n);this.segmentedInputs=[e],this.hasMasterPlaylist=!1,this.trackBackings=await e.getTrackBackings();return}}if(a.length>256||o.length>256)throw Error(`Unsupported M3U8 file; too many variant streams or media tags.`);this.masterPlaylistVariables=i;let s=await Promise.all(a.map(async(e,n)=>{let i=[],a=e.attributes.get(`codecs`),s;if(a)s=a.split(`,`).map(e=>e.trim());else{let t=await this.getSegmentedInputForPath(e.fullPath).getTrackBackings(),n=await Promise.all(t.map(async e=>({track:e,codec:await e.getCodec()})));s=await Promise.all(n.filter(e=>e.codec!==null).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}let c=e.attributes.get(`video`),l=e.attributes.get(`audio`),u=s.some(e=>Fl.includes(su(e))),d=s.some(e=>Rl.includes(su(e)));if(c!==null&&!u){let e=o.find(e=>{let t=e.attributes.get(`group-id`),n=e.attributes.get(`type`);return t===c&&n.toLowerCase()===`video`});outer:if(e){let n=e.attributes.get(`uri`);if(n===null)break outer;let i=lt(r,n),a=(await this.getSegmentedInputForPath(i).getTrackBackings()).find(e=>e.getType()===`video`);if(!a||await a.getCodec()===null)break outer;let o=await a.getDecoderConfig().then(e=>e?.codec??null);t(o!==null),s.push(o)}}if(l!==null&&!d){let e=o.find(e=>{let t=e.attributes.get(`group-id`),n=e.attributes.get(`type`);return t===l&&n.toLowerCase()===`audio`});outer:if(e){let n=e.attributes.get(`uri`);if(n===null)break outer;let i=lt(r,n),a=(await this.getSegmentedInputForPath(i).getTrackBackings()).find(e=>e.getType()===`audio`);if(!a||await a.getCodec()===null)break outer;let o=await a.getDecoderConfig().then(e=>e?.codec??null);t(o!==null),s.push(o)}}s=[...new Set(s)];let f=e.attributes.getAsNumber(`bandwidth`);t(f!==null);let p=e.attributes.getAsNumber(`average-bandwidth`),m=e.attributes.get(`name`),h=async(e,n,r)=>{let i=new Set(e.map(e=>su(e)));if(i.size===1){let[n]=i;return t(n),{codec:n,fullCodecString:e.length===1?e[0]:null}}let a=(await this.getSegmentedInputForPath(n).getTrackBackings()).filter(e=>e.getType()===r);if(a.length!==1)throw Error(`Unsupported M3U8 file; a variant stream lists several ${r} codecs, but its media doesn't contain exactly one ${r} track.`);let o=await a[0].getCodec();if(o===null)return null;let s=await a[0].getDecoderConfig();return t(s),{codec:o,fullCodecString:s.codec}},g=s.filter(e=>Fl.includes(su(e))),_=s.filter(e=>Rl.includes(su(e)));for(let t of s)if(t===g[0]){let t=o.filter(e=>e.attributes.get(`group-id`)===c&&e.attributes.get(`type`).toLowerCase()===`video`);if(t.length===0){let t=e.attributes.get(`resolution`),r=null,a=null;if(t){let e=t.match(/^(\d+)x(\d+)$/);e&&(r=Number(e[1]),a=Number(e[2]))}let o=await h(g,e.fullPath,`video`);o&&i.push({demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:`und`,lineNumber:e.lineNumber,fullPath:e.fullPath,codec:o.codec,fullCodecString:o.fullCodecString,pairingMask:1n<<BigInt(n),peakBitrate:f,averageBitrate:p,name:m,hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`video`,width:r,height:a}})}else{let r=await Promise.all(t.map(t=>h(g,t.fullPath??e.fullPath,`video`)));for(let a=0;a<t.length;a++){let o=t[a],s=r[a];if(!s)continue;let c=o.attributes.get(`resolution`)??e.attributes.get(`resolution`),l=null,u=null;if(c){let e=c.match(/^(\d+)x(\d+)$/);e&&(l=Number(e[1]),u=Number(e[2]))}i.push({demuxer:this,backingTrack:null,default:Ks(o.attributes),autoselect:Ks(o.attributes)||qs(o.attributes),languageCode:Js(o.attributes.get(`language`)),lineNumber:o.lineNumber,fullPath:o.fullPath??e.fullPath,codec:s.codec,fullCodecString:s.fullCodecString,pairingMask:1n<<BigInt(n),peakBitrate:o.fullPath===null?f:null,averageBitrate:o.fullPath===null?p:null,name:o.attributes.get(`name`),hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`video`,width:l,height:u}})}}}else if(t===_[0]){let t=o.filter(e=>e.attributes.get(`group-id`)===l&&e.attributes.get(`type`).toLowerCase()===`audio`);if(t.length===0){let t=await h(_,e.fullPath,`audio`);if(t){let r=e.attributes.get(`channels`);i.push({demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:`und`,lineNumber:e.lineNumber,fullPath:e.fullPath,codec:t.codec,fullCodecString:t.fullCodecString,pairingMask:1n<<BigInt(n),peakBitrate:f,averageBitrate:p,name:m,hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`audio`,numberOfChannels:Ys(r)}})}}else{let r=await Promise.all(t.map(t=>h(_,t.fullPath??e.fullPath,`audio`)));for(let a=0;a<t.length;a++){let o=t[a],s=r[a];if(!s)continue;let c=o.attributes.get(`channels`)??e.attributes.get(`channels`);i.push({demuxer:this,backingTrack:null,default:Ks(o.attributes),autoselect:Ks(o.attributes)||qs(o.attributes),languageCode:Js(o.attributes.get(`language`)),lineNumber:o.lineNumber,fullPath:o.fullPath??e.fullPath,codec:s.codec,fullCodecString:s.fullCodecString,pairingMask:1n<<BigInt(n),peakBitrate:o.fullPath===null?f:null,averageBitrate:o.fullPath===null?p:null,name:o.attributes.get(`name`),hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`audio`,numberOfChannels:Ys(c)}})}}}return i})),c=[],l=e=>{let t=c.find(t=>t.fullPath===e.fullPath&&t.info.type===e.info.type);t?(t.pairingMask|=e.pairingMask,t.default||=e.default,t.autoselect||=e.autoselect,t.lineNumber=Math.min(t.lineNumber,e.lineNumber),e.peakBitrate!==null&&(t.peakBitrate=Math.max(t.peakBitrate??-1/0,e.peakBitrate)),e.averageBitrate!==null&&(t.averageBitrate=Math.max(t.averageBitrate??-1/0,e.averageBitrate)),t.languageCode===`und`&&(t.languageCode=e.languageCode)):c.push(e)};for(let e of s)for(let t of e)l(t);c.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(let e of c)e.info.type===`video`?this.trackBackings.push(new Ws(e)):this.trackBackings.push(new Gs(e));this.internalTracks=c})()}async getTrackBackings(){return await this.readMetadata(),t(this.trackBackings),this.trackBackings}getMediaOffsetForDiscontinuity(e){let t=this.mediaOffsets.get(e);return t||(t=(async()=>{let t=this.getReferenceSegmentedInput(),n=await t.getFirstSegment();for(;n&&n.discontinuityNumber<e;)n=await t.getNextSegment(n,{});if(!n||n.discontinuityNumber!==e)throw Error(`The reference playlist contains no segment in discontinuity ${e}, so the discontinuity can't be synchronized across tracks. If you think this is a bug, please raise an issue and include the playlist.`);let r=t.getInputForSegment(n),i=await t.getRawTimestampOffset(r)??0,a=await xs(r);if(a===null)throw Error(`The reference playlist's segment contains no media.`);return n.timestamp-(i+a)})(),this.mediaOffsets.set(e,t),t)}getReferenceSegmentedInput(){if(!this.hasMasterPlaylist)return this.segmentedInputs[0];t(this.internalTracks);let e=this.internalTracks.filter(e=>!e.hasOnlyKeyPackets),n=e.length>0?e:this.internalTracks,r=n.filter(e=>e.info.type===`video`),i=r.length>0?r:n,a=ft(i,e=>e.peakBitrate??1/0);return t(a!==-1),this.getSegmentedInputForPath(i[a].fullPath)}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(t=>t.path===e);if(t)return t;let n=null;return this.internalTracks&&(n=this.internalTracks.filter(t=>t.fullPath===e).map(e=>({type:e.info.type}))),t=new Vs(this,e,n,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return ps}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},Us=class{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),n=null,r=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(r.length===1)n=r[0];else if(this instanceof Ws){for(let e of r)if(await e.getCodec()===this.getCodec()){n=e;break}}else{t(this instanceof Gs);for(let e of r)if(await e.getCodec()===this.getCodec()){n=e;break}}if(!n)throw Error(`Could not find matching track in underlying media data.`);this.internalTrack.backingTrack=n})()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw Error(`Not implemented on base class.`)}getDisposition(){return{...Dt,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){t(this.internalTrack.demuxer.internalTracks);let e=this.internalTrack.info.type,n=0;for(let t of this.internalTrack.demuxer.internalTracks)if(t.info.type===e&&n++,t===this.internalTrack)break;return n}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}},Ws=class extends Us{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return`video`}getCodec(){return this.internalTrack.codec}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getTransformationMatrix(){return this.delegate(()=>this.backingVideoTrack.getTransformationMatrix())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){if(await this.hydrate(),await this.backingVideoTrack.getCodec()!==this.getCodec())throw Error(`The codec in the playlist doesn't match the codec of the media data.`);return this.backingVideoTrack.getDecoderConfig()}},Gs=class extends Us{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return`audio`}getCodec(){return this.internalTrack.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels===null?this.delegate(()=>this.backingAudioTrack.getNumberOfChannels()):this.internalTrack.info.numberOfChannels}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){if(await this.hydrate(),await this.backingAudioTrack.getCodec()!==this.getCodec())throw Error(`The codec in the playlist doesn't match the codec of the media data.`);return this.backingAudioTrack.getDecoderConfig()}};const Ks=e=>{let t=e.get(`default`);if(t===null)return!1;let n=t.toUpperCase();if(n===`YES`)return!0;if(n===`NO`)return!1;throw Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${t}".`)},qs=e=>{let t=e.get(`autoselect`);if(t===null)return!1;let n=t.toUpperCase();if(n===`YES`)return!0;if(n===`NO`)return!1;throw Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${t}".`)},Js=e=>e===null?`und`:e.split(`-`)[0]||`und`,Ys=e=>{if(e===null)return null;let[t,n]=e.split(`/`);if(n!==void 0&&n!==`-`)return null;let r=Number(t);return Number.isInteger(r)&&r>0?r:null};
335
+ /*!
336
+ * Copyright (c) 2026-present, Vanilagy and contributors
337
+ *
338
+ * This Source Code Form is subject to the terms of the Mozilla Public
339
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
340
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
341
+ */
342
+ var Xs=class{constructor(){this._isIsobmff=!1}},Zs=class extends Xs{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(j(t)&&(t=await t),!t)return null;let n=W(t),r=G(t,4);if(r!==`ftyp`&&r!==`styp`)return null;if(n===1){let t=e._reader.requestSlice(16,4);return j(t)&&(t=await t),t?G(t,4):null}return G(t,4)}_createDemuxer(e){return new na(e)}get supportsTimestampedMediaData(){return!0}},Qs=class extends Zs{async _getMatchPosition(e){let t=await this._getMajorBrand(e);if(t!==null)return t===`qt `?null:0;let n=0;for(let t=0;t<10;t++){let t=e._reader.requestSlice(n,8);if(j(t)&&(t=await t),!t)return null;let r=W(t),i=8;if(r===1){let t=e._reader.requestSlice(n+8,8);if(j(t)&&(t=await t),!t)return null;r=$c(t),i=16}if(r<i)return null;let a=G(t,4);if(a===`moof`||a===`sidx`||a===`moov`||a===`mdat`)return 0;if(a===`emsg`||a===`prft`||a===`free`||a===`skip`||a===`wide`)n+=r;else return null}return null}get name(){return`MP4`}get mimeType(){return`video/mp4`}},$s=class extends Zs{async _getMatchPosition(e){return await this._getMajorBrand(e)===`qt `?0:null}get name(){return`QuickTime File Format`}get mimeType(){return`video/quicktime`}},ec=class extends Xs{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,16);if(j(n)&&(n=await n),!n)return!1;let r=za(n);if(r===null||r<1||r>8||z(n,r)!==R.EBML)return!1;let i=Wa(n);if(typeof i!=`number`)return!1;let a=e._reader.requestSlice(n.filePos,i);if(j(a)&&(a=await a),!a)return!1;let o=n.filePos;for(;a.filePos<=o+i-2;){let e=Ga(a);if(!e)break;let{id:n,size:r}=e,s=a.filePos;if(r===void 0||s+r>o+i||r>8&&n!==R.DocType)return!1;switch(n){case R.EBMLReadVersion:if(z(a,r)!==1)return!1;break;case R.DocType:if(Ka(a,r)!==t)return!1;break;case R.DocTypeReadVersion:if(z(a,r)>4)return!1}a.filePos=s+r}return!0}async _getMatchPosition(e){return await this.isSupportedEBMLOfDocType(e,`matroska`)?0:null}_createDemuxer(e){return new ao(e)}get name(){return`Matroska`}get mimeType(){return`video/x-matroska`}get supportsTimestampedMediaData(){return!0}},tc=class extends ec{async _getMatchPosition(e){return await this.isSupportedEBMLOfDocType(e,`webm`)?0:null}get name(){return`WebM`}get mimeType(){return`video/webm`}},nc=class extends Xs{async _getMatchPosition(e){let t=await ho(e._reader,0),n=await yo(e._reader,t,4096,null);return n?n.startPos===t?0:n.startPos:null}_createDemuxer(e){return new xo(e)}get name(){return`MP3`}get mimeType(){return`audio/mpeg`}get supportsTimestampedMediaData(){return!1}},rc=class extends Xs{async _getMatchPosition(e){let t=e._reader.requestSlice(0,12);if(j(t)&&(t=await t),!t)return null;let n=G(t,4);return n!==`RIFF`&&n!==`RIFX`&&n!==`RF64`?null:(t.skip(4),G(t,4)===`WAVE`?0:null)}_createDemuxer(e){return new Fo(e)}get name(){return`WAVE`}get mimeType(){return`audio/wav`}get supportsTimestampedMediaData(){return!1}},ic=class extends Xs{async _getMatchPosition(e){let t=e._reader.requestSlice(0,4);return j(t)&&(t=await t),t&&G(t,4)===`OggS`?0:null}_createDemuxer(e){return new Ao(e)}get name(){return`Ogg`}get mimeType(){return`application/ogg`}get supportsTimestampedMediaData(){return!0}},ac=class extends Xs{async _getMatchPosition(e){let t=await ho(e._reader,0),n=e._reader.requestSlice(t,4);return j(n)&&(n=await n),n&&G(n,4)===`fLaC`?0:null}get name(){return`FLAC`}get mimeType(){return`audio/flac`}get supportsTimestampedMediaData(){return!1}_createDemuxer(e){return new Yo(e)}},oc=class extends Xs{async _getMatchPosition(e){let t=await ho(e._reader,0),n=await Ro(e._reader,t,4096,null);return n?n.startPos===t?0:n.startPos:null}_createDemuxer(e){return new Vo(e)}get name(){return`ADTS`}get mimeType(){return`audio/aac`}get supportsTimestampedMediaData(){return!1}},sc=class extends Xs{async _getMatchPosition(e){let t=e._reader.requestSlice(0,205);if(j(t)&&(t=await t),!t)return null;let n=V(t,205);return n[0]===71&&n[188]===71||n[0]===71&&n[204]===71||n[4]===71&&n[196]===71?0:null}_createDemuxer(e){return new as(e)}get name(){return`MPEG Transport Stream`}get mimeType(){return`video/MP2T`}get supportsTimestampedMediaData(){return!0}},cc=class extends Xs{async _getMatchPosition(e){let t=e._reader.requestSlice(0,7);if(j(t)&&(t=await t),!t||G(t,7)!==`#EXTM3U`)return null;if(!(e._rootSource instanceof ks))throw TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return e._rootSource._usedForHls=!0,0}_createDemuxer(e){return new Hs(e)}get name(){return`HTTP Live Streaming (HLS)`}get mimeType(){return ps}get supportsTimestampedMediaData(){return!0}};const lc=[/* @__PURE__ */ new cc,/* @__PURE__ */ new Qs,/* @__PURE__ */ new $s,/* @__PURE__ */ new ec,/* @__PURE__ */ new tc,/* @__PURE__ */ new rc,/* @__PURE__ */ new ic,/* @__PURE__ */ new ac,/* @__PURE__ */ new nc,/* @__PURE__ */ new oc,/* @__PURE__ */ new sc],uc=(e,t)=>{if(!e||typeof e!=`object`)throw TypeError(`${t}, when provided, must be an object.`);if(e.isobmff!==void 0){if(!e.isobmff||typeof e.isobmff!=`object`)throw TypeError(`${t}.isobmff, when provided, must be an object.`);if(e.isobmff.resolveKeyId!==void 0&&typeof e.isobmff.resolveKeyId!=`function`)throw TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(e.hls!==void 0){if(!e.hls||typeof e.hls!=`object`)throw TypeError(`${t}.hls, when provided, must be an object.`);if(e.hls.offsetTimestampsByDateTime!==void 0&&typeof e.hls.offsetTimestampsByDateTime!=`boolean`)throw TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}},dc=e=>{
343
+ /*!
344
+ * Copyright (c) 2026-present, Vanilagy and contributors
345
+ *
346
+ * This Source Code Form is subject to the terms of the Mozilla Public
347
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
348
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
349
+ */
350
+ if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.metadataOnly!==void 0&&typeof e.metadataOnly!=`boolean`)throw TypeError(`options.metadataOnly, when defined, must be a boolean.`);if(e.verifyKeyPackets!==void 0&&typeof e.verifyKeyPackets!=`boolean`)throw TypeError(`options.verifyKeyPackets, when defined, must be a boolean.`);if(e.verifyKeyPackets&&e.metadataOnly)throw TypeError(`options.verifyKeyPackets and options.metadataOnly cannot be enabled together.`);if(e.skipLiveWait!==void 0&&typeof e.skipLiveWait!=`boolean`)throw TypeError(`options.skipLiveWait, when defined, must be a boolean.`)},fc=e=>{if(!ct(e))throw TypeError(`timestamp must be a number.`)},pc=(e,t,n)=>n.verifyKeyPackets?t.then(async t=>{if(!t||t.type===`delta`)return t;let n=await e.determinePacketType(t);return n&&(t.type=n),t}):t;var mc=class{constructor(e){if(!(e instanceof Ec))throw TypeError(`track must be an InputTrack.`);this._track=e}async getFirstPacket(e={}){if(dc(e),this._track.input._disposed)throw new Vc;return pc(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){dc(e);let t=await this.getFirstPacket(e);return t?t.type===`key`?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(fc(e),dc(t),this._track.input._disposed)throw new Vc;return pc(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof L))throw TypeError(`packet must be an EncodedPacket.`);if(dc(t),this._track.input._disposed)throw new Vc;return pc(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,n={}){if(fc(e),dc(n),this._track.input._disposed)throw new Vc;if(!n.verifyKeyPackets)return this._track._backing.getKeyPacket(e,n);let r=await this._track._backing.getKeyPacket(e,n);for(;r;){if(t(r.type===`key`),await this._track.determinePacketType(r)!==`delta`)return r;let e=1/await this._track.getTimeResolution(),i;for(;i=await this._track._backing.getKeyPacket(r.timestamp-e,n),!(!i||i.timestamp<r.timestamp);)e*=2;r=i}return null}async getNextKeyPacket(e,n={}){if(!(e instanceof L))throw TypeError(`packet must be an EncodedPacket.`);if(dc(n),this._track.input._disposed)throw new Vc;if(!n.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,n);let r=await this._track._backing.getNextKeyPacket(e,n);for(;r;){if(t(r.type===`key`),await this._track.determinePacketType(r)!==`delta`)return r;r=await this._track._backing.getNextKeyPacket(r,n)}return null}packets(e,t,n={}){if(e!==void 0&&!(e instanceof L))throw TypeError(`startPacket must be an EncodedPacket.`);if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw TypeError(`startPacket can only be metadata-only if options.metadataOnly is enabled.`);if(t!==void 0&&!(t instanceof L))throw TypeError(`endPacket must be an EncodedPacket.`);if(dc(n),this._track.input._disposed)throw new Vc;let r=[],{promise:i,resolve:a}=O(),{promise:o,resolve:s}=O(),c=!1,l=!1,u=null,d=!1,f=[],p=()=>Math.max(2,f.length);(async()=>{let u=e??await this.getFirstPacket(n);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);)r.length>p()?({promise:o,resolve:s}=O(),await o):(r.push(u),a(),{promise:i,resolve:a}=O(),u=await this.getNextPacket(u,n));c=!0,a()})().catch(e=>{d||(u=e,d=!0,a())});let m=this._track;return{async next(){for(;;)if(m.input._disposed)throw new Vc;else if(l)return{value:void 0,done:!0};else if(d)throw u;else if(r.length>0){let e=r.shift(),t=performance.now();for(f.push(t);f.length>0&&t-f[0]>=1e3;)f.shift();return s(),{value:e,done:!1}}else if(c)return{value:void 0,done:!0};else await i},async return(){return l=!0,s(),a(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},hc=class{constructor(e,t){this.onSample=e,this.onError=t,this.onDequeue=null}},gc=class{mediaSamplesInRange(e=-1/0,t=1/0,n){fc(e),fc(t);let r=[],i=!1,a=null,{promise:o,resolve:s}=O(),{promise:c,resolve:l}=O(),u=!1,d=!1,f=!1,p=null,m=null,h=!1,g={...n,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{p=await this._createDecoder(n=>{l(),n.timestamp>=t&&(d=!0),d?n.close():(a&&(n.timestamp>e?(r.push(a),i=!0):a.close()),n.timestamp>=e&&(r.push(n),i=!0),a=i?null:n,r.length>0&&(s(),{promise:o,resolve:s}=O()))},e=>{h||(m=e,h=!0,s())}),p.onDequeue=()=>l();let n=this._createPacketSink(),_=await this._getPreRollDuration(),v=await n.getPacket(e,g),y=await n.getKeyPacket((v?.timestamp??e)-_,g)??await n.getFirstKeyPacket(g),b=y,x=n.packets(y??void 0,void 0,g);for(await x.next();b&&!d&&!this._track.input._disposed;){if(r.length+p.getDecodeQueueSize()>=4){({promise:c,resolve:l}=O()),await c;continue}p.decode(b);let e=await x.next();if(e.done)break;b=e.value}await x.return(),!f&&!this._track.input._disposed&&await p.flush(),!i&&a&&(r.push(a),a=null),u=!0,s()})().catch(e=>{h||(m=e,h=!0,s())}).finally(()=>{p?.close()});let _=this._track,v=()=>{a?.close();for(let e of r)e.close()};return{async next(){for(;;)if(_.input._disposed)throw f=!0,d=!0,l(),v(),new Vc;else if(f)return{value:void 0,done:!0};else if(h)throw f=!0,d=!0,l(),v(),m;else if(r.length>0){let e=r.shift();return l(),{value:e,done:!1}}else if(!u)await o;else return{value:void 0,done:!0}},async return(){return f=!0,d=!0,l(),s(),v(),{value:void 0,done:!0}},async throw(e){throw await this.return(),e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,n){Se(e);let r=xe(e),i=[],a=[],{promise:o,resolve:s}=O(),{promise:c,resolve:l}=O(),u=!1,d=!1,{promise:f,resolve:p}=O(),m=null,h=null,g=!1,_=e=>{a.push(e),s(),{promise:o,resolve:s}=O()},v=null,y=e=>{for(let t=0;t<e;t++)_(v&&(t<e-1?v.clone():v));e===0&&v?.close(),v=null},b={...n,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{m=await this._createDecoder(e=>{if(l(),d){e.close();return}let t=0;for(;i.length>0&&e.timestamp-i[0]>1e-10;)t++,i.shift();y(t),v=e},e=>{g||(h=e,g=!0,s())}),m.onDequeue=()=>l();let e=this._createPacketSink(),n=await this._getPreRollDuration(),o=null,p=-1/0,x=null,S=null,C=-1,w=async()=>{t(x),t(m);let n=S;for(n||(n=x,m.decode(n));n.sequenceNumber<C;){for(;a.length+m.getDecodeQueueSize()>=4&&!d;)({promise:c,resolve:l}=O()),await c;if(d)break;let t=await e.getNextPacket(n,b);if(!t)throw Error(`Internal error: couldn't get next packet when one was expected.`);m.decode(t),n=t}S=n},ee=async()=>{t(m),await m.flush(),y(i.length),i.length=0};try{for(;;){let t=r.next();t.catch(()=>{});let a=await Promise.race([t,f]);if(!a||a.done)break;let s=a.value;if(fc(s),d||this._track.input._disposed)break;let c=await e.getPacket(s,b),l=c&&await e.getKeyPacket(c.timestamp-n,b);if(c&&!l){let t=await e.getFirstKeyPacket(b);t&&t.timestamp<=c.timestamp&&(l=t)}!c||!l?(o&&await ee(),_(null),o=null):((!o||l.sequenceNumber>C+1||s<p)&&(o&&await ee(),x=l,S=null,C=-1),i.push(s),C=Math.max(c.sequenceNumber,C),o=c,p=s,await w())}}finally{r.return().catch(()=>{})}!d&&!this._track.input._disposed&&await ee(),u=!0,s()})().catch(e=>{g||(h=e,g=!0,s())}).finally(()=>{m?.close()});let x=this._track,S=()=>{v?.close(),v=null;for(let e of a)e?.close()};return{async next(){for(;;)if(x.input._disposed)throw d=!0,p(),l(),S(),new Vc;else if(d)return{value:void 0,done:!0};else if(g)throw d=!0,p(),l(),S(),h;else if(a.length>0){let e=a.shift();return t(e!==void 0),l(),{value:e,done:!1}}else if(!u)await o;else return{value:void 0,done:!0}},async return(){return d=!0,p(),l(),s(),S(),{value:void 0,done:!0}},async throw(e){throw await this.return(),e},[Symbol.asyncIterator](){return this}}}},_c=class extends hc{constructor(e,n,r,i,a,o,s){super(e,n),this.codec=r,this.decoderConfig=i,this.rotation=a,this.flip=o,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Ve,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.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[],this.flushing=!1,this.frameCopyContext=null;let c=Ni.find(e=>e.supports(r,i));if(c)this.customDecoder=new c,this.customDecoder.codec=r,this.customDecoder.config=i,this.customDecoder.onSample=e=>{if(!(e instanceof Vr))throw TypeError(`The argument passed to onSample must be a VideoSample.`);this.finalizeAndEmitSample(e)},this.customDecoder.onError=e=>{n(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>n(e));else{let e=e=>{if(this.alphaQueue.length>0){let n=this.alphaQueue.shift();t(n!==void 0),this.mergeAlpha(e,n)}else this.colorQueue.push(e)};if(qe()){if(r===`avc`&&this.decoderConfig.description){let e=hn(b(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){let t=vn(e.sequenceParameterSets[0]);t&&t.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:`prefer-software`});let n=!1;for(let t=0;t<e.sequenceParameterSets.length;t++){let r=vn(e.sequenceParameterSets[t]);r&&r.maxDecFrameBuffering!==0&&r.bitstreamRestrictionFlag!==1&&(e.sequenceParameterSets[t]=bn(r),n=!0)}n&&(this.decoderConfig={...this.decoderConfig,description:mn(e)})}}se(this.decoderConfig.colorSpace)||(this.decoderConfig={...this.decoderConfig,colorSpace:{primaries:this.decoderConfig.colorSpace?.primaries??`bt709`,matrix:this.decoderConfig.colorSpace?.matrix??`bt709`,transfer:this.decoderConfig.colorSpace?.transfer??`bt709`,fullRange:this.decoderConfig.colorSpace?.fullRange??!1}})}let n=(/* @__PURE__ */ Error(`Decoding error`)).stack;this.decoder=new VideoDecoder({output:t=>{try{e(this.copyFrameIfNeeded(t))}catch(e){this.onError(e)}},error:e=>{e.stack=n,this.onError(e)}}),this.decoder.addEventListener(`dequeue`,()=>{this.onDequeue?.()}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(t(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0)+this.finalSamples.length)}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)).catch(e=>this.onError(e)).finally(()=>{this.customDecoderQueueSize--,this.onDequeue?.()});else{if(t(this.decoder),!Ue()){let t=Yn(this.codec,e.data);for(let n=0;n<t;n++)_e(this.inputTimestamps,e.timestamp,e=>e)}if(qe()&&this.currentPacketIndex===0){let t=this.fixFirstPacketDataForChromium(e.data);t&&(e=e.clone({data:t}))}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||=new yc,!this.alphaDecoder){let e=e=>{if(this.colorQueue.length>0){let n=this.colorQueue.shift();t(n!==void 0),this.mergeAlpha(n,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let e=this.colorQueue.shift();t(e!==void 0),this.mergeAlpha(e,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},n=(/* @__PURE__ */ Error(`Decoding error`)).stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(this.copyFrameIfNeeded(t))}catch(e){this.onError(e)}},error:e=>{e.stack=n,this.onError(e)}}),this.alphaDecoder.addEventListener(`dequeue`,()=>{this.onDequeue?.()}),this.alphaDecoder.configure({...this.decoderConfig,colorSpace:{fullRange:!0,matrix:`bt709`,primaries:`bt709`,transfer:`bt709`}})}let n=Jn(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||=n===`key`,this.alphaHadKeyframe){if(this.codec===`hevc`&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}if(qe()&&this.currentAlphaPacketIndex===0){let t=this.fixFirstPacketDataForChromium(e.sideData.alpha);t&&(e=e.clone({sideData:{...e.sideData,alpha:t}}))}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(n??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}fixFirstPacketDataForChromium(e){if(this.codec===`avc`){let t=[],n=!1;for(let r of an(e,this.decoderConfig)){let i=on(e[r.offset]);if(n||=i>=1&&i<=5,i===P.AUD){if(n)break;t.length=0}i>=20&&i<=31||t.push(e.subarray(r.offset,r.offset+r.length))}if(!this.decoderConfig.description)for(let e=0;e<t.length;e++){let n=t[e];if(on(n[0])!==P.SPS)continue;let r=vn(n);r&&r.maxDecFrameBuffering!==0&&r.bitstreamRestrictionFlag!==1&&(t[e]=bn(r))}return fn(t,this.decoderConfig)}return this.codec===`hevc`?In(e,this.decoderConfig):null}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let t of Sn(e,this.decoderConfig)){let n=Cn(e[t.offset]);if(n===F.RASL_N||n===F.RASL_R)return!0}return!1}sampleHandler(e){if(Ue()){if(this.sampleQueue.length>0&&e.timestamp>=m(this.sampleQueue).timestamp){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}_e(this.sampleQueue,e,e=>e.timestamp)}else{let n=this.inputTimestamps.shift();t(n!==void 0),e.setTimestamp(n),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),e.setFlip(this.flip),this.onSample(e)}async mergeAlpha(e,n){let r=O();this.mergeAlphaPromises.push(r.promise);let i={sample:null};this.finalSamples.push(i);try{for(n?(t(this.merger),i.sample=new Vr(await this.merger.merge(e,n))):i.sample=new Vr(e);this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){let e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(e){for(ve(this.finalSamples,i);this.finalSamples.length>0&&this.finalSamples[0].sample!==null;)this.finalSamples.shift().sample.close();this.onError(e)}finally{ve(this.mergeAlphaPromises,r.promise),r.resolve()}}copyFrameIfNeeded(e){if(!qe()||!Ze())return e;let t=e.visibleRect,n=t.width,r=t.height;if(!this.frameCopyContext){let e;if(e=typeof OffscreenCanvas<`u`?new OffscreenCanvas(n,r).getContext(`2d`,{alpha:!1}):document.createElement(`canvas`).getContext(`2d`,{alpha:!1}),!e)throw Error(`The '2d' canvas context is required to decode video on Chromium for Android.`);this.frameCopyContext=e}let i=this.frameCopyContext.canvas;(i.width!==n||i.height!==r)&&(i.width=n,i.height=r),this.frameCopyContext.drawImage(e,0,0,n,r),this.flushing&&this.frameCopyContext.getImageData(0,0,1,1);let a=new VideoFrame(i,{timestamp:e.timestamp,duration:e.duration??void 0,displayWidth:e.displayWidth,displayHeight:e.displayHeight});return e.close(),a}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(t(this.decoder),this.flushing=!0,await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.flushing=!1,await Promise.all(this.mergeAlphaPromises),this.inputTimestamps.length=0,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),Ue()){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()).catch(e=>this.onError(e)):(t(this.decoder),this.decoder.state!==`closed`&&this.decoder.close(),this.alphaDecoder&&this.alphaDecoder.state!==`closed`&&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}};let vc=null;var yc=class{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=/* @__PURE__ */ new Map,this.nextRequestId=0}merge(e,t){if(this.workers.length===0){if(!vc){let e=new Blob([`(${bc.toString()})()`],{type:`application/javascript`});vc=URL.createObjectURL(e)}let e=A(navigator.hardwareConcurrency,1,4);for(let t=0;t<e;t++){let e=new Worker(vc);e.addEventListener(`message`,e=>{let t=e.data,n=this.pendingRequests.get(t.id);n?(this.pendingRequests.delete(t.id),`error`in t?n.reject(Error(t.error)):n.resolve(t.frame)):`frame`in t&&t.frame.close()}),e.addEventListener(`error`,e=>{let t=Error(e.message||`Color/alpha merge worker error.`);for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}),this.workers.push(e)}}let n=this.nextRequestId++,r=O();this.pendingRequests.set(n,r);let i=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,i.postMessage({id:n,color:e,alpha:t},{transfer:[e,t]}),r.promise}close(){for(let e of this.workers)e.terminate();this.workers.length=0;let e=/* @__PURE__ */ Error(`Color/alpha merger closed.`);for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};const bc=()=>{let e=null,t=null,n=Promise.resolve();self.addEventListener(`message`,e=>{let{id:t,color:i,alpha:a}=e.data;n=n.then(async()=>{try{let e=await r(i,a);self.postMessage({id:t,frame:e},{transfer:[e]})}catch(e){self.postMessage({id:t,error:e.message})}finally{i.close(),a.close()}})});let r=async(e,t)=>{let n=e.format,r=t.format;if(!n||!r)throw Error(`CPU color/alpha merging requires a known VideoFrame format.`);let s=n.includes(`P10`),c=n.includes(`P12`),l=r.includes(`P10`),u=r.includes(`P12`);if(l!==s||u!==c)throw Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${n}', alpha: '${r}').`);if(n===`RGBX`||n===`RGBA`||n===`BGRX`||n===`BGRA`)return await i(e,t,n);if(n===`I420`||n===`I420P10`||n===`I420P12`||n===`I422`||n===`I422P10`||n===`I422P12`||n===`I444`||n===`I444P10`||n===`I444P12`)return await a(e,t,n);if(n===`NV12`)return await o(e,t);throw Error(`CPU color/alpha merging does not support format '${n}'.`)},i=async(e,t,n)=>{let r=e.visibleRect?.width??e.codedWidth,i=e.visibleRect?.height??e.codedHeight,a=r*i,o=new Uint8Array(a*4);await e.copyTo(o);let c=await s(t,r,i,1);for(let e=0,t=3;e<a;e++,t+=4)o[t]=c[e];let l={format:n===`RGBX`||n===`RGBA`?`RGBA`:`BGRA`,codedWidth:r,codedHeight:i,displayWidth:e.displayWidth,displayHeight:e.displayHeight,colorSpace:e.colorSpace.toJSON(),timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,l)},a=async(e,t,n)=>{let r=e.visibleRect?.width??e.codedWidth,i=e.visibleRect?.height??e.codedHeight,a=n.includes(`P10`),o=n.includes(`P12`),c=a||o?2:1,l,u;n.startsWith(`I420`)?(l=Math.ceil(r/2),u=Math.ceil(i/2)):n.startsWith(`I422`)?(l=Math.ceil(r/2),u=i):(l=r,u=i);let d=r*i,f=l*u,p=d*c,m=f*c,h=d*c,g=p+2*m+h,_=new Uint8Array(g);await e.copyTo(_);let v=await s(t,r,i,c),y=p+2*m;_.set(v,y);let b={format:n.slice(0,4)+`A`+n.slice(4),codedWidth:r,codedHeight:i,displayWidth:e.displayWidth,displayHeight:e.displayHeight,colorSpace:e.colorSpace.toJSON(),timestamp:e.timestamp,duration:e.duration??void 0,transfer:[_.buffer]};return new VideoFrame(_,b)},o=async(e,n)=>{let r=e.visibleRect?.width??e.codedWidth,i=e.visibleRect?.height??e.codedHeight,a=r*i,o=Math.ceil(r/2)*Math.ceil(i/2),c=e.allocationSize();t&&t.byteLength===c||(t=new Uint8Array(c)),await e.copyTo(t);let l=new Uint8Array(a+2*o+a);l.set(t.subarray(0,a),0);let u=a,d=a+o,f=a;for(let e=0;e<o;e++)l[u+e]=t[f+e*2],l[d+e]=t[f+e*2+1];let p=await s(n,r,i,1);l.set(p,a+2*o);let m={format:`I420A`,codedWidth:r,codedHeight:i,displayWidth:e.displayWidth,displayHeight:e.displayHeight,colorSpace:e.colorSpace.toJSON(),timestamp:e.timestamp,duration:e.duration??void 0,transfer:[l.buffer]};return new VideoFrame(l,m)},s=async(t,n,r,i)=>{let a=t.allocationSize();e&&e.byteLength===a||(e=new Uint8Array(a)),await t.copyTo(e);let o=t.format;if(o===`RGBA`||o===`BGRA`||o===`RGBX`||o===`BGRX`){let t=o===`RGBA`||o===`RGBX`?0:2,i=n*r;for(let n=0;n<i;n++)e[n]=e[n*4+t];return e.subarray(0,i)}{let a=e.subarray(0,n*r*i);if(t.colorSpace.fullRange===!1){let e=o.includes(`P12`)?12:o.includes(`P10`)?10:8,t=16<<e-8,s=235<<e-8,c=(1<<e)-1,l=i===2?new Uint16Array(a.buffer,0,n*r):a;for(let e=0;e<l.length;e++){let n=Math.round((l[e]-t)*c/(s-t));l[e]=Math.min(Math.max(n,0),c)}}return a}}},xc=e=>{if(!e||typeof e!=`object`)throw TypeError(`decoderOptions must be an object.`);if(e.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(e.hardwareAcceleration))throw TypeError(`decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(e.optimizeForLatency!==void 0&&typeof e.optimizeForLatency!=`boolean`)throw TypeError(`decoderOptions.optimizeForLatency, when provided, must be a boolean.`)};var Sc=class extends gc{constructor(e,t={}){if(!(e instanceof Oc))throw TypeError(`videoTrack must be an InputVideoTrack.`);xc(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,n){if(!await this._track.canDecode())throw Error(typeof VideoDecoder>`u`?Qe(`VideoDecoder`):`This video track cannot be decoded in this environment. Make sure to check decodability before using a track.`);let r=await this._track.getCodec(),i=await this._track.getRotation(),a=await this._track.getFlip(),o=await this._track.getDecoderConfig(),s=await this._track.getTimeResolution();return t(r&&o),o={...o,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new _c(e,n,r,o,i,a,s)}_createPacketSink(){return new mc(this._track)}async _getPreRollDuration(){return 0}async getSample(e,t={}){fc(e);for await(let n of this.mediaSamplesAtTimestamps([e],t))return n;throw Error(`Internal error: Iterator returned nothing.`)}samples(e,t,n={}){return this.mediaSamplesInRange(e,t,n)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}},Cc=class extends hc{constructor(e,t,n,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Ve,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;let i=n===`opus`&&r.description?Wn(b(r.description)).preSkip/ru:0,a=t=>{let n=t.timestamp;this.expectedFirstTimestamp!==null&&this.currentTimestamp===null&&(this.timestampOffset=this.expectedFirstTimestamp+i-n),n+=this.timestampOffset,(this.currentTimestamp===null||Math.abs(n-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=n);let a=this.currentTimestamp;if(this.currentTimestamp+=t.duration,t.numberOfFrames===0){t.close();return}let o=r.sampleRate;t.setTimestamp(Math.round(a*o)/o),e(t)},o=Pi.find(e=>e.supports(n,r));if(o)this.customDecoder=new o,this.customDecoder.codec=n,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof oi))throw TypeError(`The argument passed to onSample must be an AudioSample.`);a(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{let e=(/* @__PURE__ */ Error(`Decoding error`)).stack;this.decoder=new AudioDecoder({output:e=>{try{a(new oi(e))}catch(e){this.onError(e)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.addEventListener(`dequeue`,()=>{this.onDequeue?.()}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(t(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>{this.customDecoderQueueSize--,this.onDequeue?.()})):(t(this.decoder),this.expectedFirstTimestamp??=e.timestamp,this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(t(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()).catch(e=>this.onError(e)):(t(this.decoder),this.decoder.state!==`closed`&&this.decoder.close())}},wc=class extends hc{constructor(e,n,r){super(e,n),this.decoderConfig=r,this.currentTimestamp=null,t(Il.includes(r.codec)),this.codec=r.codec;let{dataType:i,sampleSize:a,littleEndian:o}=ou(this.codec);switch(this.inputSampleSize=a,a){case 1:i===`unsigned`?this.readInputValue=(e,t)=>e.getUint8(t)-128:i===`signed`?this.readInputValue=(e,t)=>e.getInt8(t):i===`ulaw`?this.readInputValue=(e,t)=>Ar(e.getUint8(t)):i===`alaw`?this.readInputValue=(e,t)=>Mr(e.getUint8(t)):t(!1);break;case 2:i===`unsigned`?this.readInputValue=(e,t)=>e.getUint16(t,o)-2**15:i===`signed`?this.readInputValue=(e,t)=>e.getInt16(t,o):t(!1);break;case 3:i===`unsigned`?this.readInputValue=(e,t)=>Ce(e,t,o)-2**23:i===`signed`?this.readInputValue=(e,t)=>we(e,t,o):t(!1);break;case 4:i===`unsigned`?this.readInputValue=(e,t)=>e.getUint32(t,o)-2**31:i===`signed`?this.readInputValue=(e,t)=>e.getInt32(t,o):i===`float`?this.readInputValue=(e,t)=>e.getFloat32(t,o):t(!1);break;case 8:i===`float`?this.readInputValue=(e,t)=>e.getFloat64(t,o):t(!1);break;default:k(a),t(!1)}switch(a){case 1:i===`ulaw`||i===`alaw`?(this.outputSampleSize=2,this.outputFormat=`s16`,this.writeOutputValue=(e,t,n)=>e.setInt16(t,n,!0)):(this.outputSampleSize=1,this.outputFormat=`u8`,this.writeOutputValue=(e,t,n)=>e.setUint8(t,n+128));break;case 2:this.outputSampleSize=2,this.outputFormat=`s16`,this.writeOutputValue=(e,t,n)=>e.setInt16(t,n,!0);break;case 3:this.outputSampleSize=4,this.outputFormat=`s32`,this.writeOutputValue=(e,t,n)=>e.setInt32(t,n<<8,!0);break;case 4:this.outputSampleSize=4,i===`float`?(this.outputFormat=`f32`,this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,!0)):(this.outputFormat=`s32`,this.writeOutputValue=(e,t,n)=>e.setInt32(t,n,!0));break;case 8:this.outputSampleSize=4,this.outputFormat=`f32`,this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,!0);break;default:k(a),t(!1)}}getDecodeQueueSize(){return 0}decode(e){let t=x(e.data),n=Math.floor(e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize);if(n===0)return;let r=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,i=new ArrayBuffer(r),a=new DataView(i);for(let e=0;e<n*this.decoderConfig.numberOfChannels;e++){let n=e*this.inputSampleSize,r=e*this.outputSampleSize,i=this.readInputValue(t,n);this.writeOutputValue(a,r,i)}let o=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=o)&&(this.currentTimestamp=e.timestamp);let s=this.currentTimestamp;this.currentTimestamp+=o;let c=this.decoderConfig.sampleRate,l=new oi({format:this.outputFormat,data:i,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:c,numberOfFrames:n,timestamp:Me(s,c),_doNotCopy:!0});this.onSample(l)}async flush(){this.currentTimestamp=null}close(){}},Tc=class extends gc{constructor(e){if(!(e instanceof Ac))throw TypeError(`audioTrack must be an InputAudioTrack.`);super(),this._track=e}async _createDecoder(e,n){if(!await this._track.canDecode())throw Error(typeof AudioDecoder>`u`?Qe(`AudioDecoder`):`This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.`);let r=await this._track.getCodec(),i=await this._track.getDecoderConfig();return t(r&&i),Il.includes(i.codec)?new wc(e,n,i):new Cc(e,n,r,i)}_createPacketSink(){return new mc(this._track)}async _getPreRollDuration(){let e=await this._track.getPreRollDuration();return t(e!==null),e}async getSample(e,t={}){fc(e);for await(let n of this.mediaSamplesAtTimestamps([e],t))return n;throw Error(`Internal error: Iterator returned nothing.`)}samples(e,t,n={}){return this.mediaSamplesInRange(e,t,n)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}},Ec=class e{constructor(e,t){
351
+ /*!
352
+ * Copyright (c) 2026-present, Vanilagy and contributors
353
+ *
354
+ * This Source Code Form is subject to the terms of the Mozilla Public
355
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
356
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
357
+ */
358
+ this.input=e,this._backing=t}isVideoTrack(){return this instanceof Oc}isAudioTrack(){return this instanceof Ac}get id(){let e=this.input._trackBackingsCache;t(e);let n=e.indexOf(this._backing);return t(n!==-1),n+1}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return B(this._backing.getInternalCodecId(),`internalCodecId`,`getInternalCodecId`)}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return B(this._backing.getLanguageCode(),`languageCode`,`getLanguageCode`)}async getName(){return this._backing.getName()}get name(){return B(this._backing.getName(),`name`,`getName`)}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return B(this._backing.getTimeResolution(),`timeResolution`,`getTimeResolution`)}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return B(this._backing.getDisposition(),`disposition`,`getDisposition`)}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return await this.getFirstTimestampOrNull()??0}async getFirstTimestampOrNull(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??null}async computeDuration(e){return await this.computeDurationOrNull(e)??0}async computeDurationOrNull(e){let t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e});return t?Me(t.timestamp+t.duration,await this.getTimeResolution()):null}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){let n=new mc(this),r=1/0,i=-1/0,a=0,o=0;for await(let s of n.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&s.timestamp>=i&&i>r)break;r=Math.min(r,s.timestamp),i=Math.max(i,s.timestamp+s.duration),a++,o+=s.byteLength}let s=i-r;return{packetCount:a,averagePacketRate:a>0?Number((a/s).toPrecision(16)):0,averageBitrate:o>0?Number((8*o/s).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an InputTrack.`);return this.input!==t.input||this===t?!1:(this._backing.getPairingMask()&t._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(Pc({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(Pc({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(Pc({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(Pc({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(Pc({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=Dc(e);let t=await this.input.getTracks();for(let n of t)if(this.canBePairedWith(n)&&(!e||await e(n)))return!0;return!1}hasPairableVideoTrack(e){return e&&=Dc(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=Dc(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}};const B=(e,t,n)=>{if(j(e))throw Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${n}()' instead.`);return e},Dc=e=>{if(e!==void 0&&typeof e!=`function`)throw TypeError(`predicate, when provided, must be a function.`);return e?t=>{let n=e=>{if(typeof e!=`boolean`)throw TypeError(`predicate must return or resolve to a boolean value.`);return e},r=e(t);return j(r)?r.then(n):n(r)}:void 0};var Oc=class extends Ec{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null}get type(){return`video`}async getCodec(){return this._backing.getCodec()}get codec(){return B(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??await this._backing.getCodec()===`prores`}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return B(this._backing.getCodedWidth(),`codedWidth`,`getCodedWidth`)}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return B(this._backing.getCodedHeight(),`codedHeight`,`getCodedHeight`)}async getTransformationMatrix(){return this._backing.getTransformationMatrix()}async getRotation(){return s(await this._backing.getTransformationMatrix())}get rotation(){return s(B(this._backing.getTransformationMatrix(),`rotation`,`getRotation`))}async getFlip(){return c(await this._backing.getTransformationMatrix())}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return B(this._backing.getSquarePixelWidth(),`squarePixelWidth`,`getSquarePixelWidth`)}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return B(this._backing.getSquarePixelHeight(),`squarePixelHeight`,`getSquarePixelHeight`)}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=kc(await this.getSquarePixelWidth()*await this.getCodedHeight(),await this.getSquarePixelHeight()*await this.getCodedWidth())}get pixelAspectRatio(){return this._pixelAspectRatioCache??=kc(B(this._backing.getSquarePixelWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)*B(this._backing.getCodedHeight(),`pixelAspectRatio`,`getPixelAspectRatio`),B(this._backing.getSquarePixelHeight(),`pixelAspectRatio`,`getPixelAspectRatio`)*B(this._backing.getCodedWidth(),`pixelAspectRatio`,`getPixelAspectRatio`))}async getDisplayWidth(){return await this._backing.getMetadataDisplayWidth?.()??(await this.getRotation()%180==0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){let e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){let t=B(e,`displayWidth`,`getDisplayWidth`);if(t!==null)return t}let t=s(B(this._backing.getTransformationMatrix(),`displayWidth`,`getDisplayWidth`))%180==0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return B(t,`displayWidth`,`getDisplayWidth`)}async getDisplayHeight(){return await this._backing.getMetadataDisplayHeight?.()??(await this.getRotation()%180==0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){let e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){let t=B(e,`displayHeight`,`getDisplayHeight`);if(t!==null)return t}let t=s(B(this._backing.getTransformationMatrix(),`displayHeight`,`getDisplayHeight`))%180==0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return B(t,`displayHeight`,`getDisplayHeight`)}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.transfer===`pq`||e.transfer===`hlg`}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return await this._backing.getMetadataCodecParameterString?.()??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let n=await this._backing.getCodec();return t(n!==null),Ni.some(t=>t.supports(n,e))?!0:typeof VideoDecoder>`u`?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return M._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof L))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`packet must not be metadata-only to determine its type.`);let n=await this.getCodec();if(n===null)return null;let r=await this.getDecoderConfig();return t(r),Jn(n,r,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.targetPacketCount!==void 0&&(!ct(e.targetPacketCount)||e.targetPacketCount<0))throw TypeError(`options.targetPacketCount must be a non-negative number.`);let t=await this.getTimeResolution(),n=e.targetPacketCount??256,r=new mc(this),i=[],a=-1/0,o=0;for await(let e of r.packets(void 0,void 0,{metadataOnly:!0})){if(i.length>=n&&e.timestamp>=a)break;i.push(e.timestamp),a=Math.max(a,e.timestamp),o++}let s=new Float64Array(i.length);for(let e=0;e<i.length;e++)s[e]=Math.round(i[e]*t);s.sort();let c=1;for(let e=1;e<s.length;e++)s[e]!==s[c-1]&&(s[c++]=s[e]);if(c<2)return{underlyingFrameRate:null,bestGuessFrameRate:t,minFrameRate:t,maxFrameRate:t,averageFrameRate:t,medianFrameRate:t,frameRateIsConstant:!0,probedPacketCount:o};let l=s.subarray(0,c),u=Ic(l,t),d=u??t,f=u===null?null:t/u,p=/* @__PURE__ */ new Map,m=1/0,h=-1/0,g=0;for(let e=1;e<c;e++){let t=l[e]-l[e-1],n=f===null?t:Math.max(1,Math.round(t/f));p.set(n,(p.get(n)??0)+1),m=Math.min(m,n),h=Math.max(h,n),g+=n}let _=c-1,v=[...p.keys()].sort((e,t)=>e-t),y=_-1>>1,b=_>>1,x=0,S=0,C=0;for(let e of v)if(C+=p.get(e),x===0&&C>y&&(x=e),C>b){S=e;break}let w=(d/x+d/S)/2;return{underlyingFrameRate:u,bestGuessFrameRate:u===null?Rc(w):u,minFrameRate:d/h,maxFrameRate:d/m,averageFrameRate:d*_/g,medianFrameRate:w,frameRateIsConstant:u!==null&&m===1&&h===1,probedPacketCount:o}}};const kc=(e,t)=>e===0||t===0?{num:1,den:1}:pt({num:e,den:t});var Ac=class extends Ec{constructor(e,t){super(e,t)}get type(){return`audio`}async getCodec(){return this._backing.getCodec()}get codec(){return B(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){let e=await this._backing.getCodec();return await this._backing.getHasOnlyKeyPackets?.()??(e===null||!Bl.includes(e))}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return B(this._backing.getNumberOfChannels(),`numberOfChannels`,`getNumberOfChannels`)}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return B(this._backing.getSampleRate(),`sampleRate`,`getSampleRate`)}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return await this._backing.getMetadataCodecParameterString?.()??(await this._backing.getDecoderConfig())?.codec??null}async getPreRollDuration(){let e=await this._backing.getCodec();if(e===null)return null;let n=await this._backing.getDecoderConfig();return t(n),tu(e,n)}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let n=await this._backing.getCodec();return t(n!==null),Pi.some(t=>t.supports(n,e))||Il.includes(e.codec)?!0:typeof AudioDecoder>`u`?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return M._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof L))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`packet must not be metadata-only to determine its type.`);let t=await this.getCodec();return t===null?null:Xn(t,e.data)}};const jc=e=>-(e??-1/0),Mc=e=>-e,Nc=e=>{if(typeof e!=`object`||!e)throw TypeError(`query must be an object.`);if(e.filter!==void 0&&typeof e.filter!=`function`)throw TypeError(`query.filter, when provided, must be a function.`);if(e.sortBy!==void 0&&typeof e.sortBy!=`function`)throw TypeError(`query.sortBy, when provided, must be a function.`);return{filter:e.filter?t=>{let n=e=>{if(typeof e!=`boolean`)throw TypeError(`query.filter must return or resolve to a boolean.`);return e},r=e.filter(t);return j(r)?r.then(n):n(r)}:void 0,sortBy:e.sortBy?t=>{let n=e=>{if(typeof e!=`number`&&(!Array.isArray(e)||!e.every(e=>typeof e==`number`)))throw TypeError(`query.sortBy must return or resolve to a number or an array of numbers.`);return e},r=e.sortBy(t);return j(r)?r.then(n):n(r)}:void 0}},Pc=(e,t)=>({filter:e?.filter||t?.filter?n=>{let r=e?.filter?.(n)??!0,i=e=>e===!1?!1:t?.filter?.(n)??!0;return j(r)?r.then(i):i(r)}:void 0,sortBy:e?.sortBy||t?.sortBy?n=>{let r=e?.sortBy?.(n)??[],i=t?.sortBy?.(n)??[],a=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return j(r)||j(i)?Promise.all([r,i]).then(([e,t])=>a(e,t)):a(r,i)}:void 0}),Fc=async(e,t)=>{let n=e;if(t?.filter){let r=e.map(e=>t.filter(e));if(r.some(e=>j(e))){let t=await Promise.all(r);n=e.filter((e,n)=>t[n])}else n=e.filter((e,t)=>r[t])}if(!t?.sortBy)return n;let r=n.map(e=>t.sortBy(e)),i=r.some(e=>j(e))?await Promise.all(r):r;return n.map((e,t)=>({track:e,sortValue:i[t]})).sort((e,t)=>{let n=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],r=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],i=Math.max(n.length,r.length);for(let e=0;e<i;e++){let t=n[e]??0,i=r[e]??0;if(t!==i)return t-i}return 0}).map(e=>e.track)},Ic=(e,t)=>{let n=1e6,r=.98,i=1+1e-9,a=1e3,o=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;let s=new Float64Array(e.length-1);for(let t=1;t<e.length;t++){let n=e[t]-e[t-1];if(!(n>0))return null;s[t-1]=n}let c=s.slice();c.sort();let l=c[Math.floor(c.length*.05)],u=1;for(let e=0;e<6;e++){let e=0,t=0;for(let n of s){let r=Math.max(1,Math.round(n/l));Math.abs(n-r*l)>=i+r*u||(e+=n,t+=r)}if(t===0)return null;let n=e/t;if(u=1/Math.min(t,a),Math.abs(n-l)<=1e-12*Math.max(1,l)){l=n;break}l=n}let d=0,f=0,p=0;for(let e of s){let t=Math.max(1,Math.round(e/l));Math.abs(e-t*l)>=i+t*u||(d++,f+=e,p+=t)}if(d/s.length<r)return null;l=f/p;let m=1/Math.min(p,a),h=Math.max(2**-52,l-m),g=l+m,_=t/g,v=t/h,y=t/l,b=null,x=1/0;for(let e of o){if(e<_||e>v)continue;let t=Math.abs(e/y-1);t<x&&(b=e,x=t)}if(b===null){let e=Lc(h,g,n),r=Lc(_,v,n);if(r&&(!e||r.den<e.den||r.den===e.den&&r.num<=e.num))b=r.num/r.den;else if(e)b=t*e.den/e.num;else return null}let S=t/b,C=0;for(let e of s){let t=Math.max(1,Math.round(e/S));Math.abs(e-t*S)<i&&C++}return C/s.length<r?null:b},Lc=(e,t,n)=>{for(let r=1;r<=n;r++){let n=Math.floor(e*r)+1;if(n/r<t)return pt({num:n,den:r})}return null},Rc=e=>{let t=[24/1.001,30/1.001,60/1.001,120/1.001],n=[12,15,20,24,25,30,48,50,60,100,120,144,240];for(let n of t)if(Math.abs(n/e-1)<=5e-4)return n;let r=e,i=1/0;for(let t of n){let n=Math.abs(t/e-1);n<=.025&&n<i&&(r=t,i=n)}return r};
359
+ /*!
360
+ * Copyright (c) 2026-present, Vanilagy and contributors
361
+ *
362
+ * This Source Code Form is subject to the terms of the Mozilla Public
363
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
364
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
365
+ */
366
+ st();var zc=class e extends _t{get disposed(){return this._disposed}constructor(t){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=/* @__PURE__ */ new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(!Array.isArray(t.formats)||t.formats.some(e=>!(e instanceof Xs)))throw TypeError(`options.formats must be an array of InputFormat.`);if(!(t.source instanceof Ds||t.source instanceof Os))throw TypeError(`options.source must be a Source or SourceRef.`);if(t.source instanceof Ds&&t.source._disposed)throw TypeError(`options.source must not be a disposed Source.`);if(t.initInput!==void 0&&!(t.initInput instanceof e))throw TypeError(`options.initInput, when provided, must be an Input.`);t.formatOptions!==void 0&&uc(t.formatOptions,`formatOptions`),this._formats=t.formats,this._initInput=t.initInput??null,this._formatOptions=t.formatOptions??{},this._rootRef=t.source instanceof Ds?t.source.ref():t.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){if(this._disposed)throw new Vc;return this._rootRef.source}async _getSourceUncached(e){t(this._rootSource instanceof ks);let n=await this._rootSource._resolveRequest(e);return this._emit(`source`,{source:n.source,request:e,isRoot:e.isRoot}),n}_getSourceCached(e,n=1){let r=this._sourceCache.find(t=>t.cacheGroup===n&&As(t.request,e));if(r)return r.age=this._nextSourceCacheAge++,Promise.resolve(r.sourceRef.source.ref());let i=this._sourceCachePromises.find(t=>t.cacheGroup===n&&As(t.request,e));if(i)return i.promise.then(e=>e.sourceRef.source.ref());let a=(async()=>{let r;try{r=await this._getSourceUncached(e)}finally{let n=this._sourceCachePromises.findIndex(t=>t.request===e);t(n!==-1),this._sourceCachePromises.splice(n,1)}if(this._disposed)throw r.free(),new Vc;if(dt(this._sourceCache,e=>e.cacheGroup===n&&e.sourceRef.source._refCount===1)>=4){let e=ft(this._sourceCache,e=>e.cacheGroup===n&&e.sourceRef.source._refCount===1?e.age:1/0);t(e!==-1);let r=this._sourceCache[e];this._sourceCache.splice(e,1),r.sourceRef.free(),ve(this._sourceRefs,r.sourceRef)}return this._sourceRefs.push(r),{request:e,sourceRef:r,age:this._nextSourceCacheAge++,cacheGroup:n}})();return this._sourceCachePromises.push({request:e,cacheGroup:n,promise:a}),a.then(e=>{let t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new Hc(this._rootSource),this._emit(`source`,{source:this._rootSource,request:null,isRoot:!0});let e=null,t=1/0;for(let n of this._formats){let r=await n._getMatchPosition(this);if(r!==null&&r<t&&(e=n,t=r,r===0))break}if(!e)throw new Bc;return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this)})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),t(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof Bc)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();let t=e.filter(e=>e!==null);if(t.length===0)return 0;let n=await Promise.all(t.map(e=>e.getFirstTimestampOrNull())),r=Math.min(...n.map(e=>e??1/0));return r===1/0?0:r}async computeDuration(e,t){e??=await this.getTracks();let n=e.filter(e=>e!==null);if(n.length===0)return 0;let r=await Promise.all(n.map(e=>e.computeDurationOrNull(t))),i=Math.max(...r.map(e=>e??-1/0));return i===-1/0?0:i}async getDurationFromMetadata(e,t){e??=await this.getTracks();let n=e.filter(e=>e!==null),r=(await Promise.all(n.map(e=>e.getDurationFromMetadata(t)))).filter(e=>e!==null);return r.length===0?null:Math.max(...r)}async getTracks(e){e&&=Nc(e);let t=(await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return Fc(t,e)}async getVideoTracks(e){e&&=Nc(e);let t=(await this.getTracks()).filter(e=>e.isVideoTrack());return Fc(t,e)}async getAudioTracks(e){e&&=Nc(e);let t=(await this.getTracks()).filter(e=>e.isAudioTrack());return Fc(t,e)}async getPrimaryVideoTrack(e){e&&=Nc(e);let t=Pc(e,{sortBy:async e=>[Mc((await e.getDisposition()).default),Mc(await e.hasPairableAudioTrack()),Mc(!await e.hasOnlyKeyPackets()),jc(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=Nc(e);let t=await this.getPrimaryVideoTrack(),n=Pc(e,{sortBy:async e=>[Mc(!t||e.canBePairedWith(t)),Mc((await e.getDisposition()).default),jc(await e.getBitrate())]});return(await this.getAudioTracks(n))[0]??null}async _getTrackBackings(){let e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){let t=this._backingToTrack.get(e);if(t)return t;let n=e.getType()===`video`?new Oc(this,e):new Ac(this,e);return this._backingToTrack.set(e,n),n}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(let e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._sourceCache.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}},Bc=class extends Error{constructor(e=`Input has an unsupported or unrecognizable format.`){super(e),this.name=`UnsupportedInputFormatError`}},Vc=class extends Error{constructor(e=`Input has been disposed.`){super(e),this.name=`InputDisposedError`}},Hc=class{constructor(e){
367
+ /*!
368
+ * Copyright (c) 2026-present, Vanilagy and contributors
369
+ *
370
+ * This Source Code Form is subject to the terms of the Mozilla Public
371
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
372
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
373
+ */
374
+ this.source=e}get fileSize(){let e=this.source._getFileSize();if(e===void 0)throw Error(`Reading file size too early; read required first.`);return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new Vc;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){let t=/* @__PURE__ */ new Uint8Array;return new Uc(t,x(t),0,e,e)}let n=e+t,r=this.source._read(e,n,0,Es);return j(r)?r.then(t=>t?new Uc(t.bytes,t.view,t.offset,e,n):null):r?new Uc(r.bytes,r.view,r.offset,e,n):null}requestSliceRange(e,n,r){if(this.source._disposed)throw new Vc;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,A(this.fileSizeNonStrict-e,n,r));{let i=this.requestSlice(e,r),a=i=>i||(t(this.fileSizeNonStrict!==null),this.requestSlice(e,A(this.fileSizeNonStrict-e,n,r)));return j(i)?i.then(a):a(i)}}requestEntireFile(){return this.fileSizeNonStrict===null?(async()=>{let e=[],t=0;for(;;){if(e.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let n=this.requestSliceRange(t,0,1024);if(j(n)&&(n=await n),!n||n.length===0)break;let r=V(n,n.length);e.push(r),t+=n.length}let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return new Uc(n,x(n),0,0,t)})():this.requestSlice(0,this.fileSizeNonStrict)}},Uc=class e{constructor(e,t,n,r,i){this.bytes=e,this.view=t,this.offset=n,this.start=r,this.end=i,this.bufferPos=r-n}static tempFromBytes(t){return new e(t,x(t),0,0,t.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(t,n=this.end-t){if(t<this.start||t+n>this.end)throw RangeError(`Slicing outside of original slice.`);return new e(this.bytes,this.view,this.offset,t,t+n)}};const Wc=(e,t)=>{if(t<0||e.filePos<e.start||e.filePos+t>e.end)throw RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},V=(e,t)=>{Wc(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},H=e=>(Wc(e,1),e.view.getUint8(e.bufferPos++)),Gc=(e,t)=>{Wc(e,2);let n=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,n},U=e=>{Wc(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},Kc=e=>{Wc(e,3);let t=Ce(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},qc=e=>{Wc(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},Jc=(e,t)=>{Wc(e,4);let n=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,n},W=e=>{Wc(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Yc=e=>{Wc(e,4);let t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Xc=e=>{Wc(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},Zc=e=>{Wc(e,4);let t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t},Qc=(e,t)=>{let n,r;return t?(n=Jc(e,!0),r=Jc(e,!0)):(r=Jc(e,!1),n=Jc(e,!1)),r*4294967296+n},$c=e=>{let t=W(e),n=W(e);return t*4294967296+n},el=e=>{let t=Xc(e),n=W(e);return t*4294967296+n},tl=e=>{let t=Yc(e);return Zc(e)*4294967296+t},nl=e=>{Wc(e,4);let t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},rl=e=>{Wc(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},G=(e,t)=>{Wc(e,t);let n=``;for(let r=0;r<t;r++)n+=String.fromCharCode(e.bytes[e.bufferPos++]);return n},il=(e,t,n)=>w.decode(V(e,t)).split(`
375
+ `).map(e=>e.trim()).filter(e=>e.length>0&&!n?.ignore?.(e)),al=e=>{
376
+ /*!
377
+ * Copyright (c) 2026-present, Vanilagy and contributors
378
+ *
379
+ * This Source Code Form is subject to the terms of the Mozilla Public
380
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
381
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
382
+ */
383
+ let t=W(e),n=G(e,4),r=8;t===1&&(t=$c(e),r=16);let i=t-r;return i<0?null:{name:n,totalSize:t,headerSize:r,contentSize:i}},ol=e=>Xc(e)/65536,sl=e=>Xc(e)/1073741824,cl=e=>{let t=0;for(let n=0;n<4;n++){t<<=7;let n=H(e);if(t|=n&127,!(n&128))break}return t},ll=e=>{if(H(e)!==3)throw Error(`Invalid esds: expected ES_Descriptor.`);cl(e),e.skip(2);let t=H(e),n=!!(t&128),r=!!(t&64),i=!!(t&32);if(n&&e.skip(2),r){let t=H(e);e.skip(t)}if(i&&e.skip(2),H(e)!==4)throw Error(`Invalid esds: expected DecoderConfigDescriptor.`);let a=cl(e),o=e.filePos,s=H(e);e.skip(12);let c=null;if(a>e.filePos-o){if(H(e)!==5)throw Error(`Invalid esds: expected DecoderSpecificInfo.`);let t=cl(e);c=V(e,t)}return{objectTypeIndication:s,decoderSpecificInfo:c}},ul=e=>{let t=U(e);return e.skip(2),t=Math.min(t,e.remainingLength),w.decode(V(e,t))},dl=e=>{let t=al(e);if(!t||t.name!==`data`||t.contentSize<8||e.remainingLength<8)return null;let n=W(e);e.skip(4);let r=V(e,t.contentSize-8);switch(n){case 1:return w.decode(r);case 2:return new C(`utf-16be`).decode(r);case 13:return new wt(r,`image/jpeg`);case 14:return new wt(r,`image/png`);case 27:return new wt(r,`image/bmp`);default:return r}};
384
+ /*!
385
+ * Copyright (c) 2026-present, Vanilagy and contributors
386
+ *
387
+ * This Source Code Form is subject to the terms of the Mozilla Public
388
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
389
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
390
+ */
391
+ var fl=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},pl=(function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var r,i=0;function a(){for(;r=t.stack.pop();)try{if(!r.async&&i===1)return i=0,t.stack.push(r),Promise.resolve().then(a);if(r.dispose){var e=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(e).then(a,function(e){return n(e),a()})}else i|=1}catch(e){n(e)}if(i===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return a()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r}),ml=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._nominalBitrate=null}_ensureValidAdd(){if(!this._connectedTrack)throw Error(`Source is not connected to an output track.`);if(this._connectedTrack.output.state===`canceled`)throw Error(`Output has been canceled.`);if(this._connectedTrack.output.state===`finalizing`||this._connectedTrack.output.state===`finalized`)throw Error(`Output has been finalized.`);if(this._connectedTrack.output.state===`pending`)throw Error(`Output has not started.`);if(this._closingPromise)throw Error(`Source is closed.`)}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error(`Cannot call close without connecting the source to an output track.`);if(e.output.state===`pending`)throw Error(`Cannot call close before output has been started.`);this._closingPromise=(async()=>{await this._flushAndClose(!1),e.output.state!==`finalizing`&&e.output.state!==`finalized`&&await e.output._muxer.onTrackClose(e)})(),this._closingPromise.catch(()=>{})}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=this._flushAndClose(e)}},hl=class extends ml{constructor(e){if(super(),!Fl.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${Fl.join(`, `)}.`);this._codec=e}};const gl=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&t.type!==`key`)throw Error(`Cannot add non-key packets to a hasOnlyKeyPackets video track.`)};var _l=class extends hl{constructor(e){super(e)}add(e,t){if(!(e instanceof L))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),gl(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},vl=class{setError(e){this.errorSet||=(this.error=e,!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.encoderConfig=null,this.encodersReclaimed=!1,this.muxer=null,this.lastMultipleOfKeyFrameInterval=null,this.emittedEncoderPackets=0,this.chunkTimestampsAreShiftedByDuration=!1,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.addMutex=new de,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new Ve,this.customEncoderQueueSize=0,this.defaultEncodeOptions={},this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,n,r){let i=e,a=null;try{if(this.checkForEncoderError(),a=await this.addMutex.acquire(),this.closed)return;let o=this.encodingConfig,s=o.sizeChangeBehavior??`deny`,c=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(c=!0,s===`deny`))throw 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 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(o.transform?.width!==void 0||o.transform?.height!==void 0||o.transform?.rotate!==void 0||o.transform?.flip!==void 0||o.transform?.crop!==void 0||o.transform?.alpha===`discard`||o.transform?.force===!0||c&&s!==`passThrough`){let r=o.transform?.width,i=o.transform?.height,a=o.transform?.fit??`fill`;s!==`deny`&&s!==`passThrough`&&(a=s),c&&s!==`passThrough`&&(t(this.outputWidth),t(this.outputHeight),r=this.outputWidth,i=this.outputHeight);let l=await e.transform({width:r,height:i,roundDimensionsTo:2,crop:o.transform?.crop,rotate:o.transform?.rotate,flip:o.transform?.flip,fit:a,alpha:o.transform?.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=l.displayWidth,this.outputHeight=l.displayHeight),n&&e.close(),e=l,n=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);let l=o.transform?.frameRate;if(l!==void 0){let t=e.timestamp+e.duration,a=Pe(e.timestamp,l);if(this.frameRateLastSample!==null){if(a<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=t;return}await this.padFrameRate(a,r)}if(e===i){let t=e.clone();n&&e.close(),e=t,n=!0}e.setTimestamp(a),e.setDuration(1/l),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=a,this.frameRateLastEndTimestamp=t}await this.processAndEncode(e,r)}finally{a?.(),n&&e.close()}}async processAndEncode(e,n){let r=this.encodingConfig,i;if(r.transform?.process){let t=r.transform.process(e);if(j(t)&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]);let n=[];try{for(let r of t)r instanceof Vr?n.push(r):typeof VideoFrame<`u`&&r instanceof VideoFrame?n.push(new Vr(r)):n.push(new Vr(r,{timestamp:e.timestamp,duration:e.duration}))}catch(r){for(let t of n)t!==e&&t.close();for(let n of t)(n instanceof Vr&&n!==e||typeof VideoFrame<`u`&&n instanceof VideoFrame)&&n.close();throw r}i=n}else i=[e];try{for(let e of i){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),t(this.encoderInitialized),this.closed)break;this.encodersReclaimed&&this.recreateWebCodecsEncoders();let r=this.encodingConfig.keyFrameInterval??2,i=Math.floor(e.timestamp/r),a={...this.defaultEncodeOptions,...e.encodeOptions,...n},o={...a,keyFrame:a.keyFrame===void 0?r===0||i!==this.lastMultipleOfKeyFrameInterval:a.keyFrame};if(this.lastMultipleOfKeyFrameInterval=i,this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t,o)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await n}else{t(this.encoder);let n=e.toVideoFrame(),r=D(this.preciseTimings,n.timestamp,e=>e.microsecondTimestamp),i=r===-1?null:this.preciseTimings[r];if(i&&i.microsecondTimestamp===n.timestamp?(i.timestamp!==e.timestamp&&(i.timestampIsValid=!1),i.duration!==e.duration&&(i.durationIsValid=!1)):(this.preciseTimings.splice(r+1,0,{microsecondTimestamp:n.timestamp,timestamp:e.timestamp,duration:e.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)try{this.encoder.encode(n,o)}finally{n.close()}else if(n.format&&!n.format.includes(`A`)||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(n,o)}finally{n.close()}}else{this.splitter||=new Sl;let{colorFrame:e,alphaFrame:t}=await this.splitter.split(n);this.alphaFrameQueue.push(t);try{this.encoder.encode(e,o)}finally{e.close()}}this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0}))}await this.lastMuxerPromise}}finally{for(let t of i)t!==e&&t.close()}}async padFrameRate(e,n){let r=this.encodingConfig.transform.frameRate;t(this.frameRateLastSample);let i=Math.round((e-this.frameRateLastTimestamp)*r);for(let e=1;e<i;e++){let t={stack:[],error:void 0,hasError:!1};try{let i=fl(t,this.frameRateLastSample.clone(),!1);i.setTimestamp(this.frameRateLastTimestamp+e/r),i.setDuration(1/r),await this.processAndEncode(i,n)}catch(e){t.error=e,t.hasError=!0}finally{pl(t)}}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let n=Ai(this.encodingConfig.quality,this.encodingConfig.bitrate);t(n!==void 0);let r=yi({...this.encodingConfig,quality:n,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate}),i=null,a;for(let e of r){let t=e.config;if(this.encodingConfig.onEncoderConfig?.(t),a=Fi.find(e=>e.supports(this.encodingConfig.codec,t)),a){i=e;break}if(typeof VideoEncoder<`u`){if(t.alpha=`discard`,this.encodingConfig.alpha===`keep`&&(t.latencyMode=`quality`),(t.width%2==1||t.height%2==1)&&(this.encodingConfig.codec===`avc`||this.encodingConfig.codec===`hevc`))throw Error(`The dimensions ${t.width}x${t.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.`);try{if((await VideoEncoder.isConfigSupported(t)).supported){i=e;break}}catch{}}}if(!i){if(typeof VideoEncoder>`u`)throw Error(Qe(`VideoEncoder`));let e=r[0].config,t=r.map(({config:e,quantizer:t})=>t===null?`${e.bitrate} bps`:`quantizer ${t}`);throw Error(`This specific encoder configuration (${e.codec}, ${t.join(` / `)}, ${e.width}x${e.height}, hardware acceleration: ${e.hardwareAcceleration??`no-preference`}) is not supported in this environment. Consider using another codec or changing your video parameters.`)}let o=i.config;i.quantizer===null?this.source._nominalBitrate=o.bitrate??null:this.defaultEncodeOptions=Di(this.encodingConfig.codec,i.quantizer),a?(this.customEncoder=new a,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=o,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof L))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);gl(this.source._connectedTrack,e),this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,e,t).catch(e=>{this.setError(e)})},this.customEncoder.onError=e=>{this.setError(e)},await this.customEncoder.init()):(this.encoderConfig=o,this.encodingConfig.codec===`avc`&&Ge()&&(this.chunkTimestampsAreShiftedByDuration=await bl()),this.createWebCodecsEncoders()),t(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})(),this.ensureEncoderPromise.catch(e=>this.setError(e))}createWebCodecsEncoders(){let e=this.encoderConfig;t(e);let n=[],r=[],i=0,a=0,o=(e,t)=>{$e(e)?this.encodersReclaimed=!0:(e.stack=t,this.setError(e))},s=(/* @__PURE__ */ Error(`Encoding error`)).stack;if(this.encoder=new VideoEncoder({output:(e,o)=>{try{if(!this.alphaEncoder){this.addPacket(e,null,o);return}let s=this.alphaFrameQueue.shift();t(s!==void 0),s?(this.alphaEncoder.encode(s,{...this.defaultEncodeOptions,keyFrame:e.type===`key`}),a++,s.close(),n.push({chunk:e,meta:o})):a===0?this.addPacket(e,null,o):(r.push(i+a),n.push({chunk:e,meta:o}))}catch(e){this.setError(e)}},error:e=>o(e,s)}),this.encoder.configure(e),this.encodingConfig.alpha===`keep`){let s=(/* @__PURE__ */ Error(`Encoding error`)).stack;this.alphaEncoder=new VideoEncoder({output:(e,o)=>{try{a--;let o=n.shift();for(t(o!==void 0),this.addPacket(o.chunk,e,o.meta),i++;r.length>0&&r[0]===i;){r.shift();let e=n.shift();t(e!==void 0),this.addPacket(e.chunk,null,e.meta)}}catch(e){this.setError(e)}},error:e=>o(e,s)}),this.alphaEncoder.configure(e)}}addPacket(e,n,r){let i={};if(n){let e=new Uint8Array(n.byteLength);n.copyTo(e),i.alpha=e}let a=L.fromEncodedChunk(e,i),o=this.encoderConfig;if(t(o),r?.decoderConfig&&(r.decoderConfig.codec=Zl({width:o.width,height:o.height,codec:this.encodingConfig.codec,codecDescription:r.decoderConfig.description?b(r.decoderConfig.description):null,colorSpace:r.decoderConfig.colorSpace??null,avcType:o.codec.includes(`avc1.`)?1:o.codec.includes(`avc3.`)?3:null,avcCodecInfo:this.encodingConfig.codec===`avc`&&!r.decoderConfig.description?pn(a.data):null,hevcType:o.codec.includes(`hev1.`)?`hev1`:o.codec.includes(`hvc1.`)?`hvc1`:null,hevcCodecInfo:this.encodingConfig.codec===`hevc`&&!r.decoderConfig.description?Tn(a.data):null,vp9CodecInfo:this.encodingConfig.codec===`vp9`?Rn(a.data):null,av1CodecInfo:this.encodingConfig.codec===`av1`?Vn(a.data):null,proresFormat:null}),this.encodingConfig.codec===`avc`&&r.decoderConfig.description&&Ge())){let e=hn(b(r.decoderConfig.description)),n=e?.sequenceParameterSets[0];if(n&&n[0]===n[1]){t(e),n=n.subarray(1);let i=e.pictureParameterSets[0];i&&=i.subarray(1);let a=mn({...e,sequenceParameterSets:[n],pictureParameterSets:i?[i]:[]});r.decoderConfig.description=a}}let s=e.timestamp;this.chunkTimestampsAreShiftedByDuration&&(s-=e.duration??0,a=a.clone({timestamp:s/1e6}));let c=D(this.preciseTimings,s,e=>e.microsecondTimestamp),l=c===-1?null:this.preciseTimings[c],u=null;this.emittedEncoderPackets===0&&a.type===`delta`&&r?.decoderConfig&&(u=Jn(this.encodingConfig.codec,r.decoderConfig,a.data)),(l&&l.microsecondTimestamp===s||u!==null)&&(a=a.clone({timestamp:l?.timestampIsValid?l.timestamp:void 0,duration:l?.durationIsValid?l.duration:void 0,type:u??void 0})),gl(this.source._connectedTrack,a),this.encodingConfig.onEncodedPacket?.(a,r),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,a,r).catch(e=>{this.setError(e)}),this.emittedEncoderPackets++}recreateWebCodecsEncoders(){t(this.encoder),this.encoder.state!==`closed`&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!==`closed`&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.alphaFrameQueue.length=0,this.encodersReclaimed=!1,this.lastMultipleOfKeyFrameInterval=null,this.createWebCodecsEncoders()}async flushAndClose(e){await this.ensureEncoderPromise?.catch(()=>{});try{if(!e){this.checkForEncoderError();let e=await this.addMutex.acquire();try{if(this.frameRateLastSample){let e=this.encodingConfig.transform.frameRate,t=Pe(this.frameRateLastEndTimestamp,e);await this.padFrameRate(t)}}finally{e()}}this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()).catch(e=>this.setError(e)):this.encoder&&!this.encodersReclaimed&&(await this.encoder.flush(),await this.alphaEncoder?.flush(),await ht(25)))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&(this.encoder.state!==`closed`&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!==`closed`&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.alphaFrameQueue.length=0,this.splitter?.close())}e||(await this.lastMuxerPromise,this.checkForEncoderError())}getQueueSize(){return this.customEncoder?this.addMutex.pending+this.customEncoderQueueSize:this.addMutex.pending+(this.encoder?.encodeQueueSize??0)}checkForEncoderError(){if(this.errorSet)throw this.error}};let yl=null;const bl=()=>yl??=(async()=>{let e=null,t=new VideoEncoder({output:t=>{e??=t.timestamp},error:()=>{}});try{t.configure({codec:`avc1.64001f`,width:1280,height:720});let e=new VideoFrame(/* @__PURE__ */ new Uint8Array(1382400),{format:`I420`,codedWidth:1280,codedHeight:720,timestamp:0,duration:500});t.encode(e,{keyFrame:!0}),e.close(),await t.flush()}catch{return!1}finally{t.state!==`closed`&&t.close()}return e===500})();let xl=null;var Sl=class{constructor(){this.worker=null,this.pendingRequests=/* @__PURE__ */ new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!xl){let e=new Blob([`(${Cl.toString()})()`],{type:`application/javascript`});xl=URL.createObjectURL(e)}this.worker=new Worker(xl),this.worker.addEventListener(`message`,e=>{let t=e.data,n=this.pendingRequests.get(t.id);n&&(this.pendingRequests.delete(t.id),`error`in t?n.reject(Error(t.error)):n.resolve({colorFrame:t.colorFrame,alphaFrame:t.alphaFrame}))}),this.worker.addEventListener(`error`,e=>{let t=Error(e.message||`Color/alpha splitter worker error.`);for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()})}let t=this.nextRequestId++,n=O();return this.pendingRequests.set(t,n),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),n.promise}close(){this.worker?.terminate(),this.worker=null;let e=/* @__PURE__ */ Error(`Color/alpha splitter closed.`);for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};const Cl=()=>{let e=null,t=Promise.resolve();self.addEventListener(`message`,e=>{let{id:r,sourceFrame:i}=e.data;t=t.then(async()=>{try{let{colorFrame:e,alphaFrame:t}=await n(i);self.postMessage({id:r,colorFrame:e,alphaFrame:t},{transfer:[e,t]})}catch(e){self.postMessage({id:r,error:e.message})}finally{i.close()}})});let n=async t=>{let n=t.format;if(!n)throw Error(`CPU color/alpha splitting requires a known VideoFrame format.`);let a=t.allocationSize();if(e&&e.byteLength===a||(e=new Uint8Array(a)),await t.copyTo(e),n===`RGBA`||n===`BGRA`)return r(e,n,t);if(n===`I420A`||n===`I420AP10`||n===`I420AP12`||n===`I422A`||n===`I422AP10`||n===`I422AP12`||n===`I444A`||n===`I444AP10`||n===`I444AP12`)return i(e,n,t);throw Error(`CPU color/alpha splitting does not support format '${n}'.`)},r=(e,t,n)=>{let r=n.visibleRect?.width??n.codedWidth,i=n.visibleRect?.height??n.codedHeight,a=r*i,o=a+Math.ceil(r/2)*Math.ceil(i/2)*2,s=new Uint8Array(o);for(let t=0,n=3;t<a;t++,n+=4)s[t]=e[n];s.fill(128,a);let c=new VideoFrame(e,{format:t===`RGBA`?`RGBX`:`BGRX`,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0}),l={format:`I420`,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0,colorSpace:{fullRange:!0,matrix:`bt709`,primaries:`bt709`,transfer:`bt709`},transfer:[s.buffer]};return{colorFrame:c,alphaFrame:new VideoFrame(s,l)}},i=(e,t,n)=>{let r=n.visibleRect?.width??n.codedWidth,i=n.visibleRect?.height??n.codedHeight,a=t.includes(`P10`),o=t.includes(`P12`),s=a||o?2:1,c,l;t.startsWith(`I420`)?(c=Math.ceil(r/2),l=Math.ceil(i/2)):t.startsWith(`I422`)?(c=Math.ceil(r/2),l=i):(c=r,l=i);let u=r*i,d=c*l,f=u*s,p=d*s,m=u*s,h=f+p*2,g=t.replace(`A`,``),_=Math.ceil(r/2)*Math.ceil(i/2),v=m+_*s*2,y=new Uint8Array(v),b=h;y.set(e.subarray(b,b+m),0);let x=m,S=a?512:o?2048:128;s===1?y.fill(S,x):new Uint16Array(y.buffer,x,2*_).fill(S);let C=a?`I420P10`:o?`I420P12`:`I420`,w=new VideoFrame(e.subarray(0,h),{format:g,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0,colorSpace:n.colorSpace}),ee={format:C,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0,colorSpace:{fullRange:!0,matrix:`bt709`,primaries:`bt709`,transfer:`bt709`},transfer:[y.buffer]};return{colorFrame:w,alphaFrame:new VideoFrame(y,ee)}}};var wl=class extends hl{constructor(e){_i(e),super(e.codec),this._encoder=new vl(this,e)}add(e,t){if(!(e instanceof Vr))throw TypeError(`videoSample must be a VideoSample.`);return this._ensureValidAdd(),this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Tl=class extends ml{constructor(e){if(super(),!Rl.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${Rl.join(`, `)}.`);this._codec=e}},El=class extends Tl{constructor(e){super(e)}add(e,t){if(!(e instanceof L))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}};const Dl=2048;var Ol=class{setError(e){this.errorSet||=(this.error=e,!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.addMutex=new de,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.pcmMeta=null,this.pcmStartTimestamp=0,this.pcmEmittedFrames=0,this.pcmReadBuffer=/* @__PURE__ */ new ArrayBuffer(0),this.pcmScratchView=null,this.pcmScratchFrames=0,this.customEncoder=null,this.customEncoderCallSerializer=new Ve,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t){let n=null;try{if(this.checkForEncoderError(),n=await this.addMutex.acquire(),this.closed)return;if(this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw 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;let r=this.encodingConfig;r.transform?.numberOfChannels!==void 0||r.transform?.sampleRate!==void 0?(this.resampler||=new Ri({targetNumberOfChannels:r.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:r.transform.sampleRate??e.sampleRate,onSample:async e=>{await this.processAndEncode(e,!0)}}),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{n?.(),t&&e.close()}}async processAndEncode(e,t){let n=this.encodingConfig;if(n.transform?.sampleFormat!==void 0&&fi(e.format)!==n.transform.sampleFormat){let r=mi(e,n.transform.sampleFormat);t&&e.close(),e=r,t=!0}if(n.transform?.process)try{let t=n.transform.process(e);if(j(t)&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]);try{for(let e of t)if(!(e instanceof oi))throw TypeError(`The audio process function must return an AudioSample, null, or an array of AudioSamples.`);for(let n of t)await this.encodeSample(n,n!==e)}finally{for(let n of t)n instanceof oi&&n!==e&&n.close()}}finally{t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,n){try{if(e.numberOfFrames===0||(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),t(this.encoderInitialized),this.closed))return;{let t=Math.round(e.timestamp*e.sampleRate),n=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let n=t-this.lastEndSampleIndex;if(n>=64){let t=si(e.format)*e.numberOfChannels,r=new Uint8Array(t*Math.min(n,e.sampleRate));(e.format===`u8`||e.format===`u8-planar`)&&r.fill(128);let i=n;for(;i>0;){let n=Math.min(i,e.sampleRate),a=new oi({data:r.subarray(0,t*n),_doNotCopy:!0,format:e.format,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:n,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(a,!0),i-=n}}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,n);else{t(this.encoder),this.checkForEncoderError();let r=e.toAudioData();try{this.encoder.encode(r)}finally{r.close()}n&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0})),await this.lastMuxerPromise}}finally{n&&e.close()}}async doPcmEncoding(e,n){t(this.outputSampleSize),t(this.writeOutputValue);let{numberOfChannels:r,numberOfFrames:i,sampleRate:a,timestamp:o}=e;this.pcmMeta||(this.pcmMeta={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:r,sampleRate:a}},this.pcmStartTimestamp=o);let s=e.format===`s32`||e.format===`s32-planar`,c=s?`s32`:`f32`,l=s?1/2147483648:1,u=e.allocationSize({planeIndex:0,format:c});this.pcmReadBuffer.byteLength<u&&(this.pcmReadBuffer=new ArrayBuffer(u));let d=s?new Int32Array(this.pcmReadBuffer,0,u/4):new Float32Array(this.pcmReadBuffer,0,u/4);e.copyTo(d,{planeIndex:0,format:c}),n&&e.close();let f=0;for(;f<i;){this.pcmScratchView??=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(Dl*r*this.outputSampleSize));let e=Math.min(Dl-this.pcmScratchFrames,i-f),t=this.pcmScratchFrames*r,n=f*r;for(let i=0;i<e*r;i++)this.writeOutputValue(this.pcmScratchView,(t+i)*this.outputSampleSize,d[n+i]*l);this.pcmScratchFrames+=e,f+=e,this.pcmScratchFrames===2048&&await this.emitPcmScratchPacket()}}async emitPcmScratchPacket(){t(this.outputSampleSize),t(this.pcmScratchView),t(this.pcmMeta?.decoderConfig);let{numberOfChannels:e,sampleRate:n}=this.pcmMeta.decoderConfig,r=this.pcmScratchFrames*e*this.outputSampleSize,i=new L(new Uint8Array(this.pcmScratchView.buffer,0,r),`key`,this.pcmStartTimestamp+this.pcmEmittedFrames/n,this.pcmScratchFrames/n);this.pcmEmittedFrames+=this.pcmScratchFrames,this.pcmScratchView=null,this.pcmScratchFrames=0,this.encodingConfig.onEncodedPacket?.(i,this.pcmMeta),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,i,this.pcmMeta)}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let{format:n,numberOfChannels:r,sampleRate:i,timestamp:a}=e,o=Ai(this.encodingConfig.quality,this.encodingConfig.bitrate),s=Si({numberOfChannels:r,sampleRate:i,...this.encodingConfig,quality:o});this.encodingConfig.onEncoderConfig?.(s),this.source._nominalBitrate=s.bitrate??null;let c=Ii.find(e=>e.supports(this.encodingConfig.codec,s));if(c)this.customEncoder=new c,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=s,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof L))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,e,t).catch(e=>{this.setError(e)})},this.customEncoder.onError=e=>{this.setError(e)},await this.customEncoder.init();else if(Il.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>`u`)throw Error(Qe(`AudioEncoder`));let e;try{e=(await AudioEncoder.isConfigSupported(s)).supported??!1}catch{e=!1}if(!e)throw Error(`This specific encoder configuration (${s.codec}, ${s.bitrate} bps, ${s.numberOfChannels} channels, ${s.sampleRate} Hz) is not supported in this environment. Consider using another codec or changing your audio parameters.`);let t=await Al(this.encodingConfig.codec,s.codec)/s.sampleRate,o=0,c=(/* @__PURE__ */ Error(`Encoding error`)).stack;this.encoder=new AudioEncoder({output:(e,n)=>{try{if(n?.decoderConfig&&(Ml(this.encodingConfig.codec,s,n.decoderConfig),this.encodingConfig.codec===`opus`&&n.decoderConfig.description)){let e=b(n.decoderConfig.description);o=Wn(e).preSkip/ru}let r=L.fromEncodedChunk(e);r=r.clone({timestamp:Me(r.timestamp-t-o,s.sampleRate),duration:e.duration==null?void 0:Me(r.duration,s.sampleRate)}),Ge()&&(o=0),this.encodingConfig.onEncodedPacket?.(r,n),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,r,n).catch(e=>{this.setError(e)})}catch(e){this.setError(e)}},error:e=>{e.stack=c,this.setError(e)}}),this.encoder.configure(s),this.encodingConfig.codec===`aac`&&Ue()&&jl(this.encoder,n,r,i,a)}t(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})(),this.ensureEncoderPromise.catch(e=>this.setError(e))}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:n,sampleSize:r,littleEndian:i}=ou(e);switch(this.outputSampleSize=r,r){case 1:n===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint8(t,A(Math.round(n*128)+128,0,255)):n===`signed`?this.writeOutputValue=(e,t,n)=>{e.setInt8(t,A(Math.round(n*128),-128,127))}:n===`ulaw`?this.writeOutputValue=(e,t,n)=>{let r=A(Math.round(n*32768),-32768,32767);e.setUint8(t,kr(r))}:n===`alaw`?this.writeOutputValue=(e,t,n)=>{let r=A(Math.round(n*32768),-32768,32767);e.setUint8(t,jr(r))}:t(!1);break;case 2:n===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint16(t,A(Math.round(n*32768)+32768,0,65535),i):n===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt16(t,A(Math.round(n*32768),-32768,32767),i):t(!1);break;case 3:n===`unsigned`?this.writeOutputValue=(e,t,n)=>Te(e,t,A(Math.round(n*8388608)+8388608,0,16777215),i):n===`signed`?this.writeOutputValue=(e,t,n)=>Ee(e,t,A(Math.round(n*8388608),-8388608,8388607),i):t(!1);break;case 4:n===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint32(t,A(Math.round(n*2147483648)+2147483648,0,4294967295),i):n===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt32(t,A(Math.round(n*2147483648),-2147483648,2147483647),i):n===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,i):t(!1);break;case 8:n===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat64(t,n,i):t(!1);break;default:k(r),t(!1)}}async flushAndClose(e){await this.ensureEncoderPromise?.catch(()=>{});try{if(!e){this.checkForEncoderError();let e=await this.addMutex.acquire();try{this.resampler&&await this.resampler.finalize(),this.pcmScratchFrames>0&&await this.emitPcmScratchPacket()}finally{e()}}this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()).catch(e=>this.setError(e)):this.encoder&&await this.encoder.flush())}finally{this.closed=!0,this.resampler=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&this.encoder.state!==`closed`&&this.encoder.close()}e||(await this.lastMuxerPromise,this.checkForEncoderError())}getQueueSize(){return this.customEncoder?this.addMutex.pending+this.customEncoderQueueSize:this.isPcmEncoder?this.addMutex.pending:this.addMutex.pending+(this.encoder?.encodeQueueSize??0)}checkForEncoderError(){if(this.errorSet)throw this.error}};const kl=/* @__PURE__ */ new Map,Al=(e,n)=>{let r=kl.get(n);return r||(r=(async()=>{let r=48e3,i={codec:n,numberOfChannels:1,sampleRate:r,...lu(e)},a=4096,o=2*a,s=`f32-planar`,c=[],l=null,u=null,d=-1/0,f=0,p=null,m=new AudioEncoder({output:(e,t)=>{t?.decoderConfig&&(l??=t.decoderConfig),c.push(e)},error:e=>{p??=e}}),h=new AudioDecoder({output:e=>{let t=new Float32Array(e.numberOfFrames);e.copyTo(t,{planeIndex:0,format:s}),e.close();for(let e=0;e<t.length;e++)t[e]>d&&(d=t[e],u=f+e);f+=t.length},error:e=>{p??=e}});try{m.configure(i),e===`aac`&&Ue()&&jl(m,s,1,r,0);let n=new Float32Array(1*o);n[a]=1;let u=new AudioData({data:n,format:s,numberOfChannels:1,numberOfFrames:o,sampleRate:r,timestamp:0});m.encode(u),u.close(),await m.flush(),t(l),Ml(e,i,l),h.configure(l);for(let e of c)h.decode(e);await h.flush()}catch(e){throw p??e}finally{m.state!==`closed`&&m.close(),h.state!==`closed`&&h.close()}t(u!==null);let g=Math.round(c[0].timestamp/1e6*r);return u-a+g})(),kl.set(n,r),r.catch(()=>kl.delete(n)),r)},jl=(e,t,n,r,i)=>{let a=1024,o=si(t),s=new Uint8Array(o*a*n);(t===`u8`||t===`u8-planar`)&&s.fill(128);let c=new AudioData({data:s,format:t,numberOfChannels:n,numberOfFrames:a,sampleRate:r,timestamp:Math.round(1e6*(i-a/r))});e.encode(c),c.close()},Ml=(e,t,n)=>{if(e===`aac`){if(n.description&&n.description.byteLength>0&&b(n.description)[0]===3){let{decoderSpecificInfo:e}=ll(Uc.tempFromBytes(b(n.description)));n.description=e??void 0}let e=!1;if(e=!n.description||n.description.byteLength<2||Mt(b(n.description)).objectType===0,e){let e=Number(m(t.codec.split(`.`)));n.description=Ft({objectType:e,outputNumberOfChannels:n.numberOfChannels,outputSampleRate:n.sampleRate,programConfigElement:null})}}};var Nl=class extends Tl{constructor(e){bi(e),super(e.codec),this._encoder=new Ol(this,e)}add(e){if(!(e instanceof oi))throw TypeError(`audioSample must be an AudioSample.`);return this._ensureValidAdd(),this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Pl=class extends ml{constructor(e){if(super(),!zl.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${zl.join(`, `)}.`);this._codec=e}};
392
+ /*!
393
+ * Copyright (c) 2026-present, Vanilagy and contributors
394
+ *
395
+ * This Source Code Form is subject to the terms of the Mozilla Public
396
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
397
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
398
+ */
399
+ const Fl=[`avc`,`hevc`,`vp9`,`av1`,`vp8`,`prores`],Il=[`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`],Ll=[`aac`,`opus`,`mp3`,`vorbis`,`flac`,`ac3`,`eac3`,`dts`,`truehd`],Rl=[...Ll,...Il],zl=[`webvtt`],Bl=[`truehd`],Vl=[{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}],Hl=[{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}],Ul=[{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}],Wl=[{maxPictureSize:147456,maxHSize:2048,maxVSize:1152,maxBitrate:15e5,tier:`M`,level:0},{maxPictureSize:278784,maxHSize:2816,maxVSize:1584,maxBitrate:3e6,tier:`M`,level:1},{maxPictureSize:665856,maxHSize:4352,maxVSize:2448,maxBitrate:6e6,tier:`M`,level:4},{maxPictureSize:1065024,maxHSize:5504,maxVSize:3096,maxBitrate:1e7,tier:`M`,level:5},{maxPictureSize:2359296,maxHSize:6144,maxVSize:3456,maxBitrate:12e6,tier:`M`,level:8},{maxPictureSize:2359296,maxHSize:6144,maxVSize:3456,maxBitrate:3e7,tier:`H`,level:8},{maxPictureSize:2359296,maxHSize:6144,maxVSize:3456,maxBitrate:2e7,tier:`M`,level:9},{maxPictureSize:2359296,maxHSize:6144,maxVSize:3456,maxBitrate:5e7,tier:`H`,level:9},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:3e7,tier:`M`,level:12},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:1e8,tier:`H`,level:12},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:4e7,tier:`M`,level:13},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:16e7,tier:`H`,level:13},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:6e7,tier:`M`,level:14},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:24e7,tier:`H`,level:14},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:6e7,tier:`M`,level:15},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:24e7,tier:`H`,level:15},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:6e7,tier:`M`,level:16},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:24e7,tier:`H`,level:16},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:1e8,tier:`M`,level:17},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:48e7,tier:`H`,level:17},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:16e7,tier:`M`,level:18},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:8e8,tier:`H`,level:18},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:16e7,tier:`M`,level:19},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:8e8,tier:`H`,level:19}],Gl=[`ap4x`,`ap4h`,`apch`,`apcn`,`apcs`,`apco`],Kl=[`dtsc`,`dtsh`,`dtsl`,`dtse`],ql=[{fourCc:`apco`,bitrate:45e6,alpha:!1},{fourCc:`apcs`,bitrate:102e6,alpha:!1},{fourCc:`apcn`,bitrate:147e6,alpha:!1},{fourCc:`apch`,bitrate:22e7,alpha:!1},{fourCc:`ap4h`,bitrate:33e7,alpha:!0},{fourCc:`ap4x`,bitrate:5e8,alpha:!0}],Jl=(e,t,n,r,i)=>{if(e===`avc`){let e=Ue(),i=e?66:100,a=Math.ceil(t/16)*Math.ceil(n/16),o=Vl.find(e=>a<=e.maxMacroblocks&&r<=e.maxBitrate)??m(Vl),s=o?o.level:0;return`avc1.${i.toString(16).padStart(2,`0`)}${e?`40`:`00`}${s.toString(16).padStart(2,`0`)}`}if(e===`hevc`){let e=t*n,i=Hl.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??m(Hl);return`hvc1.1.6.${i.tier}${i.level}.B0`}if(e===`vp8`)return`vp8`;if(e===`vp9`){let e=t*n;return`vp09.00.${(Ul.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??m(Ul)).level.toString().padStart(2,`0`)}.08`}if(e===`av1`){let e=t*n,i=Wl.find(i=>e<=i.maxPictureSize&&t<=i.maxHSize&&n<=i.maxVSize&&r<=i.maxBitrate)??m(Wl);return`av01.0.${i.level.toString().padStart(2,`0`)}${i.tier}.08`}if(e===`prores`){let e=(t*n/2073600)**.95,a=ql.filter(e=>e.alpha===i),o=a[0].fourCc,s=1/0;for(let{fourCc:t,bitrate:n}of a){let i=Math.abs(n*e-r);i<s&&(s=i,o=t)}return o}throw k(e),TypeError(`Unhandled codec '${String(e)}'.`)},Yl=e=>{let t=e.split(`.`);return[1,1,Number(t[1]),2,1,Number(t[2]),3,1,Number(t[3]),4,1,t[4]?Number(t[4]):1]},Xl=e=>{let t=e.split(`.`),n=Number(t[1]),r=t[2],i=Number(r.slice(0,-1)),a=(n<<5)+i,o=+(r.slice(-1)===`H`),s=Number(t[3]),c=s===8?0:1,l=+(s===12),u=t[4]?Number(t[4]):0,d=t[5]?Number(t[5][0]):1,f=t[5]?Number(t[5][1]):1,p=t[5]?Number(t[5][2]):0;return[129,a,(o<<7)+(c<<6)+(l<<5)+(u<<4)+(d<<3)+(f<<2)+p,0]},Zl=e=>{let{codec:n,codecDescription:r,colorSpace:i,avcCodecInfo:a,hevcCodecInfo:o,vp9CodecInfo:s,av1CodecInfo:c,proresFormat:l}=e;if(n===`avc`){if(t(e.avcType!==null),a){let t=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc${e.avcType}.${pe(t)}`}if(!r||r.byteLength<4)throw TypeError(`AVC decoder description is not provided or is not at least 4 bytes long.`);return`avc${e.avcType}.${pe(r.subarray(1,4))}`}if(n===`hevc`){t(e.hevcType!==null);let n,i,a,s,c,l;if(o)n=o.generalProfileSpace,i=o.generalProfileIdc,a=he(o.generalProfileCompatibilityFlags),s=o.generalTierFlag,c=o.generalLevelIdc,l=[...o.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw TypeError(`HEVC decoder description is not provided or is not at least 23 bytes long.`);let e=x(r),t=e.getUint8(1);n=t>>6&3,i=t&31,a=he(e.getUint32(2)),s=t>>5&1,c=e.getUint8(12),l=[];for(let t=0;t<6;t++)l.push(e.getUint8(6+t))}let u=`${e.hevcType}.`;for(u+=[``,`A`,`B`,`C`][n]+i,u+=`.`,u+=a.toString(16).toUpperCase(),u+=`.`,u+=s===0?`L`:`H`,u+=c;l.length>0&&l[l.length-1]===0;)l.pop();return l.length>0&&(u+=`.`,u+=l.map(e=>e.toString(16).toUpperCase()).join(`.`)),u}if(n===`vp8`)return`vp8`;if(n===`vp9`){let t=e.width*e.height,n=m(Ul).level;for(let e of Ul)if(t<=e.maxPictureSize){n=e.level;break}if(!s)return`vp09.00.${n.toString().padStart(2,`0`)}.08`;let r=s.profile.toString().padStart(2,`0`),i=(s.level===0?n:s.level).toString().padStart(2,`0`),a=s.bitDepth.toString().padStart(2,`0`),o=s.chromaSubsampling.toString().padStart(2,`0`),c=s.colourPrimaries.toString().padStart(2,`0`),l=s.transferCharacteristics.toString().padStart(2,`0`),u=s.matrixCoefficients.toString().padStart(2,`0`),d=s.videoFullRangeFlag.toString().padStart(2,`0`),f=`vp09.${r}.${i}.${a}.${o}`;return f+=`.${c}.${l}.${u}.${d}`,f.endsWith(`.01.01.01.01.00`)&&(f=f.slice(0,-15)),f}if(n===`av1`){if(!c){let t=e.width*e.height,n=m(Wl).level;for(let r of Wl)if(t<=r.maxPictureSize&&e.width<=r.maxHSize&&e.height<=r.maxVSize){n=r.level;break}return`av01.0.${n.toString().padStart(2,`0`)}M.08`}let t=c.profile,n=c.level.toString().padStart(2,`0`),r=c.tier?`H`:`M`,a=c.bitDepth.toString().padStart(2,`0`),o=c.monochrome?`1`:`0`,s=100*c.chromaSubsamplingX+10*c.chromaSubsamplingY+1*(c.chromaSubsamplingX&&c.chromaSubsamplingY?c.chromaSamplePosition:0),l,u,d,f;Hn(c)?(l=c.colourPrimaries,u=c.transferCharacteristics,d=c.matrixCoefficients,f=c.videoFullRangeFlag):(l=i?.primaries?E[i.primaries]:1,u=i?.transfer?re[i.transfer]:1,d=i?.matrix?ae[i.matrix]:1,f=+!!i?.fullRange);let p=`av01.${t}.${n}${r}.${a}`;return p+=`.${o}.${s.toString().padStart(3,`0`)}`,p+=`.${l.toString().padStart(2,`0`)}`,p+=`.${u.toString().padStart(2,`0`)}`,p+=`.${d.toString().padStart(2,`0`)}`,p+=`.${f}`,p.endsWith(`.0.110.01.01.01.0`)&&(p=p.slice(0,-17)),p}if(n===`prores`)return l??`apch`;throw n!==null&&k(n),TypeError(`Unhandled codec '${n}'.`)},Ql=e=>{switch(e.codec){case`avc`:{let t=e.avcCodecInfo?.sequenceParameterSets[0];if(!t&&e.codecDescription&&(t=hn(e.codecDescription)?.sequenceParameterSets[0]),t){let e=vn(t);if(e)return{primaries:ne[e.colourPrimaries],transfer:ie[e.transferCharacteristics],matrix:oe[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case`hevc`:{let t=e.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===F.SPS_NUT)?.nalUnits[0];if(!t&&e.codecDescription&&(t=Pn(e.codecDescription)?.arrays.find(e=>e.nalUnitType===F.SPS_NUT)?.nalUnits[0]),t){let e=wn(t);if(e)return{primaries:ne[e.colourPrimaries],transfer:ie[e.transferCharacteristics],matrix:oe[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case`vp8`:break;case`vp9`:if(e.vp9CodecInfo)return{primaries:ne[e.vp9CodecInfo.colourPrimaries],transfer:ie[e.vp9CodecInfo.transferCharacteristics],matrix:oe[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case`av1`:if(e.av1CodecInfo)return{primaries:ne[e.av1CodecInfo.colourPrimaries],transfer:ie[e.av1CodecInfo.transferCharacteristics],matrix:oe[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case`prores`:if(e.proresCodecInfo)return{primaries:ne[e.proresCodecInfo.colourPrimaries],transfer:ie[e.proresCodecInfo.transferCharacteristics],matrix:e.proresCodecInfo.matrixCoefficients===0?void 0:oe[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},$l=e=>{if(e===`aac`)return`mp4a.40.2`;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===`dts`)return`dtsc`;if(e===`truehd`)return`mlpa`;if(Il.includes(e))return e;throw TypeError(`Unhandled codec '${e}'.`)},eu=e=>{let{codec:t,codecDescription:n,aacCodecInfo:r,dtsFormat:i}=e;if(t===`aac`){if(!r)throw TypeError(`AAC codec info must be provided.`);if(r.isMpeg2)return`mp4a.67`;{let e;return e=r.objectType===null?Mt(n).objectType:r.objectType,`mp4a.40.${e}`}}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(t===`dts`)return i??`dtsc`;if(t===`truehd`)return`mlpa`;if(t&&Il.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},tu=(e,n)=>{switch(e){case`aac`:{if(!n.description)return 1024/n.sampleRate;let e=Mt(b(n.description));if(e.coreSampleRate===null)throw Error(`Invalid AAC sampling frequency index.`);return e.frameLength/e.coreSampleRate}case`opus`:return iu;case`mp3`:{let{sampleRate:e,numberOfChannels:t}=n,r=e>=32e3,i=r?1152:576,a=r?32e3:8e3,o=r?511:255,s=r?t===1?17:32:t===1?9:17,c=Math.floor(i/8*a/e)-4-s;return(1+Math.ceil(o/c))*i/e}case`vorbis`:{t(n.description);let e=b(n.description),r=1,i=2;for(;i>0;)e[r++]<255&&i--;return(1<<(e[r+28]>>4))/2/n.sampleRate}case`ac3`:case`eac3`:return 256/n.sampleRate;case`dts`:return 512/n.sampleRate;case`flac`:case`truehd`:case`pcm-s16`:case`pcm-s16be`:case`pcm-s24`:case`pcm-s24be`:case`pcm-s32`:case`pcm-s32be`:case`pcm-f32`:case`pcm-f32be`:case`pcm-f64`:case`pcm-f64be`:case`pcm-u8`:case`pcm-s8`:case`ulaw`:case`alaw`:return 0;default:k(e),t(!1)}},nu=(e,n)=>{switch(e){case`aac`:return 1024;case`opus`:return .02*n;case`mp3`:return 576;case`vorbis`:return 256;case`flac`:return 1152;case`ac3`:return 1536;case`eac3`:return 256;case`dts`:return 512;case`truehd`:return 40;case`pcm-s16`:case`pcm-s16be`:case`pcm-s24`:case`pcm-s24be`:case`pcm-s32`:case`pcm-s32be`:case`pcm-f32`:case`pcm-f32be`:case`pcm-f64`:case`pcm-f64be`:case`pcm-u8`:case`pcm-s8`:case`ulaw`:case`alaw`:return Dl;default:k(e),t(!1)}},ru=48e3,iu=.4,au=/^pcm-([usf])(\d+)(be)?$/,ou=e=>{if(t(Il.includes(e)),e===`ulaw`)return{dataType:`ulaw`,sampleSize:1,littleEndian:!0,silentValue:255};if(e===`alaw`)return{dataType:`alaw`,sampleSize:1,littleEndian:!0,silentValue:213};let n=au.exec(e);t(n);let r;r=n[1]===`u`?`unsigned`:n[1]===`s`?`signed`:`float`;let i=Number(n[2])/8,a=n[3]!==`be`;return{dataType:r,sampleSize:i,littleEndian:a,silentValue:e===`pcm-u8`?128:0}},su=e=>e.startsWith(`avc1`)||e.startsWith(`avc3`)?`avc`:e.startsWith(`hev1`)||e.startsWith(`hvc1`)?`hevc`:e===`vp8`?`vp8`:e.startsWith(`vp09`)?`vp9`:e.startsWith(`av01`)?`av1`:Gl.includes(e)?`prores`:e===`mp3`||e===`mp4a.69`||e===`mp4a.6B`||e===`mp4a.6b`||e===`mp4a.40.34`?`mp3`:e.startsWith(`mp4a.40.`)||e===`mp4a.67`?`aac`:e===`opus`||e===`Opus`?`opus`:e===`vorbis`?`vorbis`:e===`flac`||e===`fLaC`?`flac`:e===`ac-3`||e===`ac3`?`ac3`:e===`ec-3`||e===`eac3`?`eac3`:Kl.includes(e)?`dts`:e===`mlpa`?`truehd`:e===`ulaw`?`ulaw`:e===`alaw`?`alaw`:au.test(e)?e:e===`webvtt`?`webvtt`:null,cu=e=>e===`avc`?{avc:{format:`avc`}}:e===`hevc`?{hevc:{format:`hevc`}}:{},lu=e=>e===`aac`?{aac:{format:`aac`}}:e===`opus`?{opus:{format:`opus`}}:{},uu=[`avc1`,`avc3`,`hev1`,`hvc1`,`vp8`,`vp09`,`av01`,...Gl],du=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,fu=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,pu=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,mu=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,hu=(e,t)=>{if(!e)throw TypeError(`Video chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Video chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Video chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Video chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Video chunk metadata decoder configuration must specify a codec string.`);if(!uu.some(t=>e.decoderConfig.codec.startsWith(t)))throw 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(e.decoderConfig.codedWidth)||e.decoderConfig.codedWidth<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).`);if(!Number.isInteger(e.decoderConfig.codedHeight)||e.decoderConfig.codedHeight<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).`);if(e.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(e.decoderConfig.displayAspectWidth)||e.decoderConfig.displayAspectWidth<=0))throw TypeError(`Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.`);if(e.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(e.decoderConfig.displayAspectHeight)||e.decoderConfig.displayAspectHeight<=0))throw TypeError(`Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.`);if(e.decoderConfig.displayAspectWidth!==void 0!=(e.decoderConfig.displayAspectHeight!==void 0))throw TypeError(`Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.`);if(e.decoderConfig.description!==void 0&&!ue(e.decoderConfig.description))throw TypeError(`Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.colorSpace!==void 0){let{colorSpace:t}=e.decoderConfig;if(typeof t!=`object`)throw TypeError(`Video chunk metadata decoder configuration colorSpace, when provided, must be an object.`);let n=Object.keys(E);if(t.primaries!=null&&!n.includes(t.primaries))throw TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${n.join(`, `)}.`);let r=Object.keys(re);if(t.transfer!=null&&!r.includes(t.transfer))throw TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(`, `)}.`);let i=Object.keys(ae);if(t.matrix!=null&&!i.includes(t.matrix))throw TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${i.join(`, `)}.`);if(t.fullRange!=null&&typeof t.fullRange!=`boolean`)throw TypeError(`Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.`)}if(e.decoderConfig.codec.startsWith(`avc1`)||e.decoderConfig.codec.startsWith(`avc3`)){if(!du.test(e.decoderConfig.codec))throw 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(e.decoderConfig.codec.startsWith(`hev1`)||e.decoderConfig.codec.startsWith(`hvc1`)){if(!fu.test(e.decoderConfig.codec))throw 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(e.decoderConfig.codec.startsWith(`vp8`)){if(e.decoderConfig.codec!==`vp8`)throw TypeError(`Video chunk metadata decoder configuration codec string for VP8 must be "vp8".`)}else if(e.decoderConfig.codec.startsWith(`vp09`)){if(!pu.test(e.decoderConfig.codec))throw 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(e.decoderConfig.codec.startsWith(`av01`)){if(!mu.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.`)}else if(Gl.some(t=>e.decoderConfig.codec.startsWith(t))&&!Gl.some(t=>e.decoderConfig.codec===t))throw TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${Gl.join(`, `)}.`);if(t!==null&&su(e.decoderConfig.codec)!==t)throw TypeError(`Video chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},gu=[`mp4a`,`mp3`,`opus`,`vorbis`,`flac`,`ulaw`,`alaw`,`pcm`,`ac-3`,`ec-3`,`dts`,`mlpa`],_u=(e,t)=>{if(!e)throw TypeError(`Audio chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Audio chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Audio chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Audio chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Audio chunk metadata decoder configuration must specify a codec string.`);if(!gu.some(t=>e.decoderConfig.codec.startsWith(t)))throw 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(e.decoderConfig.sampleRate)||e.decoderConfig.sampleRate<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).`);if(!Number.isInteger(e.decoderConfig.numberOfChannels)||e.decoderConfig.numberOfChannels<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).`);if(e.decoderConfig.description!==void 0&&!ue(e.decoderConfig.description))throw TypeError(`Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.codec.startsWith(`mp4a`)&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`){if(![`mp4a.40.2`,`mp4a.40.02`,`mp4a.40.5`,`mp4a.40.05`,`mp4a.40.29`,`mp4a.40.42`,`mp4a.67`].includes(e.decoderConfig.codec))throw 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(e.decoderConfig.codec.startsWith(`mp3`)||e.decoderConfig.codec.startsWith(`mp4a`)){if(e.decoderConfig.codec!==`mp3`&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`)throw TypeError(`Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".`)}else if(e.decoderConfig.codec.startsWith(`opus`)){if(e.decoderConfig.codec!==`opus`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Opus must be "opus".`);if(e.decoderConfig.description&&e.decoderConfig.description.byteLength<18)throw 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(e.decoderConfig.codec.startsWith(`vorbis`)){if(e.decoderConfig.codec!==`vorbis`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".`);if(!e.decoderConfig.description)throw 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(e.decoderConfig.codec.startsWith(`flac`)){if(e.decoderConfig.codec!==`flac`)throw TypeError(`Audio chunk metadata decoder configuration codec string for FLAC must be "flac".`);if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<42)throw 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(e.decoderConfig.codec.startsWith(`ac-3`)||e.decoderConfig.codec.startsWith(`ac3`)){if(e.decoderConfig.codec!==`ac-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".`)}else if(e.decoderConfig.codec.startsWith(`ec-3`)||e.decoderConfig.codec.startsWith(`eac3`)){if(e.decoderConfig.codec!==`ec-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".`)}else if(e.decoderConfig.codec.startsWith(`dts`)){if(!Kl.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${Kl.join(`, `)}.`)}else if(e.decoderConfig.codec.startsWith(`mlpa`)){if(e.decoderConfig.codec!==`mlpa`)throw TypeError(`Audio chunk metadata decoder configuration codec string for TrueHD must be "mlpa".`)}else if((e.decoderConfig.codec.startsWith(`pcm`)||e.decoderConfig.codec.startsWith(`ulaw`)||e.decoderConfig.codec.startsWith(`alaw`))&&!Il.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Il.join(`, `)}).`);if(t!==null&&su(e.decoderConfig.codec)!==t)throw TypeError(`Audio chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},vu=e=>{if(!e)throw TypeError(`Subtitle metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Subtitle metadata must be an object.`);if(!e.config)throw TypeError(`Subtitle metadata must include a config object.`);if(typeof e.config!=`object`)throw TypeError(`Subtitle metadata config must be an object.`);if(typeof e.config.description!=`string`)throw TypeError(`Subtitle metadata config description must be a string.`)};
400
+ /*!
401
+ * Copyright (c) 2026-present, Vanilagy and contributors
402
+ *
403
+ * This Source Code Form is subject to the terms of the Mozilla Public
404
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
405
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
406
+ */
407
+ var yu=class{constructor(e){this.mutex=new de,this.trackPacketOrderValidators=/* @__PURE__ */ new WeakMap,this.output=e}async onTrackClose(e){}validateTimestamp(e,t,n){let r=this.trackPacketOrderValidators.get(e);r||(r=new bu,this.trackPacketOrderValidators.set(e,r));let i=n?`key`:`delta`;if(r.digest(t,i))return;if(r.maxTimestamp===null)throw Error(`First packet must be a key packet.`);let a=i===`key`?r.maxTimestamp:r.maxTimestampBeforeLastKeyPacket;throw 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 ${t}s, but largest timestamp is ${a}s.`)}},bu=class{constructor(){this.maxTimestamp=null,this.maxTimestampBeforeLastKeyPacket=null}check(e,t){if(this.maxTimestamp===null)return t===`key`;let n=t===`key`?this.maxTimestamp:this.maxTimestampBeforeLastKeyPacket;return n===null||e>=n}digest(e,t){return this.check(e,t)?(t===`key`&&(this.maxTimestampBeforeLastKeyPacket=this.maxTimestamp),this.maxTimestamp=Math.max(this.maxTimestamp??-1/0,e),!0):!1}},xu=class extends yu{async start(){}async getMimeType(){return`application/x-black-hole`}async addEncodedVideoPacket(){}async addEncodedAudioPacket(){}async addSubtitleCue(){}async finalize(){}},Su=class{constructor(e){
408
+ /*!
409
+ * Copyright (c) 2026-present, Vanilagy and contributors
410
+ *
411
+ * This Source Code Form is subject to the terms of the Mozilla Public
412
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
413
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
414
+ */
415
+ this.writer=e,this.helper=/* @__PURE__ */ new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */ 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 t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%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 t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let n=this.offsets.get(e);t(n!==void 0);let r=this.writer.getPos();this.writer.seek(n),this.writeBox(e),this.writer.seek(r)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}};const K=/* #__PURE__ */ new Uint8Array(8),Cu=/* #__PURE__ */ new DataView(K.buffer),q=e=>[(e%256+256)%256],J=e=>(Cu.setUint16(0,e,!1),[K[0],K[1]]),wu=e=>(Cu.setInt16(0,e,!1),[K[0],K[1]]),Tu=e=>(Cu.setUint32(0,e,!1),[K[1],K[2],K[3]]),Y=e=>(Cu.setUint32(0,e,!1),[K[0],K[1],K[2],K[3]]),Eu=e=>(Cu.setInt32(0,e,!1),[K[0],K[1],K[2],K[3]]),Du=e=>(Cu.setUint32(0,Math.floor(e/2**32),!1),Cu.setUint32(4,e,!1),[K[0],K[1],K[2],K[3],K[4],K[5],K[6],K[7]]),Ou=e=>(Cu.setInt32(0,Math.floor(e/2**32),!1),Cu.setUint32(4,e,!1),[K[0],K[1],K[2],K[3],K[4],K[5],K[6],K[7]]),ku=e=>(Cu.setFloat64(0,e,!1),[K[0],K[1],K[2],K[3],K[4],K[5],K[6],K[7]]),Au=e=>(Cu.setInt16(0,256*e,!1),[K[0],K[1]]),ju=e=>(Cu.setInt32(0,2**16*e,!1),[K[0],K[1],K[2],K[3]]),Mu=e=>(Cu.setInt32(0,2**30*e,!1),[K[0],K[1],K[2],K[3]]),Nu=(e,t)=>{let n=[],r=e;do{let e=r&127;r>>=7,n.length>0&&(e|=128),n.push(e),t!==void 0&&t--}while(r>0||t);return n.reverse()},X=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},Pu=e=>[ju(e[0]),ju(e[1]),Mu(e[2]),ju(e[3]),ju(e[4]),Mu(e[5]),ju(e[6]),ju(e[7]),Mu(e[8])],Z=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),Q=(e,t,n,r,i)=>Z(e,[q(t),Tu(n),r??[]],i),Fu=e=>e.isQuickTime?Z(`ftyp`,[X(`qt `),Y(512),X(`qt `)]):e.fragmented?e.cmaf?Z(`ftyp`,[X(`iso5`),Y(512),X(`iso5`),X(`iso6`),X(`mp41`),X(`cmfc`),X(`dash`)]):Z(`ftyp`,[X(`iso5`),Y(512),X(`iso5`),X(`iso6`),X(`mp41`)]):Z(`ftyp`,[X(`isom`),Y(512),X(`isom`),e.holdsAvc?X(`avc1`):[],X(`mp41`)]),Iu=()=>Z(`styp`,[X(`iso5`),Y(0),X(`iso5`),X(`iso6`),X(`mp41`),X(`cmfc`),X(`dash`)]),Lu=(e,n)=>{t(n<2**31);let r=Math.max(0,e.minWrittenTimestamp),i=Math.max(0,e.maxWrittenEndTimestamp-r);Number.isFinite(i)||(i=0);let a=$(i,bf);if(a>=2**32)throw Error(`CMAF segments must be shorter than 20.712612 hours.`);return Q(`sidx`,1,0,[Y(1),Y(bf),Du($(r,bf)),Du(0),J(0),J(1),Y(n),Y(a),Y(0)])},Ru=e=>({type:`mdat`,largeSize:e}),zu=e=>({type:`free`,size:e}),Bu=e=>Z(`moov`,void 0,[Vu(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>Hu(t,e.creationTime)),e.isFragmented?Pd(e.trackDatas):null,Yd(e)]),Vu=(e,t)=>{let n=Math.max(0,...t.map(e=>Math.max(0,$(Cf(e),bf)+$(e.startTimestampOffset??0,bf)))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!h(e)||!h(n),o=i?Du:Y;return Q(`mvhd`,+i,0,[o(e),o(e),Y(bf),o(n),ju(1),Au(1),Array(10).fill(0),Pu(a),Array(24).fill(0),Y(r)])},Hu=(e,t)=>{let n=Sf(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset!==0;return Z(`trak`,void 0,[Uu(e,t),r?Wu(e):null,Gu(e,t),n.name===void 0?null:Z(`udta`,void 0,[Z(`name`,[...T.encode(n.name)])])])},Uu=(e,t)=>{let n=Math.max(0,$(Cf(e),bf)+$(e.startTimestampOffset??0,bf)),r=!h(t)||!h(n),i=r?Du:Y,s;if(e.type===`video`&&e.track.metadata.transformationMatrix)s=e.track.metadata.transformationMatrix;else if(e.type===`video`){let{rotation:t,flip:n}=e.track.metadata,r=f(l(t??0),d(n?-1:1,1));s=o(r,e.info.width,e.info.height)}else s=a;let c=2;e.track.metadata.disposition?.default!==!1&&(c|=1);let u=e.type===`video`?0:e.type===`audio`?1:e.type===`subtitle`?2:k(e);return Q(`tkhd`,+r,c,[i(t),i(t),Y(e.track.id),Y(0),i(n),Array(8).fill(0),J(0),J(u),Au(+(e.type===`audio`)),J(0),Pu(s),ju(e.type===`video`?e.info.width:0),ju(e.type===`video`?e.info.height:0)])},Wu=e=>{let n=e.startTimestampOffset;if(t(n!==null),n>0){let t=$(n,bf),r=$(Cf(e),bf),i=!h(t)||!h(r),a=i?Du:Y,o=i?Ou:Eu;return Z(`edts`,void 0,[Q(`elst`,+!!i,0,[Y(2),a(t),o(-1),ju(1),a(r),o(0),ju(1)])])}{let t=$(-n,e.timescale),r=Math.max(0,$(Cf(e),bf)+$(n,bf)),i=!g(t)||!h(r),a=i?Du:Y,o=i?Ou:Eu;return Z(`edts`,void 0,[Q(`elst`,+!!i,0,[Y(1),a(r),o(t),ju(1)])])}},Gu=(e,t)=>Z(`mdia`,void 0,[Ku(e,t),Yu(!0,qu[e.type],Ju[e.type],void 0,e.muxer.isQuickTime),Xu(e)]),Ku=(e,t)=>{let n=$(Cf(e),e.timescale),r=!h(t)||!h(n),i=r?Du:Y;return Q(`mdhd`,+r,0,[i(t),i(t),Y(e.timescale),i(n),J(df(e.track.metadata.languageCode??`und`)),J(0)])},qu={video:`vide`,audio:`soun`,subtitle:`text`},Ju={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},Yu=(e,t,n,r=`\0\0\0\0`,i=!1)=>Q(`hdlr`,0,0,[e?X(`mhlr`):Y(0),X(t),X(r),Y(0),Y(0),i?[q(n.length),X(n)]:X(n,!0)]),Xu=e=>Z(`minf`,void 0,[Zu[e.type](),Qu(),td(e)]),Zu={video:()=>Q(`vmhd`,0,1,[J(0),J(0),J(0),J(0)]),audio:()=>Q(`smhd`,0,0,[J(0),J(0)]),subtitle:()=>Q(`nmhd`,0,0)},Qu=()=>Z(`dinf`,void 0,[$u()]),$u=()=>Q(`dref`,0,0,[Y(1)],[ed()]),ed=()=>Q(`url `,0,1),td=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return Z(`stbl`,void 0,[nd(e),Ed(e),t?jd(e):null,t?Md(e):null,Od(e),kd(e),Ad(e),Dd(e),...Nd(e.samples,!1)])},nd=e=>{let n;if(e.type===`video`)n=rd(af(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let r=sf(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime);t(r),n=dd(r,e)}else e.type===`subtitle`&&(n=wd(lf[e.track.source._codec],e));return t(n),Q(`stsd`,0,0,[Y(1)],[n])},rd=(e,t)=>Z(e,[[,,,,,,].fill(0),J(1),J(0),J(0),Array(12).fill(0),J(t.info.width),J(t.info.height),Y(4718592),Y(4718592),Y(0),J(1),q(18),X(tn),Array(13).fill(0),J(t.info.hasAlphaChannel?32:24),wu(65535)],[of[t.track.source._codec]?.(t)??null,ad(t),ce(t.info.decoderConfig.colorSpace)?null:od(t),id(t)]),id=e=>e.avgBitrate===0&&e.maxBitrate===0?null:Z(`btrt`,[Y(0),Y(e.maxBitrate),Y(e.avgBitrate)]),ad=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:Z(`pasp`,[Y(e.info.pixelAspectRatio.num),Y(e.info.pixelAspectRatio.den)]),od=e=>{let t=e.info.decoderConfig.colorSpace;return Z(`colr`,[X(e.muxer.isQuickTime?`nclc`:`nclx`),J(t?.primaries==null?2:E[t.primaries]),J(t?.transfer==null?2:re[t.transfer]),J(t?.matrix==null?2:ae[t.matrix]),e.muxer.isQuickTime?[]:q(!!t?.fullRange<<7)])},sd=e=>e.info.decoderConfig&&Z(`avcC`,[...b(e.info.decoderConfig.description)]),cd=e=>e.info.decoderConfig&&Z(`hvcC`,[...b(e.info.decoderConfig.description)]),ld=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,n=t.codec.split(`.`),r=Number(n[1]),i=Number(n[2]),a=n[3]?Number(n[3]):8,o=n[4]?Number(n[4]):1,s=n[8]?Number(n[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(o<<1)+s,l=n[5]?Number(n[5]):t.colorSpace?.primaries?E[t.colorSpace.primaries]:1,u=n[6]?Number(n[6]):t.colorSpace?.transfer?re[t.colorSpace.transfer]:1,d=n[7]?Number(n[7]):t.colorSpace?.matrix?ae[t.colorSpace.matrix]:1;return Q(`vpcC`,1,0,[q(r),q(i),q(c),q(l),q(u),q(d),J(0)])},ud=e=>Z(`av1C`,Xl(e.info.decoderConfig.codec)),dd=(e,n)=>{let r=0,i,a=16,o=n.info.sampleRate,s=cf(n.track.source._codec,n.muxer.isQuickTime)?.(n)??null,c=Il.includes(n.track.source._codec);if(c){let e=n.track.source._codec,{sampleSize:t}=ou(e);a=8*t}else if(n.track.source._codec===`flac`){let e=n.info.decoderConfig?.description;t(e);let r=new N(b(e));for(r.skipBits(167),a=r.readBits(5)+1;o>=2**16;)o=Math.floor(o/2)}if(n.muxer.isQuickTime&&n.track.source._codec!==`truehd`&&(r=n.info.sampleRate<2**16&&n.info.numberOfChannels<=2?1:2),r===0)i=[[,,,,,,].fill(0),J(1),J(r),J(0),Y(0),J(n.info.numberOfChannels),J(a),J(0),J(0),n.track.source._codec===`truehd`?Y(n.info.sampleRate):[J(o<2**16?o:0),J(0)]];else if(r===1){let e=c?0:-2;i=[[,,,,,,].fill(0),J(1),J(r),J(0),Y(0),J(n.info.numberOfChannels),J(Math.min(a,16)),wu(e),J(0),J(n.info.sampleRate<2**16?n.info.sampleRate:0),J(0),c?[Y(1),Y(a/8),Y(n.info.numberOfChannels*a/8)]:[Y(0),Y(0),Y(0)],Y(2)]}else if(r===2){let t=0;if(c){let{dataType:r,littleEndian:i}=ou(n.track.source._codec);r!==`ulaw`&&r!==`alaw`&&(e=`lpcm`,s=null,t=r===`float`|(i?0:2)|(r===`signed`?4:0)|8)}i=[[,,,,,,].fill(0),J(1),J(r),J(0),Y(0),J(3),J(16),wu(-2),J(0),Y(65536),Y(72),ku(n.info.sampleRate),Y(n.info.numberOfChannels),Y(2130706432),c?[Y(a),Y(t),Y(n.info.numberOfChannels*a/8),Y(1)]:[Y(0),Y(0),Y(0),Y(0)]]}else k(r),t(!1);return Z(e,i,[(e===`ipcm`||e===`fpcm`)&&n.info.sampleRate>=2**16?fd(n):null,s,id(n)])},fd=e=>Q(`srat`,0,0,[Y(e.info.sampleRate)]),pd=e=>{let t;switch(e.track.source._codec){case`aac`:t=64;break;case`mp3`:t=107;break;case`vorbis`:t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let n=[...q(t),...q(21),...Tu(0),...Y(e.maxBitrate),...Y(e.avgBitrate)];if(e.info.decoderConfig.description){let t=b(e.info.decoderConfig.description);n=[...n,...q(5),...Nu(t.byteLength),...t]}return n=[...J(1),...q(0),...q(4),...Nu(n.length),...n,...q(6),...q(1),...q(2)],n=[...q(3),...Nu(n.length),...n],Q(`esds`,0,0,n)},md=e=>Z(`wave`,void 0,[hd(e),e.track.source._codec===`ac3`?bd(e):e.track.source._codec===`eac3`?xd(e):gd(e),Z(`\0\0\0\0`)]),hd=e=>Z(`frma`,[X(sf(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime))]),gd=e=>{let{littleEndian:t}=ou(e.track.source._codec);return Z(`enda`,[J(+t)])},_d=e=>{let n=e.info.numberOfChannels,r=312,i=e.info.sampleRate,a=0,o=0,s=/* @__PURE__ */ new Uint8Array,c=e.info.decoderConfig?.description;if(c){t(c.byteLength>=18);let e=b(c),l=Wn(e);n=l.outputChannelCount,r=l.preSkip,i=l.inputSampleRate,a=l.outputGain,o=l.channelMappingFamily,l.channelMappingTable&&(s=l.channelMappingTable)}return Z(`dOps`,[q(0),q(n),J(r),Y(i),wu(a),q(o),...s])},vd=e=>{let n=e.info.decoderConfig?.description;t(n);let r=b(n);return Q(`dfLa`,0,0,[...r.subarray(4)])},yd=e=>{let{littleEndian:t,sampleSize:n}=ou(e.track.source._codec),r=+t;return Q(`pcmC`,0,0,[q(r),q(8*n)])},bd=e=>{t(e.info.primingPacket);let n=tr(e.info.primingPacket.data);if(!n)throw 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=/* @__PURE__ */ new Uint8Array(3),i=new N(r);return i.writeBits(2,n.fscod),i.writeBits(5,n.bsid),i.writeBits(3,n.bsmod),i.writeBits(3,n.acmod),i.writeBits(1,n.lfeon),i.writeBits(5,n.bitRateCode),i.writeBits(5,0),Z(`dac3`,[...r])},xd=e=>{t(e.info.primingPacket);let n=ir(e.info.primingPacket.data);if(!n)throw 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 e of n.substreams)r+=23,e.numDepSub>0?r+=9:r+=1;let i=Math.ceil(r/8),a=new Uint8Array(i),o=new N(a);o.writeBits(13,n.dataRate),o.writeBits(3,n.substreams.length-1);for(let e of n.substreams)o.writeBits(2,e.fscod),o.writeBits(5,e.bsid),o.writeBits(1,0),o.writeBits(1,0),o.writeBits(3,e.bsmod),o.writeBits(3,e.acmod),o.writeBits(1,e.lfeon),o.writeBits(3,0),o.writeBits(4,e.numDepSub),e.numDepSub>0?o.writeBits(9,e.chanLoc):o.writeBits(1,0);return Z(`dec3`,[...a])},Sd=e=>{t(e.info.primingPacket);let n=_r(e.info.primingPacket.data);if(!n)throw Error(`Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.`);return Z(`ddts`,[...Cr(n)])},Cd=e=>{t(e.info.primingPacket);let n=e.info.primingPacket.data;if(Xn(`truehd`,n)!==`key`)throw Error(`Couldn't extract TrueHD stream info from the audio packet. Ensure the first packet is an access unit carrying a major sync.`);let r=x(n),i=r.getUint32(8),a=r.getUint16(18)&32767;return Z(`dmlp`,[Y(i),J(a<<1),Y(0)])},wd=(e,t)=>Z(e,[[,,,,,,].fill(0),J(1)],[uf[t.track.source._codec](t),id(t)]),Td=e=>Z(`vttC`,[...T.encode(e.info.config.description)]),Ed=e=>Q(`stts`,0,0,[Y(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[Y(e.sampleCount),Y(e.sampleDelta)])]),Dd=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return Q(`stss`,0,0,[Y(t.length),t.map(([e])=>Y(e+1))])},Od=e=>Q(`stsc`,0,0,[Y(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[Y(e.firstChunk),Y(e.samplesPerChunk),Y(1)])]),kd=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=ou(e.track.source._codec);return Q(`stsz`,0,0,[Y(t*e.info.numberOfChannels),Y(e.samples.reduce((t,n)=>t+$(n.duration,e.timescale),0))])}return Q(`stsz`,0,0,[Y(0),Y(e.samples.length),e.samples.map(e=>Y(e.size))])},Ad=e=>e.finalizedChunks.length>0&&m(e.finalizedChunks).offset>=2**32?Q(`co64`,0,0,[Y(e.finalizedChunks.length),e.finalizedChunks.map(e=>Du(e.offset))]):Q(`stco`,0,0,[Y(e.finalizedChunks.length),e.finalizedChunks.map(e=>Y(e.offset))]),jd=e=>Q(`ctts`,1,0,[Y(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[Y(e.sampleCount),Eu(e.sampleCompositionTimeOffset)])]),Md=e=>{if(t(e.compositionTimeOffsetTable.length>0),e.samples.length===0)return null;let n=1/0,r=-1/0,i=1/0,a=-1/0;for(let t=0;t<e.compositionTimeOffsetTable.length;t++){let i=e.compositionTimeOffsetTable[t];n=Math.min(n,i.sampleCompositionTimeOffset),r=Math.max(r,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];i=Math.min(i,$(n.timestamp,e.timescale)),a=Math.max(a,$(n.timestamp+n.duration,e.timescale))}let o=Math.max(-n,0);return a>=2**31?null:Q(`cslg`,0,0,[Eu(o),Eu(n),Eu(r),Eu(i),Eu(a)])},Nd=(e,t)=>{let n=[];for(let t of e)if(n.length===0)n.push({sampleCount:1,prerollSamples:t.prerollSamples});else{let e=n[n.length-1];e.prerollSamples===t.prerollSamples?e.sampleCount++:n.push({sampleCount:1,prerollSamples:t.prerollSamples})}let r=n.filter(e=>e.prerollSamples!==0);if(r.length===0)return[];let i=t?65537:1;return[Q(`sgpd`,1,0,[X(`roll`),Y(2),Y(r.length),...r.map(e=>wu(e.prerollSamples))]),Q(`sbgp`,0,0,[X(`roll`),Y(n.length),...n.map(e=>[Y(e.sampleCount),Y(e.prerollSamples===0?0:i++)])])]},Pd=e=>Z(`mvex`,void 0,e.map(Fd)),Fd=e=>Q(`trex`,0,0,[Y(e.track.id),Y(1),Y(0),Y(0),Y(0)]),Id=(e,t)=>Z(`moof`,void 0,[Ld(e),...t.map(zd)]),Ld=e=>Q(`mfhd`,0,0,[Y(e)]),Rd=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,t|=r?1:2,t<<24|n<<16},zd=e=>Z(`traf`,void 0,[Bd(e),Vd(e),Hd(e),...Nd(e.currentChunk.samples,!0)]),Bd=e=>{t(e.currentChunk);let n=0;n|=8,n|=16,n|=32,n|=131072;let r=e.currentChunk.samples[1]??e.currentChunk.samples[0],i={duration:r.timescaleUnitsToNextSample,size:r.size,flags:Rd(r)};return Q(`tfhd`,0,n,[Y(e.track.id),Y(i.duration),Y(i.size),Y(i.flags)])},Vd=e=>(t(e.currentChunk),Q(`tfdt`,1,0,[Du($(e.currentChunk.startTimestamp,e.timescale))])),Hd=e=>{t(e.currentChunk);let n=e.currentChunk.offset-e.currentChunk.moofOffset||0;t(g(n));let r=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),i=e.currentChunk.samples.map(e=>e.size),a=e.currentChunk.samples.map(Rd),o=e.currentChunk.samples.map(t=>$(t.timestamp-t.decodeTimestamp,e.timescale)),s=new Set(r),c=new Set(i),l=new Set(a),u=new Set(o),d=l.size===2&&a.lastIndexOf(a[0])===0,f=s.size>1,p=c.size>1,m=!d&&l.size>1,h=u.size>1||[...u].some(e=>e!==0),_=0;return _|=1,_|=4*d,_|=256*f,_|=512*p,_|=1024*m,_|=2048*h,Q(`trun`,1,_,[Y(e.currentChunk.samples.length),Eu(n),d?Y(a[0]):[],e.currentChunk.samples.map((e,t)=>[f?Y(r[t]):[],p?Y(i[t]):[],m?Y(a[t]):[],h?Eu(o[t]):[]])])},Ud=e=>Z(`mfra`,void 0,[...e.map(Wd),Gd()]),Wd=e=>{let t=[];for(let n of e.finalizedChunks){let r=n.samples.findIndex(e=>e.type===`key`);if(r===-1)continue;let i=n.samples[r];t.push([Du($(i.timestamp,e.timescale)),Du(n.moofOffset),Y(n.trafIndex+1),Y(1),Y(r+1)])}return Q(`tfra`,1,0,[Y(e.track.id),Y(63),Y(t.length),t])},Gd=()=>Q(`mfro`,0,0,[Y(0)]),Kd=()=>Z(`vtte`),qd=(e,t,n,r,i)=>Z(`vttc`,void 0,[i===null?null:Z(`vsid`,[Eu(i)]),n===null?null:Z(`iden`,[...T.encode(n)]),t===null?null:Z(`ctim`,[...T.encode(Or(t))]),r===null?null:Z(`sttg`,[...T.encode(r)]),Z(`payl`,[...T.encode(e)])]),Jd=e=>Z(`vtta`,[...T.encode(e)]),Yd=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=tf(r);e&&t.push(e)}else if(n===`mdta`){let e=nf(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&Xd(t,e.output._metadataTags);return t.length===0?null:Z(`udta`,void 0,t)},Xd=(e,t)=>{for(let{key:n,value:r}of nt(t))switch(n){case`title`:e.push(Zd(`©nam`,r));break;case`description`:e.push(Zd(`©des`,r));break;case`artist`:e.push(Zd(`©ART`,r));break;case`album`:e.push(Zd(`©alb`,r));break;case`albumArtist`:e.push(Zd(`albr`,r));break;case`genre`:e.push(Zd(`©gen`,r));break;case`date`:e.push(Zd(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(Zd(`©cmt`,r));break;case`lyrics`:e.push(Zd(`©lyr`,r));break;case`raw`:break;case`creationTime`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`beatsPerMinute`:case`images`:break;default:k(n)}if(t.raw)for(let n in t.raw){let r=t.raw[n];r==null||n.length!==4||e.some(e=>e.type===n)||(typeof r==`string`?e.push(Zd(n,r)):r instanceof Uint8Array&&e.push(Z(n,Array.from(r))))}},Zd=(e,t)=>{let n=T.encode(t);return Z(e,[J(n.length),J(df(`und`)),Array.from(n)])},Qd={"image/jpeg":13,"image/png":14,"image/bmp":27},$d=/* @__PURE__ */ new Set([`HMMT`,`loci`,`chpl`]),ef=(e,t)=>{let n=[];for(let{key:r,value:i}of nt(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:rf(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:rf(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:rf(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:rf(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:rf(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:rf(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:rf(i)});break;case`beatsPerMinute`:t||n.push({key:`tmpo`,value:Z(`data`,[Y(21),Y(0),J(i)])});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:rf(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:rf(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:Z(`data`,[Y(Qd[e.mimeType]??0),Y(0),Array.from(e.data)])});break;case`trackNumber`:if(t){let t=e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`;n.push({key:`track`,value:rf(t)})}else n.push({key:`trkn`,value:Z(`data`,[Y(0),Y(0),J(0),J(i),J(e.tracksTotal??0),J(0)])});break;case`discNumber`:t||n.push({key:`disk`,value:Z(`data`,[Y(0),Y(0),J(0),J(i),J(e.discsTotal??0),J(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;case`creationTime`:break;default:k(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||!t&&(r.length!==4||$d.has(r))||n.some(e=>e.key===r)||(typeof i==`string`?n.push({key:r,value:rf(i)}):i instanceof Uint8Array?n.push({key:r,value:Z(`data`,[Y(0),Y(0),Array.from(i)])}):i instanceof wt&&n.push({key:r,value:Z(`data`,[Y(Qd[i.mimeType]??0),Y(0),Array.from(i.data)])}))}return n},tf=e=>{let t=ef(e,!1);return t.length===0?null:Q(`meta`,0,0,void 0,[Yu(!1,`mdir`,``,`appl`),Z(`ilst`,void 0,t.map(e=>Z(e.key,void 0,[e.value])))])},nf=e=>{let t=ef(e,!0);return t.length===0?null:Z(`meta`,void 0,[Yu(!1,`mdta`,``),Q(`keys`,0,0,[Y(t.length)],t.map(e=>Z(`mdta`,[...T.encode(e.key)]))),Z(`ilst`,void 0,t.map((e,t)=>{let n=String.fromCharCode(...Y(t+1));return Z(n,void 0,[e.value])}))])},rf=e=>Z(`data`,[Y(1),Y(0),...T.encode(e)]),af=(e,t)=>{switch(e){case`avc`:return t.startsWith(`avc3`)?`avc3`:`avc1`;case`hevc`:return`hvc1`;case`vp8`:return`vp08`;case`vp9`:return`vp09`;case`av1`:return`av01`;case`prores`:return t}},of={avc:sd,hevc:cd,vp8:ld,vp9:ld,av1:ud,prores:null},sf=(e,t,n)=>{switch(e){case`aac`:return`mp4a`;case`mp3`:return n?`.mp3`:`mp4a`;case`opus`:return`Opus`;case`vorbis`:return`mp4a`;case`flac`:return`fLaC`;case`ulaw`:return`ulaw`;case`alaw`:return`alaw`;case`pcm-u8`:return`raw `;case`pcm-s8`:return`sowt`;case`ac3`:return`ac-3`;case`eac3`:return`ec-3`;case`dts`:return t;case`truehd`:return`mlpa`}if(n)switch(e){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(e){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`}},cf=(e,t)=>{switch(e){case`aac`:return pd;case`mp3`:return t?null:pd;case`opus`:return _d;case`vorbis`:return pd;case`flac`:return vd;case`ac3`:return t?md:bd;case`eac3`:return t?md:xd;case`dts`:return Sd;case`truehd`:return Cd}if(t)switch(e){case`pcm-s24`:return md;case`pcm-s24be`:return md;case`pcm-s32`:return md;case`pcm-s32be`:return md;case`pcm-f32`:return md;case`pcm-f32be`:return md;case`pcm-f64`:return md;case`pcm-f64be`:return md}else switch(e){case`pcm-s16`:return yd;case`pcm-s16be`:return yd;case`pcm-s24`:return yd;case`pcm-s24be`:return yd;case`pcm-s32`:return yd;case`pcm-s32be`:return yd;case`pcm-f32`:return yd;case`pcm-f32be`:return yd;case`pcm-f64`:return yd;case`pcm-f64be`:return yd}return null},lf={webvtt:`wvtt`},uf={webvtt:Td},df=e=>{t(e.length===3);let n=0;for(let t=0;t<3;t++)n<<=5,n+=e.charCodeAt(t)-96;return n};
416
+ /*!
417
+ * Copyright (c) 2026-present, Vanilagy and contributors
418
+ *
419
+ * This Source Code Form is subject to the terms of the Mozilla Public
420
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
421
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
422
+ */
423
+ var ff=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw Error(`Can't have multiple Writers for the same Target.`);if(e._closed)throw Error(`Can't create a Writer for a Target that has already been closed.`);this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){t(!this.started),this.target._start(),this.started=!0}write(e){t(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return t(this.started&&!this.finalized),this.target._flush()}async finalize(){t(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=this.trackedStart}let n=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<n;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=/* @__PURE__ */ new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error(`Internal error: Can't get tracked writes since nothing was tracked.`);let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}},pf=class extends _t{constructor(){
424
+ /*!
425
+ * Copyright (c) 2026-present, Vanilagy and contributors
426
+ *
427
+ * This Source Code Form is subject to the terms of the Mozilla Public
428
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
429
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
430
+ */
431
+ super(...arguments),this._writerAcquired=!1,this._closed=!1,this._monotonicity=null,this.onwrite=null}_close(){return this._closed=!0,this._release()}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit(`write`,{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);return new vf(this,e)}};const mf=2**16,hf=2**32;var gf=class extends pf{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!=`object`)throw TypeError(`BufferTarget options, when provided, must be an object.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);if(this._options=e,this._supportsResize=`resize`in/* @__PURE__ */ new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(mf,{maxByteLength:hf})}catch{this._buffer=new ArrayBuffer(mf),this._supportsResize=!1}else this._buffer=new ArrayBuffer(mf);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){t(this._buffer),t(this._bytes);let n=this._buffer.byteLength;for(;n<e;)n*=2;if(n!==this._buffer.byteLength){if(n>hf)throw Error(`ArrayBuffer exceeded maximum size of ${hf} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(n);else{let e=new ArrayBuffer(n),t=new Uint8Array(e);t.set(this._bytes,0),this._buffer=e,this._bytes=t}}}_start(){}_write(e,n){t(this._bytes),this._ensureSize(n+e.byteLength),this._bytes.set(e,n),this._maxPos=Math.max(this._maxPos,n+e.byteLength),this._dispatchWrite(n,n+e.byteLength)}async _flush(){}async _finalize(){t(this._buffer),this.buffer=`transferToFixedLength`in this._buffer?this._buffer.transferToFixedLength(this._maxPos):this._buffer.slice(0,this._maxPos),this._buffer=null,this._bytes=null,this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit(`finalized`)}async _release(){}_getSlice(e,n){return t(this._bytes),this._bytes.slice(e,n)}},_f=class extends pf{_start(){}_write(e,t){this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this._emit(`finalized`)}async _release(){}},vf=class extends pf{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit(`finalized`)}async _release(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}},yf=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`getTarget must be a function.`)}};
432
+ /*!
433
+ * Copyright (c) 2026-present, Vanilagy and contributors
434
+ *
435
+ * This Source Code Form is subject to the terms of the Mozilla Public
436
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
437
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
438
+ */
439
+ const bf=57600,xf=.5,Sf=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},$=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},Cf=e=>{if(e.samples.length===0)return 0;let t=1/0,n=-1/0;for(let r=0;r<e.samples.length;r++){let i=e.samples[r];i.timestamp<t&&(t=i.timestamp),i.timestamp+i.duration>n&&(n=i.timestamp+i.duration)}return t===1/0?0:n-t};var wf=class extends yu{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new gf,this.auxWriter=new ff(this.auxTarget,!1),this.auxBoxWriter=new Su(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.closedTracks=/* @__PURE__ */ new Set,this.allTracksKnown=O(),this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.formatOptions={...t._options},this.isQuickTime=t instanceof Pf,this.isCmaf=t instanceof Nf,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof Nf?1/0:1),this.auxWriter.start()}async start(){let e=await this.mutex.acquire();try{let e=this.output._metadataTags.creationTime===void 0?/* @__PURE__ */ new Date:this.output._metadataTags.creationTime;if(this.creationTime=e?Math.floor(e.getTime()/1e3)+Bi:0,e&&this.creationTime<=0)throw Error(`creationTime must be after 1904-01-01T00:00:00Z for MP4/QuickTime files.`);if(this.isCmaf?(this.fastStart=`fragmented`,this.isFragmented=!0):(this.writer=await this.output._getRootWriter(e=>this.formatOptions.fastStart===void 0?e instanceof gf:this.formatOptions.fastStart===`in-memory`||this.formatOptions.fastStart===`fragmented`),this.boxWriter=new Su(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof gf&&`in-memory`),this.isFragmented=this.fastStart===`fragmented`),this.isCmaf){if(!this.output._hasInitTarget())throw Error(`CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.`);let e=new ff(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new Su(e)}let n=this.output.tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(t(e),this.formatOptions.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(Fu({isQuickTime:this.isQuickTime,holdsAvc:n,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onFtyp(t,n)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!==`in-memory`){if(this.fastStart===`reserve`)for(let e of this.output.tracks){if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`);if(e.metadata.maximumPacketCount>2**32-1)throw Error(`Track #${e.id} has a maximumPacketCount of ${e.metadata.maximumPacketCount}, which exceeds the maximum of ${2**32-1} packets per track that a non-fragmented file can hold.`)}else this.isFragmented||(t(this.writer),t(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ru(!0),this.boxWriter.writeBox(this.mdat))}await this.writer?.flush();for(let e of this.output.tracks)e.isVideoTrack()&&e.metadata.decoderConfig?this.getVideoTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig}):e.isAudioTrack()&&e.metadata.decoderConfig&&this.getAudioTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig})}finally{e()}}allTracksAreKnown(){for(let e of this.output.tracks)if(!this.closedTracks.has(e)&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return Vi({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,n,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;hu(r,e.source._codec),t(r),t(r.decoderConfig);let a={...r.decoderConfig};t(a.codedWidth!==void 0),t(a.codedHeight!==void 0);let o=!1;if(e.source._codec===`avc`&&!a.description){if(!n)throw Error(`No AVC description provided; you must therefore provide a priming packet.`);let e=pn(n.data);if(!e)throw 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.`);a.description=mn(e),o=!0}else if(e.source._codec===`hevc`&&!a.description){if(!n)throw Error(`No HEVC description provided; you must therefore provide a priming packet.`);let e=Tn(n.data);if(!e)throw 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.`);a.description=Nn(e),o=!0}let s=Be(1/(e.metadata.frameRate??57600),1e6).den,c=a.displayAspectWidth,l=a.displayAspectHeight,u=c===void 0||l===void 0?{num:1,den:1}:pt({num:c*a.codedHeight,den:l*a.codedWidth}),d=a.codec===`ap4h`||a.codec===`ap4x`,f={muxer:this,track:e,type:`video`,info:{width:a.codedWidth,height:a.codedHeight,pixelAspectRatio:u,decoderConfig:a,requiresAnnexBTransformation:o,hasAlphaChannel:d},timescale:s,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(f),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),f}getAudioTrackData(e,n,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;_u(r,e.source._codec),t(r),t(r.decoderConfig);let a={...r.decoderConfig},o=!1;if(e.source._codec===`aac`&&!a.description){if(!n)throw Error(`No AAC description provided; you must therefore provide a priming packet.`);let e=zo(Uc.tempFromBytes(n.data));if(!e)throw 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 t,r=null;if(e.channelConfiguration===0){let i=e.crcCheck===null?7:9,a=Vt(n.data.subarray(i));if(!a)throw Error(`ADTS frames with channel configuration 0 must begin with a program config element.`);r=a.programConfigElement,t=Ut(r)}else t=At[e.channelConfiguration];a.description=Ft({objectType:e.objectType,outputSampleRate:kt[e.samplingFrequencyIndex],outputNumberOfChannels:t,programConfigElement:r}),o=!0}if(!n){if(e.source._codec===`ac3`||e.source._codec===`eac3`)throw Error(`AC-3/E-AC-3 require a priming packet.`);if(e.source._codec===`dts`)throw Error(`DTS requires a priming packet.`);if(e.source._codec===`truehd`)throw Error(`TrueHD requires a priming packet.`)}let s={muxer:this,track:e,type:`audio`,info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:a,requiresPcmTransformation:!this.isFragmented&&Il.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,primingPacket:n,pendingEac3Packets:[],preroll:{packetCount:0,accumulatedAudioSamples:0,audioSampleDurationHistory:[]}},timescale:a.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(s),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(e,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;vu(n),t(n),t(n.config);let i={muxer:this,track:e,type:`subtitle`,info:{config:n.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:/* @__PURE__ */ new WeakMap};return this.trackDatas.push(i),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.data;if(r.info.requiresAnnexBTransformation){let e=[...nn(i)].map(e=>i.subarray(e.offset,e.offset+e.length));if(e.length===0)throw 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.`);i=dn(e,4)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=this.createSampleForTrack(r,i,t.timestamp,t.duration,t.type,0);await this.registerSample(r,a)}finally{r()}}async addEncodedAudioPacket(e,n,r){let i=await this.mutex.acquire();try{let i=this.getAudioTrackData(e,n,r),a=n.data;if(i.info.requiresAdtsStripping){let e=zo(Uc.tempFromBytes(a));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;if(a=a.subarray(t),e.channelConfiguration===0){let e=Vt(a);e&&(a=a.subarray(e.size))}}if(this.validateTimestamp(i.track,n.timestamp,n.type===`key`),e.source._codec===`eac3`){let e=ar(a),t=e?e.reduce((e,t)=>e+t.blockCount,0):6,r=i.info.pendingEac3Packets,o=r.reduce((e,t)=>e+t.blockCount,0)+t;if(o>6)throw Error(`E-AC-3 frames must add up to exactly six blocks to be muxed into MP4 samples.`);r.push({packet:n,blockCount:t}),o===6&&await this.writePendingEac3Packets(i);return}let o=n.timestamp,s=n.duration;if(i.info.requiresPcmTransformation){let e=ou(i.info.decoderConfig.codec).sampleSize*i.info.numberOfChannels;if(s=a.byteLength/e/i.info.sampleRate,i.info.expectedNextPcmPacketTimestamp!==null){let e=o-i.info.expectedNextPcmPacketTimestamp;if(e<.01)o=i.info.expectedNextPcmPacketTimestamp;else{let t=await this.padWithSilence(i,i.info.expectedNextPcmPacketTimestamp,e);o=i.info.expectedNextPcmPacketTimestamp+t}}i.info.expectedNextPcmPacketTimestamp=o+s}let{preroll:c}=i.info,l=0;if(e.source._codec===`aac`||e.source._codec===`vorbis`)l=-Math.min(1,c.packetCount);else if(e.source._codec===`mp3`)l=-Math.min(2,c.packetCount);else if(e.source._codec===`opus`){l=-c.audioSampleDurationHistory.length;let e=Kn(a);for(c.accumulatedAudioSamples+=e.durationInSamples,c.audioSampleDurationHistory.push(e.durationInSamples);c.accumulatedAudioSamples-c.audioSampleDurationHistory[0]>=19200;)c.accumulatedAudioSamples-=c.audioSampleDurationHistory.shift(),t(c.audioSampleDurationHistory.length>0)}c.packetCount++;let u=this.createSampleForTrack(i,a,o,s,n.type,l);await this.registerSample(i,u)}finally{i()}}async padWithSilence(e,t,n){let r=$(n,e.timescale),{sampleSize:i,silentValue:a}=ou(e.info.decoderConfig.codec),o=i*e.info.numberOfChannels,s=new Uint8Array(o*Math.min(r,e.timescale)).fill(a);for(let n=0;n<r;n+=e.timescale){let i=Math.min(r-n,e.timescale),a=this.createSampleForTrack(e,s.subarray(0,o*i),t+n/e.timescale,i/e.timescale,`key`,0);await this.registerSample(e,a)}return r/e.timescale}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);if(this.validateTimestamp(r.track,t.timestamp,!0),e.source._codec===`webvtt`){let e=$(t.timestamp,r.timescale)/r.timescale,n=$(t.timestamp+t.duration,r.timescale)/r.timescale;n>e&&r.cueQueue.push({cue:t,start:e,end:n}),await this.processWebVTTCues(r,e)}}finally{r()}}async processWebVTTCues(e,n){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].start);let r=/* @__PURE__ */ new Set([]);for(let{start:i,end:a}of e.cueQueue)t(i<=n),t(e.lastCueEndTimestamp<=a),r.add(Math.max(i,e.lastCueEndTimestamp)),r.add(a);let i=[...r].sort((e,t)=>e-t),a=i[0],o=i[1]??a;if(n<o)break;if(e.lastCueEndTimestamp<a){this.auxWriter.seek(0);let t=Kd();this.auxBoxWriter.writeBox(t);let n=this.auxTarget._getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,n,e.lastCueEndTimestamp,a-e.lastCueEndTimestamp,`key`,0);await this.registerSample(e,r),e.lastCueEndTimestamp=a}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let{cue:n,start:r,end:i}=e.cueQueue[t];if(r>=o)break;Tr.lastIndex=0;let s=Tr.test(n.text),c=e.cueToSourceId.get(n);if(c===void 0&&o<i&&(c=e.nextSourceId++,e.cueToSourceId.set(n,c)),n.notes){let e=Jd(n.notes);this.auxBoxWriter.writeBox(e)}let l=qd(n.text,s?a:null,n.identifier??null,n.settings??null,c??null);this.auxBoxWriter.writeBox(l),i===o&&e.cueQueue.splice(t--,1)}let s=this.auxTarget._getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,s,a,o-a,`key`,0);await this.registerSample(e,c),e.lastCueEndTimestamp=o}}createSampleForTrack(e,t,n,r,i,a){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:$(r,e.timescale),prerollSamples:a}}processTimestamps(e,n){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){t(!this.isFragmented),e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp;let n=0;for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t],i=$(r.duration,e.timescale);n+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:n,sampleDelta:1});else{let t=m(e.timeToSampleTable);t.sampleCount+=n}e.timestampProcessingQueue.length=0;return}let r=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);this.isFragmented?e.startTimestampOffset??=Math.min(r[0],0):e.startTimestampOffset??=r[0];for(let n=0;n<e.timestampProcessingQueue.length;n++){let i=e.timestampProcessingQueue[n];i.decodeTimestamp=r[n];let a=$(i.timestamp-i.decodeTimestamp,e.timescale),o=$(i.duration,e.timescale);if(e.lastTimescaleUnits!==null){t(e.lastSample);let n=$(i.decodeTimestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);if(t(r>=0),e.lastTimescaleUnits+=r,e.lastSample.timescaleUnitsToNextSample=r,!this.isFragmented){let n=m(e.timeToSampleTable);if(t(n),n.sampleCount===1){n.sampleDelta=r;let t=e.timeToSampleTable[e.timeToSampleTable.length-2];t&&t.sampleDelta===r&&(t.sampleCount++,e.timeToSampleTable.pop(),n=t)}else n.sampleDelta!==r&&(n.sampleCount--,e.timeToSampleTable.push(n={sampleCount:1,sampleDelta:r}));n.sampleDelta===o?n.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});let i=m(e.compositionTimeOffsetTable);t(i),i.sampleCompositionTimeOffset===a?i.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=$(i.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=i}if(e.timestampProcessingQueue.length=0,t(e.lastSample),t(e.lastTimescaleUnits!==null),n!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){t(n.type===`key`);let r=$(n.timestamp,e.timescale,!1),i=Math.round(r-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=i}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),e.sampleQueue.push(t),await this.interleaveSamples()}async addSampleToTrack(e,n){if(!this.isFragmented&&(e.samples.push(n),this.fastStart===`reserve`)){let n=e.track.metadata.maximumPacketCount;if(t(n!==void 0),e.samples.length>n)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${n}). Either add fewer packets or increase the maximum packet count.`)}let r=!1;if(!e.currentChunk)r=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,n.timestamp);let t=n.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(t=>{if(e===t)return n.type===`key`;let r=t.sampleQueue[0];return r?r.type===`key`:this.closedTracks.has(t.track)}),a=this.wroteFragmentedHeader||this.trackDatas.every(e=>e.startTimestampOffset!==null||this.closedTracks.has(e.track));t>=this.minimumFragmentDuration&&i&&n.timestamp>this.maxWrittenTimestamp&&a&&(r=!0,await this.finalizeFragment())}else r=t>=xf}if(r){if(!this.isFragmented){let e=this.trackDatas.filter(e=>e.currentChunk&&n.timestamp-e.currentChunk.startTimestamp>=xf).sort((e,t)=>e.currentChunk.startTimestamp-t.currentChunk.startTimestamp);for(let t of e)await this.finalizeCurrentChunk(t)}e.currentChunk={startTimestamp:n.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}}t(e.currentChunk),e.currentChunk.samples.push(n),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,n.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,n.timestamp+n.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,n.timestamp))}async finalizeCurrentChunk(e){t(!this.isFragmented),t(this.writer);let n=e.currentChunk;t(n),e.currentChunk=null,e.finalizedChunks.push(n),this.finalizedChunks.push(n);let r=n.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(r=n.samples.reduce((t,n)=>t+$(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||m(e.compactlyCodedChunkTable).samplesPerChunk!==r)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:r}),this.fastStart===`in-memory`)n.offset=0;else{n.offset=this.writer.getPos();for(let e of n.samples)t(e.data),this.writer.write(e.data),e.data=null;await this.writer.flush()}}async interleaveSamples(e=!1){if(e||this.allTracksAreKnown()){this.fastStart===`reserve`&&!this.mdat&&await this.createFastStartReserveMdat();outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!this.closedTracks.has(r.track))break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}}async finalizeFragment(e=!this.isCmaf){if(t(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let e=this.initBoxWriter??this.boxWriter;t(e),this.formatOptions.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let n=Bu(this);if(e.writeBox(n),this.formatOptions.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onMoov(t,n)}if(this.isCmaf){t(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Su(this.writer);let e=this.boxWriter.measureBox(Iu()),n=this.boxWriter.measureBox(Lu(this,0));this.segmentHeaderSize=e+n,this.writer.seek(this.segmentHeaderSize)}}t(this.writer),t(this.boxWriter);let n=this.trackDatas.filter(e=>e.currentChunk);if(n.length===0){e&&await this.writer.flush();return}let r=this.nextFragmentNumber++,i=Id(r,n),a=this.writer.getPos(),o=a+this.boxWriter.measureBox(i),s=o+8,c=1/0;for(let e=0;e<n.length;e++){let r=n[e];t(r.currentChunk),t(r.startTimestampOffset!==null),c=Math.min(c,r.currentChunk.startTimestamp),r.currentChunk.offset=s,r.currentChunk.moofOffset=a,r.currentChunk.trafIndex=e,r.currentChunk.startTimestamp-=r.startTimestampOffset;for(let e of r.currentChunk.samples)s+=e.size,e.timestamp-=r.startTimestampOffset,e.decodeTimestamp-=r.startTimestampOffset}let l=s-o,u=l>=2**32;if(u){for(let e of n)e.currentChunk.offset+=8;l+=8}if(m(n).currentChunk.offset-a>=2**31)throw Error(`The data of a fragment's track must start less than 2 GiB after its moof box; use shorter fragments.`);this.formatOptions.onMoof&&this.writer.startTrackingWrites();let d=Id(r,n);if(this.boxWriter.writeBox(d),this.formatOptions.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(e,t,c)}t(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let f=Ru(u);f.size=l,this.boxWriter.writeBox(f),this.writer.seek(o+(u?16:8));for(let e of n)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}for(let e of n)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async createFastStartReserveMdat(){t(this.writer),t(this.boxWriter),this.ensureOneEnabledTrack();let e=Bu(this),n=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;t(this.ftypSize!==null),this.writer.seek(this.ftypSize+n),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ru(!0),this.boxWriter.writeBox(this.mdat)}computeSampleTableSizeUpperBound(){t(this.fastStart===`reserve`);let e=0;for(let n of this.trackDatas){let r=n.track.metadata.maximumPacketCount;t(r!==void 0),e+=8*Math.ceil(2/3*r),e+=4*r,e+=8*Math.ceil(2/3*r),e+=12*Math.ceil(2/3*r),e+=4*r,e+=8*r,n.type===`audio`&&(e+=2*r,e+=8*r)}return e}async onTrackClose(e){let t=await this.mutex.acquire();try{let t=this.trackDatas.find(t=>t.track===e);t?.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(t,1/0),t?.type===`audio`&&t.info.pendingEac3Packets.length>0&&await this.writePendingEac3Packets(t),this.closedTracks.add(e),t&&this.processTimestamps(t),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveSamples()}finally{t()}}ensureOneEnabledTrack(){for(let e of[`video`,`audio`,`subtitle`]){let t=this.trackDatas.filter(t=>t.type===e);if(t.length!==0&&!t.some(e=>e.track.metadata.disposition?.default!==!1)){let e=t[0];e.track.metadata.disposition={...e.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){t(this.isFragmented);let e=await this.mutex.acquire();try{for(let e of this.trackDatas)e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async writePendingEac3Packets(e){let t=e.info.pendingEac3Packets.map(e=>e.packet);e.info.pendingEac3Packets.length=0;let n=t[0].data;if(t.length>1){n=new Uint8Array(t.reduce((e,t)=>e+t.data.byteLength,0));let e=0;for(let r of t)n.set(r.data,e),e+=r.data.byteLength}let r=t.reduce((e,t)=>e+t.duration,0),i=this.createSampleForTrack(e,n,t[0].timestamp,r,`key`,0);await this.registerSample(e,i)}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack();for(let e of this.trackDatas)e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),e.type===`audio`&&e.info.pendingEac3Packets.length>0&&await this.writePendingEac3Packets(e),this.closedTracks.add(e.track),this.processTimestamps(e);if(await this.interleaveSamples(!0),this.isFragmented)await this.finalizeFragment(!1);else{let e=this.trackDatas.filter(e=>e.currentChunk).sort((e,t)=>e.currentChunk.startTimestamp-t.currentChunk.startTimestamp);for(let t of e)await this.finalizeCurrentChunk(t);for(let e of this.trackDatas){let t=Cf(e);if(t>0){let n=0;for(let t of e.samples)n+=t.size;e.avgBitrate=Math.round(8*n/t)}else e.avgBitrate=0;let n=0,r=0,i=0;for(let t=0;t<e.samples.length;t++){let a=e.samples[t];for(r+=a.size;a.decodeTimestamp-e.samples[n].decodeTimestamp>=1;)r-=e.samples[n].size,n++;i=Math.max(i,r)}if(e.maxBitrate=8*i,e.startTimestampOffset!==null)for(let t=0;t<e.samples.length;t++){let n=e.samples[t];n.timestamp-=e.startTimestampOffset,n.decodeTimestamp-=e.startTimestampOffset}}}if(t(this.writer),t(this.boxWriter),this.fastStart===`in-memory`){this.mdat=Ru(!1);let e,n=null;for(;;){let r=this.boxWriter.measureBox(Bu(this)),i=this.boxWriter.measureBox(this.mdat),a=r+i;if(a===n)break;n=a,e=i;let o=this.writer.getPos()+a;for(let n of this.finalizedChunks){n.offset=o;for(let{data:r}of n.samples)t(r),o+=r.byteLength,e+=r.byteLength}e>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let r=Bu(this);if(this.boxWriter.writeBox(r),this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks){for(let n of e.samples)t(n.data),this.writer.write(n.data),n.data=null;await this.writer.flush()}if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}}else if(this.isFragmented){if(this.isCmaf){let e=this.segmentHeaderSize===null?0:this.writer.getPos()-this.segmentHeaderSize;if(e>=2**31)throw Error(`CMAF segments must be smaller than 2 GiB, as their sidx box can't index anything larger.`);this.writer.seek(0),this.boxWriter.writeBox(Iu()),this.boxWriter.writeBox(Lu(this,e))}else{let e=this.writer.getPos(),t=Ud(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}}else{t(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);t(e!==void 0);let n=this.writer.getPos()-e;if(this.mdat.size=n,this.mdat.largeSize=n>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}let r=Bu(this);if(this.fastStart===`reserve`){t(this.ftypSize!==null);let e=this.boxWriter.offsets.get(this.mdat)-this.ftypSize,n=this.boxWriter.measureBox(r);if(n+8>e)throw Error(`The moov box (${n} bytes) plus a free box (8 bytes) exceed the space reserved for them (${e} bytes) with fastStart: 'reserve'. This is a bug; please report it.`);this.writer.seek(this.ftypSize+n),this.boxWriter.writeBox(zu(e-n)),this.writer.seek(this.ftypSize)}if(this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r),this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}}e()}};
440
+ /*!
441
+ * Copyright (c) 2026-present, Vanilagy and contributors
442
+ *
443
+ * This Source Code Form is subject to the terms of the Mozilla Public
444
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
445
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
446
+ */
447
+ const Tf=-(2**15),Ef=2**15-1,Df={video:1,audio:2,subtitle:17};var Of=class extends yu{constructor(e,t){super(e),this.trackDatas=[],this.closedTracks=/* @__PURE__ */ new Set,this.allTracksKnown=O(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentClusterBlocks=[],this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.endTimestamp=-1/0,this.warnedAboutTooNegativeTimestamp=!1,this.format=t}async start(){let e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new Ia(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush();for(let e of this.output.tracks)e.isVideoTrack()&&e.metadata.decoderConfig?this.getVideoTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig}):e.isAudioTrack()&&e.metadata.decoderConfig&&this.getAudioTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig})}finally{e()}}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();let e={id:R.EBML,data:[{id:R.EBMLVersion,data:1},{id:R.EBMLReadVersion,data:1},{id:R.EBMLMaxIDLength,data:4},{id:R.EBMLMaxSizeLength,data:8},{id:R.DocType,data:this.format instanceof If?`webm`:`matroska`},{id:R.DocTypeVersion,data:4},{id:R.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(e,t)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;let t=new Uint8Array([28,83,187,107]),n=new Uint8Array([21,73,169,102]),r=new Uint8Array([22,84,174,107]),i=new Uint8Array([25,65,164,105]),a=new Uint8Array([18,84,195,103]),o={id:R.SeekHead,data:[{id:R.Seek,data:[{id:R.SeekID,data:n},{id:R.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:R.Seek,data:[{id:R.SeekID,data:r},{id:R.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:R.Seek,data:[{id:R.SeekID,data:i},{id:R.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:R.Seek,data:[{id:R.SeekID,data:a},{id:R.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null,{id:R.Seek,data:[{id:R.SeekID,data:t},{id:R.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]}]};this.seekHead=o}createSegmentInfo(){let e={id:R.Duration,data:new Ea(0)};this.segmentDuration=e;let t=this.output._metadataTags.creationTime===void 0?/* @__PURE__ */ new Date:this.output._metadataTags.creationTime,n=null;if(t){let e=1000000n*BigInt(t.getTime()-Ra);if(BigInt.asIntN(64,e)!==e)throw Error(`creationTime is out of the range representable by Matroska files.`);n={id:R.DateUTC,size:8,data:BigInt.asUintN(64,e)}}let r={id:R.Info,data:[{id:R.TimestampScale,data:1e6},this.format._options.appendOnly?null:e,n,{id:R.MuxingApp,data:tn},{id:R.WritingApp,data:tn}]};this.segmentInfo=r}createTracks(){let e={id:R.Tracks,data:[]};this.tracksElement=e;for(let n of this.trackDatas){let r=Za[n.track.source._codec];t(r),n.type===`audio`&&n.track.source._codec===`dts`?n.info.decoderConfig.codec===`dtse`?r=`A_DTS/EXPRESS`:n.info.decoderConfig.codec===`dtsl`&&(r=`A_DTS/LOSSLESS`):n.type===`subtitle`&&this.format instanceof If&&(r=`D_WEBVTT/SUBTITLES`);let i=0;if(n.type===`audio`){let e=tu(n.track.source._codec,n.info.decoderConfig);i=Math.round(1e9*e)}e.data.push({id:R.TrackEntry,data:[{id:R.TrackNumber,data:n.track.id},{id:R.TrackUID,data:n.track.id},{id:R.TrackType,data:Df[n.type]},n.track.metadata.disposition?.default===!1?{id:R.FlagDefault,data:0}:null,n.track.metadata.disposition?.forced?{id:R.FlagForced,data:1}:null,n.track.metadata.disposition?.hearingImpaired?{id:R.FlagHearingImpaired,data:1}:null,n.track.metadata.disposition?.visuallyImpaired?{id:R.FlagVisualImpaired,data:1}:null,n.track.metadata.disposition?.original?{id:R.FlagOriginal,data:1}:null,n.track.metadata.disposition?.commentary?{id:R.FlagCommentary,data:1}:null,{id:R.FlagLacing,data:0},n.type===`video`&&n.info.alphaMode||n.type===`subtitle`&&!(this.format instanceof If)?{id:R.MaxBlockAdditionID,data:1}:null,{id:R.Language,data:n.track.metadata.languageCode??`und`},{id:R.CodecID,data:r},n.codecPrivate?{id:R.CodecPrivate,data:b(n.codecPrivate)}:null,n.type===`audio`&&n.info.codecDelay?{id:R.CodecDelay,data:Math.round(1e9*n.info.codecDelay)}:null,i>0?{id:R.SeekPreRoll,data:i}:null,n.track.metadata.name===void 0?null:{id:R.Name,data:new Oa(n.track.metadata.name)},n.type===`video`?this.videoSpecificTrackInfo(n):null,n.type===`audio`?this.audioSpecificTrackInfo(n):null,n.type===`subtitle`?this.subtitleSpecificTrackInfo(n):null]})}}videoSpecificTrackInfo(e){let{frameRate:t,transformationMatrix:n}=e.track.metadata,a=[t?{id:R.DefaultDuration,data:Math.round(1e9/t)}:null],o,c,u;if(n){o=s(n);let e=f(l(-o),n);c=Math.sign(e[0]),u=Math.sign(e[4]),u===-1&&(u=1,c=-c,o=i(o+180))}else o=e.track.metadata.rotation??0,c=e.track.metadata.flip?-1:1,u=1;let d=o?i(c===-1?o:-o):0,p=Math.round(Math.acos(c)*r),m=Math.round(Math.acos(u)*r),h=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,g=e.info.decoderConfig.colorSpace,_={id:R.Video,data:[{id:R.PixelWidth,data:e.info.width},{id:R.PixelHeight,data:e.info.height},h?{id:R.DisplayWidth,data:e.info.aspectRatio.num}:null,h?{id:R.DisplayHeight,data:e.info.aspectRatio.den}:null,h?{id:R.DisplayUnit,data:3}:null,e.info.alphaMode?{id:R.AlphaMode,data:1}:null,ce(g)?null:{id:R.Colour,data:[{id:R.MatrixCoefficients,data:g?.matrix==null?2:ae[g.matrix]},{id:R.TransferCharacteristics,data:g?.transfer==null?2:re[g.transfer]},{id:R.Primaries,data:g?.primaries==null?2:E[g.primaries]},{id:R.Range,data:g?.fullRange==null?0:g.fullRange?2:1}]},d||p||m?{id:R.Projection,data:[{id:R.ProjectionType,data:0},p?{id:R.ProjectionPoseYaw,data:new Ta(p)}:null,m?{id:R.ProjectionPosePitch,data:new Ta(m)}:null,d?{id:R.ProjectionPoseRoll,data:new Ta((d+180)%360-180)}:null]}:null]};return a.push(_),a}audioSpecificTrackInfo(e){let n=Il.includes(e.track.source._codec)?ou(e.track.source._codec):null,r=e.info.sampleRate;return e.track.source._codec===`aac`&&(t(e.codecPrivate),r=Mt(b(e.codecPrivate)).coreSampleRate??r),[{id:R.Audio,data:[{id:R.SamplingFrequency,data:new Ta(r)},r===e.info.sampleRate?null:{id:R.OutputSamplingFrequency,data:new Ta(e.info.sampleRate)},{id:R.Channels,data:e.info.numberOfChannels},n?{id:R.BitDepth,data:8*n.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[]}maybeCreateTags(){let e=[],t=(t,n)=>{e.push({id:R.SimpleTag,data:[{id:R.TagName,data:new Oa(t)},typeof n==`string`?{id:R.TagString,data:new Oa(n)}:{id:R.TagBinary,data:n}]})},n=this.output._metadataTags,r=/* @__PURE__ */ new Set;for(let{key:e,value:i}of nt(n))switch(e){case`title`:t(`TITLE`,i),r.add(`TITLE`);break;case`description`:t(`DESCRIPTION`,i),r.add(`DESCRIPTION`);break;case`artist`:t(`ARTIST`,i),r.add(`ARTIST`);break;case`album`:t(`ALBUM`,i),r.add(`ALBUM`);break;case`albumArtist`:t(`ALBUM_ARTIST`,i),r.add(`ALBUM_ARTIST`);break;case`genre`:t(`GENRE`,i),r.add(`GENRE`);break;case`beatsPerMinute`:t(`BPM`,i.toString()),r.add(`BPM`);break;case`comment`:t(`COMMENT`,i),r.add(`COMMENT`);break;case`lyrics`:t(`LYRICS`,i),r.add(`LYRICS`);break;case`date`:t(`DATE`,i.toISOString().slice(0,10)),r.add(`DATE`);break;case`trackNumber`:t(`PART_NUMBER`,n.tracksTotal===void 0?i.toString():`${i}/${n.tracksTotal}`),r.add(`PART_NUMBER`);break;case`discNumber`:t(`DISC`,n.discsTotal===void 0?i.toString():`${i}/${n.discsTotal}`),r.add(`DISC`);break;case`tracksTotal`:case`discsTotal`:break;case`images`:case`raw`:case`creationTime`:break;default:k(e)}if(n.raw)for(let e in n.raw){let i=n.raw[e];i==null||r.has(e)||(typeof i==`string`||i instanceof Uint8Array)&&t(e,i)}e.length!==0&&(this.tagsElement={id:R.Tags,data:[{id:R.Tag,data:[{id:R.Targets,data:[{id:R.TargetTypeValue,data:50},{id:R.TargetType,data:`MOVIE`}]},...e]}]})}maybeCreateAttachments(){let e=this.output._metadataTags,t=[],n=/* @__PURE__ */ new Set,r=e.images??[];for(let e of r){let r=e.name;r===void 0&&(r=(e.kind===`coverFront`?`cover`:e.kind===`coverBack`?`back`:`image`)+(rt(e.mimeType)??``));let i;for(;;){i=0n;for(let e=0;e<8;e++)i<<=8n,i|=BigInt(Math.floor(Math.random()*256));if(i!==0n&&!n.has(i))break}n.add(i),t.push({id:R.AttachedFile,data:[e.description===void 0?null:{id:R.FileDescription,data:new Oa(e.description)},{id:R.FileName,data:new Oa(r)},{id:R.FileMediaType,data:e.mimeType},{id:R.FileData,data:e.data},{id:R.FileUID,data:i}]})}for(let[n,i]of Object.entries(e.raw??{}))i instanceof Tt&&/^\d+$/.test(n)&&(r.find(e=>e.mimeType===i.mimeType&&ot(e.data,i.data))||t.push({id:R.AttachedFile,data:[i.description===void 0?null:{id:R.FileDescription,data:new Oa(i.description)},{id:R.FileName,data:new Oa(i.name??``)},{id:R.FileMediaType,data:i.mimeType??``},{id:R.FileData,data:i.data},{id:R.FileUID,data:BigInt(n)}]}));t.length!==0&&(this.attachmentsElement={id:R.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);let e={id:R.Segment,size:this.format._options.appendOnly?-1:6,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(e,t)}}createCues(){this.cues={id:R.Cues,data:[]}}get segmentDataOffset(){return t(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(let e of this.output.tracks)if(!this.closedTracks.has(e)&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return $a({isWebM:this.format instanceof If,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,n,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;hu(r,e.source._codec),t(r),t(r.decoderConfig),t(r.decoderConfig.codedWidth!==void 0),t(r.decoderConfig.codedHeight!==void 0);let a=r.decoderConfig.displayAspectWidth,o=r.decoderConfig.displayAspectHeight,s=a===void 0||o===void 0?null:pt({num:a,den:o}),c={track:e,type:`video`,info:{width:r.decoderConfig.codedWidth,height:r.decoderConfig.codedHeight,aspectRatio:s,decoderConfig:r.decoderConfig,alphaMode:e.metadata.canBeTransparent||(n?!!n.sideData.alpha:null)},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:r.decoderConfig.description??null};return e.source._codec===`vp9`?c.codecPrivate=new Uint8Array(Yl(c.info.decoderConfig.codec)):e.source._codec===`av1`?c.codecPrivate=new Uint8Array(Xl(c.info.decoderConfig.codec)):e.source._codec===`prores`&&(c.codecPrivate=T.encode(r.decoderConfig.codec)),this.trackDatas.push(c),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,n,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;_u(r,e.source._codec),t(r),t(r.decoderConfig);let a={...r.decoderConfig},o=!1;if(e.source._codec===`aac`&&!a.description){if(!n)throw Error(`No AAC description provided; you must therefore provide a priming packet.`);let e=zo(Uc.tempFromBytes(n.data));if(!e)throw 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 t,r=null;if(e.channelConfiguration===0){let i=e.crcCheck===null?7:9,a=Vt(n.data.subarray(i));if(!a)throw Error(`ADTS frames with channel configuration 0 must begin with a program config element.`);r=a.programConfigElement,t=Ut(r)}else t=At[e.channelConfiguration];a.description=Ft({objectType:e.objectType,outputSampleRate:kt[e.samplingFrequencyIndex],outputNumberOfChannels:t,programConfigElement:r}),o=!0}let s={track:e,type:`audio`,info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:a,requiresAdtsStripping:o,codecDelay:null},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:a.description??null};return this.trackDatas.push(s),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(e,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;vu(n),t(n),t(n.config);let i={track:e,type:`subtitle`,info:{config:n.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:T.encode(n.config.description)};return this.trackDatas.push(i),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n);r.info.alphaMode??=!!t.sideData.alpha;let i=t.data;if(e.source._codec===`prores`){if(i.byteLength<8)throw Error(`ProRes packet too small, expected at least 8 bytes.`);i=i.subarray(8)}let a=t.type===`key`;this.validateTimestamp(r.track,t.timestamp,a);let o=t.timestamp,s=t.duration;e.metadata.frameRate!==void 0&&(o=Me(o,e.metadata.frameRate),s=Me(s,e.metadata.frameRate));let c=r.info.alphaMode?t.sideData.alpha??null:null,l=this.createInternalChunk(i,o,s,t.type,c);r.chunkQueue.push(l),await this.interleaveChunks()}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=zo(Uc.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;if(i=i.subarray(t),e.channelConfiguration===0){let e=Vt(i);e&&(i=i.subarray(e.size))}}let a=t.type===`key`;this.validateTimestamp(r.track,t.timestamp,a),r.info.codecDelay??=Math.max(-t.timestamp,0);let o=this.createInternalChunk(i,t.timestamp+r.info.codecDelay,t.duration,t.type);r.chunkQueue.push(o),await this.interleaveChunks()}finally{r()}}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,!0);let i=t.text,a=Math.round(t.timestamp*1e3);Tr.lastIndex=0,i=i.replace(Tr,e=>{let t=Dr(e.slice(1,-1))-a;return`<${Or(t/1e3)}>`});let o;if(this.format instanceof If){let e=T.encode(`${t.identifier??``}\n${t.settings??``}\n${i}`);o=this.createInternalChunk(e,t.timestamp,t.duration,`key`)}else{let e=T.encode(i),n=`${t.settings??``}\n${t.identifier??``}\n${t.notes??``}`;o=this.createInternalChunk(e,t.timestamp,t.duration,`key`,n.trim()?T.encode(n):null)}r.chunkQueue.push(o),await this.interleaveChunks()}finally{r()}}async interleaveChunks(e=!1){if(e||this.allTracksAreKnown()){outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.chunkQueue.length===0&&!this.closedTracks.has(r.track))break outer;r.chunkQueue.length>0&&r.chunkQueue[0].timestamp<n&&(t=r,n=r.chunkQueue[0].timestamp)}if(!t)break;let r=t.chunkQueue.shift();this.addBlock(t,r)}e||await this.writer.flush()}}createInternalChunk(e,t,n,r,i=null){return{data:e,type:r,timestamp:t,duration:n,additions:i}}addBlock(e,n){this.segment||this.createSegment();let r=Math.round(1e3*n.timestamp),i=this.trackDatas.every(t=>{if(e===t)return n.type===`key`;let r=t.chunkQueue[0];return r?r.type===`key`:this.closedTracks.has(t.track)}),a=!1;if(this.currentClusterStartMsTimestamp===null)a=!0;else{t(this.currentClusterMaxMsTimestamp!==null);let e=r-this.currentClusterStartMsTimestamp;a=i&&r>this.currentClusterMaxMsTimestamp&&e>=1e3*(this.format._options.minimumClusterDuration??1)||e>Ef}if(a&&this.startNewCluster(r),r-this.currentClusterStartMsTimestamp<Tf){if(!this.warnedAboutTooNegativeTimestamp){let e=this.format instanceof If?`WebM`:`Matroska`;M._warn(`Packets had to be discarded because their timestamp is too negative to represent in ${e}.`),this.warnedAboutTooNegativeTimestamp=!0}}else this.currentClusterBlocks.push({trackData:e,chunk:n,msTimestamp:r,previousMsTimestamp:e.lastWrittenMsTimestamp}),this.endTimestamp=Math.max(this.endTimestamp,r+Math.round(1e3*n.duration)),e.lastWrittenMsTimestamp=r,this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,r)}startNewCluster(e){this.currentClusterStartMsTimestamp!==null&&this.writeCurrentCluster();let t=Math.max(0,e);this.currentClusterStartMsTimestamp=t,this.currentClusterMaxMsTimestamp=t}writeCurrentCluster(){t(this.currentClusterStartMsTimestamp!==null);let e=this.currentClusterStartMsTimestamp,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let e of this.currentClusterBlocks){e.chunk.type===`key`&&!n.has(e.trackData)&&n.set(e.trackData,e);let t=r.get(e.trackData);(!t||e.msTimestamp>=t.msTimestamp)&&r.set(e.trackData,e)}let i=/* @__PURE__ */ new Map;for(let t of this.currentClusterBlocks)i.set(t,this.createBlockElement(t,e,r.get(t.trackData)===t));let a={id:R.Cluster,size:this.format._options.appendOnly?-1:6,data:[{id:R.Timestamp,data:e},...i.values()]};if(this.format._options.onCluster&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(a),this.currentClusterBlocks=[],this.format._options.onCluster){let{data:t,start:n}=this.writer.stopTrackingWrites();this.format._options.onCluster(t,n,e/1e3)}let o=this.ebmlWriter.offsets.get(a)-this.segmentDataOffset,s=this.ebmlWriter.dataOffsets.get(a),c=/* @__PURE__ */ new Map;for(let e of n.values())c.has(e.msTimestamp)||c.set(e.msTimestamp,[]),c.get(e.msTimestamp).push(e);let l=[...c.entries()].sort((e,t)=>e[0]-t[0]);for(let[e,n]of l)t(this.cues),this.cues.data.push({id:R.CuePoint,data:[{id:R.CueTime,data:Math.max(0,e)},...n.map(e=>{let t=this.ebmlWriter.offsets.get(i.get(e));return{id:R.CueTrackPositions,data:[{id:R.CueTrack,data:e.trackData.track.id},{id:R.CueClusterPosition,data:o},{id:R.CueRelativePosition,data:t-s}]}})]})}createBlockElement(e,t,n){let{trackData:r,chunk:i,msTimestamp:a}=e,o=/* @__PURE__ */ new Uint8Array(4),s=new DataView(o.buffer);s.setUint8(0,128|r.track.id),s.setInt16(1,a-t,!1);let c=Math.round(1e3*i.duration);return i.additions||r.type===`subtitle`||n&&c>0?{id:R.BlockGroup,data:[{id:R.Block,data:[o,i.data]},i.type===`delta`?{id:R.ReferenceBlock,data:new Da(e.previousMsTimestamp-a)}:null,i.additions?{id:R.BlockAdditions,data:[{id:R.BlockMore,data:[{id:R.BlockAddID,data:1},{id:R.BlockAdditional,data:i.additions}]}]}:null,c>0?{id:R.BlockDuration,data:c}:null]}:(s.setUint8(3,Number(i.type===`key`)<<7),{id:R.SimpleBlock,data:[o,i.data]})}async onTrackClose(e){let t=await this.mutex.acquire();try{this.closedTracks.add(e),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks()}finally{t()}}async finalize(){let e=await this.mutex.acquire();try{this.allTracksKnown.resolve();for(let e of this.trackDatas)this.closedTracks.add(e.track);if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentClusterStartMsTimestamp!==null&&this.writeCurrentCluster(),t(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let e=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(e,6);let n=Math.max(this.endTimestamp,0);this.segmentDuration.data=new Ea(n),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),t(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}}finally{e()}}},kf=class extends yu{constructor(e,t){
448
+ /*!
449
+ * Copyright (c) 2026-present, Vanilagy and contributors
450
+ *
451
+ * This Source Code Form is subject to the terms of the Mozilla Public
452
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
453
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
454
+ */
455
+ super(e),this.trackDatas=[],this.closedTracks=/* @__PURE__ */ new Set,this.bosPagesWritten=!1,this.allTracksKnown=O(),this.warnedAboutTooNegativeTimestamp=!1,this.pageBytes=new Uint8Array(Do),this.pageView=new DataView(this.pageBytes.buffer),this.format=t}async start(){let e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!0);for(let e of this.output.tracks)t(e.isAudioTrack()),e.metadata.decoderConfig&&this.getTrackData(e,{decoderConfig:e.metadata.decoderConfig})}finally{e()}}async getMimeType(){return await this.allTracksKnown.promise,Eo({codecStrings:this.trackDatas.map(e=>e.codecInfo.codec)})}addEncodedVideoPacket(){throw Error(`Video tracks are not supported.`)}getTrackData(e,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;let i;do i=Math.floor(2**32*Math.random());while(this.trackDatas.some(e=>e.serialNumber===i));t(e.source._codec===`vorbis`||e.source._codec===`opus`),_u(n,e.source._codec),t(n),t(n.decoderConfig);let a;e.source._codec===`vorbis`?a=n.decoderConfig.sampleRate:e.source._codec===`opus`?a=ru:(k(e.source._codec),t(!1));let o={track:e,serialNumber:i,internalSampleRate:a,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],leadingPackets:[],startOffsetInSamples:0,currentTimestampInSamples:null,audioPacketCount:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0,currentPageStartTimestampInSamples:0};return this.queueHeaderPackets(o,n),this.trackDatas.push(o),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}queueHeaderPackets(e,n){if(t(n.decoderConfig),e.codecInfo.codec===`vorbis`){t(n.decoderConfig.description);let r=b(n.decoderConfig.description);if(r[0]!==2)throw TypeError(`First byte of Vorbis decoder description must be 2.`);let i=1,a=()=>{let e=0;for(;;){let t=r[i++];if(t===void 0)throw TypeError(`Vorbis decoder description is too short.`);if(e+=t,t<255)return e}},o=a(),s=a();if(r.length-i<=0)throw TypeError(`Vorbis decoder description is too short.`);let c=r.subarray(i,i+=o);i+=s;let l=r.subarray(i),u=/* @__PURE__ */ new Uint8Array(7);u[0]=3,u[1]=118,u[2]=111,u[3]=114,u[4]=98,u[5]=105,u[6]=115;let d=$n(u,this.output._metadataTags,!0),f=new Uint8Array(d.length+1);f.set(d),f[d.length]=1,e.packetQueue.push({data:c,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0,holdPage:!1,isHeader:!0},{data:f,timestampInSamples:0,durationInSamples:0,forcePageFlush:!1,holdPage:!1,isHeader:!0},{data:l,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0,holdPage:!1,isHeader:!0});let p=x(c).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(p&15),1<<(p>>4)],modeBlockflags:qn(l).modeBlockflags}}else if(e.codecInfo.codec===`opus`){if(!n.decoderConfig.description)throw TypeError(`For Ogg, Opus decoder description is required.`);let t=b(n.decoderConfig.description),r=/* @__PURE__ */ new Uint8Array(8),i=x(r);i.setUint32(0,1332770163,!1),i.setUint32(4,1415669619,!1);let a=$n(r,this.output._metadataTags,!0);e.packetQueue.push({data:t,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0,holdPage:!1,isHeader:!0},{data:a,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0,holdPage:!1,isHeader:!0}),e.codecInfo.opusInfo={preSkip:Wn(t).preSkip}}else k(e.codecInfo.codec)}async addEncodedAudioPacket(e,n,r){let i=await this.mutex.acquire();try{let i=this.getTrackData(e,r);this.validateTimestamp(i.track,n.timestamp,n.type===`key`);let{durationInSamples:a,vorbisBlockSize:o}=To(n.data,i.codecInfo,i.vorbisLastBlocksize);if(i.vorbisLastBlocksize=o,i.currentTimestampInSamples===null){let e=Math.round(n.timestamp*i.internalSampleRate);if(i.codecInfo.codec===`vorbis`)i.currentTimestampInSamples=e;else if(i.codecInfo.codec===`opus`){let n=i.codecInfo.opusInfo;if(t(n),i.pagesWritten===0){let r=A(-e,n.preSkip,2**16-1),a=i.packetQueue[0];t(a?.isHeader),a.data=a.data.slice(),x(a.data).setUint16(10,r,!0),n.preSkip=r}i.currentTimestampInSamples=e+n.preSkip}else k(i.codecInfo.codec),t(!1)}let s={data:n.data,timestampInSamples:i.currentTimestampInSamples,durationInSamples:a,forcePageFlush:!1,holdPage:!1,isHeader:!1};if(i.currentTimestampInSamples+=a,i.audioPacketCount===0){let e=s.timestampInSamples+a;if(i.codecInfo.codec===`opus`){if(s.timestampInSamples<0){this.warnAboutDiscardedPackets();return}i.startOffsetInSamples=s.timestampInSamples}else if(i.codecInfo.codec===`vorbis`){if(e<0){i.leadingPackets.push(s);return}let t=Math.floor(s.data.length/255)+1,n=i.leadingPackets.length;for(;n>0;){let e=i.leadingPackets[n-1],r=Math.floor(e.data.length/255)+1;if(t+r>255)break;t+=r,n--}n>0&&this.warnAboutDiscardedPackets();let r=i.leadingPackets.slice(n);if(i.leadingPackets.length=0,r.length>0){for(let e of r)e.holdPage=!0,i.packetQueue.push(e);s.holdPage=!0,s.forcePageFlush=!0,i.audioPacketCount+=r.length}else i.startOffsetInSamples=e}else k(i.codecInfo.codec)}i.startOffsetInSamples>0&&i.audioPacketCount===1&&(s.forcePageFlush=!0),i.audioPacketCount++,i.packetQueue.push(s),await this.interleavePages()}finally{i()}}addSubtitleCue(){throw Error(`Subtitle tracks are not supported.`)}allTracksAreKnown(){for(let e of this.output.tracks)if(!this.closedTracks.has(e)&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async interleavePages(e=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown()&&!e)return;for(let e of this.trackDatas)for(;e.packetQueue.length>0;){let t=e.packetQueue.shift();if(this.writePacket(e,t,!1),t.forcePageFlush)break}this.bosPagesWritten=!0}outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.packetQueue.length<=1&&!this.closedTracks.has(r.track))break outer;if(r.packetQueue.length===0)continue;let i=r.packetQueue[0],a=i.isHeader?-1/0:i.timestampInSamples/r.internalSampleRate;a<n&&(t=r,n=a)}if(!t)break;let r=t.packetQueue.shift(),i=t.packetQueue.length===0;this.writePacket(t,r,i)}e||await this.writer.flush()}writePacket(e,t,n){let r=t.timestampInSamples+t.durationInSamples;if(e.currentLacingValues.length===0&&(e.currentPageStartTimestampInSamples=t.timestampInSamples),this.format._options.maximumPageDuration!==void 0&&!t.holdPage){let t=this.format._options.maximumPageDuration*e.internalSampleRate;e.currentLacingValues.length>0&&r-e.currentPageStartTimestampInSamples>t&&this.writePage(e,!1)}let i=t.data.length,a=0,o=0;for(;;){e.currentLacingValues.length===0&&a>0&&(e.currentPageStartsWithFreshPacket=!1);let s=Math.min(255,i);e.currentLacingValues.push(s),e.currentPageSize++,o+=s;let c=i<255;if(e.currentLacingValues.length===255){let i=t.data.subarray(a,o);if(a=o,e.currentPageData.push(i),e.currentPageSize+=i.length,c&&(e.currentGranulePosition=r),this.writePage(e,n&&c),c)return}if(c)break;i-=255}let s=t.data.subarray(a);e.currentPageData.push(s),e.currentPageSize+=s.length,e.currentGranulePosition=r,(e.currentPageSize>=8192&&!t.holdPage||t.forcePageFlush||n)&&this.writePage(e,n)}writePage(e,t){this.pageView.setUint32(0,1399285583,!0),this.pageView.setUint8(4,0);let n=0;e.currentPageStartsWithFreshPacket||(n|=1),e.pagesWritten===0&&(n|=2),t&&(n|=4),this.pageView.setUint8(5,n);let r=e.currentLacingValues.every(e=>e===255)?-1:e.currentGranulePosition;De(this.pageView,6,r,!0),this.pageView.setUint32(14,e.serialNumber,!0),this.pageView.setUint32(18,e.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,e.currentLacingValues.length),this.pageBytes.set(e.currentLacingValues,27);let i=27+e.currentLacingValues.length;for(let t of e.currentPageData)this.pageBytes.set(t,i),i+=t.length;let a=this.pageBytes.subarray(0,i),o=wo(a);if(this.pageView.setUint32(22,o,!0),e.pagesWritten++,e.currentLacingValues.length=0,e.currentPageData.length=0,e.currentPageSize=27,e.currentPageStartsWithFreshPacket=!0,e.currentPageStartTimestampInSamples=e.currentGranulePosition,this.format._options.onPage&&this.writer.startTrackingWrites(),this.writer.write(a),this.format._options.onPage){let{data:t,start:n}=this.writer.stopTrackingWrites();this.format._options.onPage(t,n,e.track.source)}}async onTrackClose(e){let t=await this.mutex.acquire();try{this.closedTracks.add(e);let t=this.trackDatas.find(t=>t.track===e);t&&t.leadingPackets.length>0&&(t.leadingPackets.length=0,this.warnAboutDiscardedPackets()),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages()}finally{t()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let e of this.trackDatas)this.closedTracks.add(e.track),e.leadingPackets.length>0&&(e.leadingPackets.length=0,this.warnAboutDiscardedPackets());await this.interleavePages(!0),e()}warnAboutDiscardedPackets(){this.warnedAboutTooNegativeTimestamp||=(M._warn(`Packets had to be discarded because their timestamp is too negative to represent in Ogg.`),!0)}},Af=class{get supportsVideoRotationMetadata(){
456
+ /*!
457
+ * Copyright (c) 2026-present, Vanilagy and contributors
458
+ *
459
+ * This Source Code Form is subject to the terms of the Mozilla Public
460
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
461
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
462
+ */
463
+ return this.supportsVideoTransformationMetadata}get requiresMaximumPacketCount(){return!1}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Fl.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Rl.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>zl.includes(e))}_codecUnsupportedHint(e){return``}_isFragmentedIsobmff(){return!1}_withoutXingHeader(){return this}},jf=class extends Af{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.fastStart!==void 0&&![!1,`in-memory`,`reserve`,`fragmented`].includes(e.fastStart))throw TypeError(`options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.`);if(e.minimumFragmentDuration!==void 0&&(!ct(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw TypeError(`options.minimumFragmentDuration, when provided, must be a non-negative number.`);if(e.onFtyp!==void 0&&typeof e.onFtyp!=`function`)throw TypeError(`options.onFtyp, when provided, must be a function.`);if(e.onMoov!==void 0&&typeof e.onMoov!=`function`)throw TypeError(`options.onMoov, when provided, must be a function.`);if(e.onMdat!==void 0&&typeof e.onMdat!=`function`)throw TypeError(`options.onMdat, when provided, must be a function.`);if(e.onMoof!==void 0&&typeof e.onMoof!=`function`)throw TypeError(`options.onMoof, when provided, must be a function.`);if(e.metadataFormat!==void 0&&![`mdir`,`mdta`,`udta`,`auto`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.`);super(),this._options=e}getSupportedTrackCounts(){let e=2**32-1;return{video:{min:0,max:e},audio:{min:0,max:e},subtitle:{min:0,max:e},total:{min:0,max:e}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`full`}get requiresMaximumPacketCount(){return this._options.fastStart===`reserve`}_createMuxer(e){return new wf(e,this)}_isFragmentedIsobmff(){return this._options.fastStart===`fragmented`}},Mf=class extends jf{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...Fl,...Ll,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...zl]}_codecUnsupportedHint(e){return new Pf().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},Nf=class extends jf{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...Fl,...Ll,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...zl]}},Pf=class extends jf{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...Fl,...Rl]}_codecUnsupportedHint(e){return new Mf().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},Ff=class extends Af{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.appendOnly!==void 0&&typeof e.appendOnly!=`boolean`)throw TypeError(`options.appendOnly, when provided, must be a boolean.`);if(e.minimumClusterDuration!==void 0&&(!ct(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw TypeError(`options.minimumClusterDuration, when provided, must be a non-negative number.`);if(e.onEbmlHeader!==void 0&&typeof e.onEbmlHeader!=`function`)throw TypeError(`options.onEbmlHeader, when provided, must be a function.`);if(e.onSegmentHeader!==void 0&&typeof e.onSegmentHeader!=`function`)throw TypeError(`options.onSegmentHeader, when provided, must be a function.`);if(e.onCluster!==void 0&&typeof e.onCluster!=`function`)throw TypeError(`options.onCluster, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new Of(e,this)}get _name(){return`Matroska`}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:0,max:127}}}get fileExtension(){return`.mkv`}get mimeType(){return`video/x-matroska`}getSupportedCodecs(){return[...Fl,...Ll,...Il.filter(e=>![`pcm-s8`,`pcm-f32be`,`pcm-f64be`,`ulaw`,`alaw`].includes(e)),...zl]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`prefer-non-negative`}},If=class extends Ff{constructor(e){super(e)}getSupportedCodecs(){return[...Fl.filter(e=>[`vp8`,`vp9`,`av1`].includes(e)),...Rl.filter(e=>[`opus`,`vorbis`].includes(e)),...zl]}get _name(){return`WebM`}get fileExtension(){return`.webm`}get mimeType(){return`video/webm`}_codecUnsupportedHint(e){return new Ff().getSupportedCodecs().includes(e)?` Switching to MKV will grant support for this codec.`:``}},Lf=class extends Af{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.maximumPageDuration!==void 0&&(!ct(e.maximumPageDuration)||e.maximumPageDuration<=0))throw TypeError(`options.maximumPageDuration, when provided, must be a positive number.`);if(e.onPage!==void 0&&typeof e.onPage!=`function`)throw TypeError(`options.onPage, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new kf(e,this)}get _name(){return`Ogg`}getSupportedTrackCounts(){let e=2**32;return{video:{min:0,max:0},audio:{min:0,max:e},subtitle:{min:0,max:0},total:{min:0,max:e}}}get fileExtension(){return`.ogg`}get mimeType(){return`application/ogg`}getSupportedCodecs(){return[...Rl.filter(e=>[`vorbis`,`opus`].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`prefer-non-negative`}},Rf=class extends Af{_createMuxer(e){return new xu(e)}get _name(){return`Null`}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:0,max:1/0}}}get fileExtension(){return``}get mimeType(){return`application/x-black-hole`}getSupportedCodecs(){return[...Fl,...Rl,...zl]}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`full`}};
464
+ /*!
465
+ * Copyright (c) 2026-present, Vanilagy and contributors
466
+ *
467
+ * This Source Code Form is subject to the terms of the Mozilla Public
468
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
469
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
470
+ */
471
+ const zf=[`video`,`audio`,`subtitle`];var Bf=class e{constructor(e,t,n,r,i){this.id=e,this.output=t,this.type=n,this.source=r,this.metadata=i}isVideoTrack(){return this.type===`video`}isAudioTrack(){return this.type===`audio`}isSubtitleTrack(){return this.type===`subtitle`}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrack.`);if(this===t)return!1;let n=gt(this.metadata.group),r=gt(t.metadata.group);for(let e of n)if(this.type!==t.type&&r.some(t=>e===t)||r.some(t=>e._pairedGroups.has(t)))return!0;return!1}},Vf=class extends Bf{constructor(e,t,n,r){super(e,t,`video`,n,r)}},Hf=class extends Bf{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},Uf=class extends Bf{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},Wf=class e{constructor(){this._pairedGroups=/* @__PURE__ */ new Set}pairWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrackGroup.`);if(this===t)throw TypeError(`Cannot pair a group with itself.`);this._pairedGroups.add(t),t._pairedGroups.add(this)}};const Gf=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!Re(e.languageCode))throw TypeError(`metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`metadata.name, when provided, must be a string.`);if(e.disposition!==void 0&&Ot(e.disposition),e.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`metadata.maximumPacketCount, when provided, must be a non-negative integer.`);if(e.bitrate!==void 0&&(!Number.isFinite(e.bitrate)||e.bitrate<0))throw TypeError(`metadata.bitrate, when provided, must be a non-negative number.`);if(e.averageBitrate!==void 0&&(!Number.isFinite(e.averageBitrate)||e.averageBitrate<0))throw TypeError(`metadata.averageBitrate, when provided, must be a non-negative number.`);if(e.group!==void 0&&!(e.group instanceof Wf)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof Wf))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)};var Kf=class extends _t{get target(){let e=`Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.`;if(this._rootTargetPromise)throw TypeError(e);let t=this._getRootTarget();if(j(t))throw t.catch(()=>{}),TypeError(e);return t}constructor(e){if(super(),this.state=`pending`,this.defaultTrackGroup=new Wf,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=/* @__PURE__ */ new Set,this._targetsClosed=!1,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._canceled=O(),this._finalizePromise=null,this._mutex=new de,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.format instanceof Af))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof pf||e.target instanceof yf))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof pf&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof pf)&&typeof e.initTarget!=`function`)throw Error(`options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof pf&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){t(this._target instanceof yf);let n=this._target.getTarget(e),r=e=>{if(!(e instanceof pf))throw TypeError(`getTarget must return a Target.`);return e};return j(n)?n.then(r):r(n)}async _getTarget(e){t(this._target instanceof yf);let n=await this._getTargetValidated(e);if(this._emit(`target`,{target:n,request:e,isRoot:e.isRoot}),this._targetsClosed)throw await n._close(),Error(this.state===`canceled`?`Output has been canceled.`:`Output has already been finalized.`);return this._rememberTarget(n),n}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on(`finalized`,()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(t(this._initTarget!==null),this._initTarget instanceof pf)return this._initTarget;let e=await this._initTarget();if(!(e instanceof pf))throw TypeError(`initTarget must return or resolve to a Target.`);return this._targetsClosed?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof pf)return this._emit(`target`,{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=t=>(this._targetsClosed?t._close().catch(()=>{}):this._rememberTarget(t),this._emit(`target`,{target:t,request:e,isRoot:!0}),this._rootTarget=t,t);return j(t)?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new ff(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof hl))throw TypeError(`source must be a VideoSource.`);if(Gf(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(t.flip!==void 0&&typeof t.flip!=`boolean`)throw TypeError(`metadata.flip, when provided, must be a boolean.`);if(t.transformationMatrix!==void 0&&(!Array.isArray(t.transformationMatrix)||t.transformationMatrix.length!==9||!t.transformationMatrix.every(e=>Number.isFinite(e))))throw TypeError(`metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);if(t.hasOnlyKeyPackets!==void 0&&typeof t.hasOnlyKeyPackets!=`boolean`)throw TypeError(`metadata.hasOnlyKeyPackets, when provided, must be a boolean.`);if(t.canBeTransparent!==void 0&&typeof t.canBeTransparent!=`boolean`)throw TypeError(`metadata.canBeTransparent, when provided, must be a boolean.`);if(t.decoderConfig!==void 0&&hu({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof L))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Vf(this.tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof Tl))throw TypeError(`source must be an AudioSource.`);if(Gf(t),t.decoderConfig!==void 0&&_u({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof L))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Hf(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Pl))throw TypeError(`source must be a SubtitleSource.`);Gf(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Uf(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(Et(e),this.state!==`pending`)throw Error(`Cannot set metadata tags after output has been started or canceled.`);this._metadataTags=e}_addTrack(e){if(this.state!==`pending`)throw Error(`Cannot add track after output has been started or canceled.`);if(e.source._connectedTrack)throw Error(`Source is already used for a track.`);let t=this.format.getSupportedTrackCounts(),n=this.tracks.reduce((t,n)=>t+ +(n.type===e.type),0),r=t[e.type].max;if(n===r)throw Error(r===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${r} ${e.type} track${r===1?``:`s`}.`);let i=t.total.max;if(this.tracks.length===i)throw Error(`${this.format._name} does not support more than ${i} track${i===1?``:`s`} in total.`);if(e.isVideoTrack()){let t=this.format.getSupportedVideoCodecs();if(t.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let t=this.format.getSupportedAudioCodecs();if(t.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let t=this.format.getSupportedSubtitleCodecs();if(t.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){let e=this.format.getSupportedTrackCounts();for(let t of zf)if(this.tracks.reduce((e,n)=>e+ +(n.type===t),0)<e[t].min)return!1;let t=e.total.min;return!(this.tracks.length<t)}async start(){let e=this.format.getSupportedTrackCounts();for(let t of zf){let n=this.tracks.reduce((e,n)=>e+ +(n.type===t),0),r=e[t].min;if(n<r)throw Error(r===e[t].max?`${this.format._name} requires exactly ${r} ${t} track${r===1?``:`s`}.`:`${this.format._name} requires at least ${r} ${t} track${r===1?``:`s`}.`)}let t=e.total.min;if(this.tracks.length<t)throw Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?``:`s`}.`:`${this.format._name} requires at least ${t} track${t===1?``:`s`}.`);if(this._cancelPromise||this.state===`canceled`)throw Error(`Output has been canceled.`);return this._startPromise?(M._warn(`Output has already been started.`),this._startPromise):this._startPromise=(async()=>{this.state=`started`;let e=this._mutex.acquire();try{try{await this._muxer.start();let e=this.tracks.map(e=>e.source._start());await Promise.all(e)}finally{(await e)()}}catch(e){throw await this.cancel(),e}})()}getMimeType(){return Promise.race([this._muxer.getMimeType(),this._canceled.promise.then(()=>{throw Error(`Output has been canceled.`)})])}async cancel(){if(this._cancelPromise||this.state===`canceled`)return this._cancelPromise??void 0;if(this.state===`finalized`)M._warn(`Output has already been finalized.`);else return this._finalizePromise?this._finalizePromise.catch(()=>{}):this._cancelPromise=(async()=>{let e=await this._mutex.acquire();try{this.state=`canceled`,this._canceled.resolve();let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0).catch(()=>{}));await Promise.all(e),this._targetsClosed=!0,await Promise.all([...this._unfinalizedTargets].map(e=>e._close().catch(()=>{}))),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state===`pending`)throw Error(`Cannot finalize before starting.`);if(this._cancelPromise||this.state===`canceled`)throw Error(`Cannot finalize after canceling.`);return this._finalizePromise?(M._warn(`Output has already been finalized.`),this._finalizePromise):this._finalizePromise=(async()=>{let e=await this._mutex.acquire();try{this.state=`finalizing`;let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(e),await this._muxer.finalize(),this._rootWriterPromise){let e=await this._rootWriterPromise;e.finalized||(await e.flush(),await e.finalize())}this._onFinalize&&await this._onFinalize(),this.state=`finalized`}catch(e){throw this.state=`canceled`,this._canceled.resolve(),e}finally{this._targetsClosed=!0,await Promise.all([...this._unfinalizedTargets].map(e=>e._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}},qf=function(e,t,n){
472
+ /*!
473
+ * Copyright (c) 2026-present, Vanilagy and contributors
474
+ *
475
+ * This Source Code Form is subject to the terms of the Mozilla Public
476
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
477
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
478
+ */
479
+ if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},Jf=(function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var r,i=0;function a(){for(;r=t.stack.pop();)try{if(!r.async&&i===1)return i=0,t.stack.push(r),Promise.resolve().then(a);if(r.dispose){var e=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(e).then(a,function(e){return n(e),a()})}else i|=1}catch(e){n(e)}if(i===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return a()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r});const Yf=e=>{if(!e||typeof e!=`object`)throw TypeError(`options.video, when provided, must be an object.`);if(e?.discard!==void 0&&typeof e.discard!=`boolean`)throw TypeError(`options.video.discard, when provided, must be a boolean.`);if(e?.forceTranscode!==void 0&&typeof e.forceTranscode!=`boolean`)throw TypeError(`options.video.forceTranscode, when provided, must be a boolean.`);if(e?.codec!==void 0&&!Fl.includes(e.codec))throw TypeError(`options.video.codec, when provided, must be one of: ${Fl.join(`, `)}.`);let t=e?.bitrate;if(e?.quality!==void 0&&!(e.quality instanceof I))throw TypeError(`options.video.quality, when provided, must be a Quality.`);if(e?.quality!==void 0&&t!==void 0)throw TypeError(`options.video.quality and options.video.bitrate cannot both be provided.`);if(t!==void 0&&!(t instanceof I)&&(!Number.isInteger(t)||t<=0))throw TypeError(`options.video.bitrate, when provided, must be a positive integer or a quality.`);if(e?.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw TypeError(`options.video.width, when provided, must be a positive integer.`);if(e?.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw TypeError(`options.video.height, when provided, must be a positive integer.`);if(e?.fit!==void 0&&![`fill`,`contain`,`cover`].includes(e.fit))throw TypeError(`options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.`);if(e?.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw TypeError(`When both options.video.width and options.video.height are provided, options.video.fit must also be provided.`);if(e?.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw TypeError(`options.video.rotate, when provided, must be 0, 90, 180 or 270.`);if(e?.flip!==void 0&&typeof e.flip!=`boolean`)throw TypeError(`options.video.flip, when provided, must be a boolean.`);if(e?.allowTransformationMetadata!==void 0&&typeof e.allowTransformationMetadata!=`boolean`)throw TypeError(`options.video.allowTransformationMetadata, when provided, must be a boolean.`);if(e?.allowRotationMetadata!==void 0&&typeof e.allowRotationMetadata!=`boolean`)throw TypeError(`options.video.allowRotationMetadata, when provided, must be a boolean.`);if(e?.crop!==void 0&&Yr(e.crop,`options.video.`),e?.frameRate!==void 0&&(!Number.isFinite(e.frameRate)||e.frameRate<=0))throw TypeError(`options.video.frameRate, when provided, must be a finite positive number.`);if(e?.alpha!==void 0&&![`discard`,`keep`].includes(e.alpha))throw TypeError(`options.video.alpha, when provided, must be either 'discard' or 'keep'.`);if(e?.keyFrameInterval!==void 0&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError(`options.video.keyFrameInterval, when provided, must be a non-negative number.`);if(e?.process!==void 0&&typeof e.process!=`function`)throw TypeError(`options.video.process, when provided, must be a function.`);if(e?.processedWidth!==void 0&&(!Number.isInteger(e.processedWidth)||e.processedWidth<=0))throw TypeError(`options.video.processedWidth, when provided, must be a positive integer.`);if(e?.processedHeight!==void 0&&(!Number.isInteger(e.processedHeight)||e.processedHeight<=0))throw TypeError(`options.video.processedHeight, when provided, must be a positive integer.`);if(e?.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(e.hardwareAcceleration))throw TypeError(`options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(e?.group!==void 0&&!(e.group instanceof Wf||Array.isArray(e.group)&&e.group.every(e=>e instanceof Wf)))throw TypeError(`options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.`);if(e?.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`options.video.maximumPacketCount, when provided, must be a non-negative integer.`)},Xf=e=>{if(!e||typeof e!=`object`)throw TypeError(`options.audio, when provided, must be an object.`);if(e?.discard!==void 0&&typeof e.discard!=`boolean`)throw TypeError(`options.audio.discard, when provided, must be a boolean.`);if(e?.forceTranscode!==void 0&&typeof e.forceTranscode!=`boolean`)throw TypeError(`options.audio.forceTranscode, when provided, must be a boolean.`);if(e?.codec!==void 0&&!Rl.includes(e.codec))throw TypeError(`options.audio.codec, when provided, must be one of: ${Rl.join(`, `)}.`);let t=e?.bitrate;if(e?.quality!==void 0&&!(e.quality instanceof I))throw TypeError(`options.audio.quality, when provided, must be a Quality.`);if(e?.quality!==void 0&&t!==void 0)throw TypeError(`options.audio.quality and options.audio.bitrate cannot both be provided.`);if(t!==void 0&&!(t instanceof I)&&(!Number.isInteger(t)||t<=0))throw TypeError(`options.audio.bitrate, when provided, must be a positive integer or a quality.`);if(e?.numberOfChannels!==void 0&&(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels<=0))throw TypeError(`options.audio.numberOfChannels, when provided, must be a positive integer.`);if(e?.sampleRate!==void 0&&(!Number.isInteger(e.sampleRate)||e.sampleRate<=0))throw TypeError(`options.audio.sampleRate, when provided, must be a positive integer.`);if(e?.sampleFormat!==void 0&&![`u8`,`s16`,`s32`,`f32`].includes(e.sampleFormat))throw TypeError(`options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.`);if(e?.process!==void 0&&typeof e.process!=`function`)throw TypeError(`options.audio.process, when provided, must be a function.`);if(e?.processedNumberOfChannels!==void 0&&(!Number.isInteger(e.processedNumberOfChannels)||e.processedNumberOfChannels<=0))throw TypeError(`options.audio.processedNumberOfChannels, when provided, must be a positive integer.`);if(e?.processedSampleRate!==void 0&&(!Number.isInteger(e.processedSampleRate)||e.processedSampleRate<=0))throw TypeError(`options.audio.processedSampleRate, when provided, must be a positive integer.`);if(e?.group!==void 0&&!(e.group instanceof Wf||Array.isArray(e.group)&&e.group.every(e=>e instanceof Wf)))throw TypeError(`options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.`);if(e?.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`options.audio.maximumPacketCount, when provided, must be a non-negative integer.`)},Zf=48e3;var Qf=class e{get state(){return this._state}static async init(t){let n=new e(t);return await n._init(),n}constructor(e){if(this._state=`idle`,this._timestampOffset=0,this._timestampOffsetAdjusted=!1,this._copyTimestampPossible=/* @__PURE__ */ new Map,this._copyStartPackets=/* @__PURE__ */ new Map,this._trackDurations=/* @__PURE__ */ new Map,this._nextOutputTrackId=0,this._outputTrackIds=[],this._outputOwnTrackGroups=[],this._trackPumps=[],this._composable=!1,this._executed=!1,this._executionUntil=1/0,this._pauseRequested=!1,this._synchronizer=new ep(this),this._totalDuration=null,this._maxTimestamps=/* @__PURE__ */ new Map,this.onProgress=void 0,this._computeProgress=!1,this._lastProgress=0,this._lastProcessedTime=0,this.isValid=!1,this.utilizedTracks=[],this.discardedTracks=[],!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.input instanceof zc))throw TypeError(`options.input must be an Input.`);if(!(e.output instanceof Kf))throw TypeError(`options.output must be an Output.`);if(e.tracks!==void 0&&e.tracks!==`all`&&e.tracks!==`primary`)throw TypeError(`options.tracks, when provided, must be either 'all' or 'primary'.`);if(e.composable!==void 0&&typeof e.composable!=`boolean`)throw TypeError(`options.composable, when provided, must be a boolean.`);if(e.copy!==void 0&&e.copy!==!1){if(!e.copy||typeof e.copy!=`object`)throw TypeError(`options.copy, when provided, must be an object or false.`);if(e.copy.mode!==void 0&&![`forced`,`preferred`].includes(e.copy.mode))throw TypeError(`options.copy.mode, when provided, must be 'forced' or 'preferred'.`);if(e.copy.shiftTolerance!==void 0&&(!ct(e.copy.shiftTolerance)||e.copy.shiftTolerance<0))throw TypeError(`options.copy.shiftTolerance, when provided, must be a non-negative number.`);if(e.copy.boundaryPolicy!==void 0&&![`expand`,`shrink`].includes(e.copy.boundaryPolicy))throw TypeError(`options.copy.boundaryPolicy, when provided, must be 'expand' or 'shrink'.`);if(e.copy.boundaryTolerance!==void 0&&(!ct(e.copy.boundaryTolerance)||e.copy.boundaryTolerance<0))throw TypeError(`options.copy.boundaryTolerance, when provided, must be a non-negative number.`)}let t=e.composable??!1;if(t){if(e.tags!==void 0)throw TypeError(`options.tags cannot be set by a composable conversion; set metadata directly on the output instead.`);if(e.output.state!==`pending`)throw TypeError(`options.output must not have been started yet.`)}else if(e.output.tracks.length>0||Object.keys(e.output._metadataTags).length>0||e.output.state!==`pending`)throw TypeError(`options.output must be fresh: no tracks or metadata tags added and not started.`);if(e.video!==void 0&&typeof e.video!=`function`){if(Array.isArray(e.video))for(let t of e.video)Yf(t);else Yf(e.video)}if(e.audio!==void 0&&typeof e.audio!=`function`){if(Array.isArray(e.audio))for(let t of e.audio)Xf(t);else Xf(e.audio)}if(e.trim!==void 0&&(!e.trim||typeof e.trim!=`object`))throw TypeError(`options.trim, when provided, must be an object.`);if(e.trim?.start!==void 0&&!Number.isFinite(e.trim.start))throw TypeError(`options.trim.start, when provided, must be a finite number.`);if(e.trim?.end!==void 0&&!ct(e.trim.end))throw TypeError(`options.trim.end, when provided, must be a number.`);if(e.trim?.start!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw 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 TypeError(`options.tags, when provided, must be an object or a function.`);if(typeof e.tags==`object`&&Et(e.tags),e.showWarnings!==void 0&&typeof e.showWarnings!=`boolean`)throw TypeError(`options.showWarnings, when provided, must be a boolean.`);this._options=e,this._copyMode=e.copy===!1?!1:e.copy?.mode??`preferred`,this._copyTimestampShiftTolerance=e.copy===!1?0:e.copy?.shiftTolerance??0,this._copyBoundaryPolicy=e.copy===!1?`expand`:e.copy?.boundaryPolicy??`expand`,this._copyBoundaryTolerance=e.copy===!1?1/0:e.copy?.boundaryTolerance??1/0,this._composable=t,this.input=e.input,this.output=e.output}async _init(){let e=await this.input.getFormat(),n,r=this._options.tracks;r===void 0&&(r=e.name.includes(`(HLS)`)?`primary`:`all`),r===`all`?n=await this.input.getTracks():r===`primary`?n=[await this.input.getPrimaryVideoTrack(),await this.input.getPrimaryAudioTrack()].filter(e=>e!==null):(k(r),t(!1));let i=this.output.format.getSupportedTrackCounts(),a=[],o=[];for(let e of n){let n;if(e.isVideoTrack()){if(this._options.video){if(typeof this._options.video==`function`){let t=await this._options.video(e,e.number)??{};if(Array.isArray(t))for(let e of t)Yf(e);else Yf(t);n=Array.isArray(t)?t:[t]}else n=Array.isArray(this._options.video)?this._options.video:[this._options.video]}else n=[{}]}else if(e.isAudioTrack()){if(this._options.audio){if(typeof this._options.audio==`function`){let t=await this._options.audio(e,e.number)??{};if(Array.isArray(t))for(let e of t)Xf(e);else Xf(t);n=Array.isArray(t)?t:[t]}else n=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio]}else n=[{}]}else t(!1);let r=n.filter(e=>e.discard);for(let t of r)this.discardedTracks.push({track:e,reason:`discarded_by_user`,trackOptions:t});if(n.length===r.length){n.length===0&&this.discardedTracks.push({track:e,reason:`discarded_by_user`,trackOptions:{}});continue}let i=n.filter(e=>!e.discard);a.push(e),o.push(i)}this._startTimestamp=this._options.trim?.start===void 0?Math.max(await this.input.getFirstTimestamp(a),0):this._options.trim.start,this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp),this._timestampOffset=-this._startTimestamp;for(let e=0;e<a.length;e++){let n=a[e],r=o[e];for(let e of r){if(this.output.tracks.length===i.total.max){this.discardedTracks.push({track:n,reason:`max_track_count_reached`,trackOptions:e});continue}if(this.output.tracks.reduce((e,t)=>e+ +(t.type===n.type),0)===i[n.type].max){this.discardedTracks.push({track:n,reason:`max_track_count_of_type_reached`,trackOptions:e});continue}let r=this._nextOutputTrackId++;n.isVideoTrack()?await this._processVideoTrack(n,e,r):n.isAudioTrack()?await this._processAudioTrack(n,e,r):t(!1)}}for(let e=0;e<this.utilizedTracks.length-1;e++)for(let n=e+1;n<this.utilizedTracks.length;n++){let r=this.utilizedTracks[e],i=this.utilizedTracks[n],a=this._outputOwnTrackGroups[e],o=this._outputOwnTrackGroups[n];t(a!==void 0),t(o!==void 0),a&&o&&r.canBePairedWith(i)&&a.pairWith(o)}if(!this._composable){let t={...await this.input.getMetadataTags()};delete t.creationTime;let n;if(this._options.tags){let e=typeof this._options.tags==`function`?await this._options.tags(t):this._options.tags;Et(e),n=e}else n=t;let r=e.mimeType===this.output.format.mimeType;t.raw===n.raw&&!r&&delete n.raw,this.output.setMetadataTags(n)}if(this.isValid=this._composable?!0:this.output.hasEnoughTracks()&&this.output.tracks.length>0,this._options.showWarnings??!0){let e=[],t=this.discardedTracks.filter(e=>e.reason!==`discarded_by_user`);t.length>0&&e.push(`Some tracks had to be discarded from the conversion:`,t),this.isValid||(e.length>0&&e.push(`
480
+
481
+ `),e.push(this._getInvalidityExplanation().join(``))),e.length>0&&M._warn(...e)}}_getInvalidityExplanation(){let e=[];if(this.discardedTracks.length===0)e.push(`Due to missing tracks, this conversion cannot be executed.`);else{let t=this.discardedTracks.every(e=>e.reason===`discarded_by_user`||e.reason===`no_encodable_target_codec`)&&this.discardedTracks.some(e=>e.reason===`no_encodable_target_codec`);if(e.push(`Due to discarded tracks, this conversion cannot be executed.`),t){let t=[],n=[];for(let e of this.discardedTracks){if(e.reason===`discarded_by_user`)continue;let r;r=e.track.type===`video`?this.output.format.getSupportedVideoCodecs():e.track.type===`audio`?this.output.format.getSupportedAudioCodecs():this.output.format.getSupportedSubtitleCodecs();let i=e.trackOptions.codec;i&&!r.includes(i)?n.push(i):t.push(...r.filter(e=>!i||e===i))}let r=[...new Set(t)],i=[...new Set(n)];i.length>0&&e.push(`
482
+ Tracks were discarded because the output format cannot contain the requested codecs ${i.map(e=>`'${e}'`).join(`, `)}.`),r.length===1?e.push(`\nTracks were discarded because your environment is not able to encode '${r[0]}' with the provided parameters.`):r.length>1&&e.push(`
483
+ Tracks were discarded because your environment is not able to encode any of the codecs ${r.map(e=>`'${e}'`).join(`, `)} with the provided parameters.`),r.includes(`mp3`)&&e.push(`
484
+ The @mediabunny/mp3-encoder extension package provides support for encoding MP3.`),r.includes(`aac`)&&e.push(`
485
+ The @mediabunny/aac-encoder extension package provides support for encoding AAC.`),(r.includes(`ac3`)||r.includes(`eac3`))&&e.push(`
486
+ The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),r.includes(`flac`)&&e.push(`
487
+ The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`),r.includes(`dts`)&&e.push(`
488
+ The @mediabunny/dts extension package provides support for encoding and decoding DTS.`),r.includes(`truehd`)&&e.push(`
489
+ The @mediabunny/truehd extension package provides support for encoding and decoding TrueHD.`),r.length>0&&typeof VideoEncoder>`u`&&e.push(`
490
+ In server-side environments, the @mediabunny/server extension package provides support for encoding and decoding all common codecs.`)}else e.push(`
491
+ Check the discardedTracks field for more info.`)}return e}async execute(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.until!==void 0&&(typeof e.until!=`number`||Number.isNaN(e.until)))throw TypeError(`options.until, when provided, must be a number.`);if(e.pauseSignal!==void 0&&!(e.pauseSignal instanceof AbortSignal))throw TypeError(`options.pauseSignal, when provided, must be an AbortSignal.`);if(!this.isValid)throw Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.
492
+ `+this._getInvalidityExplanation().join(``));if(this._state===`executing`)throw Error(`Cannot call execute() while a previous call to execute() is still running.`);if(this._state===`canceled`)throw new $f;if(this._state===`done`)return;if(this._composable&&this.output.state===`pending`)throw Error(`A composable conversion requires the output to be started. Call start() on the output before executing the conversion.`);this._state=`executing`,this._executionUntil=e.until??1/0,this._pauseRequested=e.pauseSignal?.aborted??!1;let t=()=>{this._state===`executing`&&(this._pauseRequested=!0,this._synchronizer.resolveAll())};e.pauseSignal?.addEventListener(`abort`,t);for(let e of this._trackPumps)e.done||(e.resolvers=O());try{if(this._executed)for(let e of this._trackPumps)e.wake?.();else{this._executed=!0;for(let e of this._outputTrackIds)this._synchronizer.declareTrack(e);if(this.onProgress){let e=[...new Set(this.utilizedTracks)].map(e=>this._getTrackDuration(e)),t=Math.max(0,...await Promise.all(e));this._computeProgress=!0,this._totalDuration=Math.min(t-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let e of this._outputTrackIds)this._maxTimestamps.set(e,0);this.onProgress?.(0,0)}this._composable||await this.output.start();for(let e of this._trackPumps)e.start()}await Promise.all(this._trackPumps.map(e=>e.resolvers.promise))}catch(e){if(this._state!==`canceled`)throw this.cancel().catch(()=>{}),e}finally{e.pauseSignal?.removeEventListener(`abort`,t)}if(this._state===`canceled`)throw new $f;if(!this._trackPumps.every(e=>e.done))this._state=`idle`;else{if(!this._composable){try{await this.output.finalize()}catch(e){throw this._state=`canceled`,e}if(this._state===`canceled`)throw new $f}this._state=`done`,this._computeProgress&&this.onProgress?.(1,this._lastProcessedTime)}}async cancel(){if(this._state!==`done`){if(this._state===`canceled`)M._warn(`Conversion already canceled.`);else{this._state=`canceled`;for(let e of this._trackPumps)e.wake?.();this._synchronizer.resolveAll(),this._composable||await this.output.cancel()}}}async _processVideoTrack(e,n,r){let i=await e.getCodec();if(!i){this.discardedTracks.push({track:e,reason:`unknown_source_codec`,trackOptions:n});return}if(this.output.format.requiresMaximumPacketCount&&n.maximumPacketCount===void 0&&this._endTimestamp===1/0&&await e.isLive()){this.discardedTracks.push({track:e,reason:`unknown_maximum_packet_count`,trackOptions:n});return}let a,o=await e.getRotation(),s=await e.getFlip(),{rotation:c,flip:l}=p(o,s,n.rotate??0,n.flip??!1),u=c,d=l,f=n.rotate||n.flip?null:await e.getTransformationMatrix(),m=this.output.format.supportsVideoTransformationMetadata&&(n.allowTransformationMetadata??n.allowRotationMetadata??!0),h=await e.getSquarePixelWidth(),g=await e.getSquarePixelHeight(),[_,v]=c%180==0?[h,g]:[g,h],y=n.crop;y&&=Jr(y,_,v);let[b,x]=y?[y.width,y.height]:[_,v],S=b,C=x,w=S/C;n.width!==void 0&&n.height===void 0?(S=vt(n.width),C=vt(Math.round(S/w))):n.width===void 0&&n.height!==void 0?(C=vt(n.height),S=vt(Math.round(C*w))):n.width!==void 0&&n.height!==void 0&&(S=vt(n.width),C=vt(n.height));let ee=this.output.format.getSupportedVideoCodecs(),T=n.alpha??`discard`,te=!this._copyMode||!!n.forceTranscode||!!n.frameRate||n.keyFrameInterval!==void 0||n.process!==void 0||n.quality!==void 0||n.bitrate!==void 0||!ee.includes(i)||n.codec&&n.codec!==i||S!==b||C!==x||c!==0&&!m||l&&!m||!!y,E=null;if(!te){let t=new mc(e),n=await t.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await t.getFirstKeyPacket({verifyKeyPackets:!0});if(n&&n.timestamp<this._startTimestamp&&n.timestamp+n.duration<=this._startTimestamp&&this._copyBoundaryPolicy===`shrink`&&(n=await t.getNextKeyPacket(n,{verifyKeyPackets:!0})),E=n,n){let e=this._copyBoundaryPolicy===`shrink`?Math.max(n.timestamp,this._startTimestamp):n.timestamp;if((this._copyBoundaryPolicy===`shrink`?e-this._startTimestamp:Math.max(this._startTimestamp-e,0))>this._copyBoundaryTolerance)te=!0;else if(!this.output.format.supportsTimestampedMediaData){if(this._timestampOffsetAdjusted)e+this._timestampOffset!==0&&(te=!0);else{let t=A(this._startTimestamp-e,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);e+t===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+t,this._timestampOffsetAdjusted=!0):te=!0}}else if(this.output.format.negativeTimestampSupport!==`full`&&e<this._startTimestamp){let t=Math.min(this._startTimestamp-e,this._copyTimestampShiftTolerance);e+t>=this._startTimestamp||this.output.format.negativeTimestampSupport===`prefer-non-negative`&&this._copyMode===`forced`?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+t):te=!0}}}if(te&&this._copyMode===`forced`){this.discardedTracks.push({track:e,reason:`cannot_copy`,trackOptions:n});return}if(te){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`,trackOptions:n});return}n.codec&&(ee=ee.filter(e=>e===n.codec));let i=Ai(n.quality,n.bitrate)??new I(`high`),o=await Mi(ee,{width:n.process&&n.processedWidth?n.processedWidth:S,height:n.process&&n.processedHeight?n.processedHeight:C,quality:i});if(!o){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`,trackOptions:n});return}let s={codec:o,quality:i,keyFrameInterval:n.keyFrameInterval,sizeChangeBehavior:n.fit??`passThrough`,alpha:T,hardwareAcceleration:n.hardwareAcceleration,transform:{}};t(s.transform);let p=S!==b||C!==x||c!==0&&(!m||n.process!==void 0)||l&&(!m||n.process!==void 0)||!!y||h!==await e.getCodedWidth()||g!==await e.getCodedHeight();if(!p){let t={stack:[],error:void 0,hasError:!1};try{let r=new Kf({format:new Rf,target:new _f}),i=new wl(s);r.addVideoTrack(i),await r.start();let a=qf(t,await new Sc(e,{hardwareAcceleration:n.hardwareAcceleration}).getSample(await e.getFirstTimestamp()),!1);if(a)try{await i.add(a),a.close(),await r.finalize()}catch(e){M._warn(`An error occurred when probing encoder support. Falling back to rerender path.`,e),r.cancel(),p=!0,s.transform.force=!0}else await r.cancel()}catch(e){t.error=e,t.hasError=!0}finally{Jf(t)}}n.frameRate&&(s.transform.frameRate=n.frameRate),n.process&&(s.transform.process=n.process),p&&(u=0,d=!1,f=null,s.transform.width=S,s.transform.height=C,s.transform.fit=n.fit??`fill`,s.transform.rotate=n.rotate,s.transform.flip=n.flip,s.transform.crop=y,s.transform.alpha=T);let _=null;s.onEncodedSample=e=>{_=e.timestamp};let v=new wl(s);a=v,this._registerTrackPump(async t=>{let i=new Sc(e,{hardwareAcceleration:n.hardwareAcceleration});for await(let e of i.samples(this._startTimestamp,this._endTimestamp)){let n={stack:[],error:void 0,hasError:!1};try{let i=qf(n,e,!1);if(this._state===`canceled`)break;let a=Math.max(this._startTimestamp,i.timestamp),o=Math.min(this._endTimestamp,i.timestamp+i.duration);if(a>o||a===o&&i.duration>0)continue;i.setTimestamp(a+this._timestampOffset),i.setDuration(o-a),this._updateProgress(r,i.timestamp+i.duration),await v.add(i),i.close(),_!==null&&(this._synchronizer.shouldWait(r,_)&&await this._synchronizer.wait(_),await this._checkpoint(t,_))}catch(e){n.error=e,n.hasError=!0}finally{Jf(n)}}v.close(),this._closeTrack(r)})}else{let t=new _l(i);a=t,this._registerTrackPump(async n=>{let i=new mc(e),a={decoderConfig:await e.getDecoderConfig()??void 0},o=new bu,s=!1,c=!1;if(E)for await(let e of i.packets(E,void 0,{verifyKeyPackets:!0})){if(this._state===`canceled`)break;if(e.timestamp>=this._endTimestamp){if(this._copyBoundaryPolicy===`shrink`)break;{let t=e,n=!1;for(let e=0;e<6;e++){let e=await i.getNextPacket(t,{metadataOnly:!0});if(!e)break;if(e.timestamp<this._endTimestamp){n=!0;break}t=e}if(!n)break}}let l=e.timestamp,u=e.timestamp+e.duration;if(this._copyBoundaryPolicy===`shrink`&&(l=Math.max(l,this._startTimestamp),u=Math.min(u,this._endTimestamp),u=Math.max(u,l)),l+=this._timestampOffset,u+=this._timestampOffset,e.type===`key`&&(s=!1),s)continue;let d=e.type;if(d===`key`&&!o.check(l,`key`)&&(d=`delta`),!o.digest(l,d)){s=e.type===`key`,c||=(M._warn(`Some video packets had to be dropped in order to produce correct output timestamps.`),!0);continue}let f=e.clone({timestamp:l,duration:u-l,sideData:T===`discard`?{}:e.sideData,type:d});this._updateProgress(r,f.timestamp+f.duration),await t.add(f,a),this._synchronizer.shouldWait(r,f.timestamp)&&await this._synchronizer.wait(f.timestamp),await this._checkpoint(n,f.timestamp)}t.close(),this._closeTrack(r)})}let ne=null;!n.group&&!this._composable&&(ne=new Wf);let re=await e.getLanguageCode(),ie=await e.getName(),ae=await e.getDisposition(),oe=te?null:await e.getBitrate(),se=te?null:await e.getAverageBitrate(),ce=T===`keep`&&await e.canBeTransparent(),le=n.maximumPacketCount;if(this.output.format.requiresMaximumPacketCount&&le===void 0){let t=te?this._startTimestamp:E?.timestamp??this._startTimestamp;le=await this._estimateMaximumPacketCount(e,t,n.frameRate??null)}this.output.addVideoTrack(a,{frameRate:n.frameRate,languageCode:Re(re)?re:void 0,name:ie??void 0,disposition:ae,rotation:u,flip:d,transformationMatrix:f??void 0,canBeTransparent:ce,group:ne??n.group,bitrate:oe??void 0,averageBitrate:se??void 0,maximumPacketCount:le}),this.utilizedTracks.push(e),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(ne)}async _processAudioTrack(e,n,r){let i=await e.getCodec();if(!i){this.discardedTracks.push({track:e,reason:`unknown_source_codec`,trackOptions:n});return}if(this.output.format.requiresMaximumPacketCount&&n.maximumPacketCount===void 0&&this._endTimestamp===1/0&&await e.isLive()){this.discardedTracks.push({track:e,reason:`unknown_maximum_packet_count`,trackOptions:n});return}let a,o=await e.getNumberOfChannels(),s=await e.getSampleRate(),c=n.numberOfChannels??o,l=n.sampleRate??s,u=null,d=this.output.format.getSupportedAudioCodecs(),f=!this._copyMode||!!n.forceTranscode||!!n.quality||!!n.bitrate||c!==o||l!==s||!d.includes(i)||!!n.codec&&n.codec!==i||n.process!==void 0||n.sampleFormat!==void 0,p=null;if(!f){let n=new mc(e),r=await n.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await n.getFirstKeyPacket({verifyKeyPackets:!0});r&&(this._copyBoundaryPolicy===`shrink`&&r.timestamp<this._startTimestamp||this._copyBoundaryPolicy===`expand`&&r.timestamp+r.duration<=this._startTimestamp&&await e.hasOnlyKeyPackets())&&(r=await n.getNextKeyPacket(r,{verifyKeyPackets:!0}));let i=await e.getPreRollDuration();if(t(i!==null),r&&this._copyBoundaryPolicy===`expand`&&i>0&&(r=await n.getKeyPacket(r.timestamp-i,{verifyKeyPackets:!0})??await n.getFirstKeyPacket({verifyKeyPackets:!0})),p=r,r){if((this._copyBoundaryPolicy===`shrink`?Math.max(r.timestamp-this._startTimestamp,0):Math.max(this._startTimestamp-r.timestamp,0))>this._copyBoundaryTolerance)f=!0;else if(!this.output.format.supportsTimestampedMediaData){if(this._timestampOffsetAdjusted)r.timestamp+this._timestampOffset!==0&&(f=!0);else{let e=A(this._startTimestamp-r.timestamp,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);r.timestamp+e===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+e,this._timestampOffsetAdjusted=!0):f=!0}}else if(this.output.format.negativeTimestampSupport!==`full`&&r.timestamp<this._startTimestamp){let e=Math.min(this._startTimestamp-r.timestamp,this._copyTimestampShiftTolerance);r.timestamp+e>=this._startTimestamp||this.output.format.negativeTimestampSupport===`prefer-non-negative`&&this._copyMode===`forced`?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+e):f=!0}}}if(f&&this._copyMode===`forced`){this.discardedTracks.push({track:e,reason:`cannot_copy`,trackOptions:n});return}if(f){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`,trackOptions:n});return}n.codec&&(d=d.filter(e=>e===n.codec));let i=Ai(n.quality,n.bitrate)??new I(`high`),f=await ji(d,{numberOfChannels:n.process&&n.processedNumberOfChannels?n.processedNumberOfChannels:c,sampleRate:n.process&&n.processedSampleRate?n.processedSampleRate:l,quality:i});if(!f.some(e=>Ll.includes(e))&&d.some(e=>Ll.includes(e))&&(c!==2||l!==Zf)){let e=(await ji(d,{numberOfChannels:2,sampleRate:Zf,quality:i})).find(e=>Ll.includes(e));e?(u=e,c=2,l=Zf):u=f[0]??null}else u=f[0]??null;if(u===null){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`,trackOptions:n});return}let p={codec:u,quality:i,transform:{sampleFormat:n.sampleFormat,process:n.process}};t(p.transform),c!==o&&(p.transform.numberOfChannels=c),l!==s&&(p.transform.sampleRate=l);let m=null;p.onEncodedSample=e=>{m=e.timestamp};let h=new Nl(p);a=h,this._registerTrackPump(async t=>{let n=null,i=new Tc(e);for await(let e of i.samples(this._startTimestamp,this._endTimestamp)){let i={stack:[],error:void 0,hasError:!1};try{let a=qf(i,e,!1);if(this._state===`canceled`)break;let o=0,s=a.numberOfFrames;if(a.timestamp<this._startTimestamp&&(o=Math.round((this._startTimestamp-a.timestamp)*a.sampleRate)),a.timestamp+a.duration>this._endTimestamp&&(s=Math.round((this._endTimestamp-a.timestamp)*a.sampleRate)),o>=s){a.close();continue}let c;if(o>0||s<a.numberOfFrames){let e=a.trim(o,s);if(a.close(),c=e,e.numberOfFrames===0){e.close();continue}}else c=a;let l=qf(i,c,!1);if(l.setTimestamp(l.timestamp+this._timestampOffset),n===null&&(n=this.output.format.supportsTimestampedMediaData?0:Math.round(l.timestamp*l.sampleRate)),n>0){let e=si(a.format)*l.numberOfChannels,i=new Uint8Array(e*Math.min(n,l.sampleRate));(a.format===`u8`||a.format===`u8-planar`)&&i.fill(128);for(let o=0;o<n;o+=l.sampleRate){let s={stack:[],error:void 0,hasError:!1};try{let c=Math.min(n-o,l.sampleRate),u=qf(s,new oi({data:i.subarray(0,e*c),_doNotCopy:!0,format:a.format,numberOfChannels:l.numberOfChannels,sampleRate:l.sampleRate,timestamp:o/l.sampleRate}),!1);await this._registerAudioSample(t,u,h,r,()=>m)}catch(e){s.error=e,s.hasError=!0}finally{Jf(s)}}n=0}await this._registerAudioSample(t,l,h,r,()=>m)}catch(e){i.error=e,i.hasError=!0}finally{Jf(i)}}h.close(),this._closeTrack(r)})}else{let t=new El(i);a=t,this._registerTrackPump(async n=>{let i=new mc(e),a={decoderConfig:await e.getDecoderConfig()??void 0},o=new bu,s=!1,c=!1;if(p)for await(let e of i.packets(p)){if(this._state===`canceled`||e.timestamp>=this._endTimestamp||this._copyBoundaryPolicy===`shrink`&&e.timestamp+e.duration>this._endTimestamp)break;let i=e.timestamp+this._timestampOffset;if(e.type===`key`&&(s=!1),s)continue;if(!o.digest(i,e.type)){s=e.type===`key`,c||=(M._warn(`Some audio packets had to be dropped in order to produce correct output timestamps.`),!0);continue}let l=e.clone({timestamp:i,duration:e.duration});this._updateProgress(r,l.timestamp+l.duration),await t.add(l,a),this._synchronizer.shouldWait(r,l.timestamp)&&await this._synchronizer.wait(l.timestamp),await this._checkpoint(n,l.timestamp)}t.close(),this._closeTrack(r)})}let m=null;!n.group&&!this._composable&&(m=new Wf);let h=await e.getLanguageCode(),g=await e.getName(),_=await e.getDisposition(),v=f?null:await e.getBitrate(),y=f?null:await e.getAverageBitrate(),b=n.maximumPacketCount;if(this.output.format.requiresMaximumPacketCount&&b===void 0){let n=null;f&&(t(u),n=l/nu(u,l));let r=f?this._startTimestamp:p?.timestamp??this._startTimestamp;b=await this._estimateMaximumPacketCount(e,r,n)}this.output.addAudioTrack(a,{languageCode:Re(h)?h:void 0,name:g??void 0,disposition:_,group:m??n.group,bitrate:v??void 0,averageBitrate:y??void 0,maximumPacketCount:b}),this.utilizedTracks.push(e),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(m)}async _estimateMaximumPacketCount(e,t,n){if(n===null){let t=await e.computePacketStats(256);if(t.averagePacketRate===1/0)return t.packetCount;n=t.averagePacketRate}let r=Math.min(await this._getTrackDuration(e),this._endTimestamp),i=Math.max(r-t,0);return Math.ceil(1.5*n*i)+64}_getTrackDuration(e){let t=this._trackDurations.get(e);return t||(t=(async()=>await e.isLive()?1/0:await e.getDurationFromMetadata()??await e.computeDuration())(),this._trackDurations.set(e,t)),t}async _registerAudioSample(e,t,n,r,i){this._updateProgress(r,t.timestamp+t.duration),await n.add(t),t.close();let a=i();a!==null&&(this._synchronizer.shouldWait(r,a)&&await this._synchronizer.wait(a),await this._checkpoint(e,a))}_registerTrackPump(e){let t={done:!1,resolvers:O(),wake:null,start:()=>{e(t).then(()=>{t.done=!0,t.resolvers.resolve()},e=>{t.resolvers.reject(e)})}};this._trackPumps.push(t)}async _checkpoint(e,t){for(;this._state!==`canceled`&&(t>=this._executionUntil||this._pauseRequested);){e.resolvers.resolve();let{promise:t,resolve:n}=O();e.wake=n,await t}}_closeTrack(e){this._synchronizer.closeTrack(e),this._maxTimestamps.delete(e),this._reportProgress()}_updateProgress(e,t){this._computeProgress&&(this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e))),this._reportProgress())}_reportProgress(){if(!this._computeProgress||this._maxTimestamps.size===0)return;t(this._totalDuration!==null);let e=Math.min(...this._maxTimestamps.values()),n=this._totalDuration>0?A(e/this._totalDuration,0,1):0;this._lastProcessedTime=e,n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n,e))}},$f=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},ep=class{constructor(e){this.maxTimestamps=/* @__PURE__ */ new Map,this.resolvers=[],this.conversion=e}declareTrack(e){this.maxTimestamps.set(e,-1/0)}shouldWait(e,n){let r=this.maxTimestamps.get(e);t(r!==void 0),this.maxTimestamps.set(e,Math.max(n,r));let i=this.computeMinAndMaybeResolve();return this.conversion._state===`canceled`||this.conversion._pauseRequested||n>=this.conversion._executionUntil?!1:n-i>1}wait(e){let{promise:t,resolve:n}=O();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}resolveAll(){for(let e of this.resolvers)e.resolve();this.resolvers.length=0}computeMinAndMaybeResolve(){let e=1/0;for(let[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){let n=this.resolvers[t];n.timestamp-e<1&&(n.resolve(),this.resolvers.splice(t,1),t--)}return e}};
493
+ /*!
494
+ * Copyright (c) 2026-present, Vanilagy and contributors
495
+ *
496
+ * This Source Code Form is subject to the terms of the Mozilla Public
497
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
498
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
499
+ */
500
+ const tp=Symbol.for(`mediabunny loaded`);globalThis[tp]&&M._error(`[WARNING]
501
+ Mediabunny was loaded twice. This will likely cause Mediabunny not to work correctly. Check if multiple dependencies are importing different versions of Mediabunny, or if something is being bundled incorrectly.`),globalThis[tp]=!0;async function np(e){let{arrayBuffer:t,fileName:n,fileType:r,format:i,quality:a=.5,videoBitrate:o,audioBitrate:s,videoCodec:c,audioCodec:l,maxWidth:u,maxHeight:d,frameRate:f,sampleRate:p,numberOfChannels:m,keepOriginalIfLarger:h=!0}=e,g=new zc({source:new Ms(t),formats:lc}),_,v;try{let e=await g.getPrimaryVideoTrack(),y=await g.getPrimaryAudioTrack();if(!e&&!y)throw Error(`文件中没有可压缩的音视频轨道`);let b=i??(/webm/i.test(r)?`webm`:/ogg/i.test(r)?`ogg`:`mp4`);if(b===`ogg`&&e)throw Error(`Ogg 输出仅支持纯音频,请使用 mp4 或 webm`);let x=b===`mp4`?new Mf({fastStart:`in-memory`}):b===`webm`?new If:b===`ogg`?new Lf:void 0;if(!x)throw Error(`不支持的输出格式:${b}`);let S=new gf;if(_=new Kf({format:x,target:S}),v=await Qf.init({input:g,output:_,tracks:`primary`,showWarnings:!1,video:async e=>{let t=await e.getDisplayWidth(),n=await e.getDisplayHeight(),r=Math.min(1,(u??t)/t,(d??n)/n);return{codec:c,quality:o===void 0?new I(a):new I({bitrate:o}),width:Math.max(2,Math.floor(t*r/2)*2),height:Math.max(2,Math.floor(n*r/2)*2),fit:`contain`,frameRate:f,forceTranscode:!0}},audio:{codec:l,quality:s===void 0?new I(a):new I({bitrate:s}),sampleRate:p,numberOfChannels:m,forceTranscode:!0}}),!v.isValid||v.discardedTracks.length>0){let e=v.discardedTracks.map(({reason:e})=>e).join(`, `);throw Error(`当前浏览器无法完成音视频压缩(${e||`没有可输出的轨道`})。请检查 WebCodecs 编解码支持或更换输出格式。`)}await v.execute();let C=S.buffer;if(!C)throw Error(`音视频压缩未生成输出数据`);if(h&&C.byteLength>=t.byteLength)return{success:!0,data:t,fileName:n,fileType:r};let w=b===`mp4`&&!e?`m4a`:b;return{success:!0,data:C,fileName:`${n.replace(/\.[^.]+$/,``)}.${w}`,fileType:`${e?`video`:`audio`}/${b}`}}finally{try{v&&_?.state!==`finalized`?await v.cancel():_&&_.state!==`finalized`&&_.state!==`canceled`&&await _.cancel()}finally{g.dispose()}}}export{np as compress};