@hyperframes/studio 0.9.21 → 0.9.22

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/dist/assets/codec-DLDwVbqW.js +314 -0
  2. package/dist/assets/{hyperframes-player-DqxUNa9H.js → hyperframes-player-C5DA6O5u.js} +1 -1
  3. package/dist/assets/index-B6RxZt-8.js +150 -0
  4. package/dist/assets/{index-Cq43Ovkf.js → index-Buvugo_O.js} +120 -119
  5. package/dist/assets/pausedVideoDecoder-BGKlQc66.js +1 -0
  6. package/dist/{chunk-3EAFE522.js → chunk-45KKBU63.js} +1 -1
  7. package/dist/chunk-4SPHDECE.js +165 -0
  8. package/dist/{chunk-OGIOFEC7.js → chunk-63DH4LRB.js} +13 -2
  9. package/dist/{chunk-NUS5R2HO.js → chunk-AX6G6YL5.js} +1 -1
  10. package/dist/{domEditingLayers-7Z6J4UOK.js → domEditingLayers-7Q56QAU5.js} +2 -2
  11. package/dist/index.d.ts +5 -1
  12. package/dist/index.html +1 -1
  13. package/dist/index.js +104 -195
  14. package/dist/pausedVideoDecoder-KBQXSWFQ.js +393 -0
  15. package/dist/player.js +2 -2
  16. package/package.json +9 -9
  17. package/src/components/editor/domEditingDom.preview.test.ts +75 -0
  18. package/src/components/editor/domEditingDom.ts +19 -2
  19. package/src/components/nle/NLEContext.tsx +4 -1
  20. package/src/hooks/useElementPicker.test.ts +13 -0
  21. package/src/hooks/useElementPicker.ts +3 -2
  22. package/src/player/components/PlayerControls.test.tsx +1 -1
  23. package/src/player/components/PlayerControls.tsx +1 -1
  24. package/src/player/components/PreviewSeekBar.test.tsx +42 -0
  25. package/src/player/components/PreviewSeekBar.tsx +20 -3
  26. package/src/player/hooks/usePlaybackKeyboard.test.ts +1 -1
  27. package/src/player/hooks/usePlaybackKeyboard.ts +2 -1
  28. package/src/player/hooks/useTimelinePlayer.ts +3 -1
  29. package/src/player/lib/mediaFetch.test.ts +3 -4
  30. package/src/player/lib/pausedVideoDecoder.test.ts +644 -0
  31. package/src/player/lib/pausedVideoDecoder.ts +428 -0
  32. package/src/player/lib/pausedVideoProvider.test.ts +53 -0
  33. package/src/player/lib/pausedVideoProvider.ts +54 -0
  34. package/src/player/lib/playbackTypes.ts +8 -2
  35. package/src/player/lib/previewVideoTime.test.ts +38 -0
  36. package/src/player/lib/previewVideoTime.ts +39 -0
  37. package/src/utils/authoredSource.test.ts +11 -0
  38. package/src/utils/authoredSource.ts +2 -0
  39. package/dist/assets/index-CFUJyYA1.js +0 -531
@@ -0,0 +1,314 @@
1
+ import{n as Ws}from"./index-Buvugo_O.js";/*!
2
+ * Copyright (c) 2026-present, Vanilagy and contributors
3
+ *
4
+ * This Source Code Form is subject to the terms of the Mozilla Public
5
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
6
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
+ */function y(r){if(!r)throw new Error("Assertion failed.")}const zn=Math.PI/180,Zc=180/Math.PI,Xr=r=>{const e=(r%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${r}.`)},Un=[1,0,0,0,1,0,0,0,1],Jc=(r,e,t)=>{const[i,n,,s,a]=r,o=Math.abs(i)*e+Math.abs(s)*t,c=Math.abs(n)*e+Math.abs(a)*t;return Ii(Ii(qs(-e/2,-t/2),r),qs(o/2,c/2))},gi=r=>{const[e,t]=r,i=Math.atan2(t,lo(r)?-e:e);return Xr(Vn(i*Zc,90))},lo=r=>{const[e,t,,i,n]=r;return e*n-t*i<0},el=r=>{const e=r*zn,t=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[t,i,0,-i,t,0,0,0,1]},qs=(r,e)=>[1,0,0,0,1,0,r,e,1],tl=(r,e)=>[r,0,0,0,e,0,0,0,1],Ii=(r,e)=>{const t=new Array(9);for(let i=0;i<3;i++)for(let n=0;n<3;n++)t[3*i+n]=r[3*i]*e[n]+r[3*i+1]*e[3+n]+r[3*i+2]*e[6+n];return t},rl=(r,e,t,i)=>({rotation:Xr(r+(e?-t:t)),flip:e!==i}),fe=r=>r&&r[r.length-1],wh=r=>r>=0&&r<2**32,kh=r=>r>=-2147483648&&r<2**31,W=r=>{let e=0;for(;r.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return 2**e-1+r.readBits(e)},Kt=(r,e)=>{const t=e+1,i=Math.floor(Math.log2(t));r.writeBits(i,0),r.writeBits(1,1),r.writeBits(i,t-2**i)},gt=r=>{const e=W(r);return e%2===0?-(e/2):(e+1)/2},yh=(r,e,t,i)=>{for(let n=e;n<t;n++){const s=Math.floor(n/8);let a=r[s];const o=7-(n&7);a&=~(1<<o),a|=(i&1<<t-n-1)>>t-n-1<<o,r[s]=a}},ke=r=>r.constructor===Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),Z=r=>r.constructor===DataView?r:ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r),il=typeof globalThis.TextEncoder<"u"?globalThis.TextEncoder:class{constructor(){this.encoding="utf-8"}encode(e=""){const t=new Uint8Array(3*e.length);let i=0;for(let n=0;n<e.length;n++){let s=e.charCodeAt(n);if(s<128)t[i++]=s;else if(s<2048)t[i++]=192|s>>6,t[i++]=128|s&63;else if(s<55296||s>57343)t[i++]=224|s>>12,t[i++]=128|s>>6&63,t[i++]=128|s&63;else{const a=n+1<e.length?e.charCodeAt(n+1):0;s<56320&&a>=56320&&a<=57343?(s=65536+(s-55296<<10)+(a-56320),n++,t[i++]=240|s>>18,t[i++]=128|s>>12&63,t[i++]=128|s>>6&63,t[i++]=128|s&63):(t[i++]=239,t[i++]=191,t[i++]=189)}}return t.slice(0,i)}},Qr=typeof globalThis.TextDecoder<"u"?globalThis.TextDecoder:class{constructor(e="utf-8"){const 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 new RangeError(`The encoding label provided ('${e}') is invalid.`)}decode(e){const t=e?ke(e):new Uint8Array(0),i=[];if(this.encoding==="utf-8"){let s=t.length>=3&&t[0]===239&&t[1]===187&&t[2]===191?3:0;for(;s<t.length;){const a=t[s];if(a<128){i.push(a),s++;continue}let o,c;if(a>=194&&a<224)o=1,c=a&31;else if(a>=224&&a<240)o=2,c=a&15;else if(a>=240&&a<245)o=3,c=a&7;else{i.push(65533),s++;continue}let u=a===224?160:a===240?144:128,l=a===237?159:a===244?143:191,d=1;for(;d<=o;d++){const f=s+d<t.length?t[s+d]:0;if(f<u||f>l)break;c=c<<6|f&63,u=128,l=191}s+=d,d<=o?i.push(65533):c>=65536?(c-=65536,i.push(55296|c>>10,56320|c&1023)):i.push(c)}}else{const s=this.encoding==="utf-16le",a=s?255:254,o=s?254:255;let c=t.length>=2&&t[0]===a&&t[1]===o?2:0;for(;c+1<t.length;){const u=s?t[c]|t[c+1]<<8:t[c]<<8|t[c+1];if(c+=2,u>=55296&&u<=56319){const l=c+1<t.length?s?t[c]|t[c+1]<<8:t[c]<<8|t[c+1]:-1;l>=56320&&l<=57343?(i.push(u,l),c+=2):i.push(65533)}else u>=56320&&u<=57343?i.push(65533):i.push(u)}c<t.length&&i.push(65533)}let n="";for(let s=0;s<i.length;s+=8192)n+=String.fromCharCode(...i.slice(s,s+8192));return n}},_e=new Qr,Ye=new il,St=r=>{for(let e=0;e<r.length;e++)if(r.charCodeAt(e)>255)return!1;return!0},us=r=>Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),li={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ht=us(li),ui={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},mt=us(ui),di={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},pt=us(di),ds=r=>!!r&&!!r.primaries&&!!r.transfer&&!!r.matrix&&r.fullRange!==void 0,Th=r=>!r||r.primaries==null&&r.transfer==null&&r.matrix==null&&r.fullRange==null,uo={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},hr=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r);class Vi{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e;const t=new Promise(n=>{let s=!1;e=()=>{s||(n(),this.pending--,s=!0)}}),i=this.currentPromise;return this.currentPromise=t,this.pending++,await i,e}}const nl=/^[0-9a-fA-F]+$/,Jr=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),sl=r=>{y(r.length%2===0);const e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)e[t/2]=parseInt(r.slice(t,t+2),16);return e},Hs=r=>(r=r>>1&1431655765|(r&1431655765)<<1,r=r>>2&858993459|(r&858993459)<<2,r=r>>4&252645135|(r&252645135)<<4,r=r>>8&16711935|(r&16711935)<<8,r=r>>16&65535|(r&65535)<<16,r>>>0),fi=(r,e,t)=>{let i=0,n=r.length-1,s=-1;for(;i<=n;){const a=i+n>>1,o=t(r[a]);o===e?(s=a,n=a-1):o<e?i=a+1:n=a-1}return s},te=(r,e,t)=>{let i=0,n=r.length-1,s=-1;for(;i<=n;){const a=i+(n-i+1)/2|0;t(r[a])<=e?(s=a,i=a+1):n=a-1}return s},js=(r,e,t)=>{const i=te(r,t(e),t);r.splice(i+1,0,e)},Se=()=>{let r,e;return{promise:new Promise((i,n)=>{r=i,e=n}),resolve:r,reject:e}},Ci=(r,e)=>{const t=r.indexOf(e);t!==-1&&r.splice(t,1)},fo=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return r[t]},fs=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1},al=async function*(r){Symbol.iterator in r?yield*r[Symbol.iterator]():yield*r[Symbol.asyncIterator]()},ol=r=>{if(!(Symbol.iterator in r)&&!(Symbol.asyncIterator in r))throw new TypeError("Argument must be an iterable or async iterable.")},ze=r=>{throw new Error(`Unexpected value: ${r}`)},Li=(r,e,t)=>{const i=r.getUint8(e),n=r.getUint8(e+1),s=r.getUint8(e+2);return t?i|n<<8|s<<16:i<<16|n<<8|s},cl=(r,e,t)=>Li(r,e,t)<<8>>8,hs=(r,e,t,i)=>{t=t>>>0,t=t&16777215,i?(r.setUint8(e,t&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t>>>16&255)):(r.setUint8(e,t>>>16&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t&255))},ll=(r,e,t,i)=>{t=pe(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),hs(r,e,t,i)},xh=(r,e,t,i)=>{r.setUint32(e+0,t,!0),r.setInt32(e+4,Math.floor(t/2**32),!0)},Ei=(r,e)=>({async next(){const t=await r.next();return t.done?{value:void 0,done:!0}:{value:e(t.value),done:!1}},return(){return r.return()},throw(t){return r.throw(t)},[Symbol.asyncIterator](){return this}}),pe=(r,e,t)=>Math.max(e,Math.min(t,r)),ul=(r,e,t)=>r+(e-r)*t,dl=(r,e)=>r-Math.floor(r/e)*e,De="und",ei=r=>{const e=Math.round(r);return Math.abs(r/e-1)<10*Number.EPSILON?e:r},Vn=(r,e)=>Math.round(r/e)*e,_i=(r,e)=>Math.round(r*e)/e,hn=(r,e)=>Math.floor(r/e)*e,Ks=(r,e)=>Math.floor(r*e)/e,fl=r=>{let e=0;for(;r;)e++,r>>=1;return e},Ln=r=>{let e=0;for(;r!==0;)r&=r-1,e++;return e},hl=/^[a-z]{3}$/,ho=r=>hl.test(r),It=1e6*(1+Number.EPSILON),Xs=(r,e)=>{const t={...r,...e};if(r.headers||e.headers){const i=r.headers?Wn(r.headers):{},n=e.headers?Wn(e.headers):{},s={...i};Object.entries(n).forEach(([a,o])=>{const c=Object.keys(s).find(u=>u.toLowerCase()===a.toLowerCase());c&&delete s[c],s[a]=o}),t.headers=s}return t},Wn=r=>{if(r instanceof Headers){const e={};return r.forEach((t,i)=>{e[i]=t}),e}if(Array.isArray(r)){const e={};return r.forEach(([t,i])=>{e[t]=i}),e}return r},Qs=async(r,e,t,i,n)=>{let s=0;for(;;)try{return await r(e,t)}catch(a){if(n())throw a;s++;const o=i(s,a,e);if(o===null)throw a;if(j._error("Retrying failed fetch. Error:",a),!Number.isFinite(o)||o<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(o>0&&await ar(1e3*o),n())throw a}},Ph=(r,e)=>{const t=r<0?-1:1;r=Math.abs(r);let i=0,n=1,s=1,a=0,o=r;for(;;){const c=Math.floor(o),u=c*s+i,l=c*a+n;if(l>e)return{num:t*s,den:a};if(i=s,n=a,s=u,a=l,o=1/(o-c),!isFinite(o))break}return{num:t*s,den:a}};class Wi{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let mn=null;const _t=()=>{var r;return mn!==null?mn:mn=!!(typeof navigator<"u"&&((r=navigator.vendor)!=null&&r.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)))};let pn=null;const Wt=()=>{var r;return pn!==null?pn:pn=typeof navigator<"u"&&((r=navigator.userAgent)==null?void 0:r.includes("Firefox"))};let gn=null;const ki=()=>{var r;return gn!==null?gn:gn=!!(typeof navigator<"u"&&((r=navigator.vendor)!=null&&r.includes("Google Inc")||/Chrome/.test(navigator.userAgent)))};let bn=null;const ml=()=>{if(bn!==null)return bn;if(typeof navigator>"u")return null;const r=/\bChrome\/(\d+)/.exec(navigator.userAgent);return r?bn=Number(r[1]):null};let wn=null;const pl=()=>wn!==null?wn:wn=typeof navigator<"u"&&/Android/.test(navigator.userAgent),qi=r=>typeof globalThis.isSecureContext<"u"&&!globalThis.isSecureContext?`${r} 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.`:`${r} is not available in this environment.`,gl=r=>r instanceof DOMException&&r.name==="QuotaExceededError"&&/reclaimed/i.test(r.message),bl=(async()=>{})().constructor,F=r=>r instanceof bl||r instanceof Promise?!0:typeof(r==null?void 0:r.then)=="function",Yt=(r,e)=>r!==-1?r:e,qn=(r,e,t,i)=>r<=i&&t<=e,mo=function*(r){for(const e in r){const t=r[e];t!==void 0&&(yield{key:e,value:t})}},Ih=r=>{switch(r.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}},vi=r=>{let e;try{e=atob(r)}catch{throw new Error("Invalid base64 string.")}const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t},wl=r=>{let e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e)},kl=(r,e)=>{if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0},ms=()=>{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},Ht=r=>typeof r=="number"&&!Number.isNaN(r),xt=(r,e)=>{if(e.includes("://"))return e;if(r.includes("://")){const o=r.indexOf("?");o!==-1&&(r=r.slice(0,o))}let t;if(e.startsWith("/")){const o=r.indexOf("://");if(o===-1)t=e;else{const c=r.indexOf("/",o+3);c===-1?t=r+e:t=r.slice(0,c)+e}}else{const o=r.lastIndexOf("/");o===-1?t=e:t=r.slice(0,o+1)+e}let i="";const n=t.indexOf("://");if(n!==-1){const o=t.indexOf("/",n+3);o!==-1&&(i=t.slice(0,o),t=t.slice(o))}const s=t.split("/"),a=[];for(const o of s)o===".."?a.pop():o!=="."&&a.push(o);return i+a.join("/")},yl=(r,e)=>{const t=r.indexOf("?");if(t===-1)return null;const i=r.indexOf("#",t),n=r.slice(t+1,i===-1?void 0:i);for(const s of n.split("&")){const a=s.indexOf("="),o=a===-1?s:s.slice(0,a),c=a===-1?"":s.slice(a+1);try{if(decodeURIComponent(o)===e)return decodeURIComponent(c)}catch{}}return null},qr=(r,e)=>{let t=0;for(let i=0;i<r.length;i++)e(r[i])&&t++;return t},Hi=(r,e)=>{let t=-1,i=1/0;for(let n=0;n<r.length;n++){const s=e(r[n]);(t===-1||s<i)&&(i=s,t=n)}return t},Ch=(r,e)=>{let t=-1,i=-1/0;for(let n=0;n<r.length;n++){const s=e(r[n]);(t===-1||s>i)&&(i=s,t=n)}return t},ps=r=>{y(Number.isInteger(r.num)),y(Number.isInteger(r.den)),y(r.den!==0);let e=Math.abs(r.num),t=Math.abs(r.den);for(;t!==0;){const n=e%t;e=t,t=n}const i=e||1;return{num:r.num/i,den:r.den/i}},kn=(r,e)=>{if(typeof r!="object"||!r)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)};let Br,Sl=1;const Gs=new Map,gs=new Map,po=()=>typeof window>"u",Al=()=>{const r=new Map,e=new Map;self.onmessage=t=>{const i=t.data;switch(i.type){case"set-timeout":{const n=setTimeout(()=>{r.delete(i.timerId),self.postMessage({type:"fire",timerId:i.timerId})},i.delay);r.set(i.timerId,n)}break;case"set-interval":{const n=setInterval(()=>{self.postMessage({type:"fire",timerId:i.timerId})},i.delay);e.set(i.timerId,n)}break;case"clear-timeout":{const n=r.get(i.timerId);n!==void 0&&(clearTimeout(n),r.delete(i.timerId))}break;case"clear-interval":{const n=e.get(i.timerId);n!==void 0&&(clearInterval(n),e.delete(i.timerId))}break}}},go=()=>{if(Br)return Br;const r=`(${Al.toString()})();`,e=URL.createObjectURL(new Blob([r],{type:"text/javascript"}));return Br=new Worker(e),URL.revokeObjectURL(e),Br.onmessage=t=>{const i=t.data,n=Gs.get(i.timerId);if(n){Gs.delete(i.timerId),n();return}const s=gs.get(i.timerId);s&&s()},Br},Tl=(r,e)=>{if(po())return{id:setInterval(r,e)};const t=Sl++;return gs.set(t,()=>{r()}),go().postMessage({type:"set-interval",timerId:t,delay:e}),{id:t}},xl=r=>{if(po()){clearInterval(r.id);return}y(typeof r.id=="number"),gs.delete(r.id),go().postMessage({type:"clear-interval",timerId:r.id})},ar=r=>new Promise(e=>setTimeout(e,r)),Pl=r=>Array.isArray(r)?r:[r];class bs{constructor(){this._listeners=new Map}on(e,t,i){this._listeners.has(e)||this._listeners.set(e,new Set);const n={fn:t,once:(i==null?void 0:i.once)??!1};return this._listeners.get(e).add(n),()=>{var s;(s=this._listeners.get(e))==null||s.delete(n)}}_emit(...e){const[t,i]=e,n=this._listeners.get(t);if(n)for(const s of n){try{s.fn(i)}catch(a){console.error(a)}s.once&&n.delete(s)}}}const Eh=r=>Math.ceil(r/2)*2;class _h{constructor(e){this._queue=[],this._errored=!1,this.parallelism=e}get errored(){return this._errored}get inFlightCount(){return this._queue.length}async run(e){for(this._errored&&await Promise.race(this._queue);this._queue.length>=this.parallelism;)await Promise.race(this._queue);const t=e();this._queue.push(t),t.then(()=>Ci(this._queue,t)).catch(()=>this._errored=!0)}async flush(){await Promise.all(this._queue)}}const bo=r=>r!==null&&typeof r=="object"&&Object.getPrototypeOf(r)===Object.prototype&&Object.values(r).every(e=>typeof e=="string");/*!
8
+ * Copyright (c) 2026-present, Vanilagy and contributors
9
+ *
10
+ * This Source Code Form is subject to the terms of the Mozilla Public
11
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
12
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
13
+ */var rt;(function(r){r[r.Silent=0]="Silent",r[r.Errors=1]="Errors",r[r.Warnings=2]="Warnings",r[r.Info=3]="Info"})(rt||(rt={}));class j{constructor(){}static get level(){return j._level}static set level(e){if(e!==rt.Silent&&e!==rt.Errors&&e!==rt.Warnings&&e!==rt.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");j._level=e}static get _emitter(){return j._emitterInstance??(j._emitterInstance=new bs)}static on(e,t,i){return j._emitter.on(e,t,i)}static _error(...e){j._emitter._emit("error",e),j._level>=rt.Errors&&console.error(...e)}static _warn(...e){j._emitter._emit("warn",e),j._level>=rt.Warnings&&console.warn(...e)}static _info(...e){j._emitter._emit("info",e),j._level>=rt.Info&&console.info(...e)}}j._level=rt.Info;j._emitterInstance=null;/*!
14
+ * Copyright (c) 2026-present, Vanilagy and contributors
15
+ *
16
+ * This Source Code Form is subject to the terms of the Mozilla Public
17
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
18
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
19
+ */class Gr{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof t!="string")throw new TypeError("mimeType must be a string.")}}class wo{constructor(e,t,i,n){if(this.data=e,this.mimeType=t,this.name=i,this.description=n,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!==void 0&&typeof t!="string")throw new TypeError("mimeType, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("name, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("description, when provided, must be a string.")}}const vh=r=>{if(!r||typeof r!="object")throw new TypeError("tags must be an object.");if(r.title!==void 0&&typeof r.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(r.description!==void 0&&typeof r.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(r.artist!==void 0&&typeof r.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(r.album!==void 0&&typeof r.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(r.albumArtist!==void 0&&typeof r.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(r.trackNumber!==void 0&&(!Number.isInteger(r.trackNumber)||r.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(r.tracksTotal!==void 0&&(!Number.isInteger(r.tracksTotal)||r.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(r.discNumber!==void 0&&(!Number.isInteger(r.discNumber)||r.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(r.discsTotal!==void 0&&(!Number.isInteger(r.discsTotal)||r.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(r.genre!==void 0&&typeof r.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(r.date!==void 0&&(!(r.date instanceof Date)||Number.isNaN(r.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(r.creationTime!==void 0&&r.creationTime!==null&&(!(r.creationTime instanceof Date)||Number.isNaN(r.creationTime.getTime())))throw new TypeError("tags.creationTime, when provided, must be a valid Date or null.");if(r.beatsPerMinute!==void 0&&(!Number.isInteger(r.beatsPerMinute)||r.beatsPerMinute<=0))throw new TypeError("tags.beatsPerMinute, when provided, must be a positive integer.");if(r.lyrics!==void 0&&typeof r.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(r.images!==void 0){if(!Array.isArray(r.images))throw new TypeError("tags.images, when provided, must be an array.");for(const e of r.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(r.comment!==void 0&&typeof r.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(r.raw!==void 0){if(!r.raw||typeof r.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(const e of Object.values(r.raw))if(e!==null&&typeof e!="string"&&!(Array.isArray(e)&&e.every(t=>typeof t=="string"))&&!(e instanceof Uint8Array)&&!(Array.isArray(e)&&e.every(t=>t instanceof Uint8Array))&&!(e instanceof Gr)&&!(e instanceof wo)&&!bo(e))throw new TypeError("Each value in tags.raw must be a string, string array, Uint8Array, Uint8Array array, RichImageData, AttachedFile, Record<string, string>, or null.")}},Rh=r=>r.title===void 0&&r.description===void 0&&r.artist===void 0&&r.album===void 0&&r.albumArtist===void 0&&r.trackNumber===void 0&&r.tracksTotal===void 0&&r.discNumber===void 0&&r.discsTotal===void 0&&r.genre===void 0&&r.beatsPerMinute===void 0&&r.date===void 0&&r.lyrics===void 0&&(!r.images||r.images.length===0)&&r.comment===void 0&&(r.raw===void 0||Object.keys(r.raw).length===0),kt={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},Bh=r=>{if(!r||typeof r!="object")throw new TypeError("disposition must be an object.");if(r.default!==void 0&&typeof r.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(r.primary!==void 0&&typeof r.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(r.forced!==void 0&&typeof r.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(r.original!==void 0&&typeof r.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(r.commentary!==void 0&&typeof r.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(r.hearingImpaired!==void 0&&typeof r.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(r.visuallyImpaired!==void 0&&typeof r.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};/*!
20
+ * Copyright (c) 2026-present, Vanilagy and contributors
21
+ *
22
+ * This Source Code Form is subject to the terms of the Mozilla Public
23
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
24
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
25
+ */class re{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,i=7-(this.pos&7),n=(t&1<<i)>>i;return this.pos++,n}readBits(e){if(e===1)return this.readBit();let t=0;for(let i=0;i<e;i++)t<<=1,t|=this.readBit();return t}writeBits(e,t){const i=this.pos+e;for(let n=this.pos;n<i;n++){const s=Math.floor(n/8);let a=this.bytes[s];const o=7-(n&7);a&=~(1<<o),a|=(t&1<<i-n-1)>>i-n-1<<o,this.bytes[s]=a}this.pos=i}copyBits(e,t){let i=0;for(i;i<e-7;i+=8)this.writeBits(8,t.readBits(8));const n=e-i;n>0&&this.writeBits(n,t.readBits(n))}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const 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(){const e=new re(this.bytes);return e.pos=this.pos,e}}/*!
26
+ * Copyright (c) 2026-present, Vanilagy and contributors
27
+ *
28
+ * This Source Code Form is subject to the terms of the Mozilla Public
29
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
30
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
31
+ */const qt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],ji=[-1,1,2,3,4,5,6,8],Il=[1,2,3,4,6,7,17,19,20,21,22],Ki=r=>{if(!r||r.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new re(r),t=yn(e),{frequencyIndex:i,sampleRate:n}=Sn(e),s=e.readBits(4);let a=null;s>=1&&s<=7&&(a=ji[s]);let o=t,c=!1,u=n;(t===5||t===29)&&(c=t===29,u=Sn(e).sampleRate,o=yn(e),o===22&&e.skipBits(4));let l=1024;if(Il.includes(o)&&(l=e.readBits(1)?960:1024),t!==5&&t!==29)for(;e.getBitsLeft()>15;){const d=e.pos;if(e.readBits(11)!==695){e.pos=d+1;continue}yn(e)===5&&e.readBits(1)&&(u=Sn(e).sampleRate,e.getBitsLeft()>11&&e.readBits(11)===1352&&(c=!!e.readBits(1)));break}return a!==null&&a>1&&(c=!1),{objectType:t,coreObjectType:o,frequencyIndex:i,channelConfiguration:s,coreSampleRate:n,outputSampleRate:u,outputNumberOfChannels:c&&a===1?2:a,frameLength:l}},yn=r=>{const e=r.readBits(5);return e===31?32+r.readBits(6):e},Sn=r=>{const e=r.readBits(4);return e===15?{frequencyIndex:e,sampleRate:r.readBits(24)}:{frequencyIndex:e,sampleRate:e<qt.length?qt[e]:null}},Cl=r=>{const e=r.objectType===5||r.objectType===29,t=r.objectType===29,i=e?r.outputSampleRate/2:r.outputSampleRate,n=t?1:r.outputNumberOfChannels,s=ji.indexOf(n);if(s===-1)throw new TypeError(`Unsupported number of channels: ${r.outputNumberOfChannels}`);let a=16;r.objectType>=32&&(a+=6),Hn(i)===15&&(a+=24),e&&(a+=9,Hn(r.outputSampleRate)===15&&(a+=24));const o=Math.ceil(a/8),c=new Uint8Array(o),u=new re(c);return $s(u,r.objectType),Ys(u,i),u.writeBits(4,s),e&&(Ys(u,r.outputSampleRate),$s(u,2)),u.writeBits(3,0),c},$s=(r,e)=>{e<32?r.writeBits(5,e):(r.writeBits(5,31),r.writeBits(6,e-32))},Ys=(r,e)=>{const t=Hn(e);r.writeBits(4,t),t===15&&r.writeBits(24,e)},Hn=r=>{const e=qt.indexOf(r);return e===-1?15:e},Fh=r=>{const e=new Uint8Array(7),t=new re(e),{coreObjectType:i,frequencyIndex:n,channelConfiguration:s}=r,a=i-1;return t.writeBits(12,4095),t.writeBits(1,0),t.writeBits(2,0),t.writeBits(1,1),t.writeBits(2,a),t.writeBits(4,n),t.writeBits(1,0),t.writeBits(3,s),t.writeBits(1,0),t.writeBits(1,0),t.writeBits(1,0),t.writeBits(1,0),t.skipBits(13),t.writeBits(11,2047),t.writeBits(2,0),{header:e,bitstream:t}},Dh=(r,e)=>{r.pos=30,r.writeBits(13,e)};/*!
32
+ * Copyright (c) 2026-present, Vanilagy and contributors
33
+ *
34
+ * This Source Code Form is subject to the terms of the Mozilla Public
35
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
36
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
37
+ */const vt=4,El=529,_l=[44100,48e3,32e3],vl=[-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],jn=1483304551,ko=1231971951,Rl=(r,e,t,i,n)=>e===0?0:e===1?Math.floor(144*t/(i<<r))+n:e===2?Math.floor(144*t/i)+n:(Math.floor(12*t/i)+n)*4,Bl=(r,e,t,i)=>e===0?0:e===1?144*t/(i<<r):e===2?144*t/i:12*t/i*4,yo=(r,e)=>r===3?e===3?21:36:e===3?13:21,ws=(r,e)=>{const t=r>>>24,i=r>>>16&255,n=r>>>8&255,s=r&255;if(t!==255&&i!==255&&n!==255&&s!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((i&224)!==224)return{header:null,bytesAdvanced:1};let a=0,o=0;i&16?a=i&8?0:1:(a=1,o=1);const c=i>>3&3,u=i>>1&3,l=n>>4&15,d=(n>>2&3)%3,f=n>>1&1,h=s>>6&3,p=s>>4&3,m=s>>3&1,b=s>>2&1,w=s&3,S=vl[a*16*4+u*16+l];if(S===-1)return{header:null,bytesAdvanced:1};const A=S*1e3,T=_l[d]>>a+o,k=Rl(a,u,A,T,f);if(e!==null&&e<k)return{header:null,bytesAdvanced:1};let x;return c===3?x=u===3?384:1152:u===3?x=384:u===2?x=1152:x=576,{header:{totalSize:k,mpegVersionId:c,lowSamplingFrequency:a,layer:u,bitrate:A,frequencyIndex:d,sampleRate:T,channel:h,modeExtension:p,copyright:m,original:b,emphasis:w,audioSamplesInFrame:x},bytesAdvanced:1}},Fl=r=>{let e=127,t=0,i=r;for(;(e^2147483647)!==0;)t=i&~e,t<<=1,t|=i&e,e=(e+1<<8)-1,i=t;return t},Kn=r=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=r&e,e>>=8;return t};var At;(function(r){r[r.FrameCount=1]="FrameCount",r[r.FileSize=2]="FileSize",r[r.Toc=4]="Toc",r[r.Quality=8]="Quality"})(At||(At={}));const ti=r=>r===3?1:2;/*!
38
+ * Copyright (c) 2026-present, Vanilagy and contributors
39
+ *
40
+ * This Source Code Form is subject to the terms of the Mozilla Public
41
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
42
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
43
+ */const Xi=[48e3,44100,32e3],So=[24e3,22050,16e3];/*!
44
+ * Copyright (c) 2026-present, Vanilagy and contributors
45
+ *
46
+ * This Source Code Form is subject to the terms of the Mozilla Public
47
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
48
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
49
+ */const Dl=4168249274;/*!
50
+ * Copyright (c) 2026-present, Vanilagy and contributors
51
+ *
52
+ * This Source Code Form is subject to the terms of the Mozilla Public
53
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
54
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
55
+ */const Ml="1.65.2",Ol=`Mediabunny v${Ml}`;/*!
56
+ * Copyright (c) 2026-present, Vanilagy and contributors
57
+ *
58
+ * This Source Code Form is subject to the terms of the Mozilla Public
59
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
60
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
61
+ */var Ae;(function(r){r[r.NON_IDR_SLICE=1]="NON_IDR_SLICE",r[r.SLICE_DPA=2]="SLICE_DPA",r[r.SLICE_DPB=3]="SLICE_DPB",r[r.SLICE_DPC=4]="SLICE_DPC",r[r.IDR=5]="IDR",r[r.SEI=6]="SEI",r[r.SPS=7]="SPS",r[r.PPS=8]="PPS",r[r.AUD=9]="AUD",r[r.SPS_EXT=13]="SPS_EXT"})(Ae||(Ae={}));var ge;(function(r){r[r.RASL_N=8]="RASL_N",r[r.RASL_R=9]="RASL_R",r[r.BLA_W_LP=16]="BLA_W_LP",r[r.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",r[r.VPS_NUT=32]="VPS_NUT",r[r.SPS_NUT=33]="SPS_NUT",r[r.PPS_NUT=34]="PPS_NUT",r[r.AUD_NUT=35]="AUD_NUT",r[r.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",r[r.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(ge||(ge={}));const Qi=function*(r){let e=0,t=-1;for(;e<r.length-2;){const i=r.indexOf(0,e);if(i===-1||i>=r.length-2)break;e=i;let n=0;if(e+3<r.length&&r[e+1]===0&&r[e+2]===0&&r[e+3]===1?n=4:r[e+1]===0&&r[e+2]===1&&(n=3),n===0){e++;continue}t!==-1&&e>t&&(yield{offset:t,length:e-t}),t=e+n,e=t}t!==-1&&t<r.length&&(yield{offset:t,length:r.length-t})},Ao=function*(r,e){let t=0;const i=new DataView(r.buffer,r.byteOffset,r.byteLength);for(;t+e<=r.length;){let n;e===1?n=i.getUint8(t):e===2?n=i.getUint16(t,!1):e===3?n=Li(i,t,!1):(y(e===4),n=i.getUint32(t,!1)),t+=e,yield{offset:t,length:n},t+=n}},To=(r,e)=>{if(e.description){const n=(ke(e.description)[4]&3)+1;return Ao(r,n)}else return Qi(r)},ri=r=>r&31,Gi=r=>{const e=new Uint8Array(r.length),t=r.length;let i=0;for(let n=0;n<t;n++)n+2<t&&r[n]===0&&r[n+1]===0&&r[n+2]===3?(e[i++]=0,e[i++]=0,n+=2):e[i++]=r[n];return e.subarray(0,i)},Nl=r=>{const e=[];let t=0;for(const i of r)t===2&&i<=3&&(e.push(3),t=0),e.push(i),t=i===0?t+1:0;return new Uint8Array(e)},An=new Uint8Array([0,0,0,1]),xo=r=>{const e=r.reduce((n,s)=>n+An.byteLength+s.byteLength,0),t=new Uint8Array(e);let i=0;for(const n of r)t.set(An,i),i+=An.byteLength,t.set(n,i),i+=n.byteLength;return t},Po=(r,e)=>{const t=r.reduce((s,a)=>s+e+a.byteLength,0),i=new Uint8Array(t);let n=0;for(const s of r){const a=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(e){case 1:a.setUint8(n,s.byteLength);break;case 2:a.setUint16(n,s.byteLength,!1);break;case 3:hs(a,n,s.byteLength,!1);break;case 4:a.setUint32(n,s.byteLength,!1);break}n+=e,i.set(s,n),n+=s.byteLength}return i},zl=(r,e)=>{if(e.description){const n=(ke(e.description)[4]&3)+1;return Po(r,n)}else return xo(r)},$i=r=>{try{const e=[],t=[],i=[];for(const o of Qi(r)){const c=r.subarray(o.offset,o.offset+o.length),u=ri(c[0]);u===Ae.SPS&&e.length<31?e.push(c):u===Ae.PPS&&t.length<255?t.push(c):u===Ae.SPS_EXT&&i.length<255&&i.push(c)}if(e.length===0||t.length===0)return null;const n=e[0],s=dr(n);if(!s)return null;const a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:t,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?i:null}}catch(e){return j._error("Error building AVC Decoder Configuration Record:",e),null}},Io=r=>{const e=[];e.push(r.configurationVersion),e.push(r.avcProfileIndication),e.push(r.profileCompatibility),e.push(r.avcLevelIndication),e.push(252|r.lengthSizeMinusOne&3),e.push(224|r.sequenceParameterSets.length&31);for(const t of r.sequenceParameterSets){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(t[n])}e.push(r.pictureParameterSets.length);for(const t of r.pictureParameterSets){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(t[n])}if((r.avcProfileIndication===100||r.avcProfileIndication===110||r.avcProfileIndication===122||r.avcProfileIndication===144)&&r.chromaFormat!==null){y(r.bitDepthLumaMinus8!==null),y(r.bitDepthChromaMinus8!==null),y(r.sequenceParameterSetExt!==null),e.push(252|r.chromaFormat&3),e.push(248|r.bitDepthLumaMinus8&7),e.push(248|r.bitDepthChromaMinus8&7),e.push(r.sequenceParameterSetExt.length);for(const t of r.sequenceParameterSetExt){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(t[n])}}return new Uint8Array(e)},Yi=r=>{try{const e=Z(r);let t=0;const i=e.getUint8(t++),n=e.getUint8(t++),s=e.getUint8(t++),a=e.getUint8(t++),o=e.getUint8(t++)&3,c=e.getUint8(t++)&31,u=[];for(let h=0;h<c;h++){const p=e.getUint16(t,!1);t+=2,u.push(r.subarray(t,t+p)),t+=p}const l=e.getUint8(t++),d=[];for(let h=0;h<l;h++){const p=e.getUint16(t,!1);t+=2,d.push(r.subarray(t,t+p)),t+=p}const f={configurationVersion:i,avcProfileIndication:n,profileCompatibility:s,avcLevelIndication:a,lengthSizeMinusOne:o,sequenceParameterSets:u,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((n===100||n===110||n===122||n===144)&&t+4<=r.length){const h=e.getUint8(t++)&3,p=e.getUint8(t++)&7,m=e.getUint8(t++)&7,b=e.getUint8(t++);f.chromaFormat=h,f.bitDepthLumaMinus8=p,f.bitDepthChromaMinus8=m;const w=[];for(let S=0;S<b;S++){const A=e.getUint16(t,!1);t+=2,w.push(r.subarray(t,t+A)),t+=A}f.sequenceParameterSetExt=w}return f}catch(e){return j._error("Error deserializing AVC Decoder Configuration Record:",e),null}},Co={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}},dr=r=>{try{const e=Gi(r),t=new re(e);if(t.skipBits(1),t.skipBits(2),t.readBits(5)!==7)return null;const n=t.readAlignedByte(),s=t.readAlignedByte(),a=t.readAlignedByte();W(t);let o=1,c=0,u=0,l=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(o=W(t),o===3&&(l=t.readBits(1)),c=W(t),u=W(t),t.skipBits(1),t.readBits(1))){for(let G=0;G<(o!==3?8:12);G++)if(t.readBits(1)){const ae=G<6?16:64;let he=8,le=8;for(let ye=0;ye<ae;ye++){if(le!==0){const Ve=gt(t);le=(he+Ve+256)%256}he=le===0?he:le}}}W(t);const d=W(t);if(d===0)W(t);else if(d===1){t.skipBits(1),gt(t),gt(t);const V=W(t);for(let G=0;G<V;G++)gt(t)}W(t),t.skipBits(1);const f=W(t),h=W(t),p=16*(f+1),m=16*(h+1);let b=p,w=m;const S=t.readBits(1);if(S||t.skipBits(1),t.skipBits(1),t.readBits(1)){const V=W(t),G=W(t),J=W(t),ae=W(t);let he,le;if((l===0?o:0)===0)he=1,le=2-S;else{const Ve=o===3?1:2,et=o===1?2:1;he=Ve,le=et*(2-S)}b-=he*(V+G),w-=le*(J+ae)}if(b<=0||w<=0)return null;let T=2,k=2,x=2,P=0,I={num:1,den:1},E=null,C=null,_=null,D=null;const q=t.pos;if(t.readBits(1)){if(t.readBits(1)){const Ve=t.readBits(8);if(Ve===255)I={num:t.readBits(16),den:t.readBits(16)};else{const et=Co[Ve];et&&(I=et)}}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),P=t.readBits(1),t.readBits(1)&&(T=t.readBits(8),k=t.readBits(8),x=t.readBits(8))),t.readBits(1)&&(W(t),W(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));const le=t.readBits(1);le&&Zs(t);const ye=t.readBits(1);ye&&Zs(t),(le||ye)&&t.skipBits(1),t.skipBits(1),_=t.pos,D=t.readBits(1),D&&(t.skipBits(1),W(t),W(t),W(t),W(t),E=Math.min(W(t),16),C=Math.min(W(t),16))}if(E===null){y(C===null);const V=s&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&V)E=0,C=0;else{const G=f+1,J=h+1,ae=(2-S)*J,he=zi.find(ye=>ye.level>=a)??fe(zi),le=Math.min(Math.floor(he.maxDpbMbs/(G*ae)),16);E=le,C=le}}return y(C!==null),{emulationUnpreventedBytes:e,profileIdc:n,constraintFlags:s,levelIdc:a,frameMbsOnlyFlag:S,chromaFormatIdc:o,bitDepthLumaMinus8:c,bitDepthChromaMinus8:u,codedWidth:p,codedHeight:m,displayWidth:b,displayHeight:w,pixelAspectRatio:I,colourPrimaries:T,matrixCoefficients:x,transferCharacteristics:k,fullRangeFlag:P,numReorderFrames:E,maxDecFrameBuffering:C,vuiParametersFlagBitOffset:q,bitstreamRestrictionFlagBitOffset:_,bitstreamRestrictionFlag:D}}catch(e){return j._error("Error parsing AVC SPS:",e),null}},Zs=r=>{const e=W(r);r.skipBits(4),r.skipBits(4);for(let t=0;t<=e;t++)W(r),W(r),r.skipBits(1);r.skipBits(5),r.skipBits(5),r.skipBits(5),r.skipBits(5)},Js=r=>{y(r.bitstreamRestrictionFlag!==1);const e=new Uint8Array(r.emulationUnpreventedBytes.byteLength+64),t=new re(r.emulationUnpreventedBytes),i=new re(e);r.bitstreamRestrictionFlag===null?(i.copyBits(r.vuiParametersFlagBitOffset,t),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)):(y(r.bitstreamRestrictionFlagBitOffset!==null),i.copyBits(r.bitstreamRestrictionFlagBitOffset,t)),i.writeBits(1,1),i.writeBits(1,1),Kt(i,2),Kt(i,1),Kt(i,16),Kt(i,16),Kt(i,r.numReorderFrames),Kt(i,r.maxDecFrameBuffering),i.writeBits(1,1),i.writeBits((8-i.pos%8)%8,0);const n=i.pos/8;return y(Number.isInteger(n)),Nl(e.subarray(0,n))},Ul=(r,e)=>{if(e.description){const n=(ke(e.description)[21]&3)+1;return Po(r,n)}else return xo(r)},Ri=(r,e)=>{if(e.description){const n=(ke(e.description)[21]&3)+1;return Ao(r,n)}else return Qi(r)},fr=r=>r>>1&63,Zi=r=>{try{const e=new re(Gi(r));e.skipBits(16),e.readBits(4);const t=e.readBits(3),i=e.readBits(1),{general_profile_space:n,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:u}=Vl(e,t);W(e);const l=W(e);let d=0;l===3&&(d=e.readBits(1));const f=W(e),h=W(e);let p=f,m=h;if(e.readBits(1)){const D=W(e),q=W(e),M=W(e),V=W(e);let G=1,J=1;const ae=d===0?l:0;ae===1?(G=2,J=2):ae===2&&(G=2,J=1),p-=(D+q)*G,m-=(M+V)*J}if(p<=0||m<=0)return null;const b=W(e),w=W(e);W(e);const A=e.readBits(1)?0:t;let T=0;for(let D=A;D<=t;D++)W(e),T=W(e),W(e);W(e),W(e),W(e),W(e),W(e),W(e),e.readBits(1)&&e.readBits(1)&&Ll(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),W(e),W(e),e.skipBits(1));const k=W(e);if(Wl(e,k),e.readBits(1)){const D=W(e);for(let q=0;q<D;q++)W(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let x=2,P=2,I=2,E=0,C=0,_={num:1,den:1};if(e.readBits(1)){const D=Hl(e,t);_=D.pixelAspectRatio,x=D.colourPrimaries,P=D.transferCharacteristics,I=D.matrixCoefficients,E=D.fullRangeFlag,C=D.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,pixelAspectRatio:_,colourPrimaries:x,transferCharacteristics:P,matrixCoefficients:I,fullRangeFlag:E,maxDecFrameBuffering:Math.min(T+1,16),spsMaxSubLayersMinus1:t,spsTemporalIdNestingFlag:i,generalProfileSpace:n,generalTierFlag:s,generalProfileIdc:a,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:u,chromaFormatIdc:l,bitDepthLumaMinus8:b,bitDepthChromaMinus8:w,minSpatialSegmentationIdc:C}}catch(e){return j._error("Error parsing HEVC SPS:",e),null}},Ji=r=>{try{const e=[],t=[],i=[],n=[];for(const l of Qi(r)){const d=r.subarray(l.offset,l.offset+l.length),f=fr(d[0]);f===ge.VPS_NUT&&e.length<65535?e.push(d):f===ge.SPS_NUT&&t.length<65535?t.push(d):f===ge.PPS_NUT&&i.length<65535?i.push(d):(f===ge.PREFIX_SEI_NUT||f===ge.SUFFIX_SEI_NUT)&&n.length<65535&&n.push(d)}if(t.length===0||i.length===0)return null;const a=Zi(t[0]);if(!a)return null;let o=0;if(i.length>0){const l=i[0],d=new re(Gi(l));d.skipBits(16),W(d),W(d),d.skipBits(1),d.skipBits(1),d.skipBits(3),d.skipBits(1),d.skipBits(1),W(d),W(d),gt(d),d.skipBits(1),d.skipBits(1),d.readBits(1)&&W(d),gt(d),gt(d),d.skipBits(1),d.skipBits(1),d.skipBits(1),d.skipBits(1);const f=d.readBits(1),h=d.readBits(1);!f&&!h?o=0:f&&!h?o=2:!f&&h?o=3:o=0}const c=[...e.length?[{arrayCompleteness:1,nalUnitType:ge.VPS_NUT,nalUnits:e}]:[],...t.length?[{arrayCompleteness:1,nalUnitType:ge.SPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:ge.PPS_NUT,nalUnits:i}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:fr(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:a.generalProfileSpace,generalTierFlag:a.generalTierFlag,generalProfileIdc:a.generalProfileIdc,generalProfileCompatibilityFlags:a.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:a.generalConstraintIndicatorFlags,generalLevelIdc:a.generalLevelIdc,minSpatialSegmentationIdc:a.minSpatialSegmentationIdc,parallelismType:o,chromaFormatIdc:a.chromaFormatIdc,bitDepthLumaMinus8:a.bitDepthLumaMinus8,bitDepthChromaMinus8:a.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:a.spsMaxSubLayersMinus1+1,temporalIdNested:a.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:c}}catch(e){return j._error("Error building HEVC Decoder Configuration Record:",e),null}},Vl=(r,e)=>{const t=r.readBits(2),i=r.readBits(1),n=r.readBits(5);let s=0;for(let l=0;l<32;l++)s=s<<1|r.readBits(1);const a=new Uint8Array(6);for(let l=0;l<6;l++)a[l]=r.readBits(8);const o=r.readBits(8),c=[],u=[];for(let l=0;l<e;l++)c.push(r.readBits(1)),u.push(r.readBits(1));if(e>0)for(let l=e;l<8;l++)r.skipBits(2);for(let l=0;l<e;l++)c[l]&&r.skipBits(88),u[l]&&r.skipBits(8);return{general_profile_space:t,general_tier_flag:i,general_profile_idc:n,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:o}},Ll=r=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!r.readBits(1))W(r);else{const n=Math.min(64,1<<4+(e<<1));e>1&&gt(r);for(let s=0;s<n;s++)gt(r)}},Wl=(r,e)=>{const t=[];for(let i=0;i<e;i++)t[i]=ql(r,i,e,t)},ql=(r,e,t,i)=>{let n=0,s=0,a=0;if(e!==0&&(s=r.readBits(1)),s){if(e===t){const c=W(r);a=e-(c+1)}else a=e-1;r.readBits(1),W(r);const o=i[a]??0;for(let c=0;c<=o;c++)r.readBits(1)||r.readBits(1);n=i[a]}else{const o=W(r),c=W(r);for(let u=0;u<o;u++)W(r),r.readBits(1);for(let u=0;u<c;u++)W(r),r.readBits(1);n=o+c}return n},Hl=(r,e)=>{let t=2,i=2,n=2,s=0,a=0,o={num:1,den:1};if(r.readBits(1)){const c=r.readBits(8);if(c===255)o={num:r.readBits(16),den:r.readBits(16)};else{const u=Co[c];u&&(o=u)}}return r.readBits(1)&&r.readBits(1),r.readBits(1)&&(r.readBits(3),s=r.readBits(1),r.readBits(1)&&(t=r.readBits(8),i=r.readBits(8),n=r.readBits(8))),r.readBits(1)&&(W(r),W(r)),r.readBits(1),r.readBits(1),r.readBits(1),r.readBits(1)&&(W(r),W(r),W(r),W(r)),r.readBits(1)&&(r.readBits(32),r.readBits(32),r.readBits(1)&&W(r),r.readBits(1)&&jl(r,!0,e)),r.readBits(1)&&(r.readBits(1),r.readBits(1),r.readBits(1),a=W(r),W(r),W(r),W(r),W(r)),{pixelAspectRatio:o,colourPrimaries:t,transferCharacteristics:i,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},jl=(r,e,t)=>{let i=!1,n=!1,s=!1;i=r.readBits(1)===1,n=r.readBits(1)===1,(i||n)&&(s=r.readBits(1)===1,s&&(r.readBits(8),r.readBits(5),r.readBits(1),r.readBits(5)),r.readBits(4),r.readBits(4),s&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5));for(let a=0;a<=t;a++){const o=r.readBits(1)===1;let c=!0;o||(c=r.readBits(1)===1);let u=!1;c?W(r):u=r.readBits(1)===1;let l=1;u||(l=W(r)+1),i&&ea(r,l,s),n&&ea(r,l,s)}},ea=(r,e,t)=>{for(let i=0;i<e;i++)W(r),W(r),t&&(W(r),W(r)),r.readBits(1)},Mh=r=>{const e=[];e.push(r.configurationVersion),e.push((r.generalProfileSpace&3)<<6|(r.generalTierFlag&1)<<5|r.generalProfileIdc&31),e.push(r.generalProfileCompatibilityFlags>>>24&255),e.push(r.generalProfileCompatibilityFlags>>>16&255),e.push(r.generalProfileCompatibilityFlags>>>8&255),e.push(r.generalProfileCompatibilityFlags&255),e.push(...r.generalConstraintIndicatorFlags),e.push(r.generalLevelIdc&255),e.push(240|r.minSpatialSegmentationIdc>>8&15),e.push(r.minSpatialSegmentationIdc&255),e.push(252|r.parallelismType&3),e.push(252|r.chromaFormatIdc&3),e.push(248|r.bitDepthLumaMinus8&7),e.push(248|r.bitDepthChromaMinus8&7),e.push(r.avgFrameRate>>8&255),e.push(r.avgFrameRate&255),e.push((r.constantFrameRate&3)<<6|(r.numTemporalLayers&7)<<3|(r.temporalIdNested&1)<<2|r.lengthSizeMinusOne&3),e.push(r.arrays.length&255);for(const t of r.arrays){e.push((t.arrayCompleteness&1)<<7|0|t.nalUnitType&63),e.push(t.nalUnits.length>>8&255),e.push(t.nalUnits.length&255);for(const i of t.nalUnits){e.push(i.length>>8&255),e.push(i.length&255);for(let n=0;n<i.length;n++)e.push(i[n])}}return new Uint8Array(e)},Eo=r=>{try{const e=Z(r);let t=0;const i=e.getUint8(t++),n=e.getUint8(t++),s=n>>6&3,a=n>>5&1,o=n&31,c=e.getUint32(t,!1);t+=4;const u=r.subarray(t,t+6);t+=6;const l=e.getUint8(t++),d=(e.getUint8(t++)&15)<<8|e.getUint8(t++),f=e.getUint8(t++)&3,h=e.getUint8(t++)&3,p=e.getUint8(t++)&7,m=e.getUint8(t++)&7,b=e.getUint16(t,!1);t+=2;const w=e.getUint8(t++),S=w>>6&3,A=w>>3&7,T=w>>2&1,k=w&3,x=e.getUint8(t++),P=[];for(let I=0;I<x;I++){const E=e.getUint8(t++),C=E>>7&1,_=E&63,D=e.getUint16(t,!1);t+=2;const q=[];for(let M=0;M<D;M++){const V=e.getUint16(t,!1);t+=2,q.push(r.subarray(t,t+V)),t+=V}P.push({arrayCompleteness:C,nalUnitType:_,nalUnits:q})}return{configurationVersion:i,generalProfileSpace:s,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:u,generalLevelIdc:l,minSpatialSegmentationIdc:d,parallelismType:f,chromaFormatIdc:h,bitDepthLumaMinus8:p,bitDepthChromaMinus8:m,avgFrameRate:b,constantFrameRate:S,numTemporalLayers:A,temporalIdNested:T,lengthSizeMinusOne:k,arrays:P}}catch(e){return j._error("Error deserializing HEVC Decoder Configuration Record:",e),null}};var Re;(function(r){r[r.audAllowed=0]="audAllowed",r[r.beforeFirstVcl=1]="beforeFirstVcl",r[r.afterFirstVcl=2]="afterFirstVcl",r[r.eoBitstreamAllowed=3]="eoBitstreamAllowed",r[r.noMoreDataAllowed=4]="noMoreDataAllowed"})(Re||(Re={}));const Kl=(r,e)=>{const t=new Set;let i=Re.audAllowed;for(const s of Ri(r,e)){if(i===Re.noMoreDataAllowed){t.add(s.offset);continue}const a=fr(r[s.offset]);if(i===Re.eoBitstreamAllowed&&a!==37){t.add(s.offset);continue}let o=!1;a===35?i>Re.audAllowed?o=!0:i=Re.beforeFirstVcl:a<=31?i>Re.afterFirstVcl?o=!0:i=Re.afterFirstVcl:a===36?i!==Re.afterFirstVcl?o=!0:i=Re.eoBitstreamAllowed:a===37?i<Re.afterFirstVcl?o=!0:i=Re.noMoreDataAllowed:a===32||a===33||a===34||a===39||a>=41&&a<=44||a>=48&&a<=55?i>Re.beforeFirstVcl?o=!0:i=Re.beforeFirstVcl:(a===38||a===40||a>=45&&a<=47||a>=56&&a<=63)&&i<Re.afterFirstVcl&&(o=!0),o&&t.add(s.offset)}if(t.size===0)return null;const n=[];for(const s of Ri(r,e))t.has(s.offset)||n.push(r.subarray(s.offset,s.offset+s.length));return Ul(n,e)},Xl={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}},ks=r=>{const e=new re(r);if(e.readBits(2)!==2)return null;const i=e.readBits(1),s=(e.readBits(1)<<1)+i;if(s===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let u=8;s>=2&&(u=e.readBits(1)?12:10);const l=e.readBits(3);let d=0,f=0;if(l!==7)if(f=e.readBits(1),s===1||s===3){const I=e.readBits(1),E=e.readBits(1);d=!I&&!E?3:I&&!E?2:1,e.skipBits(1)}else d=1;else d=3,f=1;const h=e.readBits(16),p=e.readBits(16),m=h+1,b=p+1,w=m*b;let S=fe(Et).level;for(const P of Et)if(w<=P.maxPictureSize){S=P.level;break}const A=Xl[l],T=(A==null?void 0:A.colourPrimaries)??2,k=(A==null?void 0:A.transferCharacteristics)??2,x=(A==null?void 0:A.matrixCoefficients)??2;return{profile:s,level:S,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:T,transferCharacteristics:k,matrixCoefficients:x}},Ql=r=>r.colourPrimaries!==2||r.transferCharacteristics!==2||r.matrixCoefficients!==2,_o=function*(r){const e=new re(r),t=()=>{let i=0;for(let n=0;n<8;n++){const s=e.readAlignedByte();if(i+=(s&127)*2**(n*7),!(s&128))break;if(n===7&&s&128)return null}return i>2**32-1?null:i};for(;e.getBitsLeft()>=8;){e.skipBits(1);const i=e.readBits(4),n=e.readBits(1),s=e.readBits(1);e.skipBits(1),n&&e.skipBits(8);let a;if(s){const o=t();if(o===null)return;a=o}else a=Math.floor(e.getBitsLeft()/8);y(e.pos%8===0),yield{type:i,data:r.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},en=r=>{for(const{type:e,data:t}of _o(r)){if(e!==1)continue;const i=new re(t),n=i.readBits(3);i.readBits(1);const s=i.readBits(1);let a=0,o=0,c=0;if(s)a=i.readBits(5);else{const E=i.readBits(1);let C=0;if(E){if(i.skipBits(32),i.skipBits(32),i.readBits(1)){let M=0;for(;M<32&&!i.readBits(1);)M++;M<32&&i.skipBits(M)}C=i.readBits(1),C&&(c=i.readBits(5),i.skipBits(32),i.skipBits(5),i.skipBits(5))}const _=i.readBits(1),D=i.readBits(5);for(let q=0;q<=D;q++){i.skipBits(12);const M=i.readBits(5);if(q===0&&(a=M),M>7){const V=i.readBits(1);q===0&&(o=V)}if(C&&i.readBits(1)){const G=c+1;i.skipBits(G),i.skipBits(G),i.skipBits(1)}_&&i.readBits(1)&&i.skipBits(4)}}const u=i.readBits(4),l=i.readBits(4),d=u+1;i.skipBits(d);const f=l+1;i.skipBits(f);let h=0;if(s?h=0:h=i.readBits(1),h&&(i.skipBits(4),i.skipBits(3)),i.skipBits(1),i.skipBits(1),i.skipBits(1),!s){i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const E=i.readBits(1);E&&(i.skipBits(1),i.skipBits(1));const C=i.readBits(1);let _=0;C?_=2:_=i.readBits(1),_>0&&(i.readBits(1)||i.skipBits(1)),E&&i.skipBits(3)}i.skipBits(1),i.skipBits(1),i.skipBits(1);const p=i.readBits(1);let m=8;n===2&&p?m=i.readBits(1)?12:10:n<=2&&(m=p?10:8);let b=0;n!==1&&(b=i.readBits(1));let w=2,S=2,A=2;i.readBits(1)&&(w=i.readBits(8),S=i.readBits(8),A=i.readBits(8));let k=0,x=1,P=1,I=0;return b?k=i.readBits(1):w===1&&S===13&&A===0?(k=1,x=0,P=0):(k=i.readBits(1),n===0?(x=1,P=1):n===1?(x=0,P=0):m===12?(x=i.readBits(1),P=x?i.readBits(1):0):(x=1,P=0),x&&P&&(I=i.readBits(2))),{profile:n,level:a,tier:o,bitDepth:m,monochrome:b,chromaSubsamplingX:x,chromaSubsamplingY:P,chromaSamplePosition:I,videoFullRangeFlag:k,colourPrimaries:w,transferCharacteristics:S,matrixCoefficients:A}}return null},vo=r=>r.colourPrimaries!==2||r.transferCharacteristics!==2||r.matrixCoefficients!==2,Ro=r=>{if(r.length<36)return null;const t=Z(r);return t.getUint32(4)!==1768124518||t.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:t.getUint8(22),transferCharacteristics:t.getUint8(23),matrixCoefficients:t.getUint8(24)}},ys=r=>{if(r.byteLength<19)throw new Error("Invalid Opus identification header: too short.");const e=Z(r),t=e.getUint8(9),i=e.getUint16(10,!0),n=e.getUint32(12,!0),s=e.getInt16(16,!0),a=e.getUint8(18);let o=null;return a&&(o=r.subarray(19,21+t)),{outputChannelCount:t,preSkip:i,inputSampleRate:n,outputGain:s,channelMappingFamily:a,channelMappingTable:o}},Gl=[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],$l=r=>{const e=r[0]>>3,t=r[0]&3;let i;return t===0?i=1:t===1||t===2?i=2:i=r[1]&63,{durationInSamples:Gl[e]*i}},Yl=r=>{if(r.length<7)throw new Error("Setup header is too short.");if(r[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...r.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");const t=r.length,i=new Uint8Array(t);for(let d=0;d<t;d++)i[d]=r[t-1-d];const n=new re(i);let s=0;for(;n.getBitsLeft()>97;)if(n.readBits(1)===1){s=n.pos;break}if(s===0)throw new Error("Invalid Setup header: framing bit not found.");let a=0,o=!1,c=0;for(;n.getBitsLeft()>=97;){const d=n.pos,f=n.readBits(8),h=n.readBits(16),p=n.readBits(16);if(f>63||h!==0||p!==0){n.pos=d;break}if(n.skipBits(1),a++,a>64)break;n.clone().readBits(6)+1===a&&(o=!0,c=a)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);const u=c;n.pos=0,n.skipBits(s);const l=Array(u).fill(0);for(let d=u-1;d>=0;d--)n.skipBits(40),l[d]=n.readBits(1);return{modeBlockflags:l}},tn=(r,e,t)=>{switch(r){case"avc":{for(const i of To(t,e)){const n=t[i.offset],s=ri(n);if(s>=Ae.NON_IDR_SLICE&&s<=Ae.SLICE_DPC)return"delta";if(s===Ae.IDR)return"key";if(s===Ae.SEI&&!ki()){const a=t.subarray(i.offset,i.offset+i.length),o=Gi(a);let c=1;do{let u=0;for(;;){const f=o[c++];if(f===void 0||(u+=f,f<255))break}let l=0;for(;;){const f=o[c++];if(f===void 0||(l+=f,f<255))break}if(u===6){const f=new re(o);f.pos=8*c;let h=-1;try{h=W(f)}catch{}const p=f.readBits(1);if(h===0&&p===1)return"key"}c+=l}while(c<o.length-1)}}return"delta"}case"hevc":{for(const i of Ri(t,e)){const n=fr(t[i.offset]);if(n<ge.BLA_W_LP)return"delta";if(n<=ge.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{const i=new re(t);if(i.readBits(2)!==2)return null;const n=i.readBits(1);return(i.readBits(1)<<1)+n===3&&i.skipBits(1),i.readBits(1)?null:i.readBits(1)===0?"key":"delta"}case"av1":{let i=!1;for(const{type:n,data:s}of _o(t))if(n===1){const a=new re(s);a.skipBits(4),i=!!a.readBits(1)}else if(n===3||n===6||n===7){if(i)return"key";const a=new re(s);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}case"prores":return"key";default:ze(r),y(!1)}},Zl=(r,e)=>r==="truehd"?(e.byteLength>=8?Z(e).getUint32(4):null)===Dl?"key":"delta":"key";var or;(function(r){r[r.STREAMINFO=0]="STREAMINFO",r[r.VORBIS_COMMENT=4]="VORBIS_COMMENT",r[r.PICTURE=6]="PICTURE"})(or||(or={}));const Xn=(r,e)=>{var o,c;const t=Z(r);let i=0;if(r.length<4)return;const n=t.getUint32(i,!0);i+=4;const s=_e.decode(r.subarray(i,i+n));if(i+=n,n>0&&(e.raw??(e.raw={}),(o=e.raw).vendor??(o.vendor=s)),i+4>r.length)return;const a=t.getUint32(i,!0);i+=4;for(let u=0;u<a&&!(i+4>r.length);u++){const l=t.getUint32(i,!0);i+=4;const d=_e.decode(r.subarray(i,i+l));i+=l;const f=d.indexOf("=");if(f===-1)continue;const h=d.slice(0,f).toUpperCase(),p=d.slice(f+1);switch(e.raw??(e.raw={}),Array.isArray(e.raw[h])?e.raw[h].push(p):typeof e.raw[h]=="string"?e.raw[h]=[e.raw[h],p]:(c=e.raw)[h]??(c[h]=p),h){case"TITLE":e.title??(e.title=p);break;case"DESCRIPTION":e.description??(e.description=p);break;case"ARTIST":e.artist??(e.artist=p);break;case"ALBUM":e.album??(e.album=p);break;case"ALBUMARTIST":e.albumArtist??(e.albumArtist=p);break;case"COMMENT":e.comment??(e.comment=p);break;case"LYRICS":e.lyrics??(e.lyrics=p);break;case"TRACKNUMBER":{const m=p.split("/"),b=Number.parseInt(m[0],10),w=m[1]&&Number.parseInt(m[1],10);Number.isInteger(b)&&b>0&&(e.trackNumber??(e.trackNumber=b)),w&&Number.isInteger(w)&&w>0&&(e.tracksTotal??(e.tracksTotal=w))}break;case"TRACKTOTAL":{const m=Number.parseInt(p,10);Number.isInteger(m)&&m>0&&(e.tracksTotal??(e.tracksTotal=m))}break;case"DISCNUMBER":{const m=p.split("/"),b=Number.parseInt(m[0],10),w=m[1]&&Number.parseInt(m[1],10);Number.isInteger(b)&&b>0&&(e.discNumber??(e.discNumber=b)),w&&Number.isInteger(w)&&w>0&&(e.discsTotal??(e.discsTotal=w))}break;case"DISCTOTAL":{const m=Number.parseInt(p,10);Number.isInteger(m)&&m>0&&(e.discsTotal??(e.discsTotal=m))}break;case"DATE":{const m=new Date(p);Number.isNaN(m.getTime())||(e.date??(e.date=m))}break;case"BPM":{const m=Number.parseInt(p,10);Number.isInteger(m)&&m>0&&(e.beatsPerMinute??(e.beatsPerMinute=m))}break;case"GENRE":e.genre??(e.genre=p);break;case"METADATA_BLOCK_PICTURE":try{const m=vi(p),b=Z(m),w=b.getUint32(0,!1),S=b.getUint32(4,!1),A=_e.decode(m.subarray(8,8+S)),T=b.getUint32(8+S,!1),k=_e.decode(m.subarray(12+S,12+S+T)),x=b.getUint32(S+T+28),P=m.subarray(S+T+32,S+T+32+x);e.images??(e.images=[]),e.images.push({data:P,mimeType:A,kind:w===3?"coverFront":w===4?"coverBack":"unknown",name:void 0,description:k||void 0})}catch{}break}}},Oh=(r,e,t)=>{const i=[r],n=Ye.encode(Ol);let s=new Uint8Array(4+n.length),a=new DataView(s.buffer);a.setUint32(0,n.length,!0),s.set(n,4),i.push(s);const o=[],c=(h,p)=>{const m=`${h}=${p}`,b=Ye.encode(m);s=new Uint8Array(4+b.length),a=new DataView(s.buffer),a.setUint32(0,b.length,!0),s.set(b,4),i.push(s),o.push(h)};for(const{key:h,value:p}of mo(e))switch(h){case"title":c("TITLE",p);break;case"description":c("DESCRIPTION",p);break;case"artist":c("ARTIST",p);break;case"album":c("ALBUM",p);break;case"albumArtist":c("ALBUMARTIST",p);break;case"genre":c("GENRE",p);break;case"date":c("DATE",p.toISOString().slice(0,10));break;case"comment":c("COMMENT",p);break;case"lyrics":c("LYRICS",p);break;case"trackNumber":c("TRACKNUMBER",p.toString());break;case"tracksTotal":c("TRACKTOTAL",p.toString());break;case"discNumber":c("DISCNUMBER",p.toString());break;case"discsTotal":c("DISCTOTAL",p.toString());break;case"beatsPerMinute":c("BPM",p.toString());break;case"images":{if(!t)break;for(const m of p){const b=m.kind==="coverFront"?3:m.kind==="coverBack"?4:0,w=new Uint8Array(m.mimeType.length);for(let x=0;x<m.mimeType.length;x++)w[x]=m.mimeType.charCodeAt(x);const S=Ye.encode(m.description??""),A=new Uint8Array(8+w.length+4+S.length+16+4+m.data.length),T=Z(A);T.setUint32(0,b,!1),T.setUint32(4,w.length,!1),A.set(w,8),T.setUint32(8+w.length,S.length,!1),A.set(S,12+w.length),T.setUint32(28+w.length+S.length,m.data.length,!1),A.set(m.data,32+w.length+S.length);const k=wl(A);c("METADATA_BLOCK_PICTURE",k)}}break;case"raw":break;case"creationTime":break;default:ze(h)}if(e.raw)for(const h in e.raw){const p=e.raw[h]??e.raw[h.toLowerCase()];if(!(h==="vendor"||p==null||o.includes(h))){if(typeof p=="string")c(h,p);else if(Array.isArray(p)&&p.every(b=>typeof b=="string"))for(const b of p)c(h,b)}}const u=new Uint8Array(4);Z(u).setUint32(0,o.length,!0),i.splice(2,0,u);const l=i.reduce((h,p)=>h+p.length,0),d=new Uint8Array(l);let f=0;for(const h of i)d.set(h,f),f+=h.length;return d},Ss=[2,1,2,3,3,4,4,5],Jl=r=>{if(r.length<7||r[0]!==11||r[1]!==119)return null;const e=new re(r);e.skipBits(16),e.skipBits(16);const t=e.readBits(2);if(t===3)return null;const i=e.readBits(6),n=e.readBits(5);if(n>8)return null;const s=e.readBits(3),a=e.readBits(3);(a&1)!==0&&a!==1&&e.skipBits(2),(a&4)!==0&&e.skipBits(2),a===2&&e.skipBits(2);const o=e.readBits(1),c=Math.floor(i/2);return{fscod:t,bsid:n,bsmod:s,acmod:a,lfeon:o,bitRateCode:c}},eu=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,288*2,384,418,288*2,448,486,336*2,448,488,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],tu=1536,Nh=new Uint8Array([5,4,65,67,45,51]),zh=new Uint8Array([5,4,69,65,67,51]),Bo=[1,2,3,6],ru=r=>{if(r.length<6||r[0]!==11||r[1]!==119)return null;const e=new re(r);e.skipBits(16);const t=e.readBits(2);if(e.skipBits(3),t!==0&&t!==2)return null;const i=e.readBits(11),n=e.readBits(2);let s=0,a;n===3?(s=e.readBits(2),a=3):a=e.readBits(2);const o=e.readBits(3),c=e.readBits(1),u=e.readBits(5);if(u<11||u>16)return null;const l=Bo[a];let d;return n<3?d=Xi[n]/1e3:d=So[s]/1e3,{dataRate:Math.round((i+1)*d/(l*16)),substreams:[{fscod:n,fscod2:s,bsid:u,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},iu=r=>{if(r.length<2)return null;const e=new re(r),t=e.readBits(13),i=e.readBits(3),n=[];for(let s=0;s<=i&&!(Math.ceil(e.pos/8)+3>r.length);s++){const a=e.readBits(2),o=e.readBits(5);e.skipBits(1),e.skipBits(1);const c=e.readBits(3),u=e.readBits(3),l=e.readBits(1);e.skipBits(3);const d=e.readBits(4);let f=0;d>0?f=e.readBits(9):e.skipBits(1),n.push({fscod:a,fscod2:null,bsid:o,bsmod:c,acmod:u,lfeon:l,numDepSub:d,chanLoc:f})}return n.length===0?null:{dataRate:t,substreams:n}},Fo=r=>{const e=r.substreams[0];return y(e),e.fscod<3?Xi[e.fscod]:e.fscod2!==null&&e.fscod2<3?So[e.fscod2]:null},Do=r=>{const e=r.substreams[0];y(e);let t=Ss[e.acmod]+e.lfeon;if(e.numDepSub>0){const i=[2,2,1,1,2,2,2,1,1];for(let n=0;n<9;n++)e.chanLoc&1<<8-n&&(t+=i[n])}return t},nu=1683496997,yi=18,Qn=10,su=4096,ta=32,As=20,au=8,ou=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],cu=[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],lu=[16,16,20,20,0,24,24,0],Bi=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],uu=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],du=8,fu=44646,hu=[32e3,44100,48e3,0],mu=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Mo=[512,1024,2048,4096],Oo=r=>{const e=zo(r),t=Z(r);let i=e?Math.ceil(e.frameSize/4)*4:0,n=null;for(;i+4<=r.length&&t.getUint32(i)===nu;){const a=Si(r.subarray(i));if(!a)break;n??(n=a),i+=a.frameSize}if(e)return{frameSize:n?i:e.frameSize,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,sampleCount:e.sampleCount,channelLayout:e.channelLayout,pcmResolution:e.pcmResolution,bitRate:e.bitRate,core:e,hasExtensions:n!==null};if(!(n!=null&&n.asset))return null;const{asset:s}=n;return{frameSize:i,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels,sampleCount:s.sampleCount,channelLayout:s.channelLayout,pcmResolution:s.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},No=r=>{const e=Oo(r);return e!=null&&e.core?e.hasExtensions?"dtsh":"dtsc":null},zo=r=>{if(r.length<yi||r[0]!==127||r[1]!==254||r[2]!==128||r[3]!==1)return null;const e=new re(r);if(e.skipBits(32),e.skipBits(1),e.readBits(5)!==ta-1)return null;const t=e.readBits(1),i=e.readBits(7)+1;if(i%au!==0)return null;const n=e.readBits(14)+1;if(n<96)return null;const s=e.readBits(6);if(s>=Bi.length)return null;const a=ou[e.readBits(4)];if(a===0)return null;const o=cu[e.readBits(5)];if(e.readBits(1)!==0)return null;e.skipBits(4),e.skipBits(5);const c=e.readBits(2);if(c===3)return null;e.skipBits(1),t&&e.skipBits(16),e.skipBits(7);const u=lu[e.readBits(3)];if(u===0)return null;const l=c!==0;return{frameSize:n,sampleRate:a,numberOfChannels:Bi[s]+(l?1:0),sampleCount:i*ta,channelLayout:uu[s]|(l?du:0),amode:s,lfePresent:l,bitRate:o,pcmResolution:u}},Si=r=>{if(r.length<Qn||r[0]!==100||r[1]!==88||r[2]!==32||r[3]!==37)return null;const e=new re(r);e.skipBits(32),e.skipBits(8);const t=e.readBits(2),i=e.readBits(1),n=8+4*i,s=16+4*i;e.skipBits(n);const a=e.readBits(s)+1,o={frameSize:a,asset:null};if(!e.readBits(1))return o;const c=hu[e.readBits(2)],u=512*(e.readBits(3)+1);e.readBits(1)&&e.skipBits(36);const l=e.readBits(3)+1,d=e.readBits(3)+1,f=[];for(let w=0;w<l;w++)f.push(e.readBits(t+1));for(const w of f)e.skipBits(8*Ln(w));if(e.readBits(1)){e.skipBits(2);const w=e.readBits(2)+1<<2,S=e.readBits(2)+1;e.skipBits(S*w)}for(let w=0;w<d;w++)e.skipBits(s);e.skipBits(9),e.skipBits(3),e.readBits(1)&&e.skipBits(4),e.readBits(1)&&e.skipBits(24),e.readBits(1)&&e.skipBits(8*(e.readBits(10)+1));const h=e.readBits(5)+1,p=mu[e.readBits(4)],m=e.readBits(8)+1;let b=0;if(e.readBits(1)&&(m>2&&e.skipBits(1),m>6&&e.skipBits(1),e.readBits(1))){const w=e.readBits(2)+1<<2;b=e.readBits(w)}return c===0||e.getBitsLeft()<0?o:{frameSize:a,asset:{sampleRate:p,numberOfChannels:m,sampleCount:Math.round(u*p/c),channelLayout:b,pcmResolution:h}}},pu=r=>{if(r.length<As)return null;const e=Z(r),t=e.getUint32(0);if(t===0)return null;const i=new re(r);i.seekToByte(13);const n=i.readBits(2);i.skipBits(5);const s=i.readBits(1),a=i.readBits(6);i.skipBits(14),i.skipBits(1),i.skipBits(3);const o=i.readBits(16);let c=null;return o!==0?c=gu(o):a<Bi.length&&(c=Bi[a]+s),{sampleRate:t,maxBitrate:e.getUint32(4),avgBitrate:e.getUint32(8),pcmSampleDepth:r[12],sampleCount:Mo[n],channelLayout:o,numberOfChannels:c}},Uh=r=>{var s,a;const e=new Uint8Array(As),t=Z(e);t.setUint32(0,r.sampleRate),t.setUint32(4,r.bitRate),t.setUint32(8,r.bitRate),e[12]=r.pcmResolution;const i=r.core&&!r.hasExtensions?1:0,n=new re(e);return n.seekToByte(13),n.writeBits(2,Math.max(Mo.indexOf(r.sampleCount),0)),n.writeBits(5,i),n.writeBits(1,(s=r.core)!=null&&s.lfePresent?1:0),n.writeBits(6,((a=r.core)==null?void 0:a.amode)??0),n.writeBits(14,r.core?r.core.frameSize-1:0),n.writeBits(1,0),n.writeBits(3,0),n.writeBits(16,r.channelLayout),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(5,0),e},gu=r=>Ln(r)+Ln(r&fu);/*!
62
+ * Copyright (c) 2026-present, Vanilagy and contributors
63
+ *
64
+ * This Source Code Form is subject to the terms of the Mozilla Public
65
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
66
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
67
+ */const Fr=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,bu=/^WEBVTT(.|\n)*?\n{2}/,Vh=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;class wu{constructor(e){this.preambleText=null,this.preambleEmitted=!1,this.options=e}parse(e){e=e.replaceAll(`\r
68
+ `,`
69
+ `).replaceAll("\r",`
70
+ `),Fr.lastIndex=0;let t;if(!this.preambleText){if(!bu.test(e))throw new Error("WebVTT preamble incorrect.");t=Fr.exec(e);const i=e.slice(0,(t==null?void 0:t.index)??e.length).trimEnd();if(!i)throw new Error("No WebVTT preamble provided.");this.preambleText=i,t&&(e=e.slice(t.index),Fr.lastIndex=0)}for(;t=Fr.exec(e);){const i=e.slice(0,t.index),n=t[1],s=t.index+t[0].length,a=e.indexOf(`
71
+ `,s)+1,o=e.slice(s,a).trim();let c=e.indexOf(`
72
+
73
+ `,s);c===-1&&(c=e.length);const u=ra(t[2]),d=ra(t[3])-u,f=e.slice(a,c).trim();e=e.slice(c).trimStart(),Fr.lastIndex=0;const h={timestamp:u/1e3,duration:d/1e3,text:f,identifier:n,settings:o,notes:i},p={};this.preambleEmitted||(p.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(h,p)}}}const ku=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,ra=r=>{const e=ku.exec(r);if(!e)throw new Error("Expected match.");return 3600*1e3*Number(e[1]||"0")+60*1e3*Number(e[2])+1e3*Number(e[3])+Number(e[4])},Lh=r=>{const e=Math.floor(r/36e5),t=Math.floor(r%(3600*1e3)/(60*1e3)),i=Math.floor(r%(60*1e3)/1e3),n=r%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")};/*!
74
+ * Copyright (c) 2026-present, Vanilagy and contributors
75
+ *
76
+ * This Source Code Form is subject to the terms of the Mozilla Public
77
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
78
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
79
+ */const yu=r=>{let i=r>>2,n=4096,s=0,a=12,o=0;for(i<0&&(i=-i,s=128),i+=33,i>8191&&(i=8191);(i&n)!==n&&a>=5;)n>>=1,a--;return o=i>>a-4&15,~(s|a-5<<4|o)&255},Su=r=>{let t=0,i=0,n=~r;n&128&&(n&=-129,t=-1),i=((n&240)>>4)+5;const s=(1<<i|(n&15)<<i-4|1<<i-5)-33;return(t===0?s:-s)<<2},Au=r=>{let t=2048,i=0,n=11,s=0,a=r>>3;for(a<0?a=-a-1:i=128,a>4095&&(a=4095);(a&t)!==t&&n>=5;)t>>=1,n--;return s=a>>(n===4?1:n-4)&15,(i|n-4<<4|s)^85},Tu=r=>{let e=0,t=0,i=r^85;i&128&&(i&=-129,e=-1),t=((i&240)>>4)+4;let n=0;return t!==4?n=1<<t|(i&15)<<t-4|1<<t-5:n=i<<1|1,(e===0?-n:n)<<3};/*!
80
+ * Copyright (c) 2026-present, Vanilagy and contributors
81
+ *
82
+ * This Source Code Form is subject to the terms of the Mozilla Public
83
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
84
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
85
+ */const Gn=new Map,$n=new Map,xu=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.codec!==void 0&&typeof e.codec!="string")throw new TypeError("options.codec, when provided, must be a string.");if(e.codec!==void 0&&Je(e.codec)!==r)throw new TypeError(`options.codec, when provided, must match the specified codec (${r}).`);if(e.codedWidth!==void 0&&(!Number.isInteger(e.codedWidth)||e.codedWidth<=0))throw new TypeError("options.codedWidth, when provided, must be a positive integer.");if(e.codedHeight!==void 0&&(!Number.isInteger(e.codedHeight)||e.codedHeight<=0))throw new TypeError("options.codedHeight, when provided, must be a positive integer.");if(e.displayAspectWidth!==void 0&&(!Number.isInteger(e.displayAspectWidth)||e.displayAspectWidth<=0))throw new TypeError("options.displayAspectWidth, when provided, must be a positive integer.");if(e.displayAspectHeight!==void 0&&(!Number.isInteger(e.displayAspectHeight)||e.displayAspectHeight<=0))throw new TypeError("options.displayAspectHeight, when provided, must be a positive integer.");if(e.description!==void 0&&!hr(e.description))throw new TypeError("options.description, when provided, must be a buffer source.");if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("options.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.optimizeForLatency!==void 0&&typeof e.optimizeForLatency!="boolean")throw new TypeError("options.optimizeForLatency, when provided, must be a boolean.")},Pu=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.codec!==void 0&&typeof e.codec!="string")throw new TypeError("options.codec, when provided, must be a string.");if(e.codec!==void 0&&Je(e.codec)!==r)throw new TypeError(`options.codec, when provided, must match the specified codec (${r}).`);if(e.numberOfChannels!==void 0&&(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels<=0))throw new TypeError("options.numberOfChannels, when provided, must be a positive integer.");if(e.sampleRate!==void 0&&(!Number.isInteger(e.sampleRate)||e.sampleRate<=0))throw new TypeError("options.sampleRate, when provided, must be a positive integer.");if(e.description!==void 0&&!hr(e.description))throw new TypeError("options.description, when provided, must be a buffer source.")},Wh=r=>Qe.includes(r)?Uo(r):Ge.includes(r)?Vo(r):!1,Uo=async(r,e={})=>{if(!Qe.includes(r))return!1;xu(r,e);const t={...e,codedWidth:e.codedWidth??1280,codedHeight:e.codedHeight??720,codec:e.codec??Kc(r,1280,720,1e6,!1)};t.description??(t.description=ah());const i=JSON.stringify(t),n=Gn.get(i);if(n)return n;const s=(async()=>ii.some(o=>o.supports(r,t))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(t)).supported===!0)();return Gn.set(i,s),s},Vo=async(r,e={})=>{if(!Ge.includes(r))return!1;Pu(r,e);const t={...e,numberOfChannels:e.numberOfChannels??2,sampleRate:e.sampleRate??48e3,codec:e.codec??Qc(r,2,48e3)};if(t.description===void 0){const a=oh(t);if(a===!1)return!1;t.description=a}const i=JSON.stringify(t),n=$n.get(i);if(n)return n;const s=(async()=>ni.some(o=>o.supports(r,t))||Me.includes(r)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(t)).supported===!0)();return $n.set(i,s),s},qh=async()=>{const[r,e]=await Promise.all([Iu(),Cu()]);return[...r,...e]},Iu=async(r=Qe,e)=>{const t=await Promise.all(r.map(i=>Uo(i,e)));return r.filter((i,n)=>t[n])},Cu=async(r=Ge,e)=>{const t=await Promise.all(r.map(i=>Vo(i,e)));return r.filter((i,n)=>t[n])};/*!
86
+ * Copyright (c) 2026-present, Vanilagy and contributors
87
+ *
88
+ * This Source Code Form is subject to the terms of the Mozilla Public
89
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
90
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
91
+ */var Eu=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,n;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],t&&(n=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");n&&(i=function(){try{n.call(this)}catch(s){return Promise.reject(s)}}),r.stack.push({value:e,dispose:i,async:t})}else t&&r.stack.push({async:!0});return e},_u=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var i,n=0;function s(){for(;i=e.stack.pop();)try{if(!i.async&&n===1)return n=0,e.stack.push(i),Promise.resolve().then(s);if(i.dispose){var a=i.dispose.call(i.value);if(i.async)return n|=2,Promise.resolve(a).then(s,function(o){return t(o),s()})}else n|=1}catch(o){t(o)}if(n===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=r,i.suppressed=e,i});ms();let ia=-1/0,na=-1/0,qe=null;typeof FinalizationRegistry<"u"&&(qe=new FinalizationRegistry(r=>{const e=performance.now();r.type==="video"?(e-ia>=1e3&&(j._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."),ia=e),typeof VideoFrame<"u"&&r.data instanceof VideoFrame&&r.data.close()):(e-na>=1e3&&(j._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."),na=e),typeof AudioData<"u"&&r.data instanceof AudioData&&r.data.close())}));class Rt{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Yn=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],vu=new Set(Yn);class Ie{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(It*this.timestamp)}get microsecondDuration(){return Math.trunc(It*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){var i,n,s,a,o,c,u,l;if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.format===void 0||!vu.has(t.format))throw new TypeError("init.format must be one of: "+Yn.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const h of t.layout){if(!h||typeof h!="object"||Array.isArray(h))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(h.offset)||h.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(h.stride)||h.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.visibleRect!==void 0&&kn(t.visibleRect,"init.visibleRect"),t.displayWidth!==void 0&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(t.displayHeight!==void 0&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(t.displayWidth!==void 0!=(t.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=t.format,this.rotation=t.rotation??0,this.flip=t.flip??!1,this.timestamp=t.timestamp,this.duration=t.duration??0;const d=t.layout??Bu(t.format,t.codedWidth,t.codedHeight);let f=t.colorSpace??null;f===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?f={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:f={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:((i=t.visibleRect)==null?void 0:i.left)??0,top:((n=t.visibleRect)==null?void 0:n.top)??0,width:((s=t.visibleRect)==null?void 0:s.width)??t.codedWidth,height:((a=t.visibleRect)==null?void 0:a.height)??t.codedHeight},t.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=t._doNotCopy?ke(e):ke(e).slice(),this._layout=d,this.colorSpace=new Tn(f)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if((t==null?void 0:t.rotation)!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if((t==null?void 0:t.flip)!==void 0&&typeof t.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if((t==null?void 0:t.timestamp)!==void 0&&!Number.isFinite(t==null?void 0:t.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if((t==null?void 0:t.duration)!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");(t==null?void 0:t.visibleRect)!==void 0&&kn(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:((o=e.visibleRect)==null?void 0:o.x)??0,top:((c=e.visibleRect)==null?void 0:c.y)??0,width:((u=e.visibleRect)==null?void 0:u.width)??e.codedWidth,height:((l=e.visibleRect)==null?void 0:l.height)??e.codedHeight},this.rotation=(t==null?void 0:t.rotation)??0,this.flip=(t==null?void 0:t.flip)??!1,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=(t==null?void 0:t.timestamp)??e.timestamp/1e6,this.duration=(t==null?void 0:t.duration)??(e.duration??0)/1e6;const{primaries:d,transfer:f,matrix:h,fullRange:p}=e.colorSpace;this.colorSpace=new Tn({primaries:d!==null&&d in li?d:null,transfer:f!==null&&f in ui?f:null,matrix:h!==null&&h in di?h:null,fullRange:p})}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(t.visibleRect!==void 0&&kn(t.visibleRect,"init.visibleRect"),typeof VideoFrame<"u")return new Ie(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*It),duration:Math.trunc((t.duration??0)*It)||void 0,visibleRect:t.visibleRect&&{x:t.visibleRect.left,y:t.visibleRect.top,width:t.visibleRect.width,height:t.visibleRect.height}}),t);let d=0,f=0;if("naturalWidth"in e?(d=e.naturalWidth,f=e.naturalHeight):"videoWidth"in e?(d=e.videoWidth,f=e.videoHeight):"width"in e&&(d=Number(e.width),f=Number(e.height)),!d||!f)throw new TypeError("Could not determine dimensions.");const h=t.visibleRect??{left:0,top:0,width:d,height:f},p=new OffscreenCanvas(h.width,h.height),m=p.getContext("2d",{alpha:Wt(),willReadFrequently:!0});if(!m)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");m.drawImage(e,-h.left,-h.top),this._data=p,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:h.width,height:h.height},this.squarePixelWidth=h.width,this.squarePixelHeight=h.height,this.rotation=t.rotation??0,this.flip=t.flip??!1,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new Tn({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof Rt){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),this.format!==null&&!Yn.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=t.rotation??0,this.flip=t.flip??!1,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=e.getColorSpace()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=(t==null?void 0:t.encodeOptions)??{},this.pixelAspectRatio=ps({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),qe==null||qe.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return y(this._data!==null),this._data instanceof Rt?new Ie(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):Mr(this._data)?new Ie(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(y(this._layout),new Ie(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 Ie(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||(qe==null||qe.unregister(this),this._data instanceof Rt?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Mr(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(oa(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return Mr(this._data)?this._data.allocationSize(e):ca(this,e).allocationSize}async copyTo(e,t={}){if(!hr(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(oa(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(y(this._data!==null),Mr(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format))if(this._data instanceof Rt){const u={stack:[],error:void 0,hasError:!1};try{const l=Eu(u,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip},t.colorSpace??"srgb"),!1);if(!(l instanceof Ie))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(l.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${l.format}' instead.`);return await l.copyTo(e,t)}catch(l){u.error=l,u.hasError=!0}finally{_u(u)}}else{if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const u=this.toVideoFrame(),l=await u.copyTo(e,t);return u.close(),l}const i=ca(this,t);y(this.format);const n=ke(e);if(n.byteLength<i.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${i.allocationSize}, Available: ${n.byteLength}`);const s=rn(this.format);let a;if(this._data instanceof Rt){let u=this._data.getDataPlanes();if(F(u)&&(u=await u),!Array.isArray(u)||u.some(l=>!(l.data instanceof Uint8Array)||!Number.isInteger(l.stride)||l.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');a=u}else if(this._data instanceof Uint8Array)y(this._layout),y(this._layout.length===s.length),a=this._layout.map((u,l)=>{const d=Math.ceil(this.codedHeight/s[l].heightDivisor);return{data:this._data.subarray(u.offset,u.offset+u.stride*d),stride:u.stride}});else{const l=this._data.getContext("2d");y(l);const d=l.getImageData(0,0,this.codedWidth,this.codedHeight);a=[{data:ke(d.data),stride:4*this.codedWidth}]}const o=[],c=s.length;for(let u=0;u<c;u++){const l=i.computedLayouts[u],d=a[u].stride,f=a[u].data;let h=l.sourceTop*d;h+=l.sourceLeftBytes;let p=l.destinationOffset;const m=l.sourceWidthBytes,b={offset:p,stride:l.destinationStride};for(let w=0;w<l.sourceHeight;w++){if(h+m>f.byteLength)throw new Error("Source buffer OOB read.");if(p+m>n.byteLength)throw new Error("Destination buffer OOB write.");const S=f.subarray(h,h+m);n.set(S,p),h+=d,p+=l.destinationStride}o.push(b)}if(t.format!==void 0){const u=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),l=this.format.includes("X")&&t.format.includes("A");if(u||l)for(let d=0;d<i.allocationSize;d+=4){if(u){const f=n[d],h=n[d+2];n[d]=h,n[d+2]=f}l&&(n[d+3]=255)}}return o}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(y(this._data!==null),this._data instanceof Rt){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const e=this._data.getDataPlanes();if(F(e))throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");const t=e.reduce((a,o)=>a+o.data.byteLength,0),i=new Uint8Array(t);let n=0;const s=[];for(const a of e)i.set(a.data,n),s.push(n),n+=a.data.byteLength;return new VideoFrame(i,{format:this.format,layout:e.map((a,o)=>({offset:s[o],stride:a.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return Mr(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(y(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,n,s,a,o,c,u){let l=0,d=0,f=this.displayWidth,h=this.displayHeight,p=0,m=0,b=this.displayWidth,w=this.displayHeight;if(a!==void 0?(l=t,d=i,f=n,h=s,p=a,m=o,c!==void 0?(b=c,w=u):(b=f,w=h)):(p=t,m=i,n!==void 0&&(b=n,w=s)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(b)||b<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(w)||w<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:d,sWidth:f,sHeight:h}=this._unmapSourceRegion(l,d,f,h,this.rotation,this.flip));const S=this.toCanvasImageSource();e.save();const A=p+b/2,T=m+w/2;e.translate(A,T),this.flip&&e.scale(-1,1),e.rotate(this.rotation*Math.PI/180);const k=this.rotation%180===0?1:b/w;e.scale(1/k,k),e.drawImage(S,l,d,f,h,-b/2,-w/2,b,w),e.restore()}drawWithFit(e,t){var A,T,k,x;if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");if(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");t.crop!==void 0&&Fi(t.crop,"options.");const i=e.canvas.width,n=e.canvas.height,s=t.rotation??this.rotation,a=t.flip??this.flip,[o,c]=s%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let u=t.crop;u&&(u=Jn(u,o,c));let l,d,f,h;const{sx:p,sy:m,sWidth:b,sHeight:w}=this._unmapSourceRegion(((A=t.crop)==null?void 0:A.left)??0,((T=t.crop)==null?void 0:T.top)??0,((k=t.crop)==null?void 0:k.width)??o,((x=t.crop)==null?void 0:x.height)??c,s,a);if(t.fit==="fill")l=0,d=0,f=i,h=n;else{const[P,I]=t.crop?[t.crop.width,t.crop.height]:[o,c],E=t.fit==="contain"?Math.min(i/P,n/I):Math.max(i/P,n/I);f=P*E,h=I*E,l=(i-f)/2,d=(n-h)/2}e.save();const S=s%180===0?1:f/h;e.translate(i/2,n/2),a&&e.scale(-1,1),e.rotate(s*Math.PI/180),e.scale(1/S,S),e.translate(-i/2,-n/2),e.drawImage(this.toCanvasImageSource(),p,m,b,w,l,d,f,h),e.restore()}_unmapSourceRegion(e,t,i,n,s,a){return a&&(e=(s%180===0?this.squarePixelWidth:this.squarePixelHeight)-e-i),s===90?[e,t,i,n]=[t,this.squarePixelHeight-e-i,n,i]:s===180?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-n]:s===270&&([e,t,i,n]=[this.squarePixelWidth-t-n,e,n,i]),{sx:e,sy:t,sWidth:i,sHeight:n}}_drawWithFitAndMipmapping(e,t,i){const n=e.width,s=e.height,[a,o]=i.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],c=i.crop?i.crop.width:a,u=i.crop?i.crop.height:o;let l=0;2*n<c&&2*s<u&&(l=Math.floor(Math.log2(Math.min(c/n,u/s))));const d=n*2**l,f=s*2**l,{canvas:h,context:p,isNew:m}=l>0?aa(d,f):{canvas:e,context:t,isNew:i.targetIsFresh};p.imageSmoothingQuality="high",i.fillBlack?(p.fillStyle="black",p.fillRect(0,0,d,f)):m||p.clearRect(0,0,d,f),this.drawWithFit(p,{fit:i.fit,rotation:i.rotation,flip:i.flip,crop:i.crop}),p.globalCompositeOperation="copy";for(let b=l;b>1;b--){const w=n*2**b,S=s*2**b;p.drawImage(h,0,0,w,S,0,0,w/2,S/2)}p.globalCompositeOperation="source-over",l>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(h,0,0,2*n,2*s,0,0,n,s),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(y(this._data!==null),this._data instanceof Rt||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}async transform(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(e.roundDimensionsTo!==void 0&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(e.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.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 new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(e.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");if(e.crop!==void 0&&Fi(e.crop,"options."),e.alpha!==void 0&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const{rotation:t,flip:i}=rl(this.rotation,this.flip,e.rotate??0,e.flip??!1),[n,s]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let a=e.crop;a&&(a=Jn(a,n,s));const o=a?a.width:n,c=a?a.height:s,u=o/c;let l,d;e.width!==void 0&&e.height===void 0?(l=e.width,d=l/u):e.width===void 0&&e.height!==void 0?(d=e.height,l=d*u):e.width!==void 0&&e.height!==void 0?(l=e.width,d=e.height):(l=o,d=c),l=Vn(l,e.roundDimensionsTo??1),d=Vn(d,e.roundDimensionsTo??1);const f={width:l,height:d,fit:e.fit??"fill",rotation:t,flip:i,crop:a??{left:0,top:0,width:n,height:s},alpha:e.alpha??"keep"};for(const b of Zn){let w=b(this,f);if(F(w)&&(w=await w),w!==null)return w}const{canvas:h,context:p,isNew:m}=aa(f.width,f.height);return this._drawWithFitAndMipmapping(h,p,{fit:f.fit,rotation:f.rotation,flip:f.flip,crop:f.crop,targetIsFresh:m,fillBlack:f.alpha==="discard"}),new Ie(h,{timestamp:this.timestamp,duration:this.duration,rotation:0,flip:!1})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setFlip(e){if(typeof e!="boolean")throw new TypeError("newFlip must be a boolean.");this.flip=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||typeof e!="object")throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}const Zn=[],Hh=r=>{Zn.includes(r)||Zn.push(r)},Ru=3,Dr=[];let sa=0;const aa=(r,e)=>{for(const n of Dr)if(n.canvas.width===r&&n.canvas.height===e)return n.age=sa++,{canvas:n.canvas,context:n.context,isNew:!1};let t;if(typeof OffscreenCanvas<"u")t=new OffscreenCanvas(r,e);else{if(typeof window>"u"||typeof document>"u")throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");t=document.createElement("canvas"),t.width=r,t.height=e}const i=t.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!i)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return Dr.length>=Ru&&Dr.splice(Hi(Dr,n=>n.age),1),Dr.push({canvas:t,context:i,age:sa++}),{canvas:t,context:i,isNew:!0}};class Tn{constructor(e){if(e!==void 0){if(!e||typeof e!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");const t=Object.keys(li);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(", ")}.`);const i=Object.keys(ui);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);const n=Object.keys(di);if(e.matrix!=null&&!n.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${n.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=(e==null?void 0:e.primaries)??null,this.transfer=(e==null?void 0:e.transfer)??null,this.matrix=(e==null?void 0:e.matrix)??null,this.fullRange=(e==null?void 0:e.fullRange)??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const Mr=r=>typeof VideoFrame<"u"&&r instanceof VideoFrame,Jn=(r,e,t)=>{const i=Math.min(r.left,e),n=Math.min(r.top,t),s=Math.min(r.width,e-i),a=Math.min(r.height,t-n);return y(s>=0),y(a>=0),{left:i,top:n,width:s,height:a}},Fi=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},oa=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.colorSpace!==void 0&&!["display-p3","srgb"].includes(r.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(r.format!==void 0&&typeof r.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(r.layout!==void 0){if(!Array.isArray(r.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const e of r.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(r.rect!==void 0){if(!r.rect||typeof r.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(r.rect.x!==void 0&&(!Number.isInteger(r.rect.x)||r.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(r.rect.y!==void 0&&(!Number.isInteger(r.rect.y)||r.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(r.rect.width!==void 0&&(!Number.isInteger(r.rect.width)||r.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(r.rect.height!==void 0&&(!Number.isInteger(r.rect.height)||r.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},Bu=(r,e,t)=>{const i=rn(r),n=[];let s=0;for(const a of i){const o=Math.ceil(e/a.widthDivisor),c=Math.ceil(t/a.heightDivisor),u=o*a.sampleBytes,l=u*c;n.push({offset:s,stride:u}),s+=l}return n},rn=r=>{const e=(t,i,n,s,a)=>{const o=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:i,widthDivisor:n,heightDivisor:s},{sampleBytes:i,widthDivisor:n,heightDivisor:s}];return a&&o.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),o};switch(r){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:ze(r),y(!1)}},ca=(r,e)=>{const t={left:0,top:0,width:r.codedWidth,height:r.codedHeight},i=e.rect,n=Fu(t,i,r.codedWidth,r.codedHeight,r.format),s=e.layout;let a;if(!e.format||e.format===r.format)a=r.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(e.format))a=e.format;else throw new Error("NotSupportedError: Invalid destination format.");return Mu(n,a,s)},Fu=(r,e,t,i,n)=>{const s={...r};if(e!==void 0){if(e.width===0||e.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>t)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>i)throw new TypeError("visibleRect exceeds codedHeight.");s.x=e.x||0,s.y=e.y||0,s.width=e.width||0,s.height=e.height||0}if(!Du(n,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},Du=(r,e)=>{if(r===null)return!0;const t=rn(r);for(let i=0;i<t.length;i++){const n=t[i],s=n.widthDivisor,a=n.heightDivisor;if((e.x||0)%s!==0||(e.y||0)%a!==0)return!1}return!0},Mu=(r,e,t)=>{const i=rn(e),n=i.length;if(t!==void 0&&t.length!==n)throw new TypeError(`Layout must have ${n} planes.`);let s=0;const a=[],o=[];for(let c=0;c<n;c++){const u=i[c],l=u.sampleBytes,d=u.widthDivisor,f=u.heightDivisor,h={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(h.sourceTop=Math.ceil(Math.trunc(r.y||0)/f),h.sourceHeight=Math.ceil(Math.trunc(r.height||0)/f),h.sourceLeftBytes=Math.floor(Math.trunc(r.x||0)/d)*l,h.sourceWidthBytes=Math.floor(Math.trunc(r.width||0)/d)*l,t!==void 0){const b=t[c];if(b.stride<h.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);h.destinationOffset=b.offset,h.destinationStride=b.stride}else h.destinationOffset=s,h.destinationStride=h.sourceWidthBytes;const m=h.destinationStride*h.sourceHeight+h.destinationOffset;if(m>4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(m),s=Math.max(s,m);for(let b=0;b<c;b++){const w=a[b];if(!(o[c]<=w.destinationOffset||o[b]<=h.destinationOffset))throw new TypeError("Planes overlap.")}a.push(h)}return{allocationSize:s,computedLayouts:a}},bi=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class Or{constructor(){this._referenceCount=0}}class Te{get microsecondTimestamp(){return Math.trunc(It*this.timestamp)}get microsecondDuration(){return Math.trunc(It*this.duration)}constructor(e){if(this._closed=!1,Nr(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else if(e instanceof Or){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!bi.has(this.format))throw new TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=e.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw new TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=e.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw new TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=e.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw new TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=e.getTimestamp(),!Number.isFinite(this.timestamp))throw new TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!bi.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e==null?void 0:e.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(st(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new 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 i;if(e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");const n=this.numberOfFrames*this.numberOfChannels*st(this.format);if(i.byteLength<n)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}qe==null||qe.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!bi.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const t=e.format??this.format,i=e.frameOffset??0;if(i>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const n=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-i;if(n>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const s=st(t),a=Ot(t);if(a&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!a&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(a?n:n*this.numberOfChannels)*s}copyTo(e,t){if(!hr(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!bi.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{format:i,frameCount:n,frameOffset:s}=t;let{planeIndex:a}=t,o=this.format;const c=i??this.format;if(!c)throw new Error("Destination format not determined");const u=this.numberOfFrames,l=this.numberOfChannels,d=s??0;if(d>=u)throw new RangeError("frameOffset out of range");const f=n!==void 0?n:u-d;if(f>u-d)throw new RangeError("frameCount out of range");const h=st(c),p=Ot(c);if(p&&a>=l)throw new RangeError("planeIndex out of range");if(!p&&a!==0)throw new RangeError("planeIndex out of range");const b=(p?f:f*l)*h;if(e.byteLength<b)throw new RangeError("Destination buffer is too small");const w=Z(e),S=Wo(c);if(Nr(this._data))if(_t()&&l>2&&c!==o){Nu(this._data,w,o,c,l,a,d,f);return}else try{this._data.copyTo(e,{planeIndex:a,frameOffset:d,frameCount:f,format:c});return}catch(I){if(c==="f32-planar")throw I;o="f32-planar"}const A=Lo(o),T=st(o),k=Ot(o);let x;if(this._data instanceof Or){const I=E=>{const C=this._data.getDataPlane(E);if(!(C instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const _=u*T*(k?1:l);if(C.byteLength!==_)throw new TypeError(`Data plane ${E} has invalid size. Expected exactly ${_} bytes, got ${C.byteLength} bytes.`);return C};if(k)if(p)x=I(a),a=0;else{x=new Uint8Array(u*T*l);for(let E=0;E<l;E++){const C=I(E);x.set(C,E*u*T)}}else x=I(0)}else if(this._data instanceof Uint8Array)x=this._data;else if(y(o==="f32-planar"),p)x=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:a})),this._data.copyTo(x,{format:"f32-planar",planeIndex:a}),a=0;else{x=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:0})*l);for(let I=0;I<l;I++)this._data.copyTo(x.subarray(I*u*T,(I+1)*u*T),{format:"f32-planar",planeIndex:I})}const P=Z(x);for(let I=0;I<f;I++)if(p){const E=I*h;let C;k?C=(a*u+(I+d))*T:C=((I+d)*l+a)*T;const _=A(P,C);S(w,E,_)}else for(let E=0;E<l;E++){const _=(I*l+E)*h;let D;k?D=(E*u+(I+d))*T:D=((I+d)*l+E)*T;const q=A(P,D);S(w,_,q)}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof Or){const e=new Te(this._data);return e.setTimestamp(this.timestamp),e}else if(Nr(this._data)){const e=new Te(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new Te({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}trim(e,t=this.numberOfFrames){if(!Number.isInteger(e)||e<0)throw new TypeError("startFrame must be a non-negative integer.");if(!Number.isInteger(t)||t<0)throw new TypeError("endFrame must be a non-negative integer.");if(e>this.numberOfFrames)throw new RangeError("startFrame out of range.");if(t>this.numberOfFrames)throw new RangeError("endFrame out of range.");if(t<e)throw new RangeError("endFrame must not be less than startFrame.");if(this._closed)throw new Error("AudioSample is closed.");const i=t-e,n=st(this.format);let s;if(Ot(this.format)){const a=i*n;if(s=new Uint8Array(a*this.numberOfChannels),i>0)for(let o=0;o<this.numberOfChannels;o++)this.copyTo(s.subarray(o*a,(o+1)*a),{planeIndex:o,format:this.format,frameOffset:e,frameCount:i})}else s=new Uint8Array(i*this.numberOfChannels*n),i>0&&this.copyTo(s,{planeIndex:0,format:this.format,frameOffset:e,frameCount:i});return new Te({data:s,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(qe==null||qe.unregister(this),this._data instanceof Or?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Nr(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof Or?this._createAudioDataFromData():Nr(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(Ot(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(new Uint8Array(t,i*e,e),{planeIndex:i,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{const 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 new Error("AudioSample is closed.");const 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 i=0;i<this.numberOfChannels;i++)this.copyTo(t,{planeIndex:i,format:"f32-planar"}),e.copyToChannel(t,i);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,n=e.numberOfChannels,s=e.sampleRate,a=e.length,o=Math.floor(i/n);let c=0,u=a;for(;u>0;){const l=Math.min(o,u),d=new Float32Array(n*l);for(let f=0;f<n;f++)e.copyFromChannel(d.subarray(f*l,(f+1)*l),f,c);yield new Te({format:"f32-planar",sampleRate:s,numberOfFrames:l,numberOfChannels:n,timestamp:t+c/s,data:d}),c+=l,u-=l}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,n=e.numberOfChannels,s=e.sampleRate,a=e.length,o=Math.floor(i/n);let c=0,u=a;const l=[];for(;u>0;){const d=Math.min(o,u),f=new Float32Array(n*d);for(let p=0;p<n;p++)e.copyFromChannel(f.subarray(p*d,(p+1)*d),p,c);const h=new Te({format:"f32-planar",sampleRate:s,numberOfFrames:d,numberOfChannels:n,timestamp:t+c/s,data:f});l.push(h),c+=d,u-=d}return l}}const st=r=>{switch(r){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},Ot=r=>{switch(r){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Lo=r=>{switch(r){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)}},Wo=r=>{switch(r){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,pe(Math.round(i*128)+128,0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,pe(Math.round(i*32768),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,pe(Math.round(i*2147483648),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Nr=r=>typeof AudioData<"u"&&r instanceof AudioData,Ou=r=>{switch(r){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return r}},Nu=(r,e,t,i,n,s,a,o)=>{const c=Lo(t),u=Wo(i),l=st(t),d=st(i),f=Ot(t);if(Ot(i))if(f){const p=new ArrayBuffer(o*l),m=Z(p);r.copyTo(p,{planeIndex:s,frameOffset:a,frameCount:o,format:t});for(let b=0;b<o;b++){const w=b*l,S=b*d,A=c(m,w);u(e,S,A)}}else{const p=new ArrayBuffer(o*n*l),m=Z(p);r.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let b=0;b<o;b++){const w=(b*n+s)*l,S=b*d,A=c(m,w);u(e,S,A)}}else if(f){const p=o*l,m=new ArrayBuffer(p),b=Z(m);for(let w=0;w<n;w++){r.copyTo(m,{planeIndex:w,frameOffset:a,frameCount:o,format:t});for(let S=0;S<o;S++){const A=S*l,T=(S*n+w)*d,k=c(b,A);u(e,T,k)}}}else{const p=new ArrayBuffer(o*n*l),m=Z(p);r.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let b=0;b<o;b++)for(let w=0;w<n;w++){const S=b*n+w,A=S*l,T=S*d,k=c(m,A);u(e,T,k)}}},zu=(r,e)=>{const t=r.allocationSize({format:e,planeIndex:0}),i=new ArrayBuffer(t);return r.copyTo(i,{format:e,planeIndex:0}),new Te({data:i,format:e,numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,timestamp:r.timestamp,duration:r.duration})};/*!
92
+ * Copyright (c) 2026-present, Vanilagy and contributors
93
+ *
94
+ * This Source Code Form is subject to the terms of the Mozilla Public
95
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
96
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
97
+ */const es=new Map,ts=new Map,Ts=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!Qe.includes(r.codec))throw new TypeError(`Invalid video codec '${r.codec}'. Must be one of: ${Qe.join(", ")}.`);const e=r.bitrate;if(r.quality===void 0&&e===void 0)throw new TypeError("config.quality must be provided.");if(r.quality!==void 0&&e!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(r.quality!==void 0&&!(r.quality instanceof ve))throw new TypeError("config.quality, when provided, must be a Quality.");if(e!==void 0&&!(e instanceof ve)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(r.keyFrameInterval!==void 0&&(!Number.isFinite(r.keyFrameInterval)||r.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(r.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.width!==void 0&&(!Number.isInteger(r.transform.width)||r.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(r.transform.height!==void 0&&(!Number.isInteger(r.transform.height)||r.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(r.transform.fit!==void 0&&!["fill","contain","cover"].includes(r.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(r.transform.width!==void 0&&r.transform.height!==void 0&&r.transform.fit===void 0&&!["fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(r.transform.fit!==void 0&&["fill","contain","cover"].includes(r.sizeChangeBehavior)&&r.transform.fit!==r.sizeChangeBehavior)throw new 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(r.transform.rotate!==void 0&&![0,90,180,270].includes(r.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(r.transform.flip!==void 0&&typeof r.transform.flip!="boolean")throw new TypeError("config.transform.flip, when provided, must be a boolean.");if(r.transform.crop!==void 0&&Fi(r.transform.crop,"config.transform."),r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(r.transform.frameRate!==void 0&&(!Number.isFinite(r.transform.frameRate)||r.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(r.transform.force!==void 0&&typeof r.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(r.onEncodedSample!==void 0&&typeof r.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");qo(r.codec,r)},qo=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");const t=e.bitrateMode;if(t!==void 0&&!["constant","variable"].includes(t))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Je(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},Ho=r=>{const e=r.bitrateMode,t=r.quality._toVideoRateControl(r.codec,r.width,r.height,e),i=(s,a,o)=>({codec:r.fullCodecString??Kc(r.codec,r.width,r.height,o,r.alpha==="keep"),width:r.width,height:r.height,displayWidth:r.squarePixelWidth,displayHeight:r.squarePixelHeight,bitrate:s,bitrateMode:a,alpha:r.alpha??"discard",framerate:r.framerate,latencyMode:r.latencyMode,hardwareAcceleration:r.hardwareAcceleration,scalabilityMode:r.scalabilityMode,contentHint:r.contentHint,...uh(r.codec)}),n=[];return t.quantizer!==null&&n.push({config:i(void 0,"quantizer",t.bitrate),quantizer:t.quantizer}),t.bitrateMode!=="quantizer"&&n.push({config:i(t.bitrate,t.bitrateMode,t.bitrate),quantizer:null}),y(n.length>0),n},xs=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!Ge.includes(r.codec))throw new TypeError(`Invalid audio codec '${r.codec}'. Must be one of: ${Ge.join(", ")}.`);const e=r.bitrate;if(r.quality===void 0&&e===void 0&&!(Me.includes(r.codec)||r.codec==="flac"||r.codec==="truehd"))throw new TypeError("config.quality must be provided for compressed audio codecs.");if(r.quality!==void 0&&e!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(r.quality!==void 0&&!(r.quality instanceof ve))throw new TypeError("config.quality, when provided, must be a Quality.");if(e!==void 0&&!(e instanceof ve)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.numberOfChannels!==void 0&&(!Number.isInteger(r.transform.numberOfChannels)||r.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(r.transform.sampleRate!==void 0&&(!Number.isInteger(r.transform.sampleRate)||r.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(r.transform.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(r.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(r.onEncodedSample!==void 0&&typeof r.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");jo(r.codec,r)},jo=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");const t=e.bitrateMode;if(t!==void 0&&!["constant","variable"].includes(t))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Je(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`)},Ko=r=>{var t,i;const e=r.bitrateMode;return{codec:r.fullCodecString??Qc(r.codec,r.numberOfChannels,r.sampleRate),numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,bitrate:(t=r.quality)==null?void 0:t._toAudioBitrate(r.codec),bitrateMode:((i=r.quality)==null?void 0:i._bitrateMode)??e,...$c(r.codec)}};class ve{constructor(e){if((typeof e=="number"||typeof e=="string")&&(e={quality:e}),!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("options.bitrateMode, when provided, must be 'constant' or 'variable'.");if("quality"in e){if(typeof e.quality=="string"?!(e.quality in la):typeof e.quality!="number"||Number.isNaN(e.quality))throw new 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 new TypeError("options.preferBitrate, when provided, must be a boolean.");if("bitrate"in e||"quantizer"in e)throw new TypeError("options.quality cannot be combined with options.bitrate or options.quantizer.");this._quality=typeof e.quality=="string"?la[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 new TypeError("options.bitrate, when provided, must be a positive integer.");if(e.quantizer!==void 0&&(!Number.isInteger(e.quantizer)||e.quantizer<0))throw new TypeError("options.quantizer, when provided, must be a non-negative integer.");if(e.bitrate===void 0&&e.quantizer===void 0)throw new TypeError("At least one of options.bitrate or options.quantizer must be set.");if("preferBitrate"in e)throw new 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,t,i,n){const s=Uu[e];let a=null,o=this._bitrateMode??n??"variable";if(this._quantizer!==void 0){if(s)if(this._quantizer<s.min||this._quantizer>s.max){if(this._bitrate===void 0)throw new Error(`Quantizer ${this._quantizer} is out of range for codec '${e}'; must be between ${s.min} and ${s.max}.`)}else a=this._quantizer,this._bitrate===void 0&&(o="quantizer");else if(this._bitrate===void 0)throw new Error(`Codec '${e}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else this._bitrate===void 0&&s&&!this._preferBitrate&&(y(this._quality!==void 0),a=pe(Math.round(ul(s.worst,s.best,this._quality)),s.min,s.max));let c;if(this._bitrate!==void 0)c=this._bitrate;else{let u=this._quality;u===void 0&&(y(a!==null&&s),u=pe((a-s.worst)/(s.best-s.worst),0,1)),c=ua(e,t,i,xn(u))}return{quantizer:a,bitrate:c,bitrateMode:o}}_toVideoBitrate(e,t,i){return this._bitrate!==void 0?this._bitrate:(y(this._quality!==void 0),ua(e,t,i,xn(this._quality)))}_toAudioBitrate(e){if(Me.includes(e)||e==="flac"||e==="truehd")return;if(this._bitrate!==void 0)return this._bitrate;if(this._quality===void 0)throw new Error("This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.");const t=xn(this._quality),n={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[e];if(!n)throw new Error(`Unhandled codec: ${e}`);let s=n*t;return e==="aac"?s=[96e3,128e3,16e4,192e3].reduce((o,c)=>Math.abs(c-s)<Math.abs(o-s)?c:o):e==="opus"||e==="vorbis"?s=Math.max(6e3,s):e==="mp3"&&(s=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((o,c)=>Math.abs(c-s)<Math.abs(o-s)?c:o)),Math.round(s/1e3)*1e3}}const la={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},Uu={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:(ml()??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}},xn=r=>.3*Math.exp(2.5538*r),ua=(r,e,t,i)=>{const n=e*t,s=1920*1080,a=3e6,o=Math.pow(n/s,.95),c=a*o,u={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:22e7/a},d=c*u[r]*i;return Math.ceil(d/1e3)*1e3},Xo=(r,e)=>{if(r==="avc")return{avc:{quantizer:e}};if(r==="hevc")return{hevc:{quantizer:e}};if(r==="vp9")return{vp9:{quantizer:e}};if(r==="av1")return{av1:{quantizer:e}};y(!1)},jh=new ve("very-low"),Kh=new ve("low"),Xh=new ve("medium"),Qh=new ve("high"),Gh=new ve("very-high"),$h=r=>{if(Qe.includes(r))return Ps(r);if(Ge.includes(r))return Is(r);if(ci.includes(r))return Cs(r);throw new TypeError(`Unknown codec '${r}'.`)},Ps=async(r,e={})=>{const{width:t=1280,height:i=720,quality:n,bitrate:s,frameRate:a,...o}=e;if(!Qe.includes(r))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("height must be a positive integer.");if(n!==void 0&&!(n instanceof ve))throw new TypeError("quality, when provided, must be a Quality.");if(n!==void 0&&s!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(s!==void 0&&!(s instanceof ve)&&(!Number.isInteger(s)||s<=0))throw new TypeError("bitrate must be a positive integer or a quality.");if(a!==void 0&&(!Number.isFinite(a)||a<=0))throw new TypeError("frameRate, when provided, must be a finite positive number.");qo(r,o);const c=nn(n,s)??new ve("medium");let u;try{u=Ho({codec:r,width:t,height:i,quality:c,framerate:a,...o,alpha:"discard"})}catch{return!1}const l=JSON.stringify(u),d=es.get(l);if(d)return d;const f=(async()=>{for(const{config:p}of u)if(Di.some(m=>m.supports(r,p)))return!0;if(typeof VideoEncoder>"u"||(t%2===1||i%2===1)&&(r==="avc"||r==="hevc"))return!1;for(const{config:p,quantizer:m}of u){try{if(!(await VideoEncoder.isConfigSupported(p)).supported)continue}catch{continue}if(!Wt()||await new Promise(async w=>{try{const S=new VideoEncoder({output:()=>{},error:()=>w(!1)});S.configure(p);const A=new Uint8Array(t*i*4),T=new VideoFrame(A,{format:"RGBA",codedWidth:t,codedHeight:i,timestamp:0});S.encode(T,m!==null?Xo(r,m):void 0),T.close(),await S.flush(),w(!0)}catch{w(!1)}}))return!0}return!1})();return es.set(l,f),f},Is=async(r,e={})=>{const{numberOfChannels:t=2,sampleRate:i=48e3,quality:n,bitrate:s,...a}=e;if(!Ge.includes(r))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("sampleRate must be a positive integer.");if(n!==void 0&&!(n instanceof ve))throw new TypeError("quality, when provided, must be a Quality.");if(n!==void 0&&s!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(s!==void 0&&!(s instanceof ve)&&(!Number.isInteger(s)||s<=0))throw new TypeError("bitrate must be a positive integer.");jo(r,a);const o=nn(n,s)??new ve("medium"),c=Ko({codec:r,numberOfChannels:t,sampleRate:i,quality:o,...a}),u=JSON.stringify(c),l=ts.get(u);if(l)return l;const d=(async()=>{if(Mi.some(f=>f.supports(r,c))||Me.includes(r))return!0;if(typeof AudioEncoder>"u")return!1;try{return(await AudioEncoder.isConfigSupported(c)).supported===!0}catch{return!1}})();return ts.set(u,d),d},nn=(r,e)=>{if(r!==void 0)return r;if(e!==void 0)return e instanceof ve?e:new ve({bitrate:e})},Cs=async r=>!!ci.includes(r),Yh=async()=>{const[r,e,t]=await Promise.all([Vu(),Lu(),Wu()]);return[...r,...e,...t]},Vu=async(r=Qe,e)=>{const t=await Promise.all(r.map(i=>Ps(i,e)));return r.filter((i,n)=>t[n])},Lu=async(r=Ge,e)=>{const t=await Promise.all(r.map(i=>Is(i,e)));return r.filter((i,n)=>t[n])},Wu=async(r=ci)=>{const e=await Promise.all(r.map(Cs));return r.filter((t,i)=>e[i])},Zh=async(r,e)=>{for(const t of r)if(await Ps(t,e))return t;return null},Jh=async(r,e)=>{for(const t of r)if(await Is(t,e))return t;return null},em=async r=>{for(const e of r)if(await Cs(e))return e;return null};/*!
98
+ * Copyright (c) 2026-present, Vanilagy and contributors
99
+ *
100
+ * This Source Code Form is subject to the terms of the Mozilla Public
101
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
102
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
103
+ */class qu{static supports(e,t){return!1}}class Hu{static supports(e,t){return!1}}class ju{static supports(e,t){return!1}}class Ku{static supports(e,t){return!1}}const ii=[],ni=[],Di=[],Mi=[],tm=r=>{if(r.prototype instanceof qu){const e=r;if(ii.includes(e)){j._warn("Video decoder already registered.");return}ii.push(e),Gn.clear()}else if(r.prototype instanceof Hu){const e=r;if(ni.includes(e)){j._warn("Audio decoder already registered.");return}ni.push(e),$n.clear()}else throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},rm=r=>{if(r.prototype instanceof ju){const e=r;if(Di.includes(e)){j._warn("Video encoder already registered.");return}Di.push(e),es.clear()}else if(r.prototype instanceof Ku){const e=r;if(Mi.includes(e)){j._warn("Audio encoder already registered.");return}Mi.push(e),ts.clear()}else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};/*!
104
+ * Copyright (c) 2026-present, Vanilagy and contributors
105
+ *
106
+ * This Source Code Form is subject to the terms of the Mozilla Public
107
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
108
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
109
+ */const je=new Uint8Array(0);class ce{constructor(e,t,i,n,s=-1,a,o){if(this.data=e,this.type=t,this.timestamp=i,this.duration=n,this.sequenceNumber=s,e===je&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(n)||n<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(s))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if((o==null?void 0:o.alpha)!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if((o==null?void 0:o.alphaByteLength)!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new 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===je}get microsecondTimestamp(){return Math.trunc(It*this.timestamp)}get microsecondDuration(){return Math.trunc(It*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(e.byteLength);return e.copyTo(i),new ce(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if((e==null?void 0:e.data)!==void 0&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if((e==null?void 0:e.type)!==void 0&&e.type!=="key"&&e.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if((e==null?void 0:e.timestamp)!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if((e==null?void 0:e.duration)!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if((e==null?void 0:e.sequenceNumber)!==void 0&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if((e==null?void 0:e.sideData)!==void 0&&(typeof e.sideData!="object"||e.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new ce((e==null?void 0:e.data)??this.data,(e==null?void 0:e.type)??this.type,(e==null?void 0:e.timestamp)??this.timestamp,(e==null?void 0:e.duration)??this.duration,(e==null?void 0:e.sequenceNumber)??this.sequenceNumber,this.byteLength,(e==null?void 0:e.sideData)??this.sideData)}}/*!
110
+ * Copyright (c) 2026-present, Vanilagy and contributors
111
+ *
112
+ * This Source Code Form is subject to the terms of the Mozilla Public
113
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
114
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
115
+ */class Xu{constructor(e){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(){y(this.sourceNumberOfChannels!==null);const e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(i,n)=>i[n*e]:e===1&&t===4?this.channelMixer=(i,n,s)=>i[n*e]*+(s<2):e===1&&t===6?this.channelMixer=(i,n,s)=>i[n*e]*+(s===2):e===2&&t===1?this.channelMixer=(i,n)=>{const s=n*e;return .5*(i[s]+i[s+1])}:e===2&&t===4?this.channelMixer=(i,n,s)=>s<2?i[n*e+s]:0:e===2&&t===6?this.channelMixer=(i,n,s)=>s<2?i[n*e+s]:0:e===4&&t===1?this.channelMixer=(i,n)=>{const s=n*e;return .25*(i[s]+i[s+1]+i[s+2]+i[s+3])}:e===4&&t===2?this.channelMixer=(i,n,s)=>{const a=n*e;return .5*(i[a+s]+i[a+s+2])}:e===4&&t===6?this.channelMixer=(i,n,s)=>{const a=n*e;return s<2?i[a+s]:s===2||s===3?0:i[a+s-2]}:e===6&&t===1?this.channelMixer=(i,n)=>{const s=n*e;return Math.SQRT1_2*(i[s]+i[s+1])+i[s+2]+.5*(i[s+4]+i[s+5])}:e===6&&t===2?this.channelMixer=(i,n,s)=>{const a=n*e;return i[a+s]+Math.SQRT1_2*(i[a+2]+i[a+s+4])}:e===6&&t===4?this.channelMixer=(i,n,s)=>{const a=n*e;return s<2?i[a+s]+Math.SQRT1_2*i[a+2]:i[a+s+2]}:this.channelMixer=(i,n,s)=>s<e?i[n*e+s]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){const i=new Float32Array(t);i.set(this.tempSourceBuffer),this.tempSourceBuffer=i}}async add(e){if(this.sourceSampleRate===null){this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp;const u=Math.ceil(this.targetSampleRate/this.sourceSampleRate);this.bufferCapacityInFrames=this.bufferSizeInFrames+u,this.outputBuffer=new Float32Array(this.bufferCapacityInFrames*this.targetNumberOfChannels),this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()}y(this.startTime!==null);const t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);const i=e.allocationSize({planeIndex:0,format:"f32"}),n=new Float32Array(this.tempSourceBuffer.buffer,0,i/4);e.copyTo(n,{planeIndex:0,format:"f32"});const s=Math.round((e.timestamp-this.startTime)*this.sourceSampleRate),a=s+e.numberOfFrames,o=Math.floor((s-1)*this.targetSampleRate/this.sourceSampleRate)+1,c=Math.ceil(a*this.targetSampleRate/this.sourceSampleRate);for(let u=o;u<c;u++){if(u<this.bufferStartFrame)continue;for(;u>=this.bufferStartFrame+this.bufferCapacityInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;const l=u-this.bufferStartFrame;y(l<this.bufferCapacityInFrames);const d=u*this.sourceSampleRate/this.targetSampleRate-s,f=Math.floor(d),h=Math.ceil(d),p=d-f;for(let m=0;m<this.targetNumberOfChannels;m++){let b=0,w=0;f>=0&&f<e.numberOfFrames&&(b=this.channelMixer(n,f,m)),h>=0&&h<e.numberOfFrames&&(w=this.channelMixer(n,h,m));const S=b+p*(w-b),A=l*this.targetNumberOfChannels+m;this.outputBuffer[A]+=S}this.maxWrittenFrame===null?this.maxWrittenFrame=l:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,l)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;y(this.startTime!==null);const e=Math.min(this.maxWrittenFrame+1,this.bufferSizeInFrames)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));const i=new Te({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(i),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}}/*!
116
+ * Copyright (c) 2026-present, Vanilagy and contributors
117
+ *
118
+ * This Source Code Form is subject to the terms of the Mozilla Public
119
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
120
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
121
+ */class yt{constructor(e){this.input=e}dispose(){}}/*!
122
+ * Copyright (c) 2026-present, Vanilagy and contributors
123
+ *
124
+ * This Source Code Form is subject to the terms of the Mozilla Public
125
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
126
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
127
+ */const Qu=2082844800,Gu=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isQuickTime?"quicktime":"mp4");if(r.codecStrings.length>0){const i=[...new Set(r.codecStrings)];t+=`; codecs="${i.join(", ")}"`}return t},Qo=r=>{if(r.length<24)throw new Error("Invalid pssh box: too small.");const e=Z(r);let t=0;const i=e.getUint8(t);t+=1,t+=3;const n=Jr(r.subarray(t,t+16));t+=16;let s=null;if(i>0){const o=e.getUint32(t);if(t+=4,t+16*o+4>r.length)throw new Error("Invalid pssh box: key ID count exceeds box size.");if(o>0){s=[];for(let c=0;c<o;c++)s.push(Jr(r.subarray(t,t+16))),t+=16}}const a=e.getUint32(t);return t+=4,{systemId:n,keyIds:s,data:r.slice(t,t+a)}},Go=(r,e)=>r.systemId===e.systemId&&kl(r.data,e.data);/*!
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
+ */const it=16,lt=new Uint32Array(256),Zt=new Uint32Array(256),Jt=new Uint32Array(256),er=new Uint32Array(256),tr=new Uint32Array(256),Ee=new Uint32Array(256),$o=new Uint32Array(10);let Yo=!1;const $u=()=>{const r=new Uint8Array(256),e=new Uint8Array(256),t=new Uint8Array(256);for(let s=0,a=1;s<256;s++)t[s]=a,e[a]=s,a=a^a<<1^(a&128?283:0);const i=(s,a)=>s&&a?t[(e[s]+e[a])%255]:0;r[0]=99;for(let s=1;s<256;s++){const a=t[255-e[s]];let o=a^a<<1^a<<2^a<<3^a<<4;o=o>>>8^o&255^99,r[s]=o}for(let s=0;s<256;s++){const a=r[s],o=r.indexOf(s);lt[s]=a<<24|a<<16|a<<8|a,Ee[s]=o<<24|o<<16|o<<8|o;const c=i(o,14),u=i(o,9),l=i(o,13),d=i(o,11),f=c<<24|u<<16|l<<8|d;Zt[s]=f,Jt[s]=f>>>8|f<<24,er[s]=f>>>16|f<<16,tr[s]=f>>>24|f<<8}let n=1;for(let s=0;s<10;s++)$o[s]=n<<24,n=n<<1^(n&128?283:0);Yo=!0};class Zo{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(it/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(it),this.out=new Uint8Array(it),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){y(e.byteLength===16),y(t.byteLength===16),Yo||$u();const i=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=i.getUint32(0,!1),this.roundkey[1]=i.getUint32(4,!1),this.roundkey[2]=i.getUint32(8,!1),this.roundkey[3]=i.getUint32(12,!1),this.iv[0]=n.getUint32(0,!1),this.iv[1]=n.getUint32(4,!1),this.iv[2]=n.getUint32(8,!1),this.iv[3]=n.getUint32(12,!1);for(let s=4;s<44;s+=4){const a=this.roundkey[s-1];this.roundkey[s]=this.roundkey[s-4]^lt[a>>>16&255]&4278190080^lt[a>>>8&255]&16711680^lt[a>>>0&255]&65280^lt[a>>>24&255]&255^$o[s/4-1],this.roundkey[s+1]=this.roundkey[s-3]^this.roundkey[s],this.roundkey[s+2]=this.roundkey[s-2]^this.roundkey[s+1],this.roundkey[s+3]=this.roundkey[s-1]^this.roundkey[s+2]}for(let s=0,a=40;s<a;s+=4,a-=4)for(let o=0;o<4;o++){const c=this.roundkey[s+o];this.roundkey[s+o]=this.roundkey[a+o],this.roundkey[a+o]=c}for(let s=4;s<40;s+=4)for(let a=0;a<4;a++){const o=this.roundkey[s+a];this.roundkey[s+a]=Zt[lt[o>>>24&255]&255]^Jt[lt[o>>>16&255]&255]^er[lt[o>>>8&255]&255]^tr[lt[o>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],i=this.inView.getUint32(8,!1)^this.roundkey[2],n=this.inView.getUint32(12,!1)^this.roundkey[3];const s=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),c=this.inView.getUint32(12,!1);let u,l,d,f;for(let w=1;w<10;w++){const S=w*4;u=Zt[e>>>24]^Jt[n>>>16&255]^er[i>>>8&255]^tr[t&255]^this.roundkey[S],l=Zt[t>>>24]^Jt[e>>>16&255]^er[n>>>8&255]^tr[i&255]^this.roundkey[S+1],d=Zt[i>>>24]^Jt[t>>>16&255]^er[e>>>8&255]^tr[n&255]^this.roundkey[S+2],f=Zt[n>>>24]^Jt[i>>>16&255]^er[t>>>8&255]^tr[e&255]^this.roundkey[S+3],e=u,t=l,i=d,n=f}const h=Ee[e>>>24&255]&4278190080^Ee[n>>>16&255]&16711680^Ee[i>>>8&255]&65280^Ee[t>>>0&255]&255^this.roundkey[40],p=Ee[t>>>24&255]&4278190080^Ee[e>>>16&255]&16711680^Ee[n>>>8&255]&65280^Ee[i>>>0&255]&255^this.roundkey[41],m=Ee[i>>>24&255]&4278190080^Ee[t>>>16&255]&16711680^Ee[e>>>8&255]&65280^Ee[n>>>0&255]&255^this.roundkey[42],b=Ee[n>>>24&255]&4278190080^Ee[i>>>16&255]&16711680^Ee[t>>>8&255]&65280^Ee[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,h^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,b^this.iv[3],!1),this.iv[0]=s,this.iv[1]=a,this.iv[2]=o,this.iv[3]=c}}const Yu=(r,e,t)=>{let i=!1,n=!1,s=0;const a=2**16,o=16,c=new Zo,u=()=>{n||(n=!0,t())};return new ReadableStream({pull:async l=>{try{i||(c.init(await e()),i=!0);const d=a+o;let f=r.requestSliceRange(s,0,d);if(F(f)&&(f=await f),!f||f.length===0)throw new Error("Invalid ciphertext.");const h=f.length;if(h%16!==0)throw new Error("Invalid ciphertext.");const p=h===d?h-o:h,m=X(f,p),b=new Uint8Array(p);for(let w=0;w<p;w+=16)c.in.set(m.subarray(w,w+16)),c.decrypt(),b.set(c.out,w);if(p<h)l.enqueue(b),s+=p;else{const w=b[p-1];if(w===0||w>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const S=b.subarray(0,p-w);l.enqueue(S),l.close(),u()}}catch(d){throw u(),d}},cancel:()=>{u()}})};/*!
134
+ * Copyright (c) 2026-present, Vanilagy and contributors
135
+ *
136
+ * This Source Code Form is subject to the terms of the Mozilla Public
137
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
138
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
139
+ */const da=[2,1,1,2,2,2,2,1,1,2,2,1,1],Zu=64;class Es extends yt{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.idToTrack=new Map,this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.movieMatrix=Un,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=new Map,this.psshBoxes=[],this.currentFragment=null,this.isReadingTraf=!1,this.lastReadFragment=null,this.fragmentSummaries=new Map,this.decryptionKeyCache=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();const e=await this.getTrackBackings(),t=await Promise.all(e.map(i=>i.getDecoderConfig().then(n=>(n==null?void 0:n.codec)??null)));return Gu({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(i=>{var n;return((n=i.info)==null?void 0:n.type)==="video"}),hasAudio:this.tracks.some(i=>{var n;return((n=i.info)==null?void 0:n.type)==="audio"}),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0,t=!1,i=!1;for(;;){let n=this.reader.requestSliceRange(e,ir,Kr);if(F(n)&&(n=await n),!n)break;const s=e,a=Tt(n);if(!a)break;if((a.name==="ftyp"||a.name==="styp")&&n.remainingLength>=4){const o=be(n,4);this.isQuickTime=o==="qt "}else if(a.name==="moov"){let o=this.reader.requestSlice(n.filePos,a.contentSize);if(F(o)&&(o=await o),!o)break;if(this.moovSlice=o,this.readContiguousBoxes(this.moovSlice),this.movieTimescale===-1)throw new Error("Invalid moov box: missing mvhd box.");for(const c of this.tracks){const u=c.editListPreviousSegmentDurations/this.movieTimescale;c.editListOffset-=Math.round(u*c.timescale)}t=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>s+a.totalSize,i=!0;break}else if(a.name==="moof"){if(!this.input._initInput)throw new 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),t=!1,i=!0;break}e=s+a.totalSize}if(!i&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),t){y(this.reader.fileSize!==null);let n=this.reader.requestSlice(this.reader.fileSize-4,4);F(n)&&(n=await n),y(n);const s=U(n),a=this.reader.fileSize-s;if(a>=0&&a<=this.reader.fileSize-Kr){let o=this.reader.requestSliceRange(a,ir,Kr);if(F(o)&&(o=await o),o){const c=Tt(o);if(c&&c.name==="mfra"){let u=this.reader.requestSlice(o.filePos,c.contentSize);F(u)&&(u=await u),u&&this.readContiguousBoxes(u)}}}}for(const n of this.tracks){const s=n.fragmentLookupTable;s.sort((o,c)=>o.timestamp-c.timestamp);let a=0;for(const o of s)(a===0||o.timestamp!==s[a-1].timestamp)&&(s[a++]=o);s.length=a}})())}async copyMetadataFromInitInput(e){const t=await e._getDemuxer();if(t.constructor!==Es)throw new Error("Init input must match the input's format.");await t.readMetadata(),this.movieTimescale=t.movieTimescale,this.movieDurationInTimescale=t.movieDurationInTimescale,this.movieMatrix=t.movieMatrix,this.metadataTags=t.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=t.fragmentTrackDefaults,this.psshBoxes=t.psshBoxes;for(const i of t.tracks){const n={id:i.id,demuxer:this,trackBacking:null,disposition:i.disposition,timescale:i.timescale,durationInMediaTimescale:i.durationInMediaTimescale,durationInMovieTimescale:i.durationInMovieTimescale,matrix:i.matrix,internalCodecId:i.internalCodecId,name:i.name,languageCode:i.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:i.editListPreviousSegmentDurations,editListOffset:i.editListOffset,encryptionInfo:i.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:i.maxBitrate,avgBitrate:i.avgBitrate,info:i.info};if(i.trackBacking){if(y(n.info),n.info.type==="video"&&n.info.width!==-1){const s=n;n.trackBacking=new fa(s),this.tracks.push(n),this.idToTrack.set(n.id,n)}else if(n.info.type==="audio"&&n.info.numberOfChannels!==-1){const s=n;n.trackBacking=new ha(s),this.tracks.push(n),this.idToTrack.set(n.id,n)}}}}getSampleTableForTrack(e){var c,u;if(e.sampleTable)return e.sampleTable;const t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],sampleCount:0,cumulativeSampleSizes:null,keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],sortedCompositionTimeOffsets:null};if(e.sampleTable=t,e.sampleTableByteOffset===null)return t;y(this.moovSlice);const i=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e;try{this.traverseBox(i)}catch(l){throw e.sampleTable=null,l}finally{this.currentTrack=null}const n=fe(t.sampleTimingEntries),s=te(t.sampleToChunk,t.chunkOffsets.length-1,l=>l.startChunkIndex),a=t.sampleToChunk[s];if(t.sampleCount=Math.min(t.sampleCount,n?n.startIndex+n.count:0,a?a.startSampleIndex+(t.chunkOffsets.length-a.startChunkIndex)*a.samplesPerChunk:0),ba(t.sampleTimingEntries,t.sampleCount),ba(t.sampleCompositionTimeOffsets,t.sampleCount),((c=e.info)==null?void 0:c.type)==="audio"&&e.info.codec&&Me.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0&&t.sampleTimingEntries.length>0){y(((u=e.info)==null?void 0:u.type)==="audio");const l=Vs(e.info.codec),d=[],f=[];for(let h=0;h<t.sampleToChunk.length;h++){const p=t.sampleToChunk[h],m=t.sampleToChunk[h+1],b=Math.min(m?m.startChunkIndex:1/0,t.chunkOffsets.length)-p.startChunkIndex,w=f.length;for(let S=0;S<b;S++){const A=p.startSampleIndex+S*p.samplesPerChunk,T=A+p.samplesPerChunk,k=te(t.sampleTimingEntries,A,M=>M.startIndex),x=t.sampleTimingEntries[k],P=te(t.sampleTimingEntries,T,M=>M.startIndex),I=t.sampleTimingEntries[P],E=x.startDecodeTimestamp+(A-x.startIndex)*x.delta,_=I.startDecodeTimestamp+(T-I.startIndex)*I.delta-E,D=fe(d);D&&D.delta===_?D.count++:d.push({startIndex:f.length,startDecodeTimestamp:E,count:1,delta:_});const q=p.samplesPerChunk*l.sampleSize*e.info.numberOfChannels;f.push(q)}p.startSampleIndex=w,p.samplesPerChunk=1}t.sampleTimingEntries=d,t.sampleSizes=f,t.sampleCount=f.length}if(t.sampleCompositionTimeOffsets.length>0){const l=t.sampleCompositionTimeOffsets,d=fe(l),f=d.startIndex+d.count;f<t.sampleCount&&l.push({startIndex:f,count:t.sampleCount-f,offset:0,startTimestamp:-1,lastTimestamp:-1,maxLastTimestamp:-1});const h=l.filter(S=>S.count>0),p=t.sampleTimingEntries;let m=0;const b=S=>{for(;m+1<p.length&&p[m+1].startIndex<=S;)m++;const A=p[m];return A.startDecodeTimestamp+(S-A.startIndex)*A.delta};for(const S of h){const A=S.startIndex+S.count-1;S.startTimestamp=b(S.startIndex)+S.offset,S.lastTimestamp=b(A)+S.offset}h.sort((S,A)=>S.startTimestamp-A.startTimestamp||S.startIndex-A.startIndex);let w=-1/0;for(const S of h)w=Math.max(w,S.lastTimestamp),S.maxLastTimestamp=w;t.sortedCompositionTimeOffsets=h}if(t.sampleSizes.length>1){t.cumulativeSampleSizes=[0];for(let l=0;l<t.sampleSizes.length;l++)t.cumulativeSampleSizes.push(t.cumulativeSampleSizes[l]+t.sampleSizes[l])}return t}async readFragment(e){var a;if(((a=this.lastReadFragment)==null?void 0:a.moofOffset)===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,ir,Kr);F(t)&&(t=await t),y(t);const i=Tt(t);y((i==null?void 0:i.name)==="moof");let n=this.reader.requestSlice(e,i.totalSize);if(F(n)&&(n=await n),!n)return null;this.traverseBox(n);const s=this.lastReadFragment;y(s&&s.moofOffset===e),this.fragmentSummaries.set(e,{moofSize:s.moofSize,trackIds:new Set(s.trackData.keys())});for(const[,o]of s.trackData){const c=o.track,{fragmentPositionCache:u}=c;if(!o.startTimestampIsFinal){const h=fi(c.fragmentLookupTable,s.moofOffset,b=>b.moofOffset),p=c.fragmentLookupTable[h];if(p&&o.trunSampleCounts.length>=p.trunNumber&&o.trunSampleCounts[p.trunNumber-1]>=p.sampleNumber){let b=0;for(let A=1;A<p.trunNumber;A++)b+=o.trunSampleCounts[A-1];b+=p.sampleNumber-1;const w=o.samples[b];y(w);const S=p.timestamp-w.presentationTimestamp;Pn(o,S)}else{const b=te(u,s.moofOffset-1,w=>w.moofOffset);if(b!==-1){const w=u[b];Pn(o,w.endTimestamp)}}o.startTimestampIsFinal=!0}const l=te(u,o.startTimestamp,h=>h.startTimestamp),d=u[l],f=u[l+1];if((!d||d.moofOffset<s.moofOffset)&&(!f||f.moofOffset>s.moofOffset)&&u.splice(l+1,0,{moofOffset:s.moofOffset,startTimestamp:o.startTimestamp,endTimestamp:o.endTimestamp,hasKeyFrame:o.firstKeyFrameTimestamp!==null}),o.encryptionAuxInfo&&c.encryptionInfo){const h=await rc(this.reader,c.encryptionInfo,o.encryptionAuxInfo);for(let p=0;p<Math.min(o.samples.length,h.length);p++){const m=h[p];o.samples[p].encryption=m}}}return s}readContiguousBoxes(e){if(this.boxNestingDepth===Zu)throw new Error("Invalid file: boxes are nested too deeply.");const t=e.filePos;this.boxNestingDepth++;try{for(;e.filePos-t<=e.length-ir&&this.traverseBox(e););}finally{this.boxNestingDepth--}}*iterateContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-ir;){const i=e.filePos,n=Tt(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=i+n.totalSize}}traverseBox(e){var a,o,c,u,l,d,f,h,p,m,b,w,S,A,T,k,x,P,I,E,C,_,D,q,M,V,G,J,ae,he,le,ye,Ve,et,pr,gr,br,wr,kr,yr,Sr,Ar,Tr,xr,Pr,Ir,Cr,Er,_r,vr,Rr,z,$,me;const t=e.filePos,i=Tt(e);if(!i)return!1;const n=e.filePos,s=t+i.totalSize;switch(i.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes(e.slice(n,i.contentSize));break;case"mvhd":{const g=K(e);e.skip(3);let v;if(g===1?(v=Oe(e),e.skip(8),this.movieTimescale=U(e),this.movieDurationInTimescale=Oe(e)):(v=U(e),e.skip(4),this.movieTimescale=U(e),this.movieDurationInTimescale=U(e)),v!==0&&(this.metadataTags.creationTime=new Date(1e3*(v-Qu))),this.movieTimescale===0)throw new Error("Invalid mvhd box: timescale must not be 0.");e.skip(16),this.movieMatrix=ma(e)}break;case"trak":{if(this.currentFragment||this.currentTrack)break;const g={id:-1,demuxer:this,trackBacking:null,disposition:{...kt,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,matrix:Un,internalCodecId:null,name:null,languageCode:De,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:null,avgBitrate:null};if(this.currentTrack=g,this.readContiguousBoxes(e.slice(n,i.contentSize)),g.id!==-1&&g.timescale!==-1&&g.info!==null&&g.sampleTableByteOffset!==-1){if(g.info.type==="video"&&g.info.width!==-1){const v=g;g.trackBacking=new fa(v),this.tracks.push(g),this.idToTrack.set(g.id,g)}else if(g.info.type==="audio"&&g.info.numberOfChannels!==-1){const v=g;g.trackBacking=new ha(v),this.tracks.push(g),this.idToTrack.set(g.id,g)}}this.currentTrack=null}break;case"tkhd":{const g=this.currentTrack;if(!g||this.currentFragment)break;const v=K(e),O=!!(dt(e)&1);if(g.disposition.default=O,v===0)e.skip(8),g.id=U(e),e.skip(4),g.durationInMovieTimescale=U(e);else if(v===1)e.skip(16),g.id=U(e),e.skip(4),g.durationInMovieTimescale=Oe(e);else throw new Error(`Incorrect track header version ${v}.`);e.skip(16);const L=ma(e);g.matrix=Ii(L,this.movieMatrix)}break;case"elst":{const g=this.currentTrack;if(!g)break;const v=K(e);e.skip(3);let R=!1,O=0;const L=U(e);for(let N=0;N<L;N++){const H=v===1?Oe(e):U(e),Q=v===1?Wf(e):Vt(e),Y=Mt(e);if(R){j._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(Q===-1){O+=H;continue}if(Y!==1){j._warn("Unsupported edit list entry: media rate must be 1.");break}g.editListPreviousSegmentDurations=O,g.editListOffset=Q,R=!0}}break;case"mdhd":{const g=this.currentTrack;if(!g)break;const v=K(e);if(e.skip(3),v===0?(e.skip(8),g.timescale=U(e),g.durationInMediaTimescale=U(e)):v===1&&(e.skip(16),g.timescale=U(e),g.durationInMediaTimescale=Oe(e)),g.timescale===0)throw new Error("Invalid mdhd box: timescale must not be 0.");let R=we(e);if(R>0){g.languageCode="";for(let O=0;O<3;O++)g.languageCode=String.fromCharCode(96+(R&31))+g.languageCode,R>>=5;ho(g.languageCode)||(g.languageCode=De)}}break;case"hdlr":{const g=this.currentTrack;if(!g)break;e.skip(8);const v=be(e,4);v==="vide"?g.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...uo},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:v==="soun"&&(g.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const g=this.currentTrack;if(!g)break;g.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(n,i.contentSize))}break;case"stsd":{const g=this.currentTrack;if(!g||g.info===null||g.sampleTable)break;const v=K(e);e.skip(3);const R=U(e);for(let O=0;O<R;O++){const L=e.filePos,N=Tt(e);if(!N)break;g.internalCodecId=N.name;const H=N.name.toLowerCase();if(g.info.type==="video"){e.skip(24),g.info.width=we(e),g.info.height=we(e),g.info.squarePixelWidth=g.info.width,g.info.squarePixelHeight=g.info.height,e.skip(50),g.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,L+N.totalSize-e.filePos));const Q=H==="encv"?g.frmaCodecString:H;g.frmaCodecString=null,Q==="avc1"||Q==="avc3"?(g.info.codec="avc",g.info.avcType=Q==="avc1"?1:3):Q==="hvc1"||Q==="hev1"?g.info.codec="hevc":Q==="vp08"?g.info.codec="vp8":Q==="vp09"?g.info.codec="vp9":Q==="av01"?g.info.codec="av1":Lt.includes(H)?(g.info.codec="prores",g.info.proresFormat=H):Q===null?j._warn("Unknown encrypted video codec due to missing frma box."):j._warn(`Unsupported video codec (sample entry type '${N.name}').`)}else{e.skip(8);const Q=we(e);e.skip(6);let Y=we(e),ie=we(e);e.skip(4);let ue=U(e)/65536,xe=null;v===0&&Q>0&&(Q===1?(e.skip(4),ie=8*U(e),e.skip(8)):Q===2&&(e.skip(4),ue=Vc(e),Y=U(e),e.skip(4),ie=U(e),xe=U(e),e.skip(8))),g.info.numberOfChannels=Y,g.info.sampleRate=ue,g.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,L+N.totalSize-e.filePos));const ne=H==="enca"?g.frmaCodecString:H;if(g.frmaCodecString=null,ne!=="mp4a")if(ne==="opus")g.info.codec="opus",g.info.sampleRate=mr;else if(ne==="flac")g.info.codec="flac";else if(ne==="ulaw")g.info.codec="ulaw";else if(ne==="alaw")g.info.codec="alaw";else if(ne==="ac-3")g.info.codec="ac3";else if(ne==="ec-3")g.info.codec="eac3";else if(Ui.includes(ne))g.info.codec="dts",g.info.dtsFormat=ne;else if(ne==="mlpa")g.info.codec="truehd";else if(ne==="twos")ie===8?g.info.codec="pcm-s8":ie===16?g.info.codec=g.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(j._warn(`Unsupported sample size ${ie} for codec 'twos'.`),g.info.codec=null);else if(ne==="sowt")ie===8?g.info.codec="pcm-s8":ie===16?g.info.codec="pcm-s16":(j._warn(`Unsupported sample size ${ie} for codec 'sowt'.`),g.info.codec=null);else if(ne==="raw ")g.info.codec="pcm-u8";else if(ne==="in24")g.info.codec=g.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(ne==="in32")g.info.codec=g.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(ne==="fl32")g.info.codec=g.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(ne==="fl64")g.info.codec=g.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(ne==="ipcm"){const se=g.info.pcmSampleSize;g.info.pcmLittleEndian?se===16?g.info.codec="pcm-s16":se===24?g.info.codec="pcm-s24":se===32?g.info.codec="pcm-s32":(j._warn(`Invalid ipcm sample size ${se}.`),g.info.codec=null):se===16?g.info.codec="pcm-s16be":se===24?g.info.codec="pcm-s24be":se===32?g.info.codec="pcm-s32be":(j._warn(`Invalid ipcm sample size ${se}.`),g.info.codec=null)}else if(ne==="fpcm"){const se=g.info.pcmSampleSize;g.info.pcmLittleEndian?se===32?g.info.codec="pcm-f32":se===64?g.info.codec="pcm-f64":(j._warn(`Invalid fpcm sample size ${se}.`),g.info.codec=null):se===32?g.info.codec="pcm-f32be":se===64?g.info.codec="pcm-f64be":(j._warn(`Invalid fpcm sample size ${se}.`),g.info.codec=null)}else if(ne==="lpcm"&&xe!==null){const se=ie+7>>3,oe=!!(xe&1),$e=!!(xe&2),ct=xe&4?-1:0;ie>0&&ie<=64&&(oe?ie===32&&(g.info.codec=$e?"pcm-f32be":"pcm-f32"):ct&1<<se-1?se===1?g.info.codec="pcm-s8":se===2?g.info.codec=$e?"pcm-s16be":"pcm-s16":se===3?g.info.codec=$e?"pcm-s24be":"pcm-s24":se===4&&(g.info.codec=$e?"pcm-s32be":"pcm-s32"):se===1&&(g.info.codec="pcm-u8")),g.info.codec===null&&j._warn("Unsupported PCM format.")}else ne===null?j._warn("Unknown encrypted audio codec due to missing frma box."):j._warn(`Unsupported audio codec (sample entry type '${N.name}').`)}e.filePos=L+N.totalSize}}break;case"frma":{const g=this.currentTrack;if(!g)break;const R=be(e,4).toLowerCase();g.frmaCodecString=R}break;case"schm":{const g=this.currentTrack;if(!g)break;e.skip(4);const v=be(e,4);v==="cenc"||v==="cens"||v==="cbcs"?g.encryptionInfo={scheme:v,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:j._warn(`Unsupported encryption scheme '${v}'.`)}break;case"tenc":{const g=this.currentTrack;if(!g||!g.encryptionInfo)break;const v=K(e);e.skip(3),e.skip(1);const R=K(e);if(v>0?(g.encryptionInfo.defaultCryptByteBlock=R>>4,g.encryptionInfo.defaultSkipByteBlock=R&15):(g.encryptionInfo.defaultCryptByteBlock=0,g.encryptionInfo.defaultSkipByteBlock=0),g.encryptionInfo.defaultIsProtected=K(e)!==0,g.encryptionInfo.defaultPerSampleIvSize=K(e),g.encryptionInfo.defaultKid=Jr(X(e,16)),g.encryptionInfo.defaultPerSampleIvSize>16)throw new Error("Invalid tenc box: IV size must not exceed 16 bytes.");if(g.encryptionInfo.defaultIsProtected&&g.encryptionInfo.defaultPerSampleIvSize===0){const O=K(e);if(O>16)throw new Error("Invalid tenc box: IV size must not exceed 16 bytes.");const L=new Uint8Array(16);L.set(X(e,O),0),g.encryptionInfo.defaultConstantIv=L}}break;case"avcC":{const g=this.currentTrack;if(!g||((a=g.info)==null?void 0:a.type)!=="video"||i.contentSize===0)break;g.info.codecDescription=X(e,i.contentSize);const v=(o=Yi(g.info.codecDescription))==null?void 0:o.sequenceParameterSets[0],R=v&&dr(v);R&&pa(g,R.pixelAspectRatio)}break;case"hvcC":{const g=this.currentTrack;if(!g||((c=g.info)==null?void 0:c.type)!=="video"||i.contentSize===0)break;g.info.codecDescription=X(e,i.contentSize);const v=(l=(u=Eo(g.info.codecDescription))==null?void 0:u.arrays.find(O=>O.nalUnitType===ge.SPS_NUT))==null?void 0:l.nalUnits[0],R=v&&Zi(v);R&&pa(g,R.pixelAspectRatio)}break;case"vpcC":{const g=this.currentTrack;if(!g||((d=g.info)==null?void 0:d.type)!=="video")break;e.skip(4);const v=K(e),R=K(e),O=K(e),L=O>>4,N=O>>1&7,H=O&1,Q=K(e),Y=K(e),ie=K(e);g.info.vp9CodecInfo={profile:v,level:R,bitDepth:L,chromaSubsampling:N,videoFullRangeFlag:H,colourPrimaries:Q,transferCharacteristics:Y,matrixCoefficients:ie}}break;case"av1C":{const g=this.currentTrack;if(!g||((f=g.info)==null?void 0:f.type)!=="video")break;e.skip(1);const v=K(e),R=v>>5,O=v&31,L=K(e),N=L>>7,H=L>>6&1,Q=L>>5&1,Y=L>>4&1,ie=L>>3&1,ue=L>>2&1,xe=L&3,ne=R===2&&H?Q?12:10:H?10:8;e.skip(1);const se=X(e,i.contentSize-4),oe=en(se);g.info.av1CodecInfo={profile:R,level:O,tier:N,bitDepth:ne,monochrome:Y,chromaSubsamplingX:ie,chromaSubsamplingY:ue,chromaSamplePosition:xe,videoFullRangeFlag:(oe==null?void 0:oe.videoFullRangeFlag)??0,colourPrimaries:(oe==null?void 0:oe.colourPrimaries)??2,transferCharacteristics:(oe==null?void 0:oe.transferCharacteristics)??2,matrixCoefficients:(oe==null?void 0:oe.matrixCoefficients)??2}}break;case"colr":{const g=this.currentTrack;if(!g||((h=g.info)==null?void 0:h.type)!=="video")break;const v=be(e,4);if(v!=="nclx"&&v!=="nclc")break;const R=we(e),O=we(e),L=we(e);let N;v==="nclx"&&(N=!!(K(e)&128)),g.info.colorSpace={primaries:ht[R],transfer:mt[O],matrix:pt[L],fullRange:N}}break;case"pasp":{const g=this.currentTrack;if(!g||((p=g.info)==null?void 0:p.type)!=="video")break;const v=U(e),R=U(e);v>0&&R>0&&(g.info.squarePixelWidth=g.info.width,g.info.squarePixelHeight=g.info.height,v>R?g.info.squarePixelWidth=Math.round(g.info.width*v/R):g.info.squarePixelHeight=Math.round(g.info.height*R/v))}break;case"btrt":{const g=this.currentTrack;if(!g)break;e.skip(4);const v=U(e),R=U(e);g.maxBitrate=v>0?v:null,g.avgBitrate=R>0?R:null}break;case"wave":this.readContiguousBoxes(e.slice(n,i.contentSize));break;case"esds":{const g=this.currentTrack;if(!g||((m=g.info)==null?void 0:m.type)!=="audio")break;e.skip(4);const{objectTypeIndication:v,decoderSpecificInfo:R}=Wc(e);if(v===64||v===103?(g.info.codec="aac",g.info.aacCodecInfo={isMpeg2:v===103,objectType:null}):v===105||v===107?g.info.codec="mp3":v===221?g.info.codec="vorbis":v===169?g.info.codec="dts":j._warn(`Unsupported audio codec (objectTypeIndication ${v}) - discarding track.`),R&&(g.info.codecDescription=R,g.info.codec==="aac")){const O=Ki(g.info.codecDescription);O.outputNumberOfChannels!==null&&(g.info.numberOfChannels=O.outputNumberOfChannels),O.outputSampleRate!==null&&(g.info.sampleRate=O.outputSampleRate)}}break;case"enda":{const g=this.currentTrack;if(!g||((b=g.info)==null?void 0:b.type)!=="audio")break;g.info.pcmLittleEndian=!!(we(e)&255)}break;case"pcmC":{const g=this.currentTrack;if(!g||((w=g.info)==null?void 0:w.type)!=="audio")break;e.skip(4);const v=K(e);g.info.pcmLittleEndian=!!(v&1),g.info.pcmSampleSize=K(e)}break;case"dOps":{const g=this.currentTrack;if(!g||((S=g.info)==null?void 0:S.type)!=="audio")break;e.skip(1);const v=K(e),R=we(e),O=U(e),L=cs(e),N=K(e);let H;N!==0?H=X(e,2+v):H=new Uint8Array(0);const Q=new Uint8Array(19+H.byteLength),Y=new DataView(Q.buffer);Y.setUint32(0,1332770163,!1),Y.setUint32(4,1214603620,!1),Y.setUint8(8,1),Y.setUint8(9,v),Y.setUint16(10,R,!0),Y.setUint32(12,O,!0),Y.setInt16(16,L,!0),Y.setUint8(18,N),Q.set(H,19),g.info.codecDescription=Q,g.info.numberOfChannels=v}break;case"dfLa":{const g=this.currentTrack;if(!g||((A=g.info)==null?void 0:A.type)!=="audio")break;e.skip(4);const v=127,R=128,O=e.filePos;for(;e.filePos<s;){const Y=K(e),ie=dt(e);if((Y&v)===or.STREAMINFO){e.skip(10);const xe=U(e),ne=xe>>>12,se=(xe>>9&7)+1;g.info.sampleRate=ne,g.info.numberOfChannels=se,e.skip(20)}else e.skip(ie);if(Y&R)break}const L=e.filePos;e.filePos=O;const N=X(e,L-O),H=new Uint8Array(4+N.byteLength);new DataView(H.buffer).setUint32(0,1716281667,!1),H.set(N,4),g.info.codecDescription=H}break;case"dac3":{const g=this.currentTrack;if(!g||((T=g.info)==null?void 0:T.type)!=="audio")break;const v=X(e,3),R=new re(v),O=R.readBits(2);R.skipBits(8);const L=R.readBits(3),N=R.readBits(1);O<3&&(g.info.sampleRate=Xi[O]),g.info.numberOfChannels=Ss[L]+N}break;case"dec3":{const g=this.currentTrack;if(!g||((k=g.info)==null?void 0:k.type)!=="audio")break;const v=X(e,i.contentSize),R=iu(v);if(!R){j._warn("Invalid dec3 box contents, ignoring.");break}const O=Fo(R);O!==null&&(g.info.sampleRate=O),g.info.numberOfChannels=Do(R)}break;case"ddts":{const g=this.currentTrack;if(!g||((x=g.info)==null?void 0:x.type)!=="audio")break;const v=X(e,Math.min(i.contentSize,As)),R=pu(v);if(!R){j._warn("Invalid ddts box contents, ignoring.");break}g.info.sampleRate=R.sampleRate,R.numberOfChannels!==null&&(g.info.numberOfChannels=R.numberOfChannels)}break;case"dmlp":{const g=this.currentTrack;if(!g||((P=g.info)==null?void 0:P.type)!=="audio")break;const v=U(e),R=v>>>28;if(R===15){j._warn("Invalid dmlp box contents, ignoring.");break}g.info.sampleRate=(R&8?44100:48e3)<<(R&7);const O=v>>>15&31,N=v&8191||O;let H=0;for(let Q=0;Q<da.length;Q++)N&1<<Q&&(H+=da[Q]);g.info.numberOfChannels=H}break;case"stts":{const g=this.currentTrack;if(!g||!g.sampleTable)break;e.skip(4);const v=U(e);let R=0,O=0;for(let L=0;L<v;L++){const N=U(e),H=U(e);g.sampleTable.sampleTimingEntries.push({startIndex:R,startDecodeTimestamp:O,count:N,delta:H}),R+=N,O+=N*H}}break;case"ctts":{const g=this.currentTrack;if(!g||!g.sampleTable)break;e.skip(4);const v=U(e);let R=0;for(let O=0;O<v;O++){const L=U(e),N=Vt(e);g.sampleTable.sampleCompositionTimeOffsets.push({startIndex:R,count:L,offset:N,startTimestamp:-1,lastTimestamp:-1,maxLastTimestamp:-1}),R+=L}}break;case"stsz":{const g=this.currentTrack;if(!g||!g.sampleTable)break;e.skip(4);const v=U(e),R=U(e);if(v===0)for(let O=0;O<R;O++){const L=U(e);g.sampleTable.sampleSizes.push(L)}else g.sampleTable.sampleSizes.push(v);g.sampleTable.sampleCount=R}break;case"stz2":{const g=this.currentTrack;if(!g||!g.sampleTable)break;e.skip(4),e.skip(3);const v=K(e),R=U(e);if(v!==4&&v!==8&&v!==16)throw new Error(`Invalid stz2 box: unsupported field size ${v}.`);const O=X(e,Math.ceil(R*v/8)),L=new re(O);for(let N=0;N<R;N++){const H=L.readBits(v);g.sampleTable.sampleSizes.push(H)}g.sampleTable.sampleCount=R}break;case"stss":{const g=this.currentTrack;if(!g||!g.sampleTable)break;e.skip(4),g.sampleTable.keySampleIndices=[];const v=U(e);for(let R=0;R<v;R++){const O=U(e)-1;g.sampleTable.keySampleIndices.push(O)}g.sampleTable.keySampleIndices.sort((R,O)=>R-O),g.sampleTable.keySampleIndices[0]!==0&&g.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const g=this.currentTrack;if(!g||!g.sampleTable)break;e.skip(4);const v=U(e);let R=0;for(let L=0;L<v;L++){const N=U(e)-1,H=U(e),Q=U(e),Y=fe(g.sampleTable.sampleToChunk);if(Y&&N<=Y.startChunkIndex){R++;continue}g.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:N,samplesPerChunk:H,sampleDescriptionIndex:Q})}R>0&&j._warn(`Skipped ${R} invalid stsc entries whose chunk indices weren't strictly increasing.`);let O=0;for(let L=0;L<g.sampleTable.sampleToChunk.length;L++)if(g.sampleTable.sampleToChunk[L].startSampleIndex=O,L<g.sampleTable.sampleToChunk.length-1){const H=g.sampleTable.sampleToChunk[L+1].startChunkIndex-g.sampleTable.sampleToChunk[L].startChunkIndex;O+=H*g.sampleTable.sampleToChunk[L].samplesPerChunk}}break;case"stco":{const g=this.currentTrack;if(!g||!g.sampleTable)break;e.skip(4);const v=U(e);for(let R=0;R<v;R++){const O=U(e);g.sampleTable.chunkOffsets.push(O)}}break;case"co64":{const g=this.currentTrack;if(!g||!g.sampleTable)break;e.skip(4);const v=U(e);for(let R=0;R<v;R++){const O=Oe(e);g.sampleTable.chunkOffsets.push(O)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(n,i.contentSize));break;case"mehd":{const g=K(e);e.skip(3);const v=g===1?Oe(e):U(e);this.movieDurationInTimescale=v}break;case"trex":{e.skip(4);const g=U(e),v=U(e),R=U(e),O=U(e),L=U(e);this.fragmentTrackDefaults.set(g,{trackId:g,defaultSampleDescriptionIndex:v,defaultSampleDuration:R,defaultSampleSize:O,defaultSampleFlags:L})}break;case"tfra":{const g=K(e);e.skip(3);const v=U(e),R=this.idToTrack.get(v);if(!R)break;const O=U(e),L=(O&48)>>4,N=(O&12)>>2,H=O&3,Q=[K,we,dt,U],Y=Q[L],ie=Q[N],ue=Q[H],xe=U(e);for(let ne=0;ne<xe;ne++){const se=g===1?Oe(e):U(e),oe=g===1?Oe(e):U(e);Y(e);const $e=ie(e),ct=ue(e);$e>=1&&ct>=1&&R.fragmentLookupTable.push({timestamp:se,moofOffset:oe,trunNumber:$e,sampleNumber:ct})}}break;case"moof":{if(this.currentFragment)break;this.currentFragment={moofOffset:t,moofSize:i.totalSize,implicitBaseDataOffset:t,trackData:new Map,psshBoxes:[],sampleCount:0};try{this.readContiguousBoxes(e.slice(n,i.contentSize)),this.lastReadFragment=this.currentFragment}finally{this.currentFragment=null,this.currentTrack=null}}break;case"traf":{if(!this.currentFragment||this.isReadingTraf)break;this.isReadingTraf=!0;try{this.readContiguousBoxes(e.slice(n,i.contentSize))}finally{this.isReadingTraf=!1}if(this.currentTrack){const g=this.currentFragment.trackData.get(this.currentTrack.id);e:if(g){if(g.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break e}g.presentationTimestamps=g.samples.map((L,N)=>({presentationTimestamp:L.presentationTimestamp,sampleIndex:N})).sort((L,N)=>L.presentationTimestamp-N.presentationTimestamp);for(let L=0;L<g.presentationTimestamps.length;L++){const N=g.presentationTimestamps[L],H=g.samples[N.sampleIndex];if(g.firstKeyFrameTimestamp===null&&H.isKeyFrame&&(g.firstKeyFrameTimestamp=H.presentationTimestamp),L<g.presentationTimestamps.length-1){const Y=g.presentationTimestamps[L+1].presentationTimestamp-N.presentationTimestamp;H.duration=Y}}const v=g.samples[g.presentationTimestamps[0].sampleIndex],R=g.samples[fe(g.presentationTimestamps).sampleIndex];g.startTimestamp=v.presentationTimestamp,g.endTimestamp=R.presentationTimestamp+R.duration;const{currentFragmentState:O}=this.currentTrack;y(O),O.startTimestamp!==null&&(Pn(g,O.startTimestamp),g.startTimestampIsFinal=!0),O.encryptionAuxInfo&&!g.samples[0].encryption&&(g.encryptionAuxInfo=O.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}}break;case"pssh":{if((I=this.input._formatOptions.isobmff)!=null&&I._suppressPsshParsing)break;const g=Qo(X(e,i.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(g):this.currentTrack||this.psshBoxes.push(g)}break;case"tfhd":{if(!this.currentFragment||!this.isReadingTraf||this.currentTrack)break;e.skip(1);const g=dt(e),v=!!(g&1),R=!!(g&2),O=!!(g&8),L=!!(g&16),N=!!(g&32),H=!!(g&65536),Q=!!(g&131072),Y=U(e),ie=this.idToTrack.get(Y);if(!ie)break;if(this.currentFragment.trackData.has(Y)){j._warn(`Multiple traf boxes for track ${Y} in the same moof box; skipping.`);break}const ue=this.fragmentTrackDefaults.get(Y);this.currentTrack=ie,ie.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:(ue==null?void 0:ue.defaultSampleDescriptionIndex)??null,defaultSampleDuration:(ue==null?void 0:ue.defaultSampleDuration)??null,defaultSampleSize:(ue==null?void 0:ue.defaultSampleSize)??null,defaultSampleFlags:(ue==null?void 0:ue.defaultSampleFlags)??null,startTimestamp:null,encryptionAuxInfo:null},v?ie.currentFragmentState.baseDataOffset=Oe(e):Q&&(ie.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),R&&(ie.currentFragmentState.sampleDescriptionIndex=U(e)),O&&(ie.currentFragmentState.defaultSampleDuration=U(e)),L&&(ie.currentFragmentState.defaultSampleSize=U(e)),N&&(ie.currentFragmentState.defaultSampleFlags=U(e)),H&&(ie.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const g=this.currentTrack;if(!(g!=null&&g.currentFragmentState))break;const v=K(e);e.skip(3);const R=v===0?U(e):Oe(e);g.currentFragmentState.startTimestamp=R}break;case"trun":{const g=this.currentTrack;if(!(g!=null&&g.currentFragmentState)||!this.currentFragment)break;e.skip(1);const v=dt(e),R=!!(v&1),O=!!(v&4),L=!!(v&256),N=!!(v&512),H=!!(v&1024),Q=!!(v&2048),Y=U(e),{defaultSampleDuration:ie,defaultSampleSize:ue,defaultSampleFlags:xe}=g.currentFragmentState;if(Y>0&&(!L&&ie===null||!N&&ue===null||!H&&xe===null))throw new Error("Invalid trun box: sample values are missing and there are no defaults.");if(this.currentFragment.sampleCount+=Y,this.currentFragment.sampleCount>2**20)throw new Error("Too many (> 2^20) samples in fragment.");let ne=null;R&&(ne=Vt(e));let se=null;O&&(se=U(e));let oe;this.currentFragment.trackData.has(g.id)?(oe=this.currentFragment.trackData.get(g.id),ne!==null&&(oe.currentOffset=g.currentFragmentState.baseDataOffset+ne)):(oe={track:g,currentTimestamp:0,currentOffset:g.currentFragmentState.baseDataOffset+(ne??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,trunSampleCounts:[],encryptionAuxInfo:null},this.currentFragment.trackData.set(g.id,oe)),oe.trunSampleCounts.push(Y);for(let $e=0;$e<Y;$e++){let ct;L?ct=U(e):ct=ie;let mi;N?mi=U(e):mi=ue;let pi;H?pi=U(e):pi=xe,$e===0&&se!==null&&(pi=se);let Ls=0;Q&&(Ls=Vt(e));const Yc=!(pi&65536);oe.samples.push({presentationTimestamp:oe.currentTimestamp+Ls,duration:ct,byteOffset:oe.currentOffset,byteSize:mi,isKeyFrame:Yc,encryption:null}),oe.currentOffset+=mi,oe.currentTimestamp+=ct}this.currentFragment.implicitBaseDataOffset=oe.currentOffset}break;case"saiz":{const g=this.currentTrack;if(!g||!g.encryptionInfo)break;if(e.skip(1),dt(e)&1){const H=be(e,4),Q=U(e);if(H!==g.encryptionInfo.scheme||Q!==0)break}const R=K(e),O=U(e);let L=null;R===0&&O>0&&(L=X(e,O));const N=wa(g);N.defaultSampleInfoSize=R,N.sampleSizes=L,N.sampleCount=O}break;case"saio":{const g=this.currentTrack;if(!g||!g.encryptionInfo)break;const v=K(e);if(dt(e)&1){const H=be(e,4),Q=U(e);if(H!==g.encryptionInfo.scheme||Q!==0)break}const O=U(e);if(O===0)break;O>1&&j._warn("Multiple saio entries are not supported; using the first offset only.");let L=v===0?U(e):Number(Oe(e));this.currentFragment&&(L+=this.currentFragment.moofOffset);const N=wa(g);N.offset=L}break;case"senc":{const g=this.currentTrack;if(!g||!g.encryptionInfo)break;const v=(E=this.currentFragment)==null?void 0:E.trackData.get(g.id);if(!v)break;e.skip(1);const O=!!(dt(e)&2),L=U(e),N=g.encryptionInfo.defaultPerSampleIvSize;if(N===null)throw new Error("Invalid file: encrypted track is missing its tenc box.");for(let H=0;H<Math.min(L,v.samples.length);H++){const Q=new Uint8Array(16);if(N>0)Q.set(X(e,N),0);else if(g.encryptionInfo.defaultConstantIv)Q.set(g.encryptionInfo.defaultConstantIv,0);else throw new Error("Invalid file: encrypted sample has no IV.");let Y=null;if(O){const ue=we(e);Y=[];for(let xe=0;xe<ue;xe++){const ne=we(e),se=U(e);Y.push({clearLen:ne,protectedLen:se})}}const ie=v.samples[H];ie.encryption={iv:Q,subsamples:Y}}}break;case"udta":{const g=this.iterateContiguousBoxes(e.slice(n,i.contentSize));for(const{boxInfo:v,slice:R}of g){if(v.name!=="meta"&&!this.currentTrack){const O=R.filePos;(C=this.metadataTags).raw??(C.raw={}),v.name[0]==="©"?(_=this.metadataTags.raw)[D=v.name]??(_[D]=tt(R)):(q=this.metadataTags.raw)[M=v.name]??(q[M]=X(R,v.contentSize)),R.filePos=O}switch(v.name){case"meta":R.skip(-v.headerSize),this.traverseBox(R);break;case"©nam":case"name":this.currentTrack?this.currentTrack.name=_e.decode(X(R,v.contentSize)):(V=this.metadataTags).title??(V.title=tt(R));break;case"©des":this.currentTrack||((G=this.metadataTags).description??(G.description=tt(R)));break;case"©ART":this.currentTrack||((J=this.metadataTags).artist??(J.artist=tt(R)));break;case"©alb":this.currentTrack||((ae=this.metadataTags).album??(ae.album=tt(R)));break;case"albr":this.currentTrack||((he=this.metadataTags).albumArtist??(he.albumArtist=tt(R)));break;case"©gen":this.currentTrack||((le=this.metadataTags).genre??(le.genre=tt(R)));break;case"©day":if(!this.currentTrack){const O=new Date(tt(R));Number.isNaN(O.getTime())||((ye=this.metadataTags).date??(ye.date=O))}break;case"©cmt":this.currentTrack||((Ve=this.metadataTags).comment??(Ve.comment=tt(R)));break;case"©lyr":this.currentTrack||((et=this.metadataTags).lyrics??(et.lyrics=tt(R)));break}}}break;case"meta":{if(this.currentTrack)break;const v=U(e)!==0;this.currentMetadataKeys=new Map,v?this.readContiguousBoxes(e.slice(n,i.contentSize)):this.readContiguousBoxes(e.slice(n+4,i.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const g=U(e);for(let v=0;v<g;v++){const R=U(e);if(R<8)throw new Error("Invalid keys box: key size must be at least 8.");e.skip(4);const O=_e.decode(X(e,R-8));this.currentMetadataKeys.set(v+1,O)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const g=this.iterateContiguousBoxes(e.slice(n,i.contentSize));for(const{boxInfo:v,slice:R}of g){let O=v.name;const L=(O.charCodeAt(0)<<24)+(O.charCodeAt(1)<<16)+(O.charCodeAt(2)<<8)+O.charCodeAt(3);this.currentMetadataKeys.has(L)&&(O=this.currentMetadataKeys.get(L));const N=jf(R);switch((pr=this.metadataTags).raw??(pr.raw={}),(gr=this.metadataTags.raw)[O]??(gr[O]=N),O){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":typeof N=="string"&&((br=this.metadataTags).title??(br.title=N));break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof N=="string"&&((wr=this.metadataTags).description??(wr.description=N));break;case"©ART":case"com.apple.quicktime.artist":case"artist":typeof N=="string"&&((kr=this.metadataTags).artist??(kr.artist=N));break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":typeof N=="string"&&((yr=this.metadataTags).album??(yr.album=N));break;case"aART":case"album_artist":typeof N=="string"&&((Sr=this.metadataTags).albumArtist??(Sr.albumArtist=N));break;case"©cmt":case"com.apple.quicktime.comment":case"comment":typeof N=="string"&&((Ar=this.metadataTags).comment??(Ar.comment=N));break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof N=="string"&&((Tr=this.metadataTags).genre??(Tr.genre=N));break;case"©lyr":case"lyrics":typeof N=="string"&&((xr=this.metadataTags).lyrics??(xr.lyrics=N));break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof N=="string"){const H=new Date(N);Number.isNaN(H.getTime())||((Pr=this.metadataTags).date??(Pr.date=H))}break;case"tmpo":if(N instanceof Uint8Array&&N.length>=2){const H=Z(N).getInt16(0,!1);H>0&&((Ir=this.metadataTags).beatsPerMinute??(Ir.beatsPerMinute=H))}break;case"covr":case"com.apple.quicktime.artwork":N instanceof Gr?((Cr=this.metadataTags).images??(Cr.images=[]),this.metadataTags.images.push({data:N.data,kind:"coverFront",mimeType:N.mimeType})):N instanceof Uint8Array&&((Er=this.metadataTags).images??(Er.images=[]),this.metadataTags.images.push({data:N,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof N=="string"){const H=N.split("/"),Q=Number.parseInt(H[0],10),Y=H[1]&&Number.parseInt(H[1],10);Number.isInteger(Q)&&Q>0&&((_r=this.metadataTags).trackNumber??(_r.trackNumber=Q)),Y&&Number.isInteger(Y)&&Y>0&&((vr=this.metadataTags).tracksTotal??(vr.tracksTotal=Y))}break;case"trkn":if(N instanceof Uint8Array&&N.length>=6){const H=Z(N),Q=H.getUint16(2,!1),Y=H.getUint16(4,!1);Q>0&&((Rr=this.metadataTags).trackNumber??(Rr.trackNumber=Q)),Y>0&&((z=this.metadataTags).tracksTotal??(z.tracksTotal=Y))}break;case"disc":case"disk":if(N instanceof Uint8Array&&N.length>=6){const H=Z(N),Q=H.getUint16(2,!1),Y=H.getUint16(4,!1);Q>0&&(($=this.metadataTags).discNumber??($.discNumber=Q)),Y>0&&((me=this.metadataTags).discsTotal??(me.discsTotal=Y))}break}}}break}return e.filePos=s,!0}}class Jo{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const n of e.tracks)if(n.trackBacking.getType()===t&&i++,n===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}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(){const e=this.internalTrack;if(e.durationInMediaTimescale<=0)return null;y(e.trackBacking);const t=await e.trackBacking.getFirstPacket({metadataOnly:!0});return((t==null?void 0:t.timestamp)??0)+e.durationInMediaTimescale/e.timescale}async getLiveRefreshInterval(){return null}async getFirstPacket(e){const t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,i=>i.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return ei(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=rs(n,i),a=await this.fetchPacketForSampleIndex(s,t);return!ga(n)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};const u=te(c.presentationTimestamps,i,f=>f.presentationTimestamp),l=u!==-1?c.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&i<c.endTimestamp;return{sampleIndex:l,correctSampleFound:d}},i,i,t)}async getNextPacket(e,t){const i=this.packetToSampleIndex.get(e);if(i!==void 0)return this.fetchPacketForSampleIndex(i+1,t);const n=this.packetToFragmentLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,s=>{if(s===n.fragment){const a=s.trackData.get(this.internalTrack.id);if(n.sampleIndex+1<a.samples.length)return{sampleIndex:n.sampleIndex+1,correctSampleFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){const i=this.mapTimestampIntoTimescale(e),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Ju(n,i),a=await this.fetchPacketForSampleIndex(s,t);return!ga(n)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};const u=fs(c.presentationTimestamps,f=>c.samples[f.sampleIndex].isKeyFrame&&f.presentationTimestamp<=i),l=u!==-1?c.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&i<c.endTimestamp;return{sampleIndex:l,correctSampleFound:d}},i,i,t,!0)}async getNextKeyPacket(e,t){const i=this.packetToSampleIndex.get(e);if(i!==void 0){const s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=rd(s,i);return this.fetchPacketForSampleIndex(a,t)}const n=this.packetToFragmentLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,s=>{if(s===n.fragment){const a=s.trackData.get(this.internalTrack.id);for(let o=n.sampleIndex+1;o<a.samples.length;o++)if(a.samples[o].isKeyFrame)return{sampleIndex:o,correctSampleFound:!0}}else{const a=s.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){const o=a.samples.findIndex(c=>c.isKeyFrame);return y(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=ed(i,e);if(!n)return null;let s;if(t.metadataOnly)s=je;else{let u=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);if(F(u)&&(u=await u),!u)return null;if(s=X(u,n.sampleSize),this.internalTrack.encryptionInfo){let l=null;if(this.internalTrack.encryptionAuxInfo){const d=await rc(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<d.length&&(l=d[e])}l??(l=ka(this.internalTrack.encryptionInfo)),l&&(s=await ya(this.internalTrack,l,s,null))}}const a=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=n.duration/this.internalTrack.timescale,c=new ce(s,n.isKeyFrame?"key":"delta",a,o,e,n.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,i){if(t===-1)return null;const s=e.trackData.get(this.internalTrack.id).samples[t];y(s);let a;if(i.metadataOnly)a=je;else{let l=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);if(F(l)&&(l=await l),!l)return null;if(a=X(l,s.byteSize),this.internalTrack.encryptionInfo){const d=s.encryption??ka(this.internalTrack.encryptionInfo);d&&(a=await ya(this.internalTrack,d,a,e))}}const o=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=s.duration/this.internalTrack.timescale,u=new ce(a,s.isKeyFrame?"key":"delta",o,c,e.moofOffset+t,s.byteSize);return this.packetToFragmentLocation.set(u,{fragment:e,sampleIndex:t}),u}async performFragmentedLookup(e,t,i,n,s,a=!1){var m,b;const{demuxer:o,fragmentLookupTable:c,fragmentPositionCache:u}=this.internalTrack;let l=null,d=-1;if(e){const{sampleIndex:w,correctSampleFound:S}=t(e);if(S)return this.fetchPacketInFragment(e,w,s);w!==-1&&(l=e,d=w)}let f=te(c,i,w=>w.timestamp),h=te(u,i,w=>w.startTimestamp),p=1/0;for(;;){for(;f!==-1&&c[f].moofOffset>=p;)f--;for(;h!==-1&&(u[h].moofOffset>=p||a&&!u[h].hasKeyFrame);)h--;const w=Math.max(((m=c[f])==null?void 0:m.moofOffset)??0,((b=u[h])==null?void 0:b.moofOffset)??0)||null;let S,A=null;e?w===null||e.moofOffset>=w?(S=e.moofOffset+e.moofSize,A=e):S=w:S=w??0;const T=A?A.moofOffset:S;for(;S<p;){if(A){const E=A.trackData.get(this.internalTrack.id);if(E&&E.startTimestamp>n)break;A=null}const k=o.fragmentSummaries.get(S);if(k&&!k.trackIds.has(this.internalTrack.id)){S+=k.moofSize;continue}let x=o.reader.requestSliceRange(S,ir,Kr);if(F(x)&&(x=await x),!x)break;const P=S,I=Tt(x);if(!I)break;if(I.name==="moof"){if(A=await o.readFragment(P),!A)break;const{sampleIndex:E,correctSampleFound:C}=t(A);if(C)return this.fetchPacketInFragment(A,E,s);E!==-1&&(l=A,d=E)}S=P+I.totalSize}if(w===null||l&&l.moofOffset>=w)break;p=T,e=null}return l?this.fetchPacketInFragment(l,d,s):null}}class fa extends Jo{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(){var t,i,n,s;const e=await this.getDecoderConfig();return e?{primaries:(t=e.colorSpace)==null?void 0:t.primaries,transfer:(i=e.colorSpace)==null?void 0:i.transfer,matrix:(n=e.colorSpace)==null?void 0:n.matrix,fullRange:(s=e.colorSpace)==null?void 0:s.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??(this.decoderConfigPromise=(async()=>{var t,i,n,s;if(this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription){const a=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=a&&$i(a.data)}else if(this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription){const a=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=a&&Ji(a.data)}else if(this.internalTrack.info.codec==="vp9"&&(!this.internalTrack.info.vp9CodecInfo||!Ql(this.internalTrack.info.vp9CodecInfo))){const a=await this.getFirstPacket({}),o=a&&ks(a.data);o&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??o,videoFullRangeFlag:o.videoFullRangeFlag,colourPrimaries:o.colourPrimaries,transferCharacteristics:o.transferCharacteristics,matrixCoefficients:o.matrixCoefficients})}else if(this.internalTrack.info.codec==="av1"&&(!this.internalTrack.info.av1CodecInfo||!vo(this.internalTrack.info.av1CodecInfo))){const a=await this.getFirstPacket({}),o=a&&en(a.data);o&&(this.internalTrack.info.av1CodecInfo=o)}else if(this.internalTrack.info.codec==="prores"&&!this.internalTrack.info.proresCodecInfo){const a=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=a&&Ro(a.data)}if(!ds(this.internalTrack.info.colorSpace)){const a=Xc(this.internalTrack.info);(t=this.internalTrack.info.colorSpace).primaries??(t.primaries=a.primaries),(i=this.internalTrack.info.colorSpace).transfer??(i.transfer=a.transfer),(n=this.internalTrack.info.colorSpace).matrix??(n.matrix=a.matrix),(s=this.internalTrack.info.colorSpace).fullRange??(s.fullRange=a.fullRange)}const e={codec:fn(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}}class ha extends Jo{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??(this.decoderConfigPromise=(async()=>{if(this.internalTrack.info.codec==="dts"&&!this.internalTrack.info.dtsFormat){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&No(e.data)}return{codec:Us(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const rs=(r,e)=>{if(r.sortedCompositionTimeOffsets)return ec(r,e,!1);{const t=te(r.sampleTimingEntries,e,n=>n.startDecodeTimestamp);if(t===-1)return-1;const i=r.sampleTimingEntries[t];return i.delta===0?i.startIndex+i.count-1:i.startIndex+Math.min(Math.floor((e-i.startDecodeTimestamp)/i.delta),i.count-1)}},Ju=(r,e)=>{if(!r.keySampleIndices)return rs(r,e);if(r.sortedCompositionTimeOffsets)return ec(r,e,!0);{const t=rs(r,e),i=te(r.keySampleIndices,t,n=>n);return r.keySampleIndices[i]??-1}},ed=(r,e)=>{if(e>=r.sampleCount)return null;const t=te(r.sampleTimingEntries,e,b=>b.startIndex),i=r.sampleTimingEntries[t];let s=i.startDecodeTimestamp+(e-i.startIndex)*i.delta;const a=te(r.sampleCompositionTimeOffsets,e,b=>b.startIndex),o=r.sampleCompositionTimeOffsets[a];o&&e-o.startIndex<o.count&&(s+=o.offset);const c=r.sampleSizes[Math.min(e,r.sampleSizes.length-1)],u=te(r.sampleToChunk,e,b=>b.startSampleIndex),l=r.sampleToChunk[u],d=l.startChunkIndex+Math.floor((e-l.startSampleIndex)/l.samplesPerChunk),f=r.chunkOffsets[d],h=l.startSampleIndex+(d-l.startChunkIndex)*l.samplesPerChunk;let p=f;r.sampleSizes.length===1?p+=c*(e-h):p+=r.cumulativeSampleSizes[e]-r.cumulativeSampleSizes[h];let m=i.delta;if(r.sortedCompositionTimeOffsets){const b=td(r,e,s);b!==null&&(m=b-s)}return{presentationTimestamp:s,duration:m,sampleOffset:p,sampleSize:c,chunkOffset:f,isKeyFrame:r.keySampleIndices?fi(r.keySampleIndices,e,b=>b)!==-1:!0}},ec=(r,e,t)=>{const i=r.sortedCompositionTimeOffsets;let n=-1,s=-1/0;const a=te(i,e,o=>o.startTimestamp);for(let o=a;o>=0;o--){const c=i[o];if(c.maxLastTimestamp<s)break;let u=c.lastTimestamp<=e?c.startIndex+c.count-1:tc(r,c,(d,f)=>f>e)-1;if(t){const d=te(r.keySampleIndices,u,f=>f);u=r.keySampleIndices[d]??-1}if(u<c.startIndex)continue;const l=_s(r,u)+c.offset;(l>s||l===s&&u>n)&&(n=u,s=l)}return n},td=(r,e,t)=>{var a;const i=r.sortedCompositionTimeOffsets,n=te(i,t,o=>o.startTimestamp);let s=((a=i[n+1])==null?void 0:a.startTimestamp)??null;for(let o=n;o>=0;o--){const c=i[o];if(c.maxLastTimestamp<t)break;const u=tc(r,c,(d,f)=>f>t||f===t&&d>e);if(u===c.startIndex+c.count)continue;const l=_s(r,u)+c.offset;(s===null||l<s)&&(s=l)}return s},tc=(r,e,t)=>{let i=e.startIndex,n=e.startIndex+e.count;for(;i<n;){const s=Math.floor((i+n)/2);t(s,_s(r,s)+e.offset)?n=s:i=s+1}return i},_s=(r,e)=>{const t=te(r.sampleTimingEntries,e,n=>n.startIndex),i=r.sampleTimingEntries[t];return i.startDecodeTimestamp+(e-i.startIndex)*i.delta},rd=(r,e)=>{if(!r.keySampleIndices)return e+1;const t=te(r.keySampleIndices,e,i=>i);return r.keySampleIndices[t+1]??-1},Pn=(r,e)=>{r.startTimestamp+=e,r.endTimestamp+=e;for(const t of r.samples)t.presentationTimestamp+=e;for(const t of r.presentationTimestamps)t.presentationTimestamp+=e},ma=r=>[Mt(r),Mt(r),Bn(r),Mt(r),Mt(r),Bn(r),Mt(r),Mt(r),Bn(r)],pa=(r,e)=>{const t=r.info;if(t.type!=="video")return;const{num:i,den:n}=e;!(i>0&&n>0)||i===n||(i>n?(t.squarePixelWidth=Math.round(t.width*i/n),t.squarePixelHeight=t.height):(t.squarePixelWidth=t.width,t.squarePixelHeight=Math.round(t.height*n/i)))},ga=r=>r.sampleSizes.length===0,ba=(r,e)=>{for(;r.length>0&&fe(r).startIndex>=e;)r.pop();const t=fe(r);t&&(t.count=Math.min(t.count,e-t.startIndex))},wa=r=>{var e;return r.currentFragmentState?(e=r.currentFragmentState).encryptionAuxInfo??(e.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}):r.encryptionAuxInfo??(r.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null})},rc=async(r,e,t)=>{if(t.resolved)return t.resolved;if(t.offset===null||t.sampleCount===0)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let i=0;if(t.defaultSampleInfoSize>0)i=t.defaultSampleInfoSize*t.sampleCount;else{y(t.sampleSizes);for(let o=0;o<t.sampleCount;o++)i+=t.sampleSizes[o]}let n=r.requestSlice(t.offset,i);if(F(n)&&(n=await n),!n)throw new Error("Failed to read auxiliary encryption info.");const s=e.defaultPerSampleIvSize;if(s===null)throw new Error("Invalid file: encrypted track is missing its tenc box.");const a=[];for(let o=0;o<t.sampleCount;o++){const c=t.defaultSampleInfoSize>0?t.defaultSampleInfoSize:t.sampleSizes[o],u=new Uint8Array(16);if(s>0)u.set(X(n,s),0);else if(e.defaultConstantIv)u.set(e.defaultConstantIv,0);else throw new Error("Invalid file: encrypted sample has no IV.");let l=null;if(c>s){const d=we(n);l=[];for(let f=0;f<d;f++){const h=we(n),p=U(n);l.push({clearLen:h,protectedLen:p})}}a.push({iv:u,subsamples:l})}return t.resolved=a,a},ka=r=>r.defaultConstantIv?{iv:r.defaultConstantIv,subsamples:null}:null,ya=async(r,e,t,i)=>{var c;y(r.encryptionInfo);const n=r.encryptionInfo;if(n.defaultKid===null)throw new Error("Invalid file: encrypted track is missing its tenc box.");const s=n.defaultKid;let a;const o=r.demuxer.decryptionKeyCache.get(s);if(o)a=await o;else{if(!((c=r.demuxer.input._formatOptions.isobmff)!=null&&c.resolveKeyId))throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const u=(async()=>{let l=r.demuxer.psshBoxes;if(i){l=[...l,...i.psshBoxes].filter(f=>f.keyIds===null||f.keyIds.includes(s));for(let f=0;f<l.length-1;f++)for(let h=f+1;h<l.length;h++)Go(l[f],l[h])&&(l.splice(h,1),h--)}const d=await r.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:s,psshBoxes:l});if(!(typeof d=="string"&&d.length===32&&nl.test(d)||d instanceof Uint8Array&&d.byteLength===16))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return d instanceof Uint8Array?d:sl(d)})();r.demuxer.decryptionKeyCache.set(s,u),a=await u}return n.scheme==="cenc"||n.scheme==="cens"?id(a,n,e,t):nd(a,n,e,t)},id=async(r,e,t,i)=>{const n=new Uint8Array(16);n.set(t.iv,0);const s=await crypto.subtle.importKey("raw",r,{name:"AES-CTR"},!1,["decrypt"]),a=async p=>{const m=await crypto.subtle.decrypt({name:"AES-CTR",counter:n,length:64},s,p);return new Uint8Array(m)};if(!t.subsamples)return a(i);y(e.defaultCryptByteBlock!==null&&e.defaultSkipByteBlock!==null);const o=ic(t.subsamples,e.defaultCryptByteBlock,e.defaultSkipByteBlock,i.length);let c=0;for(const p of o)for(const m of p.perSubsample)c+=m.length;const u=new Uint8Array(c);let l=0;for(const p of o)for(const m of p.perSubsample)u.set(i.subarray(m.offset,m.offset+m.length),l),l+=m.length;const d=await a(u),f=new Uint8Array(i);let h=0;for(const p of o)for(const m of p.perSubsample)f.set(d.subarray(h,h+m.length),m.offset),h+=m.length;return f},nd=(r,e,t,i)=>{const n=new Zo;n.init({key:r,iv:t.iv});const s=e.defaultCryptByteBlock,a=e.defaultSkipByteBlock;if(y(s!==null&&a!==null),!t.subsamples){const l=new Uint8Array(i),d=Math.floor(i.length/16);for(let f=0;f<d;f++){const h=f*16;n.in.set(i.subarray(h,h+16)),n.decrypt(),l.set(n.out,h)}return l}if(s===0&&a===0)throw new Error("cbcs with subsamples requires pattern encryption.");const o=new Uint8Array(i),c=ic(t.subsamples,s,a,i.length),u=new DataView(t.iv.buffer,t.iv.byteOffset,16);for(const l of c){n.iv[0]=u.getUint32(0,!1),n.iv[1]=u.getUint32(4,!1),n.iv[2]=u.getUint32(8,!1),n.iv[3]=u.getUint32(12,!1);for(const d of l.perSubsample){const f=d.length/16;for(let h=0;h<f;h++){const p=d.offset+h*16;n.in.set(i.subarray(p,p+16)),n.decrypt(),o.set(n.out,p)}}}return o},ic=(r,e,t,i)=>{const n=[],s=e!==0||t!==0;let a=0;for(const o of r){if(a+o.clearLen+o.protectedLen>i)throw new Error("Invalid encryption info: subsamples exceed the sample size.");a+=o.clearLen;const c=[];if(!s)o.protectedLen>0&&c.push({offset:a,length:o.protectedLen}),a+=o.protectedLen;else{let u=o.protectedLen,l=a;for(;u>0&&!(u<16*e);){const d=16*e;c.push({offset:l,length:d}),l+=d,u-=d;const f=Math.min(16*t,u);l+=f,u-=f}a+=o.protectedLen}n.push({perSubsample:c})}return n};/*!
140
+ * Copyright (c) 2026-present, Vanilagy and contributors
141
+ *
142
+ * This Source Code Form is subject to the terms of the Mozilla Public
143
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
144
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
145
+ */class sd{constructor(e){this.value=e}}class ad{constructor(e){this.value=e}}class od{constructor(e){this.value=e}}class cd{constructor(e){this.value=e}}var B;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Duration=17545]="Duration",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.DateUTC=17505]="DateUTC",r[r.MuxingApp=19840]="MuxingApp",r[r.WritingApp=22337]="WritingApp",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.TrackNumber=215]="TrackNumber",r[r.TrackUID=29637]="TrackUID",r[r.TrackType=131]="TrackType",r[r.FlagEnabled=185]="FlagEnabled",r[r.FlagDefault=136]="FlagDefault",r[r.FlagForced=21930]="FlagForced",r[r.FlagOriginal=21934]="FlagOriginal",r[r.FlagHearingImpaired=21931]="FlagHearingImpaired",r[r.FlagVisualImpaired=21932]="FlagVisualImpaired",r[r.FlagCommentary=21935]="FlagCommentary",r[r.FlagLacing=156]="FlagLacing",r[r.Name=21358]="Name",r[r.Language=2274716]="Language",r[r.LanguageBCP47=2274717]="LanguageBCP47",r[r.CodecID=134]="CodecID",r[r.CodecPrivate=25506]="CodecPrivate",r[r.CodecDelay=22186]="CodecDelay",r[r.SeekPreRoll=22203]="SeekPreRoll",r[r.DefaultDuration=2352003]="DefaultDuration",r[r.Video=224]="Video",r[r.PixelWidth=176]="PixelWidth",r[r.PixelHeight=186]="PixelHeight",r[r.DisplayWidth=21680]="DisplayWidth",r[r.DisplayHeight=21690]="DisplayHeight",r[r.DisplayUnit=21682]="DisplayUnit",r[r.AlphaMode=21440]="AlphaMode",r[r.Audio=225]="Audio",r[r.SamplingFrequency=181]="SamplingFrequency",r[r.Channels=159]="Channels",r[r.BitDepth=25188]="BitDepth",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.Block=161]="Block",r[r.BlockAdditions=30113]="BlockAdditions",r[r.BlockMore=166]="BlockMore",r[r.BlockAdditional=165]="BlockAdditional",r[r.BlockAddID=238]="BlockAddID",r[r.BlockDuration=155]="BlockDuration",r[r.ReferenceBlock=251]="ReferenceBlock",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.CueRelativePosition=240]="CueRelativePosition",r[r.Colour=21936]="Colour",r[r.MatrixCoefficients=21937]="MatrixCoefficients",r[r.TransferCharacteristics=21946]="TransferCharacteristics",r[r.Primaries=21947]="Primaries",r[r.Range=21945]="Range",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPoseYaw=30323]="ProjectionPoseYaw",r[r.ProjectionPosePitch=30324]="ProjectionPosePitch",r[r.ProjectionPoseRoll=30325]="ProjectionPoseRoll",r[r.Attachments=423732329]="Attachments",r[r.AttachedFile=24999]="AttachedFile",r[r.FileDescription=18046]="FileDescription",r[r.FileName=18030]="FileName",r[r.FileMediaType=18016]="FileMediaType",r[r.FileData=18012]="FileData",r[r.FileUID=18094]="FileUID",r[r.Chapters=272869232]="Chapters",r[r.Tags=307544935]="Tags",r[r.Tag=29555]="Tag",r[r.Targets=25536]="Targets",r[r.TargetTypeValue=26826]="TargetTypeValue",r[r.TargetType=25546]="TargetType",r[r.TagTrackUID=25541]="TagTrackUID",r[r.TagEditionUID=25545]="TagEditionUID",r[r.TagChapterUID=25540]="TagChapterUID",r[r.TagAttachmentUID=25542]="TagAttachmentUID",r[r.SimpleTag=26568]="SimpleTag",r[r.TagName=17827]="TagName",r[r.TagLanguage=17530]="TagLanguage",r[r.TagString=17543]="TagString",r[r.TagBinary=17541]="TagBinary",r[r.ContentEncodings=28032]="ContentEncodings",r[r.ContentEncoding=25152]="ContentEncoding",r[r.ContentEncodingOrder=20529]="ContentEncodingOrder",r[r.ContentEncodingScope=20530]="ContentEncodingScope",r[r.ContentCompression=20532]="ContentCompression",r[r.ContentCompAlgo=16980]="ContentCompAlgo",r[r.ContentCompSettings=16981]="ContentCompSettings",r[r.ContentEncryption=20533]="ContentEncryption"})(B||(B={}));const ld=[B.EBML,B.Segment],si=[B.SeekHead,B.Info,B.Cluster,B.Tracks,B.Cues,B.Attachments,B.Chapters,B.Tags],Ai=[...ld,...si],Sa=r=>r<256?1:r<65536?2:r<1<<24?3:r<2**32?4:r<2**40?5:6,Aa=r=>r<1n<<8n?1:r<1n<<16n?2:r<1n<<24n?3:r<1n<<32n?4:r<1n<<40n?5:r<1n<<48n?6:r<1n<<56n?7:8,Ta=r=>r>=-64&&r<64?1:r>=-8192&&r<8192?2:r>=-1048576&&r<1<<20?3:r>=-134217728&&r<1<<27?4:r>=-17179869184&&r<2**34?5:6,ud=r=>{if(r<127)return 1;if(r<16383)return 2;if(r<(1<<21)-1)return 3;if(r<(1<<28)-1)return 4;if(r<2**35-1)return 5;if(r<2**42-1)return 6;throw new Error("EBML varint size not supported "+r)};class im{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=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=Sa(e)){let i=0;switch(t){case 6:this.helperView.setUint8(i++,e/2**40|0);case 5:this.helperView.setUint8(i++,e/2**32|0);case 4:this.helperView.setUint8(i++,e>>24);case 3:this.helperView.setUint8(i++,e>>16);case 2:this.helperView.setUint8(i++,e>>8);case 1:this.helperView.setUint8(i++,e);break;default:throw new Error("Bad unsigned int size "+t)}this.writer.write(this.helper.subarray(0,i))}writeUnsignedBigInt(e,t=Aa(e)){let i=0;for(let n=t-1;n>=0;n--)this.helperView.setUint8(i++,Number(e>>BigInt(n*8)&0xffn));this.writer.write(this.helper.subarray(0,i))}writeSignedInt(e,t=Ta(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=ud(e)){let i=0;switch(t){case 1:this.helperView.setUint8(i++,128|e);break;case 2:this.helperView.setUint8(i++,64|e>>8),this.helperView.setUint8(i++,e);break;case 3:this.helperView.setUint8(i++,32|e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 4:this.helperView.setUint8(i++,16|e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 5:this.helperView.setUint8(i++,8|e/2**32&7),this.helperView.setUint8(i++,e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 6:this.helperView.setUint8(i++,4|e/2**40&3),this.helperView.setUint8(i++,e/2**32|0),this.helperView.setUint8(i++,e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;default:throw new Error("Bad EBML varint size "+t)}this.writer.write(this.helper.subarray(0,i))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split("").map(t=>t.charCodeAt(0))))}writeEBML(e){if(e!==null)if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(const t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){const t=this.writer.getPos(),i=e.size===-1?1:e.size??4;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+i);const n=this.writer.getPos();if(this.dataOffsets.set(e,n),this.writeEBML(e.data),e.size!==-1){const s=this.writer.getPos()-n,a=this.writer.getPos();this.writer.seek(t),this.writeVarInt(s,i),this.writer.seek(a)}}else if(typeof e.data=="number"){const t=e.size??Sa(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data=="bigint"){const t=e.size??Aa(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 sd)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof ad)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof od){const t=e.size??Ta(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof cd){const t=Ye.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else ze(e.data)}}const dd=Date.UTC(2001,0,1),nc=8,We=2,at=2*nc,sc=r=>{if(r.remainingLength<1)return null;const e=K(r);if(r.skip(-1),e===0)return null;let t=1,i=128;for(;(e&i)===0;)t++,i>>=1;return r.remainingLength<t?null:t},Hr=r=>{if(r.remainingLength<1)return null;const e=K(r);if(e===0)return null;let t=1,i=128;for(;(e&i)===0;)t++,i>>=1;if(r.remainingLength<t-1)return null;let n=e&i-1;for(let s=1;s<t;s++)n*=256,n+=K(r);return n},ee=(r,e)=>{if(e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let i=0;i<e;i++)t*=256,t+=K(r);return t},ac=(r,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0n;for(let i=0;i<e;i++)t<<=8n,t+=BigInt(K(r));return t},fd=(r,e)=>e===0?0n:BigInt.asIntN(8*e,ac(r,e)),vs=r=>{const e=sc(r);return e===null||r.remainingLength<e?null:ee(r,e)},oc=r=>{if(r.remainingLength<1)return null;if(K(r)===255)return;r.skip(-1);const t=Hr(r);if(t===null)return null;if(t!==72057594037927940)return t},nt=r=>{y(r.remainingLength>=We);const e=vs(r);if(e===null)return null;const t=oc(r);return t===null?null:{id:e,size:t}},rr=(r,e)=>{const t=X(r,e);let i="";for(let n=0;n<e&&t[n]!==0;n++)i+=String.fromCharCode(t[n]);return i},zr=(r,e)=>{const t=X(r,e);let i=0;for(;i<e&&t[i]!==0;)i+=1;return _e.decode(t.subarray(0,i))},Ur=(r,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?Hf(r):Vc(r)},is=async(r,e,t,i)=>{const n=new Set(t);let s=e;for(;i===null||s<i;){let a=r.requestSliceRange(s,We,at);if(F(a)&&(a=await a),!a)break;const o=nt(a);if(!o)break;if(n.has(o.id))return{pos:s,found:!0};ut(o.size),s=a.filePos+o.size}return{pos:i!==null&&i>s?i:s,found:!1}},cc=async(r,e,t,i)=>{const s=new Set(t);let a=e;for(;a<i;){let o=r.requestSliceRange(a,0,Math.min(65536,i-a));if(F(o)&&(o=await o),!o||o.length===0)break;const c=Math.max(o.length-nc,1);for(let u=0;u<c;u++){o.filePos=a;const l=vs(o);if(l!==null&&s.has(l))return a;a++}}return null},Be={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 ut(r){if(r===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}/*!
146
+ * Copyright (c) 2026-present, Vanilagy and contributors
147
+ *
148
+ * This Source Code Form is subject to the terms of the Mozilla Public
149
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
150
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
151
+ */const hd=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isWebM?"webm":"x-matroska");if(r.codecStrings.length>0){const i=[...new Set(r.codecStrings.filter(Boolean))];t+=`; codecs="${i.join(", ")}"`}return t};/*!
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
+ */var ft;(function(r){r[r.None=0]="None",r[r.Xiph=1]="Xiph",r[r.FixedSize=2]="FixedSize",r[r.Ebml=3]="Ebml"})(ft||(ft={}));var Oi;(function(r){r[r.Block=1]="Block",r[r.Private=2]="Private",r[r.Next=4]="Next"})(Oi||(Oi={}));var $r;(function(r){r[r.Zlib=0]="Zlib",r[r.Bzlib=1]="Bzlib",r[r.lzo1x=2]="lzo1x",r[r.HeaderStripping=3]="HeaderStripping"})($r||($r={}));const In=[{id:B.SeekHead,flag:"seekHeadSeen"},{id:B.Info,flag:"infoSeen"},{id:B.Tracks,flag:"tracksSeen"},{id:B.Cues,flag:"cuesSeen"}],lc=10*2**20,md=64;class pd extends yt{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.claimedSeekTargets=new Set,this.elementNestingDepth=0,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(t=>t.trackBacking))}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(i=>i.getDecoderConfig().then(n=>(n==null?void 0:n.codec)??null)));return hd({isWebM:this.isWebM,hasVideo:this.segments.some(i=>i.tracks.some(n=>{var s;return((s=n.info)==null?void 0:s.type)==="video"})),hasAudio:this.segments.some(i=>i.tracks.some(n=>{var s;return((s=n.info)==null?void 0:s.type)==="audio"})),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const t of this.segments)t.metadataTagsPromise||(this.reader.fileSize!==null?t.metadataTagsPromise=this.loadSegmentMetadata(t):t.metadataTagsPromise=Promise.resolve()),await t.metadataTagsPromise;let e={};for(const t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??(this.readMetadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,We,at);if(F(t)&&(t=await t),!t)break;const i=nt(t);if(!i)break;const n=i.id;let s=i.size;const a=t.filePos;if(n===B.EBML){ut(s);let o=this.reader.requestSlice(a,s);if(F(o)&&(o=await o),!o)break;this.readContiguousElements(o)}else if(n===B.Segment){if(await this.readSegment(a,s),s===void 0||this.reader.fileSize===null)break}else if(n===B.Cluster){if(this.reader.fileSize===null)break;s===void 0&&(s=(await is(this.reader,a,Ai,this.reader.fileSize)).pos-a);const o=fe(this.segments);o&&(o.elementEndPos=a+s)}ut(s),e=a+s}})())}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:new Map,cuePoints:[],dataStartPos:e,elementEndPos:t===void 0?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,clusterSummaries:new Map,metadataTags:{},metadataTagsPromise:null},this.segments.push(this.currentSegment);let i=e;const n=new Set;for(;this.currentSegment.elementEndPos===null||i<this.currentSegment.elementEndPos;){let o=this.reader.requestSliceRange(i,We,at);if(F(o)&&(o=await o),!o)break;const c=i,u=nt(o);if(!u||!si.includes(u.id)&&u.id!==B.Void){const p=await cc(this.reader,c+1,si,Math.min(this.currentSegment.elementEndPos??1/0,c+lc));if(p){i=p;continue}else break}const{id:l,size:d}=u,f=o.filePos,h=In.findIndex(p=>p.id===l);if(h!==-1){const p=In[h].flag;this.currentSegment[p]=!0,l===B.SeekHead&&n.add(c-e),ut(d);let m=this.reader.requestSlice(f,d);F(m)&&(m=await m),m&&this.readContiguousElements(m)}else if(l===B.Tags||l===B.Attachments){l===B.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,ut(d);let p=this.reader.requestSlice(f,d);F(p)&&(p=await p),p&&this.readContiguousElements(p)}else if(l===B.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(d===void 0)break;i=f+d}if(this.reader.fileSize!==null)for(let o=0;o<this.currentSegment.seekEntries.length;o++){const c=this.currentSegment.seekEntries[o];if(c.id!==B.SeekHead||n.has(c.segmentPosition)||(n.add(c.segmentPosition),!this.claimSeekTarget(e+c.segmentPosition)))continue;let u=this.reader.requestSliceRange(e+c.segmentPosition,We,at);if(F(u)&&(u=await u),!u)continue;const l=nt(u);if(!l||l.id!==B.SeekHead)continue;const{size:d}=l;ut(d);let f=this.reader.requestSlice(u.filePos,d);F(f)&&(f=await f),f&&this.readContiguousElements(f)}if(this.currentSegment.seekEntries.sort((o,c)=>o.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(const o of this.currentSegment.seekEntries){const c=In.find(p=>p.id===o.id);if(!c||this.currentSegment[c.flag]||!this.claimSeekTarget(e+o.segmentPosition))continue;let u=this.reader.requestSliceRange(e+o.segmentPosition,We,at);if(F(u)&&(u=await u),!u)continue;const l=nt(u);if(!l)continue;const{id:d,size:f}=l;if(d!==c.id)continue;ut(f),this.currentSegment[c.flag]=!0;let h=this.reader.requestSlice(u.filePos,f);F(h)&&(h=await h),h&&this.readContiguousElements(h)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(const o of this.currentSegment.tracks)o.defaultDurationNs!==null&&(o.defaultDuration=this.currentSegment.timestampFactor*o.defaultDurationNs/1e9),o.codecDelay=Math.round(this.currentSegment.timestampFactor*o.codecDelayNs/1e9);for(const o of this.currentSegment.cuePoints){const c=this.currentSegment.idToTrack.get(o.trackId);c&&c.cuePoints.push(o)}for(const o of this.currentSegment.tracks){const c=o.cuePoints;c.sort((l,d)=>l.time-d.time);let u=0;for(const l of c)(u===0||l.time!==c[u-1].time)&&(c[u++]=l);c.length=u}let s=null,a=-1/0;for(const o of this.currentSegment.tracks)o.cuePoints.length>a&&(a=o.cuePoints.length,s=o);for(const o of this.currentSegment.tracks)o.cuePoints.length===0&&(o.cuePoints=s.cuePoints);this.currentSegment=null}async readCluster(e,t){var d;if(((d=t.lastReadCluster)==null?void 0:d.elementStartPos)===e)return t.lastReadCluster;let i=this.reader.requestSliceRange(e,We,at);F(i)&&(i=await i),y(i);const n=e,s=nt(i);y(s);const a=s.id;y(a===B.Cluster);let o=s.size;const c=i.filePos;o===void 0&&(o=(await is(this.reader,c,Ai,t.elementEndPos)).pos-c);let u=this.reader.requestSlice(c,o);F(u)&&(u=await u);const l={segment:t,elementStartPos:n,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(u){this.currentCluster=l;try{const f=this.readContiguousElements(u,Ai);l.elementEndPos=f}finally{this.currentCluster=null,this.currentBlock=null}}for(const[,f]of l.trackData){const h=f.track;y(f.blocks.length>0);let p=!1;for(let T=0;T<f.blocks.length;T++){const k=f.blocks[T];k.timestamp+=l.timestamp,p||(p=k.lacing!==ft.None)}f.presentationTimestamps=f.blocks.map((T,k)=>({timestamp:T.timestamp,blockIndex:k})).sort((T,k)=>T.timestamp-k.timestamp);for(let T=0;T<f.presentationTimestamps.length;T++){const k=f.presentationTimestamps[T],x=f.blocks[k.blockIndex];if(f.firstKeyFrameTimestamp===null&&x.isKeyFrame&&(f.firstKeyFrameTimestamp=x.timestamp),T<f.presentationTimestamps.length-1){const P=f.presentationTimestamps[T+1];x.duration=P.timestamp-x.timestamp}else x.duration===0&&h.defaultDuration!=null&&x.lacing===ft.None&&(x.duration=h.defaultDuration)}p&&(f.blocks=this.expandLacedBlocks(f.blocks,h),f.presentationTimestamps=f.blocks.map((T,k)=>({timestamp:T.timestamp,blockIndex:k})).sort((T,k)=>T.timestamp-k.timestamp));const m=f.blocks[f.presentationTimestamps[0].blockIndex],b=f.blocks[fe(f.presentationTimestamps).blockIndex];f.startTimestamp=m.timestamp,f.endTimestamp=b.timestamp+b.duration;const w=te(h.clusterPositionCache,f.startTimestamp,T=>T.startTimestamp),S=h.clusterPositionCache[w],A=h.clusterPositionCache[w+1];(!S||S.elementStartPos<n)&&(!A||A.elementStartPos>n)&&h.clusterPositionCache.splice(w+1,0,{elementStartPos:l.elementStartPos,startTimestamp:f.startTimestamp,hasKeyFrame:f.firstKeyFrameTimestamp!==null})}return t.lastReadCluster=l,t.clusterSummaries.set(e,{elementEndPos:l.elementEndPos,trackIds:new Set(l.trackData.keys())}),l}getTrackDataInCluster(e,t){let i=e.trackData.get(t);if(!i){const n=e.segment.idToTrack.get(t);if(!n)return null;i={track:n,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,i)}return i}expandLacedBlocks(e,t){const i=[];for(const n of e){if(n.lacing===ft.None){i.push(n);continue}const s=Ke.tempFromBytes(n.data);if(s.length===0)throw new Error("Invalid laced block: no data.");const a=[],o=K(s)+1;switch(n.lacing){case ft.Xiph:{let u=0;for(let l=0;l<o-1;l++){let d=0;for(;s.bufferPos<s.length;){const f=K(s);if(d+=f,f<255){a.push(d),u+=d;break}}}a.push(s.length-(s.bufferPos+u))}break;case ft.FixedSize:{const u=s.length-1,l=Math.floor(u/o);for(let d=0;d<o;d++)a.push(l)}break;case ft.Ebml:{const u=Hr(s);if(u===null)throw new Error("Invalid EBML lacing: bad frame size.");let l=u;a.push(l);let d=l;for(let f=1;f<o-1;f++){const h=s.bufferPos,p=Hr(s);if(p===null)throw new Error("Invalid EBML lacing: bad frame size.");const m=p,w=(1<<(s.bufferPos-h)*7-1)-1,S=m-w;l+=S,a.push(l),d+=l}a.push(s.length-(s.bufferPos+d))}break;default:y(!1)}if(a.length!==o||a.some(u=>u<=0))throw new Error("Invalid block lacing: frame sizes don't match the block.");const c=n.duration||o*(t.defaultDuration??0);for(let u=0;u<o;u++){const l=a[u],d=X(s,l),f=n.timestamp+c*u/o,h=c/o;i.push({timestamp:f,duration:h,isKeyFrame:n.isKeyFrame,data:d,lacing:ft.None,decoded:n.decoded,postProcessed:!1,mainAdditional:n.mainAdditional})}}return i}async loadSegmentMetadata(e){for(const t of e.seekEntries){if(!(t.id===B.Tags&&!e.tagsSeen)){if(!(t.id===B.Attachments&&!e.attachmentsSeen))continue}if(!this.claimSeekTarget(e.dataStartPos+t.segmentPosition))continue;let i=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,We,at);if(F(i)&&(i=await i),!i)continue;const n=nt(i);if(!n||n.id!==t.id)continue;const{size:s}=n;ut(s);let a=this.reader.requestSlice(i.filePos,s);if(F(a)&&(a=await a),a){y(!this.currentSegment),this.currentSegment=e;try{this.readContiguousElements(a)}finally{this.currentSegment=null}}t.id===B.Tags?e.tagsSeen=!0:t.id===B.Attachments&&(e.attachmentsSeen=!0)}}claimSeekTarget(e){return this.claimedSeekTargets.has(e)?!1:(this.claimedSeekTargets.add(e),!0)}readContiguousElements(e,t){if(this.elementNestingDepth===md)throw new Error("Invalid file: elements are nested too deeply.");this.elementNestingDepth++;try{for(;e.remainingLength>=We;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}finally{this.elementNestingDepth--}}traverseElement(e,t){var o,c,u,l,d,f,h,p,m,b,w,S,A,T,k,x,P,I,E,C,_,D,q,M,V,G,J,ae,he,le,ye,Ve,et,pr,gr,br,wr,kr,yr,Sr,Ar,Tr,xr,Pr,Ir,Cr,Er,_r,vr,Rr;const i=nt(e);if(!i||t&&t.includes(i.id))return!1;const{id:n,size:s}=i,a=e.filePos;if(ut(s),a+s>e.end)return!1;switch(n){case B.DocType:this.isWebM=rr(e,s)==="webm";break;case B.Seek:{if(!this.currentSegment)break;const z={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(z),this.readContiguousElements(e.slice(a,s)),(z.id===-1||z.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case B.SeekID:{const z=(o=this.currentSegment)==null?void 0:o.seekEntries[this.currentSegment.seekEntries.length-1];if(!z)break;z.id=ee(e,s)}break;case B.SeekPosition:{const z=(c=this.currentSegment)==null?void 0:c.seekEntries[this.currentSegment.seekEntries.length-1];if(!z)break;z.segmentPosition=ee(e,s)}break;case B.TimestampScale:{if(!this.currentSegment)break;const z=ee(e,s);if(z===0)throw new Error("Invalid TimestampScale element: must not be 0.");this.currentSegment.timestampScale=z,this.currentSegment.timestampFactor=1e9/z}break;case B.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Ur(e,s)}break;case B.DateUTC:{if(!this.currentSegment)break;const z=fd(e,s);this.currentSegment.metadataTags.creationTime=new Date(dd+Number(z/1000000n))}break;case B.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...kt,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(a,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(z=>{var $;return(($=z.data)==null?void 0:$.type)!=="decompress"||z.scope!==Oi.Block||z.data.algorithm!==$r.HeaderStripping})&&(j._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentSegment.idToTrack.has(this.currentTrack.id)&&(j._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){const z=this.currentTrack.codecId.indexOf("/"),$=z===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,z);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){const g=this.currentTrack.info.displayWidth*this.currentTrack.info.height,v=this.currentTrack.info.displayHeight*this.currentTrack.info.width;g>0&&v>0&&(g>v?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*g/v):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*v/g))}if(this.currentTrack.codecId===Be.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===Be.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if($===Be.vp8)this.currentTrack.info.codec="vp8";else if($===Be.vp9)this.currentTrack.info.codec="vp9";else if($===Be.av1)this.currentTrack.info.codec="av1";else if($===Be.prores){const g=this.currentTrack.codecPrivate?_e.decode(this.currentTrack.codecPrivate):"";Lt.includes(g)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=g)}const me=this.currentTrack;this.currentTrack.trackBacking=new gd(me),this.currentSegment.tracks.push(this.currentTrack),this.currentSegment.idToTrack.set(this.currentTrack.id,this.currentTrack)}else if(this.currentTrack.info.type==="audio"){$===Be.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Be.mp3?this.currentTrack.info.codec="mp3":$===Be.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=mr):$===Be.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):$===Be.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):$===Be.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):$===Be.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):$===Be.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")):$===Be.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"));const me=this.currentTrack;this.currentTrack.trackBacking=new bd(me),this.currentSegment.tracks.push(this.currentTrack),this.currentSegment.idToTrack.set(this.currentTrack.id,this.currentTrack)}}this.currentTrack=null}break;case B.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=ee(e,s)}break;case B.TrackType:{if(!this.currentTrack)break;const z=ee(e,s);z===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,horizontalScale:1,verticalScale:1,rotation:0,codec:null,codecDescription:null,colorSpace:{...uo},alphaMode:!1,proresFormat:null}:z===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case B.FlagEnabled:{if(!this.currentTrack)break;ee(e,s)||(this.currentTrack=null)}break;case B.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!ee(e,s)}break;case B.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!ee(e,s)}break;case B.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!ee(e,s)}break;case B.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!ee(e,s)}break;case B.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!ee(e,s)}break;case B.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!ee(e,s)}break;case B.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=rr(e,s)}break;case B.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=X(e,s)}break;case B.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=ee(e,s)}break;case B.CodecDelay:{if(!this.currentTrack)break;this.currentTrack.codecDelayNs=ee(e,s)}break;case B.Name:{if(!this.currentTrack)break;this.currentTrack.name=zr(e,s)}break;case B.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=rr(e,s),ho(this.currentTrack.languageCode)||(this.currentTrack.languageCode=De)}break;case B.LanguageBCP47:{if(!this.currentTrack)break;const $=rr(e,s).split("-")[0];$?this.currentTrack.languageCode=$:this.currentTrack.languageCode=De,this.currentTrack.hasLanguageBcp47=!0}break;case B.Video:{if(((l=(u=this.currentTrack)==null?void 0:u.info)==null?void 0:l.type)!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case B.PixelWidth:{if(((f=(d=this.currentTrack)==null?void 0:d.info)==null?void 0:f.type)!=="video")break;this.currentTrack.info.width=ee(e,s)}break;case B.PixelHeight:{if(((p=(h=this.currentTrack)==null?void 0:h.info)==null?void 0:p.type)!=="video")break;this.currentTrack.info.height=ee(e,s)}break;case B.DisplayWidth:{if(((b=(m=this.currentTrack)==null?void 0:m.info)==null?void 0:b.type)!=="video")break;this.currentTrack.info.displayWidth=ee(e,s)}break;case B.DisplayHeight:{if(((S=(w=this.currentTrack)==null?void 0:w.info)==null?void 0:S.type)!=="video")break;this.currentTrack.info.displayHeight=ee(e,s)}break;case B.DisplayUnit:{if(((T=(A=this.currentTrack)==null?void 0:A.info)==null?void 0:T.type)!=="video")break;this.currentTrack.info.displayUnit=ee(e,s)}break;case B.AlphaMode:{if(((x=(k=this.currentTrack)==null?void 0:k.info)==null?void 0:x.type)!=="video")break;this.currentTrack.info.alphaMode=ee(e,s)===1}break;case B.Colour:{if(((I=(P=this.currentTrack)==null?void 0:P.info)==null?void 0:I.type)!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case B.MatrixCoefficients:{if(((C=(E=this.currentTrack)==null?void 0:E.info)==null?void 0:C.type)!=="video")break;const z=ee(e,s),$=pt[z];this.currentTrack.info.colorSpace.matrix=$}break;case B.Range:{if(((D=(_=this.currentTrack)==null?void 0:_.info)==null?void 0:D.type)!=="video")break;const z=ee(e,s);this.currentTrack.info.colorSpace.fullRange=z===1||z===2?z===2:void 0}break;case B.TransferCharacteristics:{if(((M=(q=this.currentTrack)==null?void 0:q.info)==null?void 0:M.type)!=="video")break;const z=ee(e,s),$=mt[z];this.currentTrack.info.colorSpace.transfer=$}break;case B.Primaries:{if(((G=(V=this.currentTrack)==null?void 0:V.info)==null?void 0:G.type)!=="video")break;const z=ee(e,s),$=ht[z];this.currentTrack.info.colorSpace.primaries=$}break;case B.Projection:{if(((ae=(J=this.currentTrack)==null?void 0:J.info)==null?void 0:ae.type)!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case B.ProjectionPoseYaw:{if(((le=(he=this.currentTrack)==null?void 0:he.info)==null?void 0:le.type)!=="video")break;const z=Ur(e,s);try{const $=Xr(z);this.currentTrack.info.horizontalScale=Math.round(Math.cos($*zn))}catch{}}break;case B.ProjectionPosePitch:{if(((Ve=(ye=this.currentTrack)==null?void 0:ye.info)==null?void 0:Ve.type)!=="video")break;const z=Ur(e,s);try{const $=Xr(z);this.currentTrack.info.verticalScale=Math.round(Math.cos($*zn))}catch{}}break;case B.ProjectionPoseRoll:{if(((pr=(et=this.currentTrack)==null?void 0:et.info)==null?void 0:pr.type)!=="video")break;const $=-Ur(e,s);try{this.currentTrack.info.rotation=Xr($)}catch{}}break;case B.Audio:{if(((br=(gr=this.currentTrack)==null?void 0:gr.info)==null?void 0:br.type)!=="audio")break;this.readContiguousElements(e.slice(a,s))}break;case B.SamplingFrequency:{if(((kr=(wr=this.currentTrack)==null?void 0:wr.info)==null?void 0:kr.type)!=="audio")break;const z=Ur(e,s);if(!(z>0)||!Number.isFinite(z))throw new Error("Invalid SamplingFrequency element: must be a positive, finite number.");this.currentTrack.info.sampleRate=z}break;case B.Channels:{if(((Sr=(yr=this.currentTrack)==null?void 0:yr.info)==null?void 0:Sr.type)!=="audio")break;const z=ee(e,s);if(z===0)throw new Error("Invalid Channels element: must not be 0.");this.currentTrack.info.numberOfChannels=z}break;case B.BitDepth:{if(((Tr=(Ar=this.currentTrack)==null?void 0:Ar.info)==null?void 0:Tr.type)!=="audio")break;this.currentTrack.info.bitDepth=ee(e,s)}break;case B.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,s)),this.currentCueTime=null}break;case B.CueTime:this.currentCueTime=ee(e,s);break;case B.CueTrackPositions:{if(this.currentCueTime===null||!this.currentSegment)break;const z={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(z),this.readContiguousElements(e.slice(a,s)),(z.trackId===-1||z.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case B.CueTrack:{const z=(xr=this.currentSegment)==null?void 0:xr.cuePoints[this.currentSegment.cuePoints.length-1];if(!z)break;z.trackId=ee(e,s)}break;case B.CueClusterPosition:{const z=(Pr=this.currentSegment)==null?void 0:Pr.cuePoints[this.currentSegment.cuePoints.length-1];if(!z)break;y(this.currentSegment),z.clusterPosition=this.currentSegment.dataStartPos+ee(e,s)}break;case B.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=ee(e,s)}break;case B.SimpleBlock:{if(!this.currentCluster)break;const z=e.slice(a,s),$=Hr(z);if($===null||z.remainingLength<3)break;const me=this.getTrackDataInCluster(this.currentCluster,$);if(!me)break;const g=cs(z),v=K(z),R=v>>1&3;let O=!!(v&128);((Ir=me.track.info)==null?void 0:Ir.type)==="audio"&&me.track.info.codec&&!jc.includes(me.track.info.codec)&&(O=!0);const L=X(z,z.remainingLength),N=me.track.decodingInstructions.length>0;me.blocks.push({timestamp:g,duration:0,isKeyFrame:O,data:L,lacing:R,decoded:!N,postProcessed:!1,mainAdditional:null})}break;case B.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,s)),this.currentBlock=null}break;case B.Block:{if(!this.currentCluster)break;const z=e.slice(a,s),$=Hr(z);if($===null||z.remainingLength<3)break;const me=this.getTrackDataInCluster(this.currentCluster,$);if(!me)break;const g=cs(z),R=K(z)>>1&3,O=X(z,z.remainingLength),L=me.track.decodingInstructions.length>0;this.currentBlock={timestamp:g,duration:0,isKeyFrame:!0,data:O,lacing:R,decoded:!L,postProcessed:!1,mainAdditional:null},me.blocks.push(this.currentBlock)}break;case B.BlockAdditions:this.readContiguousElements(e.slice(a,s));break;case B.BlockMore:{const z=this.currentBlock;if(!z)break;const $={addId:1,data:null};this.currentBlockAdditional=$,this.readContiguousElements(e.slice(a,s)),$.data&&$.addId===1&&(z.mainAdditional=$.data),this.currentBlockAdditional=null}break;case B.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=X(e,s)}break;case B.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=ee(e,s)}break;case B.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=ee(e,s)}break;case B.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case B.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,s));break;case B.Targets:this.readContiguousElements(e.slice(a,s));break;case B.TargetTypeValue:ee(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case B.TagTrackUID:case B.TagEditionUID:case B.TagChapterUID:case B.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case B.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,s))}break;case B.TagName:this.currentSimpleTagName=zr(e,s);break;case B.TagString:{if(!this.currentSimpleTagName)break;const z=zr(e,s);this.processTagValue(this.currentSimpleTagName,z)}break;case B.TagBinary:{if(!this.currentSimpleTagName)break;const z=X(e,s);this.processTagValue(this.currentSimpleTagName,z)}break;case B.AttachedFile:{if(!this.currentSegment||this.currentAttachedFile)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,s));const z=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(z.raw??(z.raw={}),z.raw[this.currentAttachedFile.fileUid.toString()]=new wo(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),(Cr=this.currentAttachedFile.fileMediaType)!=null&&Cr.startsWith("image/")&&this.currentAttachedFile.fileData){const $=this.currentAttachedFile.fileName;let me="unknown";if($){const g=$.toLowerCase();g.startsWith("cover.")?me="coverFront":g.startsWith("back.")&&(me="coverBack")}z.images??(z.images=[]),z.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:me,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case B.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=ac(e,s)}break;case B.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=zr(e,s)}break;case B.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=rr(e,s)}break;case B.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=X(e,s)}break;case B.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=zr(e,s)}break;case B.ContentEncodings:{const z=this.currentTrack;if(!z)break;this.readContiguousElements(e.slice(a,s)),z.decodingInstructions.sort(($,me)=>me.order-$.order)}break;case B.ContentEncoding:{const z=this.currentTrack;if(!z)break;const $={order:0,scope:Oi.Block,data:null};this.currentDecodingInstruction=$,this.readContiguousElements(e.slice(a,s)),$.data&&z.decodingInstructions.push($),this.currentDecodingInstruction=null}break;case B.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=ee(e,s)}break;case B.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=ee(e,s)}break;case B.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:$r.Zlib,settings:null},this.readContiguousElements(e.slice(a,s))}break;case B.ContentCompAlgo:{if(((_r=(Er=this.currentDecodingInstruction)==null?void 0:Er.data)==null?void 0:_r.type)!=="decompress")break;this.currentDecodingInstruction.data.algorithm=ee(e,s)}break;case B.ContentCompSettings:{if(((Rr=(vr=this.currentDecodingInstruction)==null?void 0:vr.data)==null?void 0:Rr.type)!=="decompress")break;this.currentDecodingInstruction.data.settings=X(e,s)}break;case B.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+s,!0}decodeBlockData(e,t){y(e.decodingInstructions.length>0);let i=t;for(const n of e.decodingInstructions)switch(y(n.data),n.data.type){case"decompress":switch(n.data.algorithm){case $r.HeaderStripping:if(n.data.settings&&n.data.settings.length>0){const s=n.data.settings,a=new Uint8Array(s.length+i.length);a.set(s,0),a.set(i,s.length),i=a}break}break}return i}processTagValue(e,t){var n,s;if(!((n=this.currentSegment)!=null&&n.metadataTags))return;const i=this.currentSegment.metadataTags;if(i.raw??(i.raw={}),(s=i.raw)[e]??(s[e]=t),typeof t=="string")switch(e.toLowerCase()){case"title":i.title??(i.title=t);break;case"description":i.description??(i.description=t);break;case"artist":i.artist??(i.artist=t);break;case"album":i.album??(i.album=t);break;case"album_artist":i.albumArtist??(i.albumArtist=t);break;case"genre":i.genre??(i.genre=t);break;case"bpm":{const a=Number.parseInt(t,10);Number.isInteger(a)&&a>0&&(i.beatsPerMinute??(i.beatsPerMinute=a))}break;case"comment":i.comment??(i.comment=t);break;case"lyrics":i.lyrics??(i.lyrics=t);break;case"date":{const a=new Date(t);Number.isNaN(a.getTime())||(i.date??(i.date=a))}break;case"track_number":case"part_number":{const a=t.split("/"),o=Number.parseInt(a[0],10),c=a[1]&&Number.parseInt(a[1],10);Number.isInteger(o)&&o>0&&(i.trackNumber??(i.trackNumber=o)),c&&Number.isInteger(c)&&c>0&&(i.tracksTotal??(i.tracksTotal=c))}break;case"disc_number":case"disc":{const a=t.split("/"),o=Number.parseInt(a[0],10),c=a[1]&&Number.parseInt(a[1],10);Number.isInteger(o)&&o>0&&(i.discNumber??(i.discNumber=o)),c&&Number.isInteger(c)&&c>0&&(i.discsTotal??(i.discsTotal=c))}break}}getDurationFromMetadata(e){if(e.duration<=0)return null;const t=Math.min(...e.tracks.map(i=>i.codecDelay));return(e.duration-t)/e.timestampFactor}}class uc{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const n of e.segments)for(const s of n.tracks)if(s.trackBacking.getType()===t&&i++,s===this.internalTrack)break;return i}getCodec(){throw new 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,t=>t.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return ei(e*this.internalTrack.segment.timestampFactor)+this.internalTrack.codecDelay}async getPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,n=>{const s=n.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};const a=te(s.presentationTimestamps,i,u=>u.timestamp),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&i<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},i,i,t)}async getNextPacket(e,t){const i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,n=>{if(n===i.cluster){const s=n.trackData.get(this.internalTrack.id);if(i.blockIndex+1<s.blocks.length)return{blockIndex:i.blockIndex+1,correctBlockFound:!0}}else if(n.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,n=>{const s=n.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};const a=fs(s.presentationTimestamps,u=>s.blocks[u.blockIndex].isKeyFrame&&u.timestamp<=i),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&i<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},i,i,t,!0)}async getNextKeyPacket(e,t){const i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,n=>{if(n===i.cluster){const s=n.trackData.get(this.internalTrack.id);for(let a=i.blockIndex+1;a<s.blocks.length;a++)if(s.blocks[a].isKeyFrame)return{blockIndex:a,correctBlockFound:!0}}else{const s=n.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){const a=s.blocks.findIndex(o=>o.isKeyFrame);return y(a!==-1),{blockIndex:a,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,i){var h,p;if(t===-1)return null;const s=e.trackData.get(this.internalTrack.id).blocks[t];if(y(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0),!s.postProcessed){if(((h=this.internalTrack.info)==null?void 0:h.codec)==="prores"&&!(s.data.length>=8&&s.data[4]===105&&s.data[5]===99&&s.data[6]===112&&s.data[7]===102)){const b=new Uint8Array(s.data.length+8);Z(b).setUint32(0,b.length,!1),b[4]=105,b[5]=99,b[6]=112,b[7]=102,b.set(s.data,8),s.data=b}s.postProcessed=!0}const a=i.metadataOnly?je:s.data,{codecDelay:o,segment:c}=this.internalTrack,u=(s.timestamp-o)/c.timestampFactor,l=s.duration/c.timestampFactor,d={};s.mainAdditional&&((p=this.internalTrack.info)==null?void 0:p.type)==="video"&&this.internalTrack.info.alphaMode&&(d.alpha=i.metadataOnly?je:s.mainAdditional,d.alphaByteLength=s.mainAdditional.byteLength);const f=new ce(a,s.isKeyFrame?"key":"delta",u,l,e.dataStartPos+t,s.data.byteLength,d);return this.packetToClusterLocation.set(f,{cluster:e,blockIndex:t}),f}async performClusterLookup(e,t,i,n,s,a=!1){var b,w;const{demuxer:o,segment:c,cuePoints:u,clusterPositionCache:l}=this.internalTrack;let d=null,f=-1;if(e){const{blockIndex:S,correctBlockFound:A}=t(e);if(A)return this.fetchPacketInCluster(e,S,s);S!==-1&&(d=e,f=S)}let h=te(u,i,S=>S.time),p=te(l,i,S=>S.startTimestamp),m=1/0;for(;;){for(;h!==-1&&u[h].clusterPosition>=m;)h--;for(;p!==-1&&(l[p].elementStartPos>=m||a&&!l[p].hasKeyFrame);)p--;const S=Math.max(((b=u[h])==null?void 0:b.clusterPosition)??0,((w=l[p])==null?void 0:w.elementStartPos)??0)||null;let A,T=null;e?S===null||e.elementStartPos>=S?(A=e.elementEndPos,T=e):A=S:A=S??c.clusterSeekStartPos;const k=T?T.elementStartPos:A;for(;(c.elementEndPos===null||A<=c.elementEndPos-We)&&A<m;){if(T){const M=T.trackData.get(this.internalTrack.id);if(M&&M.startTimestamp>n)break;T=null}const x=c.clusterSummaries.get(A);if(x&&!x.trackIds.has(this.internalTrack.id)){A=x.elementEndPos;continue}let P=o.reader.requestSliceRange(A,We,at);if(F(P)&&(P=await P),!P)break;const I=A,E=nt(P);if(!E||!si.includes(E.id)&&E.id!==B.Void){const M=await cc(o.reader,I+1,si,Math.min(c.elementEndPos??1/0,I+lc));if(M){A=M;continue}else break}const C=E.id;let _=E.size;const D=P.filePos;if(C===B.Cluster){T=await o.readCluster(I,c),_=T.elementEndPos-D;const{blockIndex:M,correctBlockFound:V}=t(T);if(V)return this.fetchPacketInCluster(T,M,s);M!==-1&&(d=T,f=M)}_===void 0&&(y(C!==B.Cluster),_=(await is(o.reader,D,Ai,c.elementEndPos)).pos-D);const q=D+_;if(c.elementEndPos===null){let M=o.reader.requestSliceRange(q,We,at);if(F(M)&&(M=await M),!M)break;if(vs(M)===B.Segment){c.elementEndPos=q;break}}A=q}if(S===null||d&&d.elementStartPos>=S)break;m=k,e=null}return d?this.fetchPacketInCluster(d,f,s):null}}class gd extends uc{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(){const e=this.internalTrack.info,t=Ii(tl(e.horizontalScale,e.verticalScale),el(e.rotation));return Jc(t,e.width,e.height)}async getColorSpace(){var t,i,n,s;const e=await this.getDecoderConfig();return e?{primaries:(t=e.colorSpace)==null?void 0:t.primaries,transfer:(i=e.colorSpace)==null?void 0:i.transfer,matrix:(n=e.colorSpace)==null?void 0:n.matrix,fullRange:(s=e.colorSpace)==null?void 0:s.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??(this.decoderConfigPromise=(async()=>{var s,a,o,c;let e=null;(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="prores"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));const i={width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?$i(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?Ji(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?ks(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?en(e.data):null,proresCodecInfo:this.internalTrack.info.codec==="prores"&&e?Ro(e.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!ds(this.internalTrack.info.colorSpace)){const u=Xc(i);(s=this.internalTrack.info.colorSpace).primaries??(s.primaries=u.primaries),(a=this.internalTrack.info.colorSpace).transfer??(a.transfer=u.transfer),(o=this.internalTrack.info.colorSpace).matrix??(o.matrix=u.matrix),(c=this.internalTrack.info.colorSpace).fullRange??(c.fullRange=u.fullRange)}const n={codec:fn(i),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)&&(n.displayAspectWidth=this.internalTrack.info.squarePixelWidth,n.displayAspectHeight=this.internalTrack.info.squarePixelHeight),n})()):null}}class bd extends uc{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??(this.decoderConfigPromise=(async()=>{if(this.internalTrack.info.codec==="dts"&&!this.internalTrack.info.dtsFormat){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&No(e.data)}return{codec:Us({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}}/*!
158
+ * Copyright (c) 2026-present, Vanilagy and contributors
159
+ *
160
+ * This Source Code Form is subject to the terms of the Mozilla Public
161
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
162
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
163
+ */var zt;(function(r){r[r.Unsynchronisation=128]="Unsynchronisation",r[r.ExtendedHeader=64]="ExtendedHeader",r[r.ExperimentalIndicator=32]="ExperimentalIndicator",r[r.Footer=16]="Footer"})(zt||(zt={}));var Pe;(function(r){r[r.ISO_8859_1=0]="ISO_8859_1",r[r.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",r[r.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",r[r.UTF_8=3]="UTF_8"})(Pe||(Pe={}));const Ti=128,He=10,nr=["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"],wd=(r,e)=>{var d;const t=r.filePos;e.raw??(e.raw={}),(d=e.raw).TAG??(d.TAG=X(r,Ti-3)),r.filePos=t;const i=Xt(r,30);i&&(e.title??(e.title=i));const n=Xt(r,30);n&&(e.artist??(e.artist=n));const s=Xt(r,30);s&&(e.album??(e.album=s));const a=Xt(r,4),o=Number.parseInt(a,10);Number.isInteger(o)&&o>0&&(e.date??(e.date=new Date(String(o))));const c=X(r,30);let u;if(c[28]===0&&c[29]!==0){const f=c[29];f>0&&(e.trackNumber??(e.trackNumber=f)),r.skip(-30),u=Xt(r,28),r.skip(2)}else r.skip(-30),u=Xt(r,30);u&&(e.comment??(e.comment=u));const l=K(r);l<nr.length&&(e.genre??(e.genre=nr[l]))},Xt=(r,e)=>{const t=X(r,e),i=Yt(t.indexOf(0),t.length),n=t.subarray(0,i);let s="";for(let a=0;a<n.length;a++)s+=String.fromCharCode(n[a]);return s.trimEnd()},wt=r=>{const e=r.filePos,t=be(r,3),i=K(r),n=K(r),s=K(r),a=U(r);if(t!=="ID3"||i===255||n===255||(a&2155905152)!==0)return r.filePos=e,null;let o=Kn(a);return s&zt.Footer&&(o+=He),{majorVersion:i,revision:n,flags:s,size:o}},sn=(r,e,t)=>{var a,o,c,u,l;if(![2,3,4].includes(e.majorVersion)){j._warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}const i=e.flags&zt.Footer?e.size-He:e.size,n=X(r,i),s=new kd(e,n);if(e.flags&zt.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&zt.ExtendedHeader){if(s.bytes.length<4)return;const d=s.readU32();e.majorVersion===3?s.pos+=d:s.pos+=d-4}for(;s.pos<=s.bytes.length-s.frameHeaderSize();){const d=s.readId3V2Frame();if(!d)break;const f=s.pos,h=Math.min(s.pos+d.size,s.bytes.length);let p=h,m=!1,b=!1,w=!1;if(e.majorVersion===3?(m=!!(d.flags&64),b=!!(d.flags&128)):e.majorVersion===4&&(m=!!(d.flags&4),b=!!(d.flags&8),w=!!(d.flags&2)||!!(e.flags&zt.Unsynchronisation)),m){j._warn(`Skipping encrypted ID3v2 frame ${d.id}`),s.pos=h;continue}if(b){j._warn(`Skipping compressed ID3v2 frame ${d.id}`),s.pos=h;continue}w&&(p=s.ununsynchronizeRegion(s.pos,p));const S=A=>{if(p-s.pos<A)throw new Error(`Invalid ID3v2 ${d.id} frame: too short.`)};if(t.raw??(t.raw={}),d.id==="TXXX"){const A=(a=t.raw).TXXX??(a.TXXX={});S(1);const T=s.readId3V2TextEncoding(),k=s.readId3V2Text(T,p),x=s.readId3V2Text(T,p);A[k]??(A[k]=x)}else if(d.id[0]==="T")(o=t.raw)[c=d.id]??(o[c]=s.readId3V2EncodingAndText(p));else{const A=s.readBytes(p-s.pos),T=t.raw[d.id];T instanceof Uint8Array?t.raw[d.id]=[T,A]:Array.isArray(T)?T.push(A):(u=t.raw)[l=d.id]??(u[l]=A)}switch(s.pos=f,d.id){case"TIT2":case"TT2":t.title??(t.title=s.readId3V2EncodingAndText(p));break;case"TIT3":case"TT3":t.description??(t.description=s.readId3V2EncodingAndText(p));break;case"TPE1":case"TP1":t.artist??(t.artist=s.readId3V2EncodingAndText(p));break;case"TALB":case"TAL":t.album??(t.album=s.readId3V2EncodingAndText(p));break;case"TPE2":case"TP2":t.albumArtist??(t.albumArtist=s.readId3V2EncodingAndText(p));break;case"TRCK":case"TRK":{const T=s.readId3V2EncodingAndText(p).split("/"),k=Number.parseInt(T[0],10),x=T[1]&&Number.parseInt(T[1],10);Number.isInteger(k)&&k>0&&(t.trackNumber??(t.trackNumber=k)),x&&Number.isInteger(x)&&x>0&&(t.tracksTotal??(t.tracksTotal=x))}break;case"TPOS":case"TPA":{const T=s.readId3V2EncodingAndText(p).split("/"),k=Number.parseInt(T[0],10),x=T[1]&&Number.parseInt(T[1],10);Number.isInteger(k)&&k>0&&(t.discNumber??(t.discNumber=k)),x&&Number.isInteger(x)&&x>0&&(t.discsTotal??(t.discsTotal=x))}break;case"TCON":case"TCO":{const A=s.readId3V2EncodingAndText(p);let T=/^\((\d+)\)/.exec(A);if(T){const k=Number.parseInt(T[1]);if(nr[k]!==void 0){t.genre??(t.genre=nr[k]);break}}if(T=/^\d+$/.exec(A),T){const k=Number.parseInt(T[0]);if(nr[k]!==void 0){t.genre??(t.genre=nr[k]);break}}t.genre??(t.genre=A)}break;case"TDRC":case"TDAT":{const A=s.readId3V2EncodingAndText(p),T=new Date(A);Number.isNaN(T.getTime())||(t.date??(t.date=T))}break;case"TYER":case"TYE":{const A=s.readId3V2EncodingAndText(p),T=Number.parseInt(A,10);Number.isInteger(T)&&(t.date??(t.date=new Date(String(T))))}break;case"TBPM":case"TBP":{const A=s.readId3V2EncodingAndText(p),T=Number.parseInt(A,10);Number.isInteger(T)&&(t.beatsPerMinute??(t.beatsPerMinute=T))}break;case"USLT":case"ULT":{S(4);const A=s.readU8();s.pos+=3,s.readId3V2Text(A,p),t.lyrics??(t.lyrics=s.readId3V2Text(A,p))}break;case"COMM":case"COM":{S(4);const A=s.readU8();s.pos+=3,s.readId3V2Text(A,p),t.comment??(t.comment=s.readId3V2Text(A,p))}break;case"APIC":case"PIC":{S(1);const A=s.readId3V2TextEncoding();let T;if(e.majorVersion===2){S(3);const I=s.readAscii(3);T=I==="PNG"?"image/png":I==="JPG"?"image/jpeg":"image/*"}else T=s.readId3V2Text(A,p);S(1);const k=s.readU8(),x=s.readId3V2Text(A,p).trimEnd(),P=p-s.pos;if(P>=0){const I=s.readBytes(P);t.images||(t.images=[]),t.images.push({data:I,mimeType:T,kind:k===3?"coverFront":k===4?"coverBack":"unknown",description:x})}}break;default:s.pos+=d.size;break}s.pos=h}};class kd{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(){const e=[];for(let t=0;t<this.bytes.length;t++){const i=this.bytes[t];e.push(i),i===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){this.ownsBytes||(this.bytes=this.bytes.slice(),this.view=Z(this.bytes),this.ownsBytes=!0);let i=e;for(let n=e;n<t;n++){const s=this.bytes[n];this.bytes[i++]=s,s===255&&n!==t-1&&this.bytes[n+1]===0&&n++}return i}readBytes(e){const t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){const e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){const e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){const e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+2);return this.pos+=3,e*256+t}readU32(){const e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let i=0;i<e;i++)t+=String.fromCharCode(this.view.getUint8(this.pos+i));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){const e=this.readAscii(3);if(e==="\0\0\0")return null;const t=this.readU24();return{id:e,size:t,flags:0}}else{const e=this.readAscii(4);if(e==="\0\0\0\0")return null;const t=this.readU32();let i=this.header.majorVersion===4?Kn(t):t;const n=this.readU16(),s=this.pos,a=o=>{const c=this.pos+o;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=o;const u=this.readAscii(4);if(u!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(u))return!1}return!0};if(!a(i)){const o=this.header.majorVersion===4?t:Kn(t);a(o)&&(i=o)}return this.pos=s,{id:e,size:i,flags:n}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const i=this.pos,n=this.readBytes(t-this.pos);switch(e){case Pe.ISO_8859_1:{let s="";for(let a=0;a<n.length;a++){const o=n[a];if(o===0){this.pos=i+a+1;break}s+=String.fromCharCode(o)}return s}case Pe.UTF_16_WITH_BOM:if(n[0]===255&&n[1]===254){const s=new Qr("utf-16le"),a=Yt(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=i+Math.min(a+2,n.length),s.decode(n.subarray(2,a))}else if(n[0]===254&&n[1]===255){const s=new Qr("utf-16be"),a=Yt(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=i+Math.min(a+2,n.length),s.decode(n.subarray(2,a))}else{const s=Yt(n.findIndex(a=>a===0),n.length);return this.pos=i+Math.min(s+1,n.length),_e.decode(n.subarray(0,s))}case Pe.UTF_16_BE_NO_BOM:{const s=new Qr("utf-16be"),a=Yt(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=i+Math.min(a+2,n.length),s.decode(n.subarray(0,a))}case Pe.UTF_8:{const s=Yt(n.findIndex(a=>a===0),n.length);return this.pos=i+Math.min(s+1,n.length),_e.decode(n.subarray(0,s))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class nm{constructor(e){this.helper=new Uint8Array(8),this.helperView=Z(this.helper),this.writer=e}writeId3V2Tag(e){const t=this.writer.getPos();this.writeAscii("ID3"),this.writeU8(4),this.writeU8(0),this.writeU8(0),this.writeSynchsafeU32(0);const i=this.writer.getPos(),n=new Set;for(const{key:o,value:c}of mo(e))switch(o){case"title":this.writeId3V2TextFrame("TIT2",c),n.add("TIT2");break;case"description":this.writeId3V2TextFrame("TIT3",c),n.add("TIT3");break;case"artist":this.writeId3V2TextFrame("TPE1",c),n.add("TPE1");break;case"album":this.writeId3V2TextFrame("TALB",c),n.add("TALB");break;case"albumArtist":this.writeId3V2TextFrame("TPE2",c),n.add("TPE2");break;case"trackNumber":{const u=e.tracksTotal!==void 0?`${c}/${e.tracksTotal}`:c.toString();this.writeId3V2TextFrame("TRCK",u),n.add("TRCK")}break;case"discNumber":{const u=e.discsTotal!==void 0?`${c}/${e.discsTotal}`:c.toString();this.writeId3V2TextFrame("TPOS",u),n.add("TPOS")}break;case"genre":this.writeId3V2TextFrame("TCON",c),n.add("TCON");break;case"date":this.writeId3V2TextFrame("TDRC",c.toISOString().slice(0,10)),n.add("TDRC");break;case"beatsPerMinute":this.writeId3V2TextFrame("TBPM",`${c}`),n.add("TBPM");break;case"lyrics":this.writeId3V2LyricsFrame(c),n.add("USLT");break;case"comment":this.writeId3V2CommentFrame(c),n.add("COMM");break;case"images":{const u={coverFront:3,coverBack:4,unknown:0};for(const l of c){const d=u[l.kind]??0,f=l.description??"";this.writeId3V2ApicFrame(l.mimeType,d,f,l.data)}}break;case"tracksTotal":case"discsTotal":break;case"raw":break;case"creationTime":break;default:ze(o)}if(e.raw)for(const o in e.raw){const c=e.raw[o];if(c==null||o.length!==4||n.has(o))continue;let u;if(typeof c=="string"){let l;if(St(c)){l=new Uint8Array(c.length+2),l[0]=Pe.ISO_8859_1;for(let f=0;f<c.length;f++)l[f+1]=c.charCodeAt(f)}else{const f=Ye.encode(c);l=new Uint8Array(f.byteLength+2),l[0]=Pe.UTF_8,l.set(f,1)}u=[l]}else if(c instanceof Uint8Array)u=[c];else if(Array.isArray(c)&&c.every(l=>l instanceof Uint8Array))u=c;else if(o==="TXXX"&&bo(c)){for(const l in c){const d=c[l],f=St(l)&&St(d),h=f?null:Ye.encode(l),p=f?null:Ye.encode(d),m=f?l.length:h.byteLength,b=f?d.length:p.byteLength,w=1+m+1+b+1;this.writeAscii("TXXX"),this.writeSynchsafeU32(w),this.writeU16(0),this.writeU8(f?Pe.ISO_8859_1:Pe.UTF_8),f?(this.writeIsoString(l),this.writeIsoString(d)):(this.writer.write(h),this.writeU8(0),this.writer.write(p),this.writeU8(0))}continue}else continue;for(const l of u)this.writeAscii(o),this.writeSynchsafeU32(l.byteLength),this.writeU16(0),this.writer.write(l)}const s=this.writer.getPos(),a=s-i;return this.writer.seek(t+6),this.writeSynchsafeU32(a),this.writer.seek(s),a+10}writeU8(e){this.helper[0]=e,this.writer.write(this.helper.subarray(0,1))}writeU16(e){this.helperView.setUint16(0,e,!1),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeAscii(e){for(let t=0;t<e.length;t++)this.helper[t]=e.charCodeAt(t);this.writer.write(this.helper.subarray(0,e.length))}writeSynchsafeU32(e){this.writeU32(Fl(e))}writeIsoString(e){const t=new Uint8Array(e.length+1);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);this.writer.write(t)}writeUtf8String(e){const t=Ye.encode(e);this.writer.write(t),this.writeU8(0)}writeId3V2TextFrame(e,t){const i=St(t),s=1+(i?t.length:Ye.encode(t).byteLength)+1;this.writeAscii(e),this.writeSynchsafeU32(s),this.writeU16(0),this.writeU8(i?Pe.ISO_8859_1:Pe.UTF_8),i?this.writeIsoString(t):this.writeUtf8String(t)}writeId3V2LyricsFrame(e){const t=St(e),i="",n=4+i.length+1+e.length+1;this.writeAscii("USLT"),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(t?Pe.ISO_8859_1:Pe.UTF_8),this.writeAscii("und"),t?(this.writeIsoString(i),this.writeIsoString(e)):(this.writeUtf8String(i),this.writeUtf8String(e))}writeId3V2CommentFrame(e){const t=St(e),i=t?e.length:Ye.encode(e).byteLength,n="",s=4+n.length+1+i+1;this.writeAscii("COMM"),this.writeSynchsafeU32(s),this.writeU16(0),this.writeU8(t?Pe.ISO_8859_1:Pe.UTF_8),this.writeU8(117),this.writeU8(110),this.writeU8(100),t?(this.writeIsoString(n),this.writeIsoString(e)):(this.writeUtf8String(n),this.writeUtf8String(e))}writeId3V2ApicFrame(e,t,i,n){const s=St(e)&&St(i),a=s?i.length:Ye.encode(i).byteLength,o=1+e.length+1+1+a+1+n.byteLength;this.writeAscii("APIC"),this.writeSynchsafeU32(o),this.writeU16(0),this.writeU8(s?Pe.ISO_8859_1:Pe.UTF_8),s?this.writeIsoString(e):this.writeUtf8String(e),this.writeU8(t),s?this.writeIsoString(i):this.writeUtf8String(i),this.writer.write(n)}}/*!
164
+ * Copyright (c) 2026-present, Vanilagy and contributors
165
+ *
166
+ * This Source Code Form is subject to the terms of the Mozilla Public
167
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
168
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
169
+ */const ns=async(r,e,t,i=null)=>{let s=e;for(;t===null||s<t;){const a=t!==null?Math.min(65536,t-s):65536;let o=r.requestSliceRange(s,vt,a);if(F(o)&&(o=await o),!o||o.length<vt)break;for(;o.remainingLength>=vt;){const c=o.filePos,u=U(o),l=r.fileSize!==null?r.fileSize-s:null,d=ws(u,l);if(d.header&&(!i||d.header.sampleRate===i.sampleRate&&d.header.mpegVersionId===i.mpegVersionId&&d.header.layer===i.layer&&ti(d.header.channel)===ti(i.channel)))return{header:d.header,startPos:s};o.filePos=c+d.bytesAdvanced,s=o.filePos}}return null};/*!
170
+ * Copyright (c) 2026-present, Vanilagy and contributors
171
+ *
172
+ * This Source Code Form is subject to the terms of the Mozilla Public
173
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
174
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
175
+ */class yd extends yt{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 Vi,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.primingDelay=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(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 new Error("No valid MP3 frame found.");this.trackBackings=[new Sd(this)]})())}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,He);if(F(o)&&(o=await o),!o){this.lastSampleLoaded=!0;return}const c=wt(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}const e=await ns(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e){this.lastSampleLoaded=!0;return}const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=yo(t.mpegVersionId,t.channel);let n=this.reader.requestSlice(e.startPos+i,4);if(F(n)&&(n=await n),n){const o=U(n);if(o===jn||o===ko){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let u=this.reader.requestSlice(e.startPos+i+4,12);if(F(u)&&(u=await u),u){const l=X(u,12),d=Z(l),f=d.getUint32(0,!1);this.xingData={isVbr:o===jn,frameCount:f&At.FrameCount?d.getUint32(4,!1):null,fileSize:f&At.FileSize?d.getUint32(8,!1):null};const h=e.startPos+i+8+(f&At.FrameCount?4:0)+(f&At.FileSize?4:0)+(f&At.Toc?100:0)+(f&At.Quality?4:0);if(!this.firstFrameHeader&&h+24<=e.startPos+t.totalSize){let p=this.reader.requestSlice(h,24);if(F(p)&&(p=await p),p){const m=X(p,24),b=String.fromCharCode(...m.subarray(0,4));(b==="LAME"||b==="Lavf"||b==="Lavc")&&(this.primingDelay=(m[21]<<4|m[22]>>4)+El,this.nextTimestampInSamples=-this.primingDelay)}}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);const s=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0,i=!1;for(;;){let n=this.reader.requestSlice(t,He);if(F(n)&&(n=await n),!n)break;const s=wt(n);if(!s)break;i=!0;let a=this.reader.requestSlice(n.filePos,s.size);if(F(a)&&(a=await a),!a)break;sn(a,s,this.metadataTags),t=n.filePos+s.size}if(!i&&this.reader.fileSize!==null&&this.reader.fileSize>=Ti){let n=this.reader.requestSlice(this.reader.fileSize-Ti,Ti);F(n)&&(n=await n),y(n),be(n,3)==="TAG"&&wd(n,this.metadataTags)}return this.metadataTags}finally{e()}}}class Sd{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return y(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){var t;const e=this.demuxer;if(y(e.firstFrameHeader!==null),y(e.firstFrameHeaderPos!==null),e.xingData&&e.xingData.frameCount!==null)return(e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame-e.primingDelay)/e.firstFrameHeader.sampleRate;if(!((t=e.xingData)!=null&&t.isVbr)&&e.reader.fileSize!==null){const i=Bl(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate),n=(e.reader.fileSize-e.firstFrameHeaderPos)/i;return(Math.round(n)*e.firstFrameHeader.audioSamplesInFrame-e.primingDelay)/e.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return De}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return y(this.demuxer.firstFrameHeader),ti(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return y(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...kt}}async getDecoderConfig(){return y(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:ti(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let n;if(t.metadataOnly)n=je;else{let s=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(F(s)&&(s=await s),!s)return null;n=X(s,i.dataSize)}return new ce(n,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const n=fi(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(n===-1)throw new Error("Packet was not created from this track.");const s=n+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const n=te(this.demuxer.loadedSamples,e,s=>s.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(n,t);if(n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}/*!
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
+ */const dc=1399285583,Ad=79764919,fc=new Uint32Array(256);for(let r=0;r<256;r++){let e=r<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^Ad:e<<1;fc[r]=e>>>0&4294967295}const sm=r=>{const e=Z(r),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let i=0;for(let n=0;n<r.length;n++){const s=r[n];i=(i<<8^fc[i>>>24^s])>>>0}return e.setUint32(22,t,!0),i},xa=(r,e,t)=>{let i=0,n=null;if(r.length>0)if(e.codec==="vorbis"){y(e.vorbisInfo);const s=e.vorbisInfo.modeBlockflags.length,o=(1<<fl(s-1))-1<<1,c=(r[0]&o)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let u=t??e.vorbisInfo.blocksizes[0];const l=e.vorbisInfo.modeBlockflags[c];if(n=e.vorbisInfo.blocksizes[l],l===1){const d=(o|1)+1,f=r[0]&d?1:0;u=e.vorbisInfo.blocksizes[f]}i=u+n>>2}else e.codec==="opus"&&(i=$l(r).durationInSamples);return{durationInSamples:i,vorbisBlockSize:n}},Td=r=>{let e="audio/ogg";if(r.codecStrings){const t=[...new Set(r.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};/*!
182
+ * Copyright (c) 2026-present, Vanilagy and contributors
183
+ *
184
+ * This Source Code Form is subject to the terms of the Mozilla Public
185
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
186
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
187
+ */const Pt=27,cr=282,xd=cr+65025,Yr=r=>{const e=r.filePos;if(Ut(r)!==dc)return null;r.skip(1);const i=K(r),n=qf(r),s=Ut(r),a=Ut(r),o=Ut(r),c=K(r);if(c===0||r.remainingLength<c)return null;const u=new Uint8Array(c);for(let h=0;h<c;h++)u[h]=K(r);const l=27+c,d=u.reduce((h,p)=>h+p,0),f=l+d;return{headerStartPos:e,totalSize:f,dataStartPos:e+l,dataSize:d,headerType:i,granulePosition:n,serialNumber:s,sequenceNumber:a,checksum:o,lacingValues:u}},Pd=(r,e,t)=>{for(;r.filePos<e-3;){const i=Ut(r),n=i&255,s=i>>>8&255,a=i>>>16&255,o=i>>>24&255,c=79;if(!(n!==c&&s!==c&&a!==c&&o!==c)){if(r.skip(-4),i===dc){if(t===void 0||r.filePos+18>r.end)return!0;r.skip(14);const u=Ut(r);if(r.skip(-18),u===t)return!0}r.skip(1)}}return!1};/*!
188
+ * Copyright (c) 2026-present, Vanilagy and contributors
189
+ *
190
+ * This Source Code Form is subject to the terms of the Mozilla Public
191
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
192
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
193
+ */const Pa=64,Id=30,Cd=19;class Ed extends yt{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,Pt,cr);if(F(t)&&(t=await t),!t)break;const i=Yr(t);if(!i||!!!(i.headerType&2))break;if(this.bitstreams.length===Pa)throw new Error(`Too many (> ${Pa}) logical bitstreams.`);this.bitstreams.push({serialNumber:i.serialNumber,bosPage:i,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=i.headerStartPos+i.totalSize}for(const t of this.bitstreams){const i=await this.readPacket(t.bosPage,0);i&&(i.data.byteLength>=Id&&i.data[0]===1&&i.data[1]===118&&i.data[2]===111&&i.data[3]===114&&i.data[4]===98&&i.data[5]===105&&i.data[6]===115?await this.readVorbisMetadata(i,t):i.data.byteLength>=Cd&&i.data[0]===79&&i.data[1]===112&&i.data[2]===117&&i.data[3]===115&&i.data[4]===72&&i.data[5]===101&&i.data[6]===97&&i.data[7]===100&&await this.readOpusMetadata(i,t),t.codecInfo.codec!==null&&this.trackBackings.push(new _d(t,this)))}})())}async readVorbisMetadata(e,t){let i=await this.findNextPacketStart(e);if(!i)return;const n=await this.readPacket(i.startPage,i.startSegmentIndex);if(!n||(i=await this.findNextPacketStart(n),!i))return;const s=await this.readPacket(i.startPage,i.startSegmentIndex);if(!s||n.data[0]!==3||s.data[0]!==5)return;const a=Z(e.data),o=a.getUint8(11),c=a.getUint32(12,!0);if(o===0||c===0)throw new Error("Invalid Vorbis identification header: channel count and sample rate must not be 0.");const u=[],l=h=>{for(;u.push(Math.min(255,h)),!(h<255);)h-=255};l(e.data.length),l(n.data.length);const d=new Uint8Array(1+u.length+e.data.length+n.data.length+s.data.length);d[0]=2,d.set(u,1),d.set(e.data,1+u.length),d.set(n.data,1+u.length+e.data.length),d.set(s.data,1+u.length+e.data.length+n.data.length),t.codecInfo.codec="vorbis",t.description=d,t.lastMetadataPacket=s,t.numberOfChannels=o,t.sampleRate=c;const f=a.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(f&15),1<<(f>>4)],modeBlockflags:Yl(s.data).modeBlockflags},Xn(n.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const i=await this.findNextPacketStart(e);if(!i)return;const n=await this.readPacket(i.startPage,i.startSegmentIndex);if(!n)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=n;const s=ys(e.data);t.numberOfChannels=s.outputChannelCount,t.sampleRate=mr,t.codecInfo.opusInfo={preSkip:s.preSkip},Xn(n.data.subarray(8),this.metadataTags)}async readPacket(e,t){y(t<e.lacingValues.length);let i=0;for(let d=0;d<t;d++)i+=e.lacingValues[d];let n=e,s=i,a=t;const o=[];e:for(;;){let d=this.reader.requestSlice(n.dataStartPos,n.dataSize);if(F(d)&&(d=await d),!d)return null;const f=X(d,n.dataSize);for(;;){if(a===n.lacingValues.length){o.push(f.subarray(i,s));break}const p=n.lacingValues[a];if(s+=p,p<255){o.push(f.subarray(i,s));break e}a++}let h=n.headerStartPos+n.totalSize;for(;;){let p=this.reader.requestSliceRange(h,Pt,cr);if(F(p)&&(p=await p),!p)return null;const m=Yr(p);if(!m)return null;if(n=m,n.serialNumber===e.serialNumber)break;h=n.headerStartPos+n.totalSize}i=0,s=0,a=0}const c=o.reduce((d,f)=>d+f.length,0);if(c===0)return null;const u=new Uint8Array(c);let l=0;for(let d=0;d<o.length;d++){const f=o[d];u.set(f,l),l+=f.length}return{data:u,endPage:n,endSegmentIndex:a}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let i=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let n=this.reader.requestSliceRange(i,Pt,cr);if(F(n)&&(n=await n),!n)return null;const s=Yr(n);if(!s)return null;if(s.serialNumber===e.endPage.serialNumber)return{startPage:s,startSegmentIndex:0};i=s.headerStartPos+s.totalSize}}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.trackBackings.map(t=>t.getDecoderConfig().then(i=>(i==null?void 0:i.codec)??null)));return Td({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class _d{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new Vi,this.firstTimestampInSamplesPromise=null,this.internalSampleRate=e.codecInfo.codec==="opus"?mr:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(t=>t.bitstream===this.bitstream);return y(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 y(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 De}getDisposition(){return{...kt,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(y(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const n=xa(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),{vorbisBlockSize:s}=n;let{durationInSamples:a}=n;if(!!(e.endPage.headerType&4)&&e.endSegmentIndex===e.endPage.lacingValues.length-1){const u=this.granulePositionToTimestampInSamples(e.endPage.granulePosition);a=pe(u-t.timestampInSamples,0,a)}const c=new ce(i.metadataOnly?je:e.data,"key",t.timestampInSamples/this.internalSampleRate,a/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(c,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:a,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:s}),c}getFirstTimestampInSamples(){return this.firstTimestampInSamplesPromise??(this.firstTimestampInSamplesPromise=(async()=>{const e=this.granulePositionToTimestampInSamples(0);y(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return e;let i=null,n=0,s=null,a=null;for(;t;){const c=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);if(!c||(i??(i=c.endPage),c.endPage.headerStartPos!==i.headerStartPos))break;const{durationInSamples:u,vorbisBlockSize:l}=xa(c.data,this.bitstream.codecInfo,a);n+=u,s??(s=u),a=l,t=await this.demuxer.findNextPacketStart(c)}if(!i)return e;y(s!==null);const o=this.bitstream.codecInfo.codec==="vorbis"?-s:0;return e+Math.max(i.granulePosition-n,o)})())}async getFirstPacket(e){y(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;const i=await this.getFirstTimestampInSamples(),n=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(n,{timestampInSamples:i,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){const i=this.encodedPacketToMetadata.get(e);if(!i)throw new Error("Packet was not created from this track.");const n=await this.demuxer.findNextPacketStart(i.packet);if(!n)return null;const s=i.timestampInSamples+i.durationInSamples,a=await this.demuxer.readPacket(n.startPage,n.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:s,vorbisLastBlocksize:i.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);const i=ei(e*this.internalSampleRate),n=await this.getFirstTimestampInSamples();if(i===n)return this.getFirstPacket(t);if(i<n)return null;y(this.bitstream.lastMetadataPacket);const s=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!s)return null;let a=s.startPage,o=this.demuxer.reader.fileSize;const c=[a];e:for(;a.headerStartPos+a.totalSize<o;){const A=a.headerStartPos,T=Math.floor((A+o)/2);let k=T;for(;;){const x=Math.min(k+xd,o-Pt);let P=this.demuxer.reader.requestSlice(k,Math.max(x-k,0));if(F(P)&&(P=await P),!P||!Pd(P,x,this.bitstream.serialNumber)){if(o<=T+Pt)break e;o=T+Pt;continue e}const I=P.filePos;let E=this.demuxer.reader.requestSliceRange(I,Pt,cr);F(E)&&(E=await E);const C=E&&Yr(E);if(!C||C.serialNumber!==this.bitstream.serialNumber){k=I+4;continue}if(C.granulePosition===-1){k=C.headerStartPos+C.totalSize;continue}this.granulePositionToTimestampInSamples(C.granulePosition)>i?o=C.headerStartPos:(a=C,c.push(C));continue e}}let u=s.startPage;for(const A of c){if(A.granulePosition===a.granulePosition)break;(!u||A.headerStartPos>u.headerStartPos)&&(u=A)}let l=u;const d=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===a.granulePosition);){const A=l.headerStartPos+l.totalSize;let T=this.demuxer.reader.requestSliceRange(A,Pt,cr);F(T)&&(T=await T);const k=T&&Yr(T);if(!k){l=a,d.push(a);break}l=k,l.serialNumber===this.bitstream.serialNumber&&d.push(l)}let f=null,h,p,m=l,b=0;if(l.headerStartPos===s.startPage.headerStartPos)h=n,p=!0,f=0;else{y(l.granulePosition!==-1),h=0,p=!1;for(let k=l.lacingValues.length-1;k>=0;k--)if(l.lacingValues[k]<255){f=k+1;break}if(f===null)throw new Error("Invalid page with granule position: no packets end on this page.");b=f-1;const A={data:je,endPage:m,endSegmentIndex:b},T=await this.demuxer.findNextPacketStart(A);if(T){const k=Ca(d,l,f);y(k);const x=Ia(d,k.page,k.segmentIndex);x?(l=x.page,f=x.segmentIndex):(l=T.startPage,f=T.startSegmentIndex)}else for(;;){const k=Ca(d,l,f);if(!k)break;const x=Ia(d,k.page,k.segmentIndex);if(!x)break;if(l=x.page,f=x.segmentIndex,k.page.headerStartPos!==m.headerStartPos){m=k.page,b=k.segmentIndex;break}}}let w=null,S=null;for(;l!==null;){y(f!==null);const A=await this.demuxer.readPacket(l,f);if(!A)break;if(!(l.headerStartPos===s.startPage.headerStartPos&&f<s.startSegmentIndex)){let x=this.createEncodedPacketFromOggPacket(A,{timestampInSamples:h,vorbisLastBlocksize:(S==null?void 0:S.vorbisBlockSize)??null},t);y(x);let P=this.encodedPacketToMetadata.get(x);if(y(P),!p&&A.endPage.headerStartPos===m.headerStartPos&&A.endSegmentIndex===b?(h=this.granulePositionToTimestampInSamples(l.granulePosition),p=!0,x=this.createEncodedPacketFromOggPacket(A,{timestampInSamples:h-P.durationInSamples,vorbisLastBlocksize:(S==null?void 0:S.vorbisBlockSize)??null},t),y(x),P=this.encodedPacketToMetadata.get(x),y(P)):h+=P.durationInSamples,w=x,S=P,p&&(h>i||P.timestampInSamples===i))break}const k=await this.demuxer.findNextPacketStart(A);if(!k)break;l=k.startPage,f=k.startSegmentIndex}return w}async getPacketSequential(e,t){const i=await this.sequentialScanMutex.acquire();try{const n=ei(e*this.internalSampleRate);e=n/this.internalSampleRate;const s=te(this.sequentialScanCache,n,c=>c.timestampInSamples);let a;if(s!==-1){const c=this.sequentialScanCache[s];a=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},t)}else if(a=await this.getFirstPacket(t),a&&a.timestamp>e)return null;let o=0;for(;a&&a.timestamp<e;){const c=await this.getNextPacket(a,t);if(!c||c.timestamp>e)break;if(a=c,o++,o===100){o=0;const u=this.encodedPacketToMetadata.get(a);y(u),this.sequentialScanCache.length>0&&y(fe(this.sequentialScanCache).timestampInSamples<=u.timestampInSamples),this.sequentialScanCache.push(u)}}return a}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Ia=(r,e,t)=>{let i=e,n=t;e:for(;;){for(n--,n;n>=0;n--)if(i.lacingValues[n]<255){n++;break e}if(y(n===-1),!(i.headerType&1)){n=0;break}const a=fo(r,o=>o.headerStartPos<i.headerStartPos);if(!a)return null;i=a,n=i.lacingValues.length}if(y(n!==-1),n===i.lacingValues.length){const s=r[r.indexOf(i)+1];y(s),i=s,n=0}return{page:i,segmentIndex:n}},Ca=(r,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};const i=fo(r,n=>n.headerStartPos<e.headerStartPos);return i?{page:i,segmentIndex:i.lacingValues.length-1}:null};/*!
194
+ * Copyright (c) 2026-present, Vanilagy and contributors
195
+ *
196
+ * This Source Code Form is subject to the terms of the Mozilla Public
197
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
198
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
199
+ */var Fe;(function(r){r[r.PCM=1]="PCM",r[r.IEEE_FLOAT=3]="IEEE_FLOAT",r[r.ALAW=6]="ALAW",r[r.MULAW=7]="MULAW",r[r.EXTENSIBLE=65534]="EXTENSIBLE"})(Fe||(Fe={}));class vd extends yt{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.trackBackings=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=this.reader.requestSlice(0,12);F(e)&&(e=await e),y(e);const t=be(e,4),i=t!=="RIFX",n=t==="RF64",s=Ct(e,i);let a=n?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(be(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,u=null,l=e.filePos;for(;a===null||l<a;){let f=this.reader.requestSlice(l,8);if(F(f)&&(f=await f),!f)break;const h=be(f,4),p=Ct(f,i),m=f.filePos;if(n&&c===0&&h!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(h==="fmt ")await this.parseFmtChunk(m,p,i);else if(h==="data"){if(u??(u=p),this.dataStart=f.filePos,this.dataSize=Math.max(Math.min(u,(a??1/0)-this.dataStart),0),this.reader.fileSize===null)break}else if(h==="ds64"){let b=this.reader.requestSlice(m,p);if(F(b)&&(b=await b),!b)break;if(p<16)throw new Error('Invalid RF64 file: "ds64" chunk is too small.');const w=no(b,i);u=no(b,i),a=Math.min(w+8,this.reader.fileSize??1/0)}else h==="LIST"?await this.parseListChunk(m,p,i):(h==="ID3 "||h==="id3 ")&&await this.parseId3Chunk(m,p);l=m+p+(p&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');const d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.trackBackings.push(new Rd(this))})())}async parseFmtChunk(e,t,i){let n=this.reader.requestSlice(e,t);if(F(n)&&(n=await n),!n)return;if(t<14)throw new Error('Invalid WAVE file - "fmt " chunk is too small');let s=Wr(n,i);const a=Wr(n,i),o=Ct(n,i);n.skip(4);const c=Wr(n,i);if(a===0||o===0||c===0)throw new Error("Invalid WAVE file - channel count, sample rate and block align must be positive");let u;if(t<16?u=8:u=Wr(n,i),t>=18&&s!==357){const l=Wr(n,i),d=t-18;if(Math.min(d,l)>=22&&s===Fe.EXTENSIBLE){n.skip(6);const h=X(n,16);s=h[0]|h[1]<<8}}if((s===Fe.MULAW||s===Fe.ALAW)&&(u=8),s!==Fe.PCM&&s!==Fe.IEEE_FLOAT&&s!==Fe.ALAW&&s!==Fe.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${s}). Only integer/float PCM, A-law, and μ-law are supported.`);if(s===Fe.PCM&&![8,16,24,32].includes(u))throw new Error(`Unsupported WAVE PCM bit depth (${u}). Only 8, 16, 24, and 32 bits are supported.`);if(s===Fe.IEEE_FLOAT&&![32,64].includes(u))throw new Error(`Unsupported WAVE float bit depth (${u}). Only 32 and 64 bits are supported.`);this.audioInfo={format:s,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(u/8),blockSizeInBytes:c}}async parseListChunk(e,t,i){var o,c,u,l,d,f,h,p,m,b,w;if(t<4)return;let n=this.reader.requestSlice(e,t);if(F(n)&&(n=await n),!n)return;const s=be(n,4);if(s!=="INFO"&&s!=="INF0")return;let a=n.filePos;for(;a<=e+t-8;){n.filePos=a;const S=be(n,4),A=Ct(n,i);if(A>n.remainingLength)break;const T=X(n,A);let k="";for(let x=0;x<T.length&&T[x]!==0;x++)k+=String.fromCharCode(T[x]);switch((o=this.metadataTags).raw??(o.raw={}),this.metadataTags.raw[S]=k,S){case"INAM":case"TITL":(c=this.metadataTags).title??(c.title=k);break;case"TIT3":(u=this.metadataTags).description??(u.description=k);break;case"IART":(l=this.metadataTags).artist??(l.artist=k);break;case"IPRD":(d=this.metadataTags).album??(d.album=k);break;case"IPRT":case"ITRK":case"TRCK":{const x=k.split("/"),P=Number.parseInt(x[0],10),I=x[1]&&Number.parseInt(x[1],10);Number.isInteger(P)&&P>0&&((f=this.metadataTags).trackNumber??(f.trackNumber=P)),I&&Number.isInteger(I)&&I>0&&((h=this.metadataTags).tracksTotal??(h.tracksTotal=I))}break;case"ICRD":case"IDIT":{const x=new Date(k);Number.isNaN(x.getTime())||((p=this.metadataTags).date??(p.date=x))}break;case"YEAR":{const x=Number.parseInt(k,10);Number.isInteger(x)&&x>0&&((m=this.metadataTags).date??(m.date=new Date(x,0,1)))}break;case"IGNR":case"GENR":(b=this.metadataTags).genre??(b.genre=k);break;case"ICMT":case"CMNT":case"COMM":(w=this.metadataTags).comment??(w.comment=k);break}a+=8+A+(A&1)}}async parseId3Chunk(e,t){if(t<He)return;let i=this.reader.requestSlice(e,t);if(F(i)&&(i=await i),!i)return;const n=wt(i);if(n){const s=t-He;if(n.size=Math.min(n.size,s),n.size>0){const a=i.slice(e+He,n.size);sn(a,n,this.metadataTags)}}}getCodec(){if(y(this.audioInfo),this.audioInfo.format===Fe.MULAW)return"ulaw";if(this.audioInfo.format===Fe.ALAW)return"alaw";if(this.audioInfo.format===Fe.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===Fe.IEEE_FLOAT){if(this.audioInfo.sampleSizeInBytes===4)return"pcm-f32";if(this.audioInfo.sampleSizeInBytes===8)return"pcm-f64"}y(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const Qt=2048;class Rd{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(y(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return y(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 y(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return De}getDisposition(){return{...kt}}async getPacketAtIndex(e,t){y(e>=0),y(this.demuxer.audioInfo);const i=e*Qt*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const n=Math.min(Qt*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-i);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,n);if(F(c)&&(c=await c),!c)return null}let s;if(t.metadataOnly)s=je;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,n);F(c)&&(c=await c),y(c),s=X(c,n)}const a=e*Qt/this.demuxer.audioInfo.sampleRate,o=n/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new ce(s,"key",a,o,e,n)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){y(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Qt,(this.demuxer.dataSize-1)/(Qt*this.demuxer.audioInfo.blockSizeInBytes)));if(i<0)return null;const n=await this.getPacketAtIndex(i,t);if(n)return n;if(i===0)return null;y(this.demuxer.reader.fileSize===null);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;s;){const a=await this.getNextPacket(s,t);if(!a)break;s=a}return s}getNextPacket(e,t){y(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Qt);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}/*!
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
+ */const ai=7,lr=9,oi=r=>{const e=r.filePos;if(r.remainingLength<ai)return null;const t=X(r,ai),i=new re(t);if(i.readBits(12)!==4095||(i.skipBits(1),i.readBits(2)!==0))return null;const a=i.readBits(1),o=i.readBits(2)+1,c=i.readBits(4);if(c>=qt.length)return null;i.skipBits(1);const u=i.readBits(3);if(u===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const l=i.readBits(13);i.skipBits(11);const d=i.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let f=null;if(a===0){if(r.remainingLength<2)return null;f=we(r)}return l<r.filePos-e?null:{objectType:o,samplingFrequencyIndex:c,channelConfiguration:u,frameLength:l,numberOfAacFrames:d,crcCheck:f,startPos:e}};/*!
206
+ * Copyright (c) 2026-present, Vanilagy and contributors
207
+ *
208
+ * This Source Code Form is subject to the terms of the Mozilla Public
209
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
210
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
211
+ */const ss=1024;class Bd extends yt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new Vi,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();y(this.firstFrameHeader),this.trackBackings=[new Fd(this)]})())}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,He);if(F(a)&&(a=await a),!a){this.lastSampleLoaded=!0;return}const o=wt(a);if(!o)break;this.lastLoadedPos=a.filePos+o.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,ai,lr);if(F(e)&&(e=await e),!e){this.lastSampleLoaded=!0;return}const t=oi(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);const i=qt[t.samplingFrequencyIndex];y(i!==void 0);const n=ss/i,s={timestamp:this.nextTimestampInSamples/i,duration:n,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=ss,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0;for(;;){let i=this.reader.requestSlice(t,He);if(F(i)&&(i=await i),!i)break;const n=wt(i);if(!n)break;let s=this.reader.requestSlice(i.filePos,n.size);if(F(s)&&(s=await s),!s)break;sn(s,n,this.metadataTags),t=i.filePos+n.size}return this.metadataTags}finally{e()}}}class Fd{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}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 De}getCodec(){return"aac"}getInternalCodecId(){return y(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){y(this.demuxer.firstFrameHeader);const e=ji[this.demuxer.firstFrameHeader.channelConfiguration];return y(e!==void 0),e}getSampleRate(){y(this.demuxer.firstFrameHeader);const e=qt[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return y(e!==void 0),e}getDisposition(){return{...kt}}async getDecoderConfig(){return y(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;const i=this.demuxer.loadedSamples[e];if(!i)return null;let n;if(t.metadataOnly)n=je;else{let s=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(F(s)&&(s=await s),!s)return null;n=X(s,i.dataSize)}return new ce(n,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const n=fi(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(n===-1)throw new Error("Packet was not created from this track.");const s=n+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const n=te(this.demuxer.loadedSamples,e,s=>s.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(n,t);if(n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}/*!
212
+ * Copyright (c) 2026-present, Vanilagy and contributors
213
+ *
214
+ * This Source Code Form is subject to the terms of the Mozilla Public
215
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
216
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
217
+ */const Dd=r=>r===0?null:r===1?192:r>=2&&r<=5?144*2**r:r===6?"uncommon-u8":r===7?"uncommon-u16":r>=8&&r<=15?2**r:null,Md=(r,e)=>{switch(r){case 0:return e;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}},Od=r=>{let e=0;const t=new re(X(r,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);const i=[],n=e-1,s=new re(X(r,n)),a=8-e-1;for(let c=0;c<a;c++)i.unshift(t.readBits(1));for(let c=0;c<n;c++)for(let u=0;u<8;u++){const l=s.readBits(1);u<2||i.unshift(l)}return i.reduce((c,u,l)=>c|u<<l,0)},Nd=(r,e)=>{if(e==="uncommon-u16")return we(r)+1;if(e==="uncommon-u8")return K(r)+1;if(typeof e=="number")return e;ze(e),y(!1)},zd=(r,e)=>e==="uncommon-u16"?we(r):e==="uncommon-u16-10"?we(r)*10:e==="uncommon-u8"?K(r):typeof e=="number"?e:null,Ud=r=>{let t=0;for(const i of r){t^=i;for(let n=0;n<8;n++)(t&128)!==0?t=t<<1^7:t<<=1,t&=255}return t};/*!
218
+ * Copyright (c) 2026-present, Vanilagy and contributors
219
+ *
220
+ * This Source Code Form is subject to the terms of the Mozilla Public
221
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
222
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
223
+ */class Vd extends yt{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 Vi,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),y(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{var t;let e=0;for(;;){let i=this.reader.requestSlice(e,He);if(F(i)&&(i=await i),!i)break;const n=wt(i);if(!n)break;let s=this.reader.requestSlice(i.filePos,n.size);F(s)&&(s=await s),y(s),sn(s,n,this.metadataTags),e=i.filePos+n.size}for(e+=4;this.reader.fileSize===null||e<this.reader.fileSize;){let i=this.reader.requestSlice(e,4);if(F(i)&&(i=await i),e+=4,i===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);y(i);const n=K(i),s=dt(i),a=(n&128)!==0;switch(n&127){case or.STREAMINFO:{if(s<34)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let c=this.reader.requestSlice(e,s);if(F(c)&&(c=await c),c===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);const u=X(c,34),l=new re(u),d=l.readBits(16),f=l.readBits(16),h=l.readBits(24),p=l.readBits(24),m=l.readBits(20);if(m===0)throw new Error("Invalid StreamInfo block: sample rate is 0. Corrupted file.");const b=l.readBits(3)+1;l.readBits(5);const w=l.readBits(36);l.skipBits(128);const S=new Uint8Array(42);S.set(new Uint8Array([102,76,97,67]),0),S.set(new Uint8Array([128,0,0,34]),4),S.set(u,8),this.audioInfo={numberOfChannels:b,sampleRate:m,totalSamples:w,minimumBlockSize:d,maximumBlockSize:f,minimumFrameSize:h,maximumFrameSize:p,description:S},this.trackBacking=new Ld(this);break}case or.VORBIS_COMMENT:{let c=this.reader.requestSlice(e,s);if(F(c)&&(c=await c),!c)throw new Error(`Vorbis comment block at position ${e} exceeds the file. Corrupted file.`);Xn(X(c,s),this.metadataTags);break}case or.PICTURE:{let c=this.reader.requestSlice(e,s);if(F(c)&&(c=await c),!c)throw new Error(`Picture block at position ${e} exceeds the file. Corrupted file.`);try{const u=U(c),l=U(c),d=_e.decode(X(c,l)),f=U(c),h=_e.decode(X(c,f));c.skip(16);const p=U(c),m=X(c,p);(t=this.metadataTags).images??(t.images=[]),this.metadataTags.images.push({data:m,mimeType:d,kind:u===3?"coverFront":u===4?"coverBack":"unknown",description:h})}catch{}break}}if(e+=s,a)break}if(this.lastLoadedPos=e,!this.audioInfo)throw new Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})())}async readNextFlacFrame(e){y(this.audioInfo);const t=6,i=16,n=10,s=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+i+2,a=this.audioInfo.minimumFrameSize||n,c=(this.audioInfo.maximumFrameSize||s)+i,u=await this.reader.requestSliceRange(e,t,c);if(!u)return null;const l=this.readFlacFrameHeader(u);if(!l)return null;for(u.filePos=e+a;;){if(u.filePos>u.end-t)return{num:l.num,blockSize:l.blockSize,sampleRate:l.sampleRate,size:u.end-e,isLastFrame:!0};if(K(u)===255){const f=u.filePos,h=K(u),p=this.blockingBit===1?249:248;if(h!==p){u.filePos=f;continue}u.skip(-2);const m=u.filePos-e,b=this.readFlacFrameHeader(u);if(!b){u.filePos=f;continue}if(this.blockingBit===0){if(b.num-l.num!==1){u.filePos=f;continue}}else if(b.num-l.num!==l.blockSize){u.filePos=f;continue}return{num:l.num,blockSize:l.blockSize,sampleRate:l.sampleRate,size:m,isLastFrame:!1}}}}readFlacFrameHeader(e){const t=e.filePos,i=X(e,4),n=new re(i);if(n.readBits(15)!==32764)return null;const a=n.readBits(1);if(this.blockingBit!==null&&a!==this.blockingBit)return null;const o=Dd(n.readBits(4));if(!o)return null;y(this.audioInfo);const c=Md(n.readBits(4),this.audioInfo.sampleRate);if(!c||(n.readBits(4),n.readBits(3),n.readBits(1)!==0))return null;const l=K(e);e.skip(-1);const f=4+Math.max(Math.clz32(~l<<24),1)+(o==="uncommon-u16"?2:o==="uncommon-u8"?1:0)+(c==="uncommon-u8"?1:typeof c=="number"?0:2)+1;if(t+f>e.end)return null;const h=Od(e),p=Nd(e,o),m=zd(e,c);if(m===null||m!==this.audioInfo.sampleRate)return null;const b=e.filePos-t,w=K(e);e.skip(-b),e.skip(-1);const S=Ud(X(e,b));return w!==S?null:(this.blockingBit=a,{num:h,blockSize:p,sampleRate:m})}async advanceReader(){await this.readMetadata(),y(this.lastLoadedPos!==null),y(this.audioInfo);const e=this.lastLoadedPos,t=await this.readNextFlacFrame(e);if(!t){this.lastSampleLoaded=!0;return}const i=this.loadedSamples[this.loadedSamples.length-1],s={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(s),t.isLastFrame){this.lastSampleLoaded=!0;return}}}class Ld{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return De}getTimeResolution(){return y(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 y(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...kt}}async getDecoderConfig(){return y(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(y(this.demuxer.audioInfo),e<0)return null;const i=await this.demuxer.readingMutex.acquire();try{for(;;){const n=te(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(n===-1){if(this.demuxer.lastSampleLoaded)return null;await this.demuxer.advanceReader();continue}const s=this.demuxer.loadedSamples[n],a=s.blockOffset/this.demuxer.audioInfo.sampleRate,o=s.blockSize/this.demuxer.audioInfo.sampleRate;if(a+o<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(n,t)}}finally{i()}}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const 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{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){const i=this.demuxer.loadedSamples[e];if(!i)return null;let n;if(t.metadataOnly)n=je;else{let o=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(F(o)&&(o=await o),!o)return null;n=X(o,i.byteSize)}y(this.demuxer.audioInfo);const s=i.blockOffset/this.demuxer.audioInfo.sampleRate,a=i.blockSize/this.demuxer.audioInfo.sampleRate;return new ce(n,"key",s,a,e,i.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}/*!
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
+ */const Ne=9e4,Zr=2**33,Le=188,Wd=r=>{let e="video/MP2T";const t=[...new Set(r.filter(Boolean))];return t.length>0&&(e+=`; codecs="${t.join(", ")}"`),e},am=r=>dl(Math.round(Ne*r),Zr),hc=r=>{const e=60*Ne;return{reference:r-e,offset:r>=Zr-e?-Zr:Zr}},mc=(r,e)=>{const{reference:t,offset:i}=e;return i<0&&r>=t||i>0&&r<t?r+i:r};/*!
230
+ * Copyright (c) 2026-present, Vanilagy and contributors
231
+ *
232
+ * This Source Code Form is subject to the terms of the Mozilla Public
233
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
234
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
235
+ */const pc="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.",Ea=5,qd=1212435798,Hd=1212436562,jd=1146376960,Kd=new Set([133,134,162]),_a=new Set;class Xd extends yt{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5*1024*1024,this.minReferencePointByteDistance=-1,this.timestampWrapInfo=null,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{const e=Le+16+1;let t=this.reader.requestSlice(0,e);F(t)&&(t=await t),y(t);const i=X(t,e);if(i[0]===71&&i[Le]===71)this.packetOffset=0,this.packetStride=Le;else if(i[0]===71&&i[Le+16]===71)this.packetOffset=0,this.packetStride=Le+16;else if(i[4]===71&&i[4+Le+4]===71)this.packetOffset=4,this.packetStride=Le+4;else throw new Error("Unreachable.");const n=256;this.minReferencePointByteDistance=n*this.packetStride;let s=this.packetOffset,a=null,o=!1,c=!1;for(;;){const u=await this.readPacketHeader(s);if(!u)break;if(u.payloadUnitStartIndicator===0){s+=this.packetStride;continue}if(c&&!this.elementaryStreams.some(m=>m.pid===u.pid&&!m.initialized)){s+=this.packetStride;continue}const l=await this.readSection(s,!0,!c);if(!l)break;const d=3,f=32;let h=!1;if(!c&&l.pid!==0&&!(l.payload[0]===0&&l.payload[1]===0&&l.payload[2]===1)){const b=new re(l.payload),w=b.readAlignedByte();b.skipBits(8*w),h=b.readBits(8)===2}if(l.pid===0&&!o){const m=new re(l.payload),b=m.readAlignedByte();m.skipBits(8*b),m.skipBits(14);const w=m.readBits(10);for(m.skipBits(40);8*(w+d)-m.pos>f;){const S=m.readBits(16);m.skipBits(3);const A=m.readBits(13);if(S!==0){if(a!==null)throw new Error("Only files with a single program are supported.");a=A}}if(a===null)throw new Error("Program Association Table must link to a Program Map Table.");o=!0}else if((l.pid===a||h)&&!c){const m=new re(l.payload),b=m.readAlignedByte();m.skipBits(8*b),m.skipBits(12);const w=m.readBits(12);m.skipBits(43),m.readBits(13),m.skipBits(6);const S=m.readBits(10),A=m.pos+8*S;let T=!1;for(;m.pos<A;){const k=m.readBits(8),x=m.readBits(8),P=m.pos+8*x;if(k===Ea&&x>=4){const I=m.readBits(32);T||(T=I===qd||I===Hd)}m.pos=P}for(m.pos=A;8*(w+d)-m.pos>f;){const k=m.readBits(8);m.skipBits(3);const x=m.readBits(13);m.skipBits(6);const P=m.readBits(10),I=m.pos+8*P;let E=!1,C=!1,_=!1;for(;m.pos<I;){const M=m.readBits(8),V=m.readBits(8),G=m.pos+8*V;if(M===106)E=!0;else if(M===122||M===204)C=!0;else if(M===123)_=!0;else if(M===Ea&&V>=4){const J=m.readBits(32);_||(_=(J&4294967040)===jd)}m.pos=G}let D=null;const q=T&&Kd.has(k)?130:k;switch(q){case 27:case 36:D={type:"video",codec:k===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 M;q===3||q===4?M="mp3":q===15?M="aac":q===129?M="ac3":q===135?M="eac3":M="dts",D={type:"audio",codec:M,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:C?D={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:E?D={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:_&&(D={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:_a.has(k)||(j._warn(`Note: MPEG-TS streams with stream_type 0x${k.toString(16)} are not currently supported.`),_a.add(k))}D&&this.elementaryStreams.push({demuxer:this,pid:x,streamType:k,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:D,referencePesPackets:[]})}c=!0}else{const m=this.elementaryStreams.find(b=>b.pid===l.pid);e:if(m&&!m.initialized){const b=sr(this,l,!0);if(!b)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${m.pid}`);if(m.firstSection=l,m.canBeTrustedWithKeyPackets=l.randomAccessIndicator===1,this.input._initInput){const A=(await this.input._initInput._getDemuxer()).elementaryStreams.find(T=>T.pid===l.pid&&T.info.codec===m.info.codec&&T.initialized);if(A){m.info=A.info,m.initialized=!0;break e}}const w=new jr(m,b);if(m.info.type==="video"){for(;;){const S=w;if(S.suppliedPacket=null,await w.markNextPacket(),m.info.codec==="avc"){if(!w.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(m.info.avcCodecInfo=$i(w.suppliedPacket.data),!m.info.avcCodecInfo)continue;const A=m.info.avcCodecInfo.sequenceParameterSets[0];y(A);const T=dr(A);m.info.width=T.displayWidth,m.info.height=T.displayHeight;const k=T.pixelAspectRatio.num,x=T.pixelAspectRatio.den;m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=m.info.height,k>0&&x>0&&(k>x?m.info.squarePixelWidth=Math.round(m.info.width*k/x):m.info.squarePixelHeight=Math.round(m.info.height*x/k)),m.info.colorSpace={primaries:ht[T.colourPrimaries],transfer:mt[T.transferCharacteristics],matrix:pt[T.matrixCoefficients],fullRange:!!T.fullRangeFlag},m.info.reorderSize=T.maxDecFrameBuffering;break}else if(m.info.codec==="hevc"){if(!w.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(m.info.hevcCodecInfo=Ji(w.suppliedPacket.data),!m.info.hevcCodecInfo)continue;const T=m.info.hevcCodecInfo.arrays.find(I=>I.nalUnitType===ge.SPS_NUT).nalUnits[0];y(T);const k=Zi(T);m.info.width=k.displayWidth,m.info.height=k.displayHeight;const x=k.pixelAspectRatio.num,P=k.pixelAspectRatio.den;m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=m.info.height,x>0&&P>0&&(x>P?m.info.squarePixelWidth=Math.round(m.info.width*x/P):m.info.squarePixelHeight=Math.round(m.info.height*P/x)),m.info.colorSpace={primaries:ht[k.colourPrimaries],transfer:mt[k.transferCharacteristics],matrix:pt[k.matrixCoefficients],fullRange:!!k.fullRangeFlag},m.info.reorderSize=k.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}m.info.decoderConfig={codec:fn({width:m.info.width,height:m.info.height,codec:m.info.codec,codecDescription:null,colorSpace:m.info.colorSpace,avcType:1,avcCodecInfo:m.info.avcCodecInfo,hevcCodecInfo:m.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:m.info.width,codedHeight:m.info.height,colorSpace:m.info.colorSpace},(m.info.width!==m.info.squarePixelWidth||m.info.height!==m.info.squarePixelHeight)&&(m.info.decoderConfig.displayAspectWidth=m.info.squarePixelWidth,m.info.decoderConfig.displayAspectHeight=m.info.squarePixelHeight),m.initialized=!0}else{if(await w.markNextPacket(),!w.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${m.pid}`);if(m.info.codec==="aac"){const S=Ke.tempFromBytes(w.suppliedPacket.data),A=oi(S);if(!A)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");m.info.aacCodecInfo={isMpeg2:!1,objectType:A.objectType},m.info.numberOfChannels=ji[A.channelConfiguration],m.info.sampleRate=qt[A.samplingFrequencyIndex]}else if(m.info.codec==="mp3"){const S=U(Ke.tempFromBytes(w.suppliedPacket.data)),A=ws(S,w.suppliedPacket.data.byteLength);if(!A.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");m.info.numberOfChannels=ti(A.header.channel),m.info.sampleRate=A.header.sampleRate}else if(m.info.codec==="ac3"){const S=Jl(w.suppliedPacket.data);if(!S)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(S.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=Ss[S.acmod]+S.lfeon,m.info.sampleRate=Xi[S.fscod]}else if(m.info.codec==="eac3"){const S=ru(w.suppliedPacket.data);if(!S)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const A=Fo(S);if(A===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=Do(S),m.info.sampleRate=A}else if(m.info.codec==="dts"){const S=Oo(w.suppliedPacket.data);if(!S)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");m.info.numberOfChannels=S.numberOfChannels,m.info.sampleRate=S.sampleRate,S.core&&(m.info.dtsFormat=S.hasExtensions?"dtsh":"dtsc")}else throw new Error("Unhandled.");m.info.decoderConfig={codec:Us({codec:m.info.codec,codecDescription:null,aacCodecInfo:m.info.aacCodecInfo,dtsFormat:m.info.dtsFormat}),numberOfChannels:m.info.numberOfChannels,sampleRate:m.info.sampleRate},m.initialized=!0}}}if(c&&this.elementaryStreams.every(m=>m.initialized))break;s+=this.packetStride}if(!c)throw o?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(const u of this.elementaryStreams)u.initialized&&(u.info.type==="video"?this.trackBackingEntries.push(new Qd(u)):this.trackBackingEntries.push(new Gd(u)))})())}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.trackBackingEntries.map(t=>t.getDecoderConfig().then(i=>(i==null?void 0:i.codec)??null)));return Wd(e)}async readSection(e,t,i=!1){let n=e,s=e;const a=[];let o=0,c=null,u=!0,l=0;for(;;){const f=await this.readPacket(s);if(s+=this.packetStride,!f)break;if(c){if(f.pid!==c.pid){if(i)break;continue}if(f.payloadUnitStartIndicator===1)break}else{if(f.payloadUnitStartIndicator===0)break;c=f}const h=!!(f.adaptationFieldControl&2),p=!!(f.adaptationFieldControl&1);let m=0;if(h&&(m=1+f.body[0],f===c&&m>1&&(l=f.body[1]>>6&1)),p&&(m===0?(a.push(f.body),o+=f.body.byteLength):(a.push(f.body.subarray(m)),o+=f.body.byteLength-m)),n=s,!t&&o>=64){u=!1;break}if(fi(this.sectionEndPositions,n,w=>w)!==-1){u=!1;break}}if(u){const f=te(this.sectionEndPositions,n,h=>h);this.sectionEndPositions.splice(f+1,0,n)}if(!c)return null;let d;if(a.length===1)d=a[0];else{const f=a.reduce((p,m)=>p+m.length,0);d=new Uint8Array(f);let h=0;for(const p of a)d.set(p,h),h+=p.length}return{startPos:e,endPos:t?n:null,pid:c.pid,payload:d,randomAccessIndicator:l}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(F(t)&&(t=await t),!t)return null;if(K(t)!==71)throw new Error("Invalid TS packet sync byte; the file is likely corrupted.");const n=we(t),s=n>>14&1,a=n&8191,c=K(t)>>4&3;return{payloadUnitStartIndicator:s,pid:a,adaptationFieldControl:c}}async readPacket(e){let t=this.reader.requestSlice(e,Le);if(F(t)&&(t=await t),!t)return null;const i=X(t,Le);if(i[0]!==71)throw new Error("Invalid TS packet sync byte; the file is likely corrupted.");const s=(i[1]<<8)+i[2],a=s>>14&1,o=s&8191,u=i[3]>>4&3;return{payloadUnitStartIndicator:a,pid:o,adaptationFieldControl:u,body:i.subarray(4)}}normalizeTimestamp(e){return this.timestampWrapInfo??(this.timestampWrapInfo=hc(e)),mc(e,this.timestampWrapInfo)}}const Ft=(r,e,t)=>{if(e.payload.byteLength<3)return null;const i=new re(e.payload);if(i.readBits(24)!==1)return null;const s=i.readBits(8);if(i.skipBits(16),s===188||s===190||s===191||s===240||s===241||s===255||s===242||s===248)return null;i.skipBits(8);const a=i.readBits(2);i.skipBits(14);let o=null;if(a===2||a===3)o=0,i.skipBits(4),o+=i.readBits(3)*(1<<30),i.skipBits(1),o+=i.readBits(15)*32768,i.skipBits(1),o+=i.readBits(15),o=r.normalizeTimestamp(o);else if(t)throw new Error(pc);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:o,randomAccessIndicator:e.randomAccessIndicator}},sr=(r,e,t)=>{y(e.endPos!==null);const i=Ft(r,e,t);if(!i)return null;const n=new re(e.payload);n.skipBits(32);const s=n.readBits(16),a=6;n.skipBits(16);const o=n.readBits(8),c=n.pos+8*o;n.pos=c;const u=c/8;y(Number.isInteger(u));const l=e.payload.subarray(u,s>0?a+s:e.payload.byteLength);return{...i,data:l}};class an{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){const e=this.elementaryStream.demuxer,t=this.elementaryStream.info.type;let i=0;for(const n of e.trackBackingEntries)if(n.getType()===t&&i++,y(n instanceof an),n.elementaryStream===this.elementaryStream)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return De}getDisposition(){return{...kt,primary:!1}}getTimeResolution(){return Ne}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,i){let n;return this.allPacketsAreKeyPackets()?n="key":n=e.randomAccessIndicator===1?"key":"delta",new ce(i.metadataOnly?je:e.data,n,e.pts/Ne,Math.max(t/Ne,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;y(t);const i=sr(this.elementaryStream.demuxer,t,!0);y(i);const n=new jr(this.elementaryStream,i),s=new Cn(this,n),a=await s.readNext();if(!a)return null;const o=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(o,s),this.packetSectionStarts.set(o,a.packet.sectionStartPos),o}async getNextPacket(e,t){let i=this.packetBuffers.get(e);if(i){const l=await i.readNext();if(!l)return null;this.packetBuffers.delete(e);const d=this.createEncodedPacket(l.packet,l.duration,t);return this.packetBuffers.set(d,i),this.packetSectionStarts.set(d,l.packet.sectionStartPos),d}const n=this.packetSectionStarts.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");const s=this.elementaryStream.demuxer,a=await s.readSection(n,!0);y(a);const o=sr(s,a,!0);y(o);const c=new jr(this.elementaryStream,o);i=new Cn(this,c);const u=e.sequenceNumber;for(;;){const l=await i.readNext();if(!l)return null;if(l.packet.sequenceNumber>u){const d=this.createEncodedPacket(l.packet,l.duration,t);return this.packetBuffers.set(d,i),this.packetSectionStarts.set(d,l.packet.sectionStartPos),d}}}async getNextKeyPacket(e,t){let i=e;for(;;){if(i=await this.getNextPacket(i,t),!i)return null;if(i.type==="key")return i}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,i){var T;const n=ei(e*Ne),s=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=s,c=this.elementaryStream.pid,u=async(k,x,P)=>{let I=k;for(;I<x;){const E=await s.readPacketHeader(I);if(!E)return null;if(E.pid===c&&E.payloadUnitStartIndicator===1){const C=await s.readSection(I,P);if(!C)return null;const _=Ft(s,C,!1);if(_&&_.pts!==null)return{pesPacketHeader:_,section:C}}I+=s.packetStride}return null},l=this.elementaryStream.firstSection;y(l);const d=Ft(s,l,!0);if(y(d),n<d.pts)return null;let f;const h=this.elementaryStream.referencePesPackets,p=te(h,n,k=>k.pts),m=p!==-1?h[p]:null;if(m&&n-m.pts<Ne/2)f=m.sectionStartPos;else{let k=0;if(a.fileSize!==null){const x=Math.ceil(a.fileSize/o);if(x>1){let P=0,I=x-1;for(k=P;P<=I;){const E=Math.floor((P+I)/2),C=hn(E*o,s.packetStride)+d.sectionStartPos,_=C+o,D=await u(C,_,!1);if(!D){I=E-1;continue}D.pesPacketHeader.pts<=n?(k=E,P=E+1):I=E-1}}}f=hn(k*o,s.packetStride)+d.sectionStartPos}const b=await u(f,a.fileSize??1/0,!1);let w=(b==null?void 0:b.pesPacketHeader)??null;w||(w=d);const S=this.getReorderSize(),A=async(k,x)=>{var G;const P=await s.readSection(k,!0);y(P);const I=sr(s,P,!0);y(I);const E=new jr(this.elementaryStream,I),C=new Cn(this,E);for(;!((((G=fe(C.presentationOrderPackets))==null?void 0:G.pts)??-1/0)>=n||!await C.readNextPacket()););const _=fs(C.presentationOrderPackets,x);if(_===-1)return null;const D=C.presentationOrderPackets[_],q=_===0?0:D.pts-C.presentationOrderPackets[_-1].pts;C.decodeOrderPackets.splice(0,C.decodeOrderPackets.indexOf(D)),C.lastDuration=q;const M=await C.readNext();y(M);const V=this.createEncodedPacket(M.packet,M.duration,i);return this.packetBuffers.set(V,C),this.packetSectionStarts.set(V,M.packet.sectionStartPos),V};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let k=w.sectionStartPos+s.packetStride;for(;;){const x=await s.readPacketHeader(k);if(!x)break e;if(x.pid===c&&x.payloadUnitStartIndicator===1){const P=await s.readSection(k,!1);if(P){const I=Ft(s,P,!1);if(I&&I.pts!==null){if(I.pts>n)break e;w=I,as(this.elementaryStream,w);break}}}k+=s.packetStride}}e:for(let k=0;k<S+1;k++){let x=w.sectionStartPos-s.packetStride;for(;x>=s.packetOffset;){const P=await s.readPacketHeader(x);if(!P)break e;if(P.pid===c&&P.payloadUnitStartIndicator===1){const I=await s.readSection(x,!1);if(I){const E=Ft(s,I,!1);if(E&&E.pts!==null){w=E;break}}}x-=s.packetStride}if(x<s.packetOffset)break}return A(w.sectionStartPos,k=>k.pts<=n)}else{let k=f,x=null;const P=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let I=null;const E=k<=d.sectionStartPos;let C,_=null;if(E)C=d,_=l;else{const V=await u(k,x??a.fileSize??1/0,P);C=(V==null?void 0:V.pesPacketHeader)??null,_=(V==null?void 0:V.section)??null}let D=!1,q=0,M=null;e:for(;C&&!(x!==null&&C.sectionStartPos>=x);){if(C.pts<=n){let G;if(this.elementaryStream.canBeTrustedWithKeyPackets)G=C.randomAccessIndicator===1;else{if(!M){y(_);const J=sr(s,_,!0);y(J),M=new jr(this.elementaryStream,J)}for(;(!M.suppliedPacket||M.suppliedPacket.sectionStartPos<C.sectionStartPos)&&(M.suppliedPacket=null,await M.markNextPacket(),!!M.suppliedPacket););G=((T=M.suppliedPacket)==null?void 0:T.sectionStartPos)===C.sectionStartPos&&M.suppliedPacket.randomAccessIndicator===1}G&&(I=C)}if(C.pts>n&&(D=!0),D&&(q++,q>S))break;let V=C.sectionStartPos+s.packetStride;for(;;){const G=await s.readPacketHeader(V);if(!G)break e;if(G.pid===c&&G.payloadUnitStartIndicator===1){const J=await s.readSection(V,P);if(J){const ae=Ft(s,J,!1);if(ae&&ae.pts!==null){C=ae,_=J,as(this.elementaryStream,C);break}}}V+=s.packetStride}}if(I){let V=I;if(q===0)e:for(let J=0;J<S;J++){let ae=V.sectionStartPos-s.packetStride;for(;ae>=s.packetOffset;){const he=await s.readPacketHeader(ae);if(!he)break e;if(he.pid===c&&he.payloadUnitStartIndicator===1){const le=await s.readSection(ae,P);if(le){const ye=Ft(s,le,!1);if(ye&&ye.pts!==null){V=ye;break}}}ae-=s.packetStride}if(ae<s.packetOffset)break}const G=await A(V.sectionStartPos,J=>J.pts<=n&&J.randomAccessIndicator===1);if(G)return G}if(E)return null;x=k,k=Math.max(hn(k-d.sectionStartPos-o,s.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}}class Qd extends an{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[...Un]}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return y(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Gd extends an{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return y(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const as=(r,e)=>{const t=r.referencePesPackets,i=te(t,e.sectionStartPos,n=>n.sectionStartPos);if(i>=0){const n=t[i];if(e.pts<=n.pts)return!1;const s=r.demuxer.minReferencePointByteDistance;if(e.sectionStartPos-n.sectionStartPos<s)return!1;if(i<t.length-1){const a=t[i+1];if(a.pts<e.pts||a.sectionStartPos-e.sectionStartPos<s)return!1}}return t.splice(i+1,0,{sectionStartPos:e.sectionStartPos,sectionEndPos:e.sectionEndPos,pts:e.pts,randomAccessIndicator:e.randomAccessIndicator}),!0};class jr{constructor(e,t){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=t}ensureBuffered(e){const t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){const e=this.pesPackets[this.currentPesPacketIndex];return y(e),e}async bufferData(e){const t=this.endPos+e;for(;this.endPos<t;){let i;if(this.pesPackets.length===0)i=this.startingPesPacket;else{let n=fe(this.pesPackets).sectionEndPos;for(y(n!==null);;){const s=await this.demuxer.readPacketHeader(n);if(!s)return;if(s.pid===this.pid){const a=await this.demuxer.readSection(n,!0);if(!a)return;const o=sr(this.demuxer,a,!1);if(o){i=o;break}}n+=this.demuxer.packetStride}}this.pesPackets.push(i),this.endPos+=i.data.byteLength}}readBytes(e){const t=this.getCurrentPesPacket(),i=this.currentPos-this.currentPesPacketPos,n=i+e;if(this.currentPos+=e,n<=t.data.byteLength)return t.data.subarray(i,n);const s=new Uint8Array(e);s.set(t.data.subarray(i));let a=t.data.byteLength-i;for(;;){this.advanceCurrentPacket();const o=this.getCurrentPesPacket(),c=e-a;if(c<=o.data.byteLength){s.set(o.data.subarray(0,c),a);break}s.set(o.data,a),a+=o.data.byteLength}return s}readU8(){let e=this.getCurrentPesPacket();const t=this.currentPos-this.currentPesPacketPos;if(this.currentPos++,t<e.data.byteLength)return e.data[t];do this.advanceCurrentPacket(),e=this.getCurrentPesPacket();while(e.data.byteLength===0);return e.data[0]}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;const t=this.getCurrentPesPacket();this.currentPesPacketPos-=t.data.byteLength}else for(;;){const t=this.getCurrentPesPacket(),i=this.currentPesPacketPos+t.data.byteLength;if(e<i)break;this.currentPesPacketPos+=t.data.byteLength,this.currentPesPacketIndex++}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}async markNextPacket(){var t;y(!this.suppliedPacket);const e=this.elementaryStream;if(e.info.type==="video"){const i=e.info.codec,n=1024;if(i!=="avc"&&i!=="hevc")throw new Error("Unhandled.");const s=i==="avc"?1:2;let a=null,o=!1,c=0;for(;;){let u=this.ensureBuffered(n);if(F(u)&&(u=await u),u===0)break;const l=this.currentPos,d=this.readBytes(u),f=d.byteLength;let h=0;for(;h<f;){const p=d.indexOf(0,h);if(p===-1||p>=f)break;h=p;const m=l+h;if(h+3>=f){this.seekTo(m);break}const b=d[h+1],w=d[h+2],S=d[h+3];let A=0;if(b===0&&w===0&&S===1?A=4:b===0&&w===1&&(A=3),A===0){h++;continue}const T=m;a??(a=T);const k=h+A,x=k+s,P=6;if(x+(i==="avc"?P:1)>f){this.seekTo(m);break}const E=d[k];let C,_,D,q;if(i==="avc")C=ri(E),_=C===Ae.NON_IDR_SLICE||C===Ae.SLICE_DPA||C===Ae.IDR,D=C===Ae.SEI||C===Ae.SPS||C===Ae.PPS||C===Ae.AUD,q=C===Ae.AUD;else{if(C=fr(E),((E&1)<<5|d[k+1]>>3)>0){h+=A;continue}_=C<=ge.RASL_R||C>=ge.BLA_W_LP&&C<=21,D=C>=ge.VPS_NUT&&C<=37||C===ge.PREFIX_SEI_NUT||C>=41&&C<=44||C>=48&&C<=55,q=C===ge.AUD_NUT}let M=!1;if(_){let V;if(i==="avc"){const G=d.subarray(x,x+P),J=W(new re(G));V=!o||J<=c,c=J}else V=d[x]>>7===1;V&&(o?M=!0:o=!0)}else D&&o?M=!0:q&&(a=T);if(M){const V=T-a;return this.seekTo(a),this.supplyPacket(V,0)}h+=A}if(u<n)break}if(o){y(a!==null);const u=this.endPos-a;return this.seekTo(a),this.supplyPacket(u,0)}}else{const i=e.info.codec,n=128;for(;;){let s=this.ensureBuffered(n);F(s)&&(s=await s);const a=this.currentPos;for(;this.currentPos-a<s;){const o=this.readU8();if(i==="aac"){if(o!==255)continue;this.skip(-1);const c=this.currentPos;let u=this.ensureBuffered(lr);if(F(u)&&(u=await u),u<lr)return;const l=this.readBytes(lr),d=oi(Ke.tempFromBytes(l));if(d){this.seekTo(c);let f=this.ensureBuffered(d.frameLength);return F(f)&&(f=await f),this.supplyPacket(f,Math.round(ss*Ne/e.info.sampleRate))}else this.seekTo(c+1)}else if(i==="mp3"){if(o!==255)continue;this.skip(-1);const c=this.currentPos;let u=this.ensureBuffered(vt);if(F(u)&&(u=await u),u<vt)return;const l=this.readBytes(vt),d=Z(l).getUint32(0),f=ws(d,null);if(f.header){this.seekTo(c);let h=this.ensureBuffered(f.header.totalSize);F(h)&&(h=await h);const p=f.header.audioSamplesInFrame*Ne/e.info.sampleRate;return this.supplyPacket(h,Math.round(p))}else this.seekTo(c+1)}else if(i==="ac3"){if(o!==11)continue;this.skip(-1);const c=this.currentPos;let u=this.ensureBuffered(5);if(F(u)&&(u=await u),u<5)return;const l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(c+1);continue}const d=l[4]>>6,f=l[4]&63;if(d===3||f>37){this.seekTo(c+1);continue}const h=eu[3*f+d];y(h!==void 0),this.seekTo(c),u=this.ensureBuffered(h),F(u)&&(u=await u);const p=Math.round(tu*Ne/e.info.sampleRate);return this.supplyPacket(u,p)}else if(i==="eac3"){if(o!==11)continue;this.skip(-1);const c=this.currentPos;let u=this.ensureBuffered(5);if(F(u)&&(u=await u),u<5)return;const l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(c+1);continue}const f=(((l[2]&7)<<8|l[3])+1)*2,p=l[4]>>6===3?3:l[4]>>4&3,m=Bo[p];this.seekTo(c),u=this.ensureBuffered(f),F(u)&&(u=await u);const b=m*256,w=Math.round(b*Ne/e.info.sampleRate);return this.supplyPacket(u,w)}else if(i==="dts"){if(o!==127&&o!==100)continue;this.skip(-1);const c=this.currentPos;let u=this.ensureBuffered(yi);if(F(u)&&(u=await u),u<yi)return;const l=this.readBytes(yi),d=zo(l);let f=d?null:Si(l);if(!d&&!f){this.seekTo(c+1);continue}if(f&&!f.asset){this.seekTo(c);const b=Math.min(f.frameSize,su);let w=this.ensureBuffered(b);F(w)&&(w=await w),f=Si(this.readBytes(w))??f}let h=d?d.frameSize:f.frameSize;if(d){let b=Math.ceil(d.frameSize/4)*4;for(;;){this.seekTo(c);const w=b+Qn;let S=this.ensureBuffered(w);if(F(S)&&(S=await S),S<w)break;this.seekTo(c+b);const A=Si(this.readBytes(Qn));if(!A)break;b+=A.frameSize,h=b}}const p=(d==null?void 0:d.sampleCount)??((t=f.asset)==null?void 0:t.sampleCount);if(p===void 0){this.seekTo(c+1);continue}this.seekTo(c),u=this.ensureBuffered(h),F(u)&&(u=await u);const m=Math.round(p*Ne/e.info.sampleRate);return this.supplyPacket(u,m)}else throw new Error("Unhandled.")}if(s<n)break}}}supplyPacket(e,t){const i=this.getCurrentPesPacket();let n;if(this.lastSuppliedPesPacket===i)y(this.nextPts!==null),n=this.nextPts;else{if(i.pts===null)throw new Error(pc);n=i.pts,as(this.elementaryStream,i)}this.lastSuppliedPesPacket=i,this.nextPts=n+t;const s=i.sectionStartPos,a=s+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e);let c=i.randomAccessIndicator;if(c===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")c=1;else if(this.elementaryStream.info.decoderConfig){const u=tn(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o)==="key";c=Number(u)}}this.suppliedPacket={pts:n,data:o,sequenceNumber:a,sectionStartPos:s,randomAccessIndicator:c},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}}class Cn{constructor(e,t){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=t,this.reorderSize=e.getReorderSize(),y(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);let i;for(t===-1||t===this.presentationOrderPackets.length-1?i=this.lastDuration:(i=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=i),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const n=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(n))break;this.presentationOrderPackets.shift()}return{packet:e,duration:i}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket?e=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(){const e=this.decodeOrderPackets[0];for(y(e);;){const 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 t=0;for(let n=1;n<this.reorderBuffer.length;n++)this.reorderBuffer[n].pts<this.reorderBuffer[t].pts&&(t=n);const i=this.reorderBuffer[t];this.presentationOrderPackets.push(i),this.reorderBuffer.splice(t,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}/*!
236
+ * Copyright (c) 2026-present, Vanilagy and contributors
237
+ *
238
+ * This Source Code Form is subject to the terms of the Mozilla Public
239
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
240
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
241
+ */const gc="application/vnd.apple.mpegurl",va="#EXT-X-STREAM-INF:",Ra="#EXT-X-I-FRAME-STREAM-INF:",Ba="#EXT-X-MEDIA:",Ni="#EXT-X-DEFINE:",os="#EXTINF:",Fa="#EXT-X-MAP:",Da="#EXT-X-KEY:",Ma="#EXT-X-MEDIA-SEQUENCE:",Oa="#EXT-X-BYTERANGE:",Na="#EXT-X-PROGRAM-DATE-TIME:",$d="#EXT-X-DISCONTINUITY",za="#EXT-X-DISCONTINUITY-SEQUENCE:",Ua="#EXT-X-TARGETDURATION:",Yd="#EXT-X-ENDLIST",Va="#EXT-X-PLAYLIST-TYPE:",Zd="#EXT-X-I-FRAMES-ONLY",Gt="com.apple.streaming.transportStreamTimestamp",bc=r=>r.length===0||r.startsWith("#")&&!r.startsWith("#EXT");class ur{constructor(e,t){this._attributes={};let i="",n="",s=!1,a=!1,o=!1;const c=()=>{if(!i)return;const u=i.trim().toLowerCase();Object.prototype.hasOwnProperty.call(this._attributes,u)&&j._warn(`Duplicate AttributeName "${u}"; using last value`);const l=o||n.startsWith("0x")||n.startsWith("0X");this._attributes[u]=l&&t?t.substitute(n):n,i="",n="",s=!1,o=!1};for(let u=0;u<e.length;u++){const l=e[u];l==='"'?(s&&!a&&n.length===0&&(o=!0),a=!a):l==="="&&!s&&!a?s=!0:l===","&&!a?c():s?n+=l:i+=l}if(a)throw new Error("Invalid M3U8 file; unterminated quoted-string AttributeValue.");c()}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){const t=this.get(e);if(t===null)return null;const i=Number(t);return Number.isFinite(i)?i:null}merge(e){Object.assign(this._attributes,e._attributes)}}const Jd=/^[A-Za-z0-9_-]+$/,ef=/\{\$([A-Za-z0-9_-]+)\}/g,tf=2**26;class wc{constructor(e,t){this.playlistPath=e,this.importedVariables=t,this.variables=new Map,this.totalSubstitutedLength=0}define(e){var o;const t=new ur(e,this),i=t.get("name"),n=t.get("import"),s=t.get("queryparam");if([i,n,s].filter(c=>c!==null).length!==1)throw new Error("Invalid #EXT-X-DEFINE tag; exactly one of NAME, IMPORT, or QUERYPARAM must be present.");if(i!==null){const c=t.get("value");if(c===null)throw new Error("Invalid #EXT-X-DEFINE tag; NAME requires VALUE.");this.set(i,c)}else if(n!==null){const c=(o=this.importedVariables)==null?void 0:o.get(n);if(c===void 0)throw new Error(`Invalid #EXT-X-DEFINE tag; cannot import undefined variable "${n}".`);this.set(n,c)}else if(s!==null){const c=yl(this.playlistPath,s);if(c===null)throw new Error(`Invalid #EXT-X-DEFINE tag; query parameter "${s}" is missing.`);this.set(s,c)}}substitute(e){return e.replaceAll(ef,(t,i)=>{const n=this.variables.get(i);if(n===void 0)throw new Error(`Invalid M3U8 file; variable "${i}" is referenced before being defined.`);if(this.totalSubstitutedLength+=n.length,this.totalSubstitutedLength>tf)throw new 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(!Jd.test(e))throw new Error(`Invalid #EXT-X-DEFINE tag; invalid variable name "${e}".`);if(this.variables.has(e))throw new Error(`Invalid #EXT-X-DEFINE tag; variable "${e}" is already defined.`);this.variables.set(e,t)}}/*!
242
+ * Copyright (c) 2026-present, Vanilagy and contributors
243
+ *
244
+ * This Source Code Form is subject to the terms of the Mozilla Public
245
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
246
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
247
+ */class rf{constructor(e,t,i){this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.learnedSegmentTimestampOffset=null,this.segmentMediaOffsets=new WeakMap,this.input=e,this.path=t,this.trackDeclarations=i}async getDurationFromMetadata(e){const 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,{});if(t??(t=await this.getFirstSegment({})),!t||t.unixEpochTimestamp===null)return null;const i=e-(t.timestamp+await this.getFirstSegmentTimestampOffset());return t.unixEpochTimestamp+i}async getTrackBackings(){return this.trackBackingsPromise??(this.trackBackingsPromise=(async()=>{const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if(t.type==="video"){const i=qr(e,n=>n.getType()==="video")+1;e.push(new La(this,t,i))}else if(t.type==="audio"){const i=qr(e,n=>n.getType()==="audio")+1;e.push(new Wa(this,t,i))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];const i=await this.getInputForSegment(this.firstSegment).getTracks();for(const n of i)if(n.type==="video"){const s=qr(e,a=>a.getType()==="video")+1;e.push(new La(this,{id:e.length+1,type:"video"},s))}else if(n.type==="audio"){const s=qr(e,a=>a.getType()==="audio")+1;e.push(new Wa(this,{id:e.length+1,type:"audio"},s))}}return e})())}getMediaOffset(e,t){let i=this.segmentMediaOffsets.get(e);return i||(i=(async()=>{const n=await this.getRawTimestampOffset(t);if(n===null)return e.timestamp;let s=n+await this.getMediaOffsetForDiscontinuity(e.discontinuityNumber);const a=this.getTimestampWrapPeriod();if(a<1/0){const o=await t.getTracks(),c=o.find(l=>l.type==="video")??o[0];y(c);const u=await c.getFirstTimestamp()+s;s+=a*Math.round((e.timestamp-u)/a)}return s})(),this.segmentMediaOffsets.set(e,i),i)}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class kc{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=null,this.segmentedInput=e,this.decl=t,this.number=i}hydrate(){return this.hydrationPromise??(this.hydrationPromise=(async()=>{var i;if((i=this.segmentedInput).firstSegment??(i.firstSegment=await this.segmentedInput.getFirstSegment({})),!this.segmentedInput.firstSegment)throw new 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(a=>a.type===this.decl.type&&a.number===this.number)??null,!t);)e=await this.segmentedInput.getNextSegment(e,{});if(!t)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=t,this.firstSegment=e})())}getId(){return this.decl.id}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(()=>{var e,t;return((t=(e=this.firstInputTrack._backing).getHasOnlyKeyPackets)==null?void 0:t.call(e))??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(),y(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,t,i){y(e.sequenceNumber>=0),y(this.segmentedInput.firstSegment);const n=await this.segmentedInput.getMediaOffset(t,i.input),s=t.timestamp-this.segmentedInput.firstSegment.timestamp,a=e.clone({timestamp:_i(e.timestamp+n,await i.getTimeResolution()),sequenceNumber:Math.floor(1e8*s)+e.sequenceNumber});return this.packetInfos.set(a,{segment:t,track:i,sourcePacket:e}),a}async getFirstPacket(e){await this.hydrate(),y(this.firstInputTrack),y(this.firstSegment);let t=this.firstInputTrack,i=this.firstSegment;for(;;){if(t){const a=await t._backing.getFirstPacket(e);if(a)return this.createAdjustedPacket(a,i,t)}if(i=await this.segmentedInput.getNextSegment(i,{skipLiveWait:e.skipLiveWait}),!i)break;t=(await this.segmentedInput.getInputForSegment(i).getTracks()).find(a=>a.type===this.firstInputTrack.type&&a.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,i){const n=this.packetInfos.get(e);if(!n)throw new Error("Packet was not created from this track.");const s=i?await n.track._backing.getNextKeyPacket(n.sourcePacket,t):await n.track._backing.getNextPacket(n.sourcePacket,t);if(s)return this.createAdjustedPacket(s,n.segment,n.track);let a=n.segment;for(;;){const o=await this.segmentedInput.getNextSegment(a,{skipLiveWait:t.skipLiveWait});if(!o)return null;const l=(await this.segmentedInput.getInputForSegment(o).getTracks()).find(f=>f.type===n.track.type&&f.number===n.track.number);if(!l){a=o;continue}let d=await l._backing.getFirstPacket(t);if(d&&i&&d.type!=="key"&&(d=await l._backing.getNextKeyPacket(d,t)),!d){a=o;continue}return this.createAdjustedPacket(d,o,l)}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,i){let n=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!n)return null;for(await this.hydrate();n;){const s=this.segmentedInput.getInputForSegment(n),o=(await s.getTracks()).find(h=>h.type===this.firstInputTrack.type&&h.number===this.firstInputTrack.number);if(!o){n=await this.segmentedInput.getPreviousSegment(n,{skipLiveWait:t.skipLiveWait});continue}const c=await this.segmentedInput.getMediaOffset(n,s),u=this.segmentedInput.learnedSegmentTimestampOffset===null?await o._backing.getFirstPacket({...t,metadataOnly:!0}):null;if(u){const h=u.timestamp+c;this.segmentedInput.learnedSegmentTimestampOffset=h-n.timestamp;const p=e-h;if(p<-n.duration||p>=2*n.duration){const m=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(m!==n){n=m;continue}}}const l=e-c,d=i?await o._backing.getKeyPacket(l,t):await o._backing.getPacket(l,t);if(!d){n=await this.segmentedInput.getPreviousSegment(n,{skipLiveWait:t.skipLiveWait});continue}const f=i?await o._backing.getPacket(l,{...t,metadataOnly:!0}):d;if(y(f),l>=f.timestamp+f.duration){const h=await this.segmentedInput.getNextSegment(n,{skipLiveWait:t.skipLiveWait});if(h){const p=this.segmentedInput.getInputForSegment(h),b=(await p.getTracks()).find(S=>S.type===this.firstInputTrack.type&&S.number===this.firstInputTrack.number);let w=b?await b._backing.getFirstPacket({...t,metadataOnly:!0}):null;if(w&&i&&w.type!=="key"&&(w=await b._backing.getNextKeyPacket(w,{...t,metadataOnly:!0})),w){const S=await this.segmentedInput.getMediaOffset(h,p);if(w.timestamp+S<=e){n=h;continue}}}}return this.createAdjustedPacket(d,n,o)}return null}}class La extends kc{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())}}class Wa extends kc{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())}}/*!
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
+ */ms();const qa=typeof Ws<"u"?Ws:void 0,yc=0,Sc=1/0;let Dt=null;typeof FinalizationRegistry<"u"&&(Dt=new FinalizationRegistry(r=>{r()}));class Xe extends bs{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 Ce;return this._sizePromise??(this._sizePromise=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,yc,Sc),e=this._getFileSize(),y(e!==void 0)),e})())}async getSize(){if(this._disposed)throw new Ce;const e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new lf(this,e,t)}_dispatchRead(e,t){var i;(i=this.onread)==null||i.call(this,e,t),this._emit("read",{start:e,end:t})}ref(){return new Rs(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}}class Rs{constructor(e){var t;if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),(t=e._refFinalizationRegistry)==null||t.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){var t;if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const e=this.source;y(e._refCount>0),e._decrementRefCount(),(t=e._refFinalizationRegistry)==null||t.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class jt extends Xe{constructor(e,t){if(typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){const t=this.requestHandler(e),i=n=>{var a;if(!(n instanceof Xe||n instanceof Rs))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const s=n instanceof Xe?n.ref():n;return(a=s.source)._usedForHls||(a._usedForHls=this._usedForHls),s};return F(t)?t.then(i):i(t)}}const Ha=(r,e)=>r.path===e.path;class nf extends jt{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,i,n){if(!this._root){if(!this._rootRequest){const s=this._resolveRequest({path:this.rootPath,isRoot:!0}),a=o=>{const c=o instanceof Xe?o.ref():o;return this._root=c,this._rootRequest=null,c};F(s)?this._rootRequest=s.then(a):(a(s),y(this._root))}if(this._rootRequest)return this._rootRequest.then(s=>s.source._read(e,t,i,n))}return this._root.source._read(e,t,i,n)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free()).catch(()=>{})}}class om extends Xe{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw new TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super(),this._onreadCalled=!1,this._bytes=ke(e),this._view=Z(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||(this._dispatchRead(0,this._bytes.byteLength),this._onreadCalled=!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}}const $t=typeof FinalizationRegistry<"u"?new FinalizationRegistry(r=>{r.cancel().catch(()=>{})}):null;class cm extends Xe{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!Ht(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.useStreamReader!==void 0&&typeof t.useStreamReader!="boolean")throw new TypeError("options.useStreamReader, when provided, must be a boolean.");if(t.handleUnhandledError!==void 0&&typeof t.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new Fs({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:i=>{const n=this._readers.get(i);n&&(this._readers.delete(i),$t==null||$t.unregister(i),n.cancel().catch(()=>{}))},prefetchProfile:Bs.fileSystem,handleUnhandledError:t.handleUnhandledError}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,n){return this._orchestrator.read(e,t,i,n)}async _runWorker(e){y(e.strictTarget);let t=this._readers.get(e);for(t===void 0&&("stream"in this._blob&&!_t()&&this._options.useStreamReader!==!1?(t=this._blob.slice(e.currentPos).stream().getReader(),$t==null||$t.register(e,t,e)):t=null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){const{done:i,value:n}=await t.read();if(i)throw this._orchestrator.onWorkerFinished(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+n.length),this._orchestrator.supplyWorkerData(e,n)}else{const i=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+i.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(i))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await(t==null?void 0:t.cancel().catch(()=>{}))}_dispose(){this._orchestrator.dispose()}}const sf=.5*2**20,af=((r,e,t)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))&&typeof window<"u"){let n=null;try{typeof window<"u"&&typeof window.location<"u"&&(n=new URL(t instanceof Request?t.url:t,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&n!==null&&n!==window.location.origin)return j._warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(r-2),16)}),ja=new Set;class Ac extends jt{constructor(e,t={}){var a;if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.requestInit!==void 0&&(!t.requestInit||typeof t.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(t.getRetryDelay!==void 0&&typeof t.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(t.maxCacheSize!==void 0&&(!Ht(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.parallelism!==void 0&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(t.fetchFn!==void 0&&typeof t.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");if(t.handleUnhandledError!==void 0&&typeof t.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");const i=e instanceof Request?e.url:e instanceof URL?e.href:e;super(i,o=>new Ac(o.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._sequentialBacking=null,this._abortControllers=new Map,this._sequentialAbortController=null,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??af,this._requestInit={...t.requestInit};let n=null;if((a=t.requestInit)!=null&&a.headers){const o={...Wn(t.requestInit.headers)},c=Object.keys(o).find(u=>u.toLowerCase()==="range");c!==void 0&&(n=o[c],delete o[c],this._requestInit.headers=o)}if(e instanceof Request){const o=e.headers.get("Range");if(o!==null){n??(n=o);const c=new Request(e);c.headers.delete("Range"),this._url=c}}if(n!==null){const o=cf(n);o&&(this._offset=o.offset,this._length=o.length)}const s=2;this._orchestrator=new Fs({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:t.parallelism??s,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:o=>this._abortControllers.delete(o),prefetchProfile:Bs.network,handleUnhandledError:t.handleUnhandledError})}_getFileSize(){if(!this._fileSizeDetermined)return this._length!==null?this._length:void 0;const e=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return e===null?this._length!==null?this._length:null:pe(e-this._offset,0,this._length??1/0)}_read(e,t,i,n){if(this._length!==null&&t>this._length)return null;const s=this._offset,a=this._sequentialBacking?this._sequentialBacking._read(s+e,s+t):this._orchestrator.read(s+e,s+t,Math.max(s+i,s),s+Math.min(n,this._length??1/0)),o=c=>c?(c.offset-=this._offset,c):null;return F(a)?a.then(o):o(a)}async _runWorker(e){let t=0;for(;;){if(e.aborted){this._orchestrator.signalWorkerStoppedRunning(e);return}const i=new AbortController;this._abortControllers.set(e,i);const n=await Qs(this._options.fetchFn??fetch,this._url,Xs(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:i.signal}),this._getRetryDelay,()=>i.signal.aborted);if(!n.ok)throw new Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);n.redirected&&(this.rootPath=n.url);e:if(this._orchestrator.fileSize===null&&!n.headers.has("Content-Encoding")&&(n.status===206||n.type==="basic")){const o=n.headers.get("Content-Range");if(o){const u=/\/(\d+)/.exec(o);if(u){this._orchestrator.supplyFileSize(Number(u[1]));break e}}const c=n.headers.get("Content-Length");if(c){const u=n.status===206?e.currentPos:0;this._orchestrator.supplyFileSize(u+Number(c))}}if(this._fileSizeDetermined=!0,!n.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(n.status!==206){if(this._sequentialBacking){n.body.cancel().catch(()=>{});return}if(!this._usedForHls){const o=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<"u"?window.location.href:void 0);o.origin!=="null"&&!(o.pathname.endsWith(".m3u8")||o.pathname.endsWith(".m3u"))&&(ja.has(o.origin)||(j._warn(`HTTP server (origin ${o.origin}) did not respond to a range request with 206 Partial Content, meaning the resource will now be streamed sequentially, with old data being evicted from the cache. Reads into evicted regions will throw. To enable efficient media file streaming across a network, please make sure your server supports range requests. Alternatively, set maxCacheSize to Infinity in the UrlSource options to keep the entire resource in memory.`),ja.add(o.origin)))}this._abortControllers.delete(e),this._transitionToSequentialMode(n.body,i);return}const s=n.body.getReader(),a=e.currentPos;for(;;){if(e.currentPos>=e.targetPos||e.aborted){i.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let o;try{o=await s.read()}catch(l){if(i.signal.aborted)throw l;const d=this._getRetryDelay(1,l,this._url);if(d!==null){j._error("Error while reading response stream. Attempting to resume.",l),await ar(1e3*d);break}else throw l}if(e.aborted)continue;const{done:c,value:u}=o;if(c){if(e.currentPos>=e.targetPos){this._orchestrator.onWorkerFinished(e);return}if(e.strictTarget){if(e.currentPos>a){t=0;break}t++;const l=new Error("Range response ended without delivering any data."),d=this._getRetryDelay(t,l,this._url);if(d===null)throw l;j._error("Retrying range request that ended without delivering any data."),await ar(1e3*d);break}else{this._orchestrator.onWorkerFinished(e);return}}this._dispatchRead(e.currentPos,e.currentPos+u.length),this._orchestrator.supplyWorkerData(e,u)}}}_transitionToSequentialMode(e,t){this._sequentialAbortController=t;let i=e.getReader(),n=0,s=0;const a=new ReadableStream({pull:async u=>{for(;;){let l;try{l=await i.read()}catch(f){if(this._disposed)throw f;const h=this._getRetryDelay(1,f,this._url);if(h===null)throw f;j._error("Error while reading response stream. Attempting to resume.",f),await ar(1e3*h),this._sequentialAbortController=new AbortController,this._disposed&&this._sequentialAbortController.abort();const p=await Qs(this._options.fetchFn??fetch,this._url,Xs(this._requestInit,{headers:{Range:`bytes=${n}-`},signal:this._sequentialAbortController.signal}),this._getRetryDelay,()=>this._disposed);if(!p.ok)throw new Error(`Error fetching ${String(this._url)}: ${p.status} ${p.statusText}`);if(!p.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");i=p.body.getReader(),s=p.status===206?0:n;continue}if(l.done){u.close();return}let d=l.value;if(s>0){const f=Math.min(s,d.length);s-=f,d=d.subarray(f)}if(d.length!==0){n+=d.length,u.enqueue(d);return}}},cancel:()=>i.cancel().catch(()=>{})}),o=new Pc(a,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});o._endIndex=this._orchestrator.fileSize,o._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. Because the HTTP server did not honor the range request, data can only be read sequentially, with old data being evicted from the cache. To fix this issue, either ensure your server responds to range requests with 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter will store the entire file in the cache if needed, no matter how large.",o.on("read",({start:u,end:l})=>this._dispatchRead(u,l)),this._sequentialBacking=o;const c=new Set;for(const u of this._orchestrator.workers){for(const l of u.pendingSlices)c.add(l);u.aborted=!0,u.pendingSlices.length=0}for(const u of this._orchestrator.queuedReads)for(const l of u.pendingSlices)c.add(l);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const[,u]of this._abortControllers)u.abort();this._abortControllers.clear();for(const u of c){const l=o._read(u.start,u.start+u.bytes.length);F(l)?l.then(d=>{d?(y(d.offset===u.start),u.resolve(d.bytes)):u.resolve(null)},d=>u.reject(d)):(y(l===null),u.resolve(null))}}_dispose(){var e;this._orchestrator.dispose();for(const[,t]of this._abortControllers)t.abort();this._abortControllers.clear(),(e=this._sequentialAbortController)==null||e.abort(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const of=/^bytes=(\d+)-(\d*)$/,cf=r=>{const e=of.exec(r.trim());if(!e)return null;const t=Number(e[1]),i=e[2]===""?null:Number(e[2]);return i!==null&&i<t?null:{offset:t,length:i!==null?i-t+1:null}};class Tc extends jt{constructor(e,t={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!Ht(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(!qa.fs)throw new Error("FilePathSource is only available in server-side environments (Node.js, Bun, Deno).");super(e,i=>new Tc(i.path,t)),this._fileHandle=null,this._customSource=new xc({getSize:async()=>{const i=await qa.fs.open(e,"r");return this._fileHandle=i,Dt==null||Dt.register(this,()=>{i.close()},this),(await i.stat()).size},read:async(i,n)=>{y(this._fileHandle);const s=new Uint8Array(n-i);return await this._fileHandle.read(s,0,n-i,i),s},maxCacheSize:t.maxCacheSize,prefetchProfile:"fileSystem",handleUnhandledError:t.handleUnhandledError})}_read(e,t,i,n){return this._customSource._read(e,t,i,n)}_getFileSize(){return this._customSource._getFileSize()}_dispose(){this._customSource._dispose(),this._fileHandle&&(this._fileHandle.close(),this._fileHandle=null,Dt==null||Dt.unregister(this))}}class xc extends Xe{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(typeof e.getSize!="function")throw new TypeError("options.getSize must be a function.");if(typeof e.read!="function")throw new TypeError("options.read must be a function.");if(e.dispose!==void 0&&typeof e.dispose!="function")throw new TypeError("options.dispose, when provided, must be a function.");if(e.handleUnhandledError!==void 0&&typeof e.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");if(e.maxCacheSize!==void 0&&(!Ht(e.maxCacheSize)||e.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(e.prefetchProfile&&!["none","fileSystem","network"].includes(e.prefetchProfile))throw new TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super(),this._readers=new Set,this._options=e,this._orchestrator=new Fs({maxCacheSize:e.maxCacheSize??8*2**20,maxWorkerCount:2,prefetchProfile:Bs[e.prefetchProfile??"none"],runWorker:this._runWorker.bind(this),handleUnhandledError:e.handleUnhandledError})}_getFileSize(){return this._orchestrator.fileSize??void 0}_read(e,t,i,n){if(this._orchestrator.fileSize!==null)return this._orchestrator.read(e,t,i,n);const s=this._options.getSize();if(F(s))return s.then(a=>{if(!Number.isInteger(a)||a<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");if(this._disposed)throw new Ce;return this._orchestrator.fileSize=a,t>a?null:this._orchestrator.read(e,t,i,n)});if(!Number.isInteger(s)||s<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=s,t>s?null:this._orchestrator.read(e,t,i,n)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){const t=e.currentPos,i=e.targetPos;let n=this._options.read(e.currentPos,i);if(F(n)&&(n=await n),e.aborted){n instanceof ReadableStream&&await n.cancel().catch(()=>{});break}if(n instanceof Uint8Array){if(n=ke(n),n.length!==i-e.currentPos)throw new Error(`options.read returned a Uint8Array with unexpected length: Requested ${i-e.currentPos} bytes, but got ${n.length}.`);this._dispatchRead(e.currentPos,e.currentPos+n.length),this._orchestrator.supplyWorkerData(e,n)}else if(n instanceof ReadableStream){const s=n.getReader();this._readers.add(s);try{for(;e.currentPos<i&&!e.aborted;){const{done:a,value:o}=await s.read();if(a){if(e.currentPos<i)throw new Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${i-t} bytes, but got ${e.currentPos-t}`);break}if(!(o instanceof Uint8Array))throw new TypeError("ReadableStream returned by options.read must yield Uint8Array chunks.");if(e.aborted)break;const c=ke(o);this._dispatchRead(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}}finally{this._readers.delete(s),s.releaseLock()}}else throw new TypeError("options.read must return or resolve to a Uint8Array or a ReadableStream.")}this._orchestrator.signalWorkerStoppedRunning(e)}_dispose(){var e,t;this._orchestrator.dispose();for(const i of this._readers)i.cancel().catch(()=>{});this._readers.clear(),(t=(e=this._options).dispose)==null||t.call(e)}}const lm=xc;class Pc extends Xe{constructor(e,t={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.handleUnhandledError!==void 0&&typeof t.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");if(t.maxCacheSize!==void 0&&(!Ht(t.maxCacheSize)||t.maxCacheSize<0))throw new 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);const i=te(this._cache,e,l=>l.start),n=i!==-1?this._cache[i]:null;if(n&&n.start<=e&&t<=n.end)return{bytes:n.bytes,view:n.view,offset:n.start};let s=e;const a=[];if(i!==-1)for(let l=i;l<this._cache.length;l++){const d=this._cache[l];if(d.start>=t)break;const f=Math.max(e,d.start);f>s&&this._throwDueToCacheMiss();const h=Math.min(t,d.end);f<h&&(a.push({start:f,bytes:d.bytes.subarray(f-d.start,h-d.start)}),s=h)}if(s===t)return Ka(e,t,a);this._currentIndex>s&&this._throwDueToCacheMiss();const{promise:o,resolve:c,reject:u}=Se();return this._pendingSlices.push({start:e,end:t,parts:a,resolve:c,reject:u}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(l=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(d=>d.reject(l)),this._pendingSlices.length=0;else if(this._handleUnhandledError)this._handleUnhandledError(l);else throw l})),o}_throwDueToCacheMiss(){throw new Error(this._cacheMissErrorMessage)}async _pull(){for(this._reader??(this._reader=this._stream.getReader());this._currentIndex<this._targetIndex&&!this._disposed;){const{done:e,value:t}=await this._reader.read();if(e){for(const s of this._pendingSlices)s.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}const i=this._currentIndex,n=this._currentIndex+t.byteLength;this._dispatchRead(i,n);for(let s=0;s<this._pendingSlices.length;s++){const a=this._pendingSlices[s],o=Math.max(i,a.start),c=Math.min(n,a.end);o<c&&(a.parts.push({start:o,bytes:t.subarray(o-i,c-i)}),c===a.end&&(a.resolve(Ka(a.start,a.end,a.parts)),this._pendingSlices.splice(s,1),s--))}for(this._cache.push({start:i,end:n,bytes:t,view:Z(t),age:0});this._cache.length>0;){const s=this._cache[0];if(this._maxRequestedIndex-s.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){var e;for(const t of this._pendingSlices)t.reject(new Ce);this._pendingSlices.length=0,this._cache.length=0,(e=this._reader)==null||e.cancel().catch(()=>{})}}const Ka=(r,e,t)=>{const i=new Uint8Array(e-r);for(const n of t)i.set(n.bytes,n.start-r);return{bytes:i,view:Z(i),offset:r}},Bs={none:(r,e)=>({start:r,end:e}),fileSystem:(r,e)=>(r=Math.floor((r-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:r,end:e}),network:(r,e,t)=>{r=Math.max(0,Math.floor((r-65536)/65536)*65536);for(const n of t){const a=Math.max((n.startPos+n.targetPos)/2,n.targetPos-8388608);if(qn(r,e,a,n.targetPos)){const o=n.targetPos-n.startPos,c=Math.ceil((o+1)/8388608)*8388608,u=2**Math.ceil(Math.log2(o+1)),l=Math.min(u,c);e=Math.max(e,n.startPos+l)}}return e=Math.max(e,r+sf),{start:r,end:e}}};class Fs{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,t,i,n){y(!this.disposed);const s=this.options.prefetchProfile(e,t,this.workers),a=Math.max(s.start,i),o=Math.min(s.end,this.fileSize??1/0,n);y(a<=e&&t<=o);let c=null;const u=te(this.cache,e,k=>k.start),l=u!==-1?this.cache[u]:null;l&&l.start<=e&&t<=l.end&&(l.age=this.nextAge++,c={bytes:l.bytes,view:l.view,offset:l.start});const d=te(this.cache,a,k=>k.start),f=c?null:new Uint8Array(t-e);let h=0,p=a;const m=[];if(d!==-1){for(let k=d;k<this.cache.length;k++){const x=this.cache[k];if(x.start>=o)break;if(x.end<=a)continue;const P=Math.max(a,x.start),I=Math.min(o,x.end);if(y(P<=I),p<P&&m.push({start:p,end:P}),p=I,f){const E=Math.max(e,x.start),C=Math.min(t,x.end);if(E<C){const _=E-e;f.set(x.bytes.subarray(E-x.start,C-x.start),_),_===h&&(h=C-e)}}x.age=this.nextAge++}p<o&&m.push({start:p,end:o})}else m.push({start:a,end:o});if(f&&h>=f.length&&(c={bytes:f,view:Z(f),offset:e}),m.length===0)return y(c),c;const{promise:b,resolve:w,reject:S}=Se(),A=[];for(const k of m){const x=Math.max(e,k.start),P=Math.min(t,k.end);x===k.start&&P===k.end?A.push(k):x<P&&A.push({start:x,end:P})}const T=f&&{start:e,bytes:f,holes:A,resolve:w,reject:S};e:for(const k of m){for(const I of this.workers)if(this.checkHoleAgainstWorker(I,k,T?[T]:[])){this.checkQueuedReadsAgainstWorker(I);continue e}const x=k.end<o||this.fileSize!==null,P=this.createWorker(k.start,k.end,x);if(P)T&&(P.pendingSlices=[T]),this.runWorker(P);else{let I=te(this.queuedReads,k.start,C=>C.hole.start),E=I!==-1?this.queuedReads[I]:null;for(E&&k.start<=E.hole.end?(E.hole.end=Math.max(E.hole.end,k.end),E.strictTarget&&(E.strictTarget=x),T&&E.pendingSlices.push(T)):(I++,E={hole:{start:k.start,end:k.end},strictTarget:x,pendingSlices:T?[T]:[],age:this.nextAge++},this.queuedReads.splice(I,0,E));I+1<this.queuedReads.length;){const C=this.queuedReads[I+1];if(C.hole.start>E.hole.end)break;E.hole.end=Math.max(E.hole.end,C.hole.end),E.pendingSlices.push(...C.pendingSlices),E.strictTarget&&(E.strictTarget=C.strictTarget),E.age=Math.min(E.age,C.age),this.queuedReads.splice(I+1,1)}}}return c?b.catch(k=>{if(!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(k);else throw k}):(y(f),c=b.then(k=>k&&{bytes:k,view:Z(k),offset:e})),c}checkHoleAgainstWorker(e,t,i){if(qn(t.start-131072,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let s=0;s<i.length;s++){const a=i[s];e.pendingSlices.includes(a)||e.pendingSlices.push(a)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let t=!1;for(let i=0;i<this.queuedReads.length;i++){const n=this.queuedReads[i];if(this.checkHoleAgainstWorker(e,n.hole,n.pendingSlices))this.queuedReads.splice(i,1),i--,t=!0;else if(t)break}}createWorker(e,t,i){var s,a;if(this.workers.length>=this.options.maxWorkerCount){let o=null,c=null;for(let u=0;u<this.workers.length;u++){const l=this.workers[u];!l.running&&l.pendingSlices.length===0&&(!o||l.age<o.age)&&(c=u,o=l)}if(o)y(c!==null),y(o.pendingSlices.length===0),this.workers.splice(c,1),(a=(s=this.options).onIdleWorkerRemoved)==null||a.call(s,o);else return null}const n={startPos:e,currentPos:e,targetPos:t,strictTarget:i,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(n),n}runWorker(e){y(!e.running),y(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(i=>i.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(t);else throw t}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let t=0;for(let s=1;s<this.queuedReads.length;s++)this.queuedReads[s].age<this.queuedReads[t].age&&(t=s);const i=this.queuedReads[t],n=this.createWorker(i.hole.start,i.hole.end,i.strictTarget);if(!n)return;this.queuedReads.splice(t,1),n.pendingSlices=i.pendingSlices,this.runWorker(n)}})}supplyWorkerData(e,t){var s,a;y(!e.aborted);const i=e.currentPos,n=i+t.length;this.insertIntoCache({start:i,end:n,bytes:t,view:Z(t),age:this.nextAge++}),e.currentPos+=t.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let o=0;o<e.pendingSlices.length;o++){const c=e.pendingSlices[o],u=Math.max(i,c.start),l=Math.min(n,c.start+c.bytes.length);u<l&&c.bytes.set(t.subarray(u-i,l-i),u-c.start);for(let d=0;d<c.holes.length;d++){const f=c.holes[d];i<=f.start&&n>f.start&&(f.start=n),f.end<=f.start&&(c.holes.splice(d,1),d--)}c.holes.length===0&&(c.resolve(c.bytes),e.pendingSlices.splice(o,1),o--)}for(let o=0;o<this.workers.length;o++){const c=this.workers[o];e===c||c.running||qn(i,n,c.currentPos,c.targetPos)&&(this.workers.splice(o,1),(a=(s=this.options).onIdleWorkerRemoved)==null||a.call(s,c),o--)}}supplyFileSize(e){y(this.fileSize===null),this.fileSize=e;for(const t of this.workers){t.targetPos=Math.min(t.targetPos,e),t.strictTarget=!0;for(let i=0;i<t.pendingSlices.length;i++){const n=t.pendingSlices[i];for(const s of n.holes)if(s.end>e){n.resolve(null),t.pendingSlices.splice(i,1),i--;break}}}for(let t=0;t<this.queuedReads.length;t++){const i=this.queuedReads[t];if(i.hole.start>=e){for(const n of i.pendingSlices)n.resolve(null);this.queuedReads.splice(t,1),t--}else if(i.hole.end>e){i.hole.end=e,i.strictTarget=!0;for(let n=0;n<i.pendingSlices.length;n++){const s=i.pendingSlices[n];s.start>=e&&(s.resolve(null),i.pendingSlices.splice(n,1),n--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.aborted||(e.pendingSlices.length=0)}onWorkerFinished(e){var i,n;const t=this.workers.indexOf(e);y(t!==-1),e.running=!1,this.workers.splice(t,1),(n=(i=this.options).onIdleWorkerRemoved)==null||n.call(i,e),this.fileSize===null&&this.supplyFileSize(e.currentPos);for(const s of e.pendingSlices)s.resolve(null)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=te(this.cache,e.start,i=>i.start)+1;if(t>0){const i=this.cache[t-1];if(i.end>=e.end)return;if(i.end>e.start){const n=new Uint8Array(e.end-i.start);n.set(i.bytes,0),n.set(e.bytes,e.start-i.start),this.currentCacheSize+=e.end-i.end,i.bytes=n,i.view=Z(n),i.end=e.end,t--,e=i}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let i=t+1;i<this.cache.length;i++){const n=this.cache[i];if(e.end<=n.start)break;if(e.end>=n.end){this.cache.splice(i,1),this.currentCacheSize-=n.bytes.length,i--;continue}const s=new Uint8Array(n.end-e.start);s.set(e.bytes,0),s.set(n.bytes,n.start-e.start),this.currentCacheSize-=e.end-n.start,e.bytes=s,e.view=Z(s),e.end=n.end,this.cache.splice(i,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let i=0,n=this.cache[0];for(let s=1;s<this.cache.length;s++){const a=this.cache[s];a.age<n.age&&(i=s,n=a)}if(this.currentCacheSize-n.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(i,1),this.currentCacheSize-=n.bytes.length}}dispose(){var e,t;for(const i of this.workers){for(const n of i.pendingSlices)n.reject(new Ce);i.pendingSlices.length=0,i.aborted=!0,i.running||(t=(e=this.options).onIdleWorkerRemoved)==null||t.call(e,i)}for(const i of this.queuedReads)for(const n of i.pendingSlices)n.reject(new Ce);this.workers.length=0,this.cache.length=0,this.queuedReads.length=0,this.disposed=!0}}class lf extends Xe{constructor(e,t,i){if(super(),this._ref=null,e._disposed)throw new Error("Cannot create a slice of a disposed source.");this._baseSource=e,this._offset=t,this._length=i??null}_getFileSize(){const e=this._baseSource._getFileSize();return e===void 0?this._length!==null?this._length:void 0:e===null?this._length!==null?this._length:null:pe(e-this._offset,0,this._length??1/0)}_read(e,t,i,n){if(this._length!==null&&t>this._length)return null;const s=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+n),a=o=>o?(o.offset-=this._offset,o):null;return F(s)?s.then(a):a(s)}_dispose(){var e;(e=this._ref)==null||e.free()}ref(){return this._ref??(this._ref=this._baseSource.ref()),super.ref()}}/*!
254
+ * Copyright (c) 2026-present, Vanilagy and contributors
255
+ *
256
+ * This Source Code Form is subject to the terms of the Mozilla Public
257
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
258
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
259
+ */var Xa=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,n;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],t&&(n=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");n&&(i=function(){try{n.call(this)}catch(s){return Promise.reject(s)}}),r.stack.push({value:e,dispose:i,async:t})}else t&&r.stack.push({async:!0});return e},Qa=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var i,n=0;function s(){for(;i=e.stack.pop();)try{if(!i.async&&n===1)return n=0,e.stack.push(i),Promise.resolve().then(s);if(i.dispose){var a=i.dispose.call(i.value);if(i.async)return n|=2,Promise.resolve(a).then(s,function(o){return t(o),s()})}else n|=1}catch(o){t(o)}if(n===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=r,i.suppressed=e,i});const uf=/^0[xX][0-9a-fA-F]+$/,df=/^data:.*;base64,/i,Ga=1e9;class $a extends rf{constructor(e,t,i,n){super(e.input,t,i),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=n}runUpdateSegments(){return this.currentUpdateSegmentsPromise??(this.currentUpdateSegmentsPromise=(async()=>{try{const e=this.getRemainingWaitTimeMs();e>0&&await ar(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})())}getRemainingWaitTimeMs(){const e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}async updateSegments(){var A;let e=this.nextLines;if(this.nextLines=null,!e){const T={stack:[],error:void 0,hasError:!1};try{const k=Xa(T,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),x=new xi(k.source);let P=x.requestSliceRange(0,0,64);if(F(P)&&(P=await P),P&&!_e.decode(X(P,P.length)).trimStart().startsWith("#EXTM3U"))throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");const I=await x.requestEntireFile();y(I),e=Lc(I,I.length,{ignore:bc}),k.source instanceof jt&&(this.rootPath=k.source.rootPath)}catch(k){T.error=k,T.hasError=!0}finally{Qa(T)}}const t=((A=this.input._formatOptions.hls)==null?void 0:A.offsetTimestampsByDateTime)!==!1,i=new wc(this.rootPath,this.demuxer.hasMasterPlaylist?this.demuxer.masterPlaylistVariables:null);let n=!1,s=0,a=null,o=null,c=null,u=0,l=0,d=null,f=null,h=null,p=null,m=null,b=fe(this.segments)??null;const w=T=>{const k=T.indexOf("@"),x=Number(k===-1?T:T.slice(0,k));if(!Number.isInteger(x)||x<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${T}'.`);let P=null;if(k!==-1&&(P=Number(T.slice(k+1)),!Number.isInteger(P)||P<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${T}'.`);return{length:x,offset:P}},S=T=>{u=T,b&&(y(b.sequenceNumber!==null),b.sequenceNumber<T&&(s=b.timestamp+b.duration,d=b.firstSegment,f=b.initSegment,m=b.lastProgramDateTimeSeconds,a=b.unixEpochTimestamp!==null?b.unixEpochTimestamp+b.duration:null,b=null))};for(let T=0;T<e.length;T++){const k=e[T];if(!n){if(k!=="#EXTM3U")throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");n=!0;continue}if(!k.startsWith("#")){if(!b){if(o===null)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let x=c;if(x&&x.method==="AES-128"&&!x.iv){const C=new Uint8Array(it),_=Z(C);_.setUint32(8,Math.floor(u/2**32)),_.setUint32(12,u),x={...x,iv:C}}const I={path:xt(this.rootPath,i.substitute(k)),offset:(p==null?void 0:p.offset)??0,length:(p==null?void 0:p.length)??null},E={index:this.segments.length,timestamp:s,unixEpochTimestamp:a,discontinuityNumber:l,firstSegment:d,sequenceNumber:u,location:I,duration:o,encryption:x,initSegment:f,lastProgramDateTimeSeconds:m};d??(d=E),s+=o,a!==null&&(a+=o),this.segments.push(E)}o=null,p===null?h=null:p=null,S(u+1)}if(k.startsWith(os)){if(b)continue;const x=k.slice(os.length),P=x.indexOf(","),I=P===-1?x:x.slice(0,P),E=Number(I);if(!Number.isFinite(E)||E<0||E>Ga)throw new Error(`Invalid #EXTINF tag duration '${I}'.`);o=E}else if(k.startsWith(Ni))i.define(k.slice(Ni.length));else if(k.startsWith(Fa)){const x=new ur(k.slice(Fa.length),i),P=x.get("uri");if(!P)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const I=x.get("byterange");let E=null;if(I!==null&&(E=w(I)),E&&E.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!b){const _={path:xt(this.rootPath,P),offset:(E==null?void 0:E.offset)??0,length:(E==null?void 0:E.length)??null};if((c==null?void 0:c.method)==="AES-128"&&!c.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");f={index:-1,timestamp:s,unixEpochTimestamp:a,discontinuityNumber:l,firstSegment:null,sequenceNumber:null,location:_,duration:0,encryption:c,initSegment:null,lastProgramDateTimeSeconds:m}}o=null,p===null?h=null:p=null}else if(k.startsWith(Da)){const x=new ur(k.slice(Da.length),i),P=x.get("method");if(P==="NONE")c=null;else if(P==="AES-128"){const I=x.get("uri");if(!I)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let E=null;const C=x.get("iv");if(C){if(!uf.test(C))throw new Error(`Unsupported IV format '${C}'.`);let D=C.slice(2);D=D.padStart(2*it,"0"),D=D.slice(-2*it),E=new Uint8Array(it);for(let q=0;q<it;q++){const M=2*q;E[q]=parseInt(D.slice(M,M+2),16)}}const _=x.get("keyformat")??"identity";if(_!=="identity")throw new 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:xt(this.rootPath,I),iv:E,keyFormat:_}}else if(P==="SAMPLE-AES"||P==="SAMPLE-AES-CTR"){const I=x.get("uri");if(!I)throw new Error(`Invalid #EXT-X-KEY: ${P} requires a URI attribute.`);if((x.get("keyformat")??"identity")==="identity")throw new 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 C=null;if(df.test(I)){const _=I.indexOf(","),D=vi(I.slice(_+1));if(D.length>=8&&D[4]===112&&D[5]===115&&D[6]===115&&D[7]===104){const q=Z(D).getUint32(0);C=Qo(D.subarray(8,Math.min(q,D.length)))}}c={method:P,psshBox:C}}else throw new Error(`Unsupported encryption method '${P}'. If you think this method should be supported, please raise an issue.`)}else if(k.startsWith(Ma)){const x=k.slice(Ma.length),P=Number(x);if(!Number.isSafeInteger(P)||P<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${x}'.`);S(P)}else if(k.startsWith(Oa)){const x=w(k.slice(Oa.length));if(x.offset===null){if(h===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");x.offset=h}p=x,h=x.offset+x.length}else if(k.startsWith(Na)){if(b)continue;const x=k.slice(Na.length),P=Date.parse(x);if(!Number.isFinite(P))continue;const I=P/1e3;if(m===I)continue;if(m===null&&this.segments.length>0){const E=fe(this.segments),C=E.timestamp+E.duration,_=I-C;for(const D of this.segments)D.unixEpochTimestamp=D.timestamp+_,t&&(D.timestamp=D.unixEpochTimestamp)}m=I,a=I,t&&(s=I)}else if(k===$d)d=null,l++;else if(k.startsWith(za)){const x=k.slice(za.length),P=Number(x);if(!Number.isSafeInteger(P)||P<0)throw new Error(`Invalid EXT-X-DISCONTINUITY-SEQUENCE value '${x}'.`);l=P}else if(k.startsWith(Ua)){const x=k.slice(Ua.length),P=Number(x);if(!Number.isFinite(P)||P<0||P>Ga)throw new Error(`Invalid EXT-X-TARGETDURATION value '${x}'.`);this.refreshInterval=pe(P,.5,3600)}else if(k===Yd){this.streamHasEnded=!0;break}else if(k.startsWith(Va)){const x=k.slice(Va.length).toLowerCase();x==="vod"&&(this.streamHasEnded=!0),(x==="vod"||x==="event")&&(this.neverRemovesSegments=!0)}}if(!n)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){this.segments.length===0&&await this.runUpdateSegments();const i=e-(this.learnedSegmentTimestampOffset??0);let n=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const s=te(this.segments,i,o=>o.timestamp);if(s===-1)return null;if(s<this.segments.length-1||this.streamHasEnded||n)return this.segments[s];const a=this.segments[s];if(i<a.timestamp+a.duration)return a;await this.runUpdateSegments(),t.skipLiveWait&&(n=!0)}}async getNextSegment(e,t){const i=e.index;y(i!==-1);const n=i+1;let s=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(n<this.segments.length)return this.segments[n];if(this.streamHasEnded||s)return null;await this.runUpdateSegments(),t.skipLiveWait&&(s=!0)}}async getPreviousSegment(e){const t=e.index;return y(t!==-1),this.segments[t-1]??null}getInputForSegment(e){var c;const t=e,i=this.inputCache.find(u=>u.segment===t);if(i)return i.age=this.nextInputCacheAge++,i.input;let n=null;(t.initSegment||t.firstSegment)&&(n=this.getInputForSegment(t.initSegment??t.firstSegment));const s={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:((c=this.input._formatOptions.isobmff)==null?void 0:c.resolveKeyId)&&(u=>{if(!t.encryption||!(t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR")||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(u);let l=u.psshBoxes;const{psshBox:d}=t.encryption;return(d.keyIds===null||d.keyIds.includes(u.keyId))&&!l.some(f=>Go(f,d))&&(l=[...l,d]),this.input._formatOptions.isobmff.resolveKeyId({...u,psshBoxes:l})})}},a=new Ms({source:new nf(t.location.path,async u=>{y(u.isRoot);const l={...u,isRoot:!1};let d;const f=t.location.offset>0||t.location.length!==null;if(!t.encryption||t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR"){if(d=await this.input._getSourceCached(l),f){const p=d.source.slice(t.location.offset,t.location.length??void 0).ref();d.free(),d=p}}else if(t.encryption.method==="AES-128"){const h=t.encryption;y(h.iv);let p=await this.input._getSourceCached(l);if(f){const S=p.source.slice(t.location.offset,t.location.length??void 0).ref();p.free(),p=S}const m=new xi(p.source),b=Yu(m,async()=>{const w={stack:[],error:void 0,hasError:!1};try{const S=Xa(w,await this.input._getSourceCached({path:h.keyUri,isRoot:!1},Vf),!1),T=await new xi(S.source).requestSlice(0,it);if(!T)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:X(T,it),iv:h.iv}}catch(S){w.error=S,w.hasError=!0}finally{Qa(w)}},()=>{p.free()});d=new Pc(b).ref()}else y(!1);return d}),formats:this.input._formats.filter(u=>!(u instanceof Rc)),initInput:n??void 0,formatOptions:s});if(a._onFormatDetermined=u=>{var l,d;if((((l=t.encryption)==null?void 0:l.method)==="SAMPLE-AES"||((d=t.encryption)==null?void 0:d.method)==="SAMPLE-AES-CTR")&&!u._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:t,input:a,age:this.nextInputCacheAge++}),this.inputCache.length>4){const u=Hi(this.inputCache,l=>l.age);y(u!==-1),this.inputCache.splice(u,1)}return a}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??(this.segmentTimestampOffsetPromise=(async()=>{const e=await this.getFirstSegment();y(e);const t=this.demuxer.getReferenceSegmentedInput();if(this===t)return 0;const i=await t.getFirstSegment();if(i&&(this.listsAllSegments()&&t.listsAllSegments()||e.unixEpochTimestamp===e.timestamp&&i.unixEpochTimestamp===i.timestamp))return 0;const n=this.getInputForSegment(e);if(await this.getRawTimestampOffset(n)===null)return 0;const s=await n.getTracks(),a=s.find(u=>u.type==="video")??s[0];if(!a)throw new Error("The playlist's first segment contains no tracks.");const o=await this.getMediaOffset(e,n),c=await a.getFirstTimestamp()+o-e.timestamp;return this.learnedSegmentTimestampOffset??(this.learnedSegmentTimestampOffset=c),c})())}listsAllSegments(){return this.segments[0].sequenceNumber===0||this.neverRemovesSegments}async getRawTimestampOffset(e){var s;if((await e.getFormat()).supportsTimestampedMediaData)return 0;const n=(s=(await e.getMetadataTags()).raw)==null?void 0:s.PRIV;for(const a of Pl(n)){if(!(a instanceof Uint8Array)||a.length!==Gt.length+1+8||_e.decode(a.subarray(0,Gt.length))!==Gt||a[Gt.length]!==0)continue;const o=Z(a),c=o.getUint32(Gt.length+1),u=o.getUint32(Gt.length+5);if(c>1)continue;const l=2**32*c+u;return mc(l,hc(l))/Ne-await e.getFirstTimestamp()}return null}getTimestampWrapPeriod(){return Zr/Ne}}/*!
260
+ * Copyright (c) 2026-present, Vanilagy and contributors
261
+ *
262
+ * This Source Code Form is subject to the terms of the Mozilla Public
263
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
264
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
265
+ */const ff=256,hf=256;class mf extends yt{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0,this.masterPlaylistVariables=null,this.mediaOffsets=new Map}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{y(this.input._rootSource instanceof jt);const e=await this.input._reader.requestEntireFile();y(e);const t=Lc(e,e.length,{ignore:bc}),{rootPath:i}=this.input._rootSource,n=new wc(i,null),s=[],a=[];for(let l=1;l<t.length;l++){const d=t[l];if(d.startsWith(Ni))n.define(d.slice(Ni.length));else if(d.startsWith(va)){const f=l;let h=t[++l];if(h===void 0)throw new Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");h=n.substitute(h);const p=xt(i,h),m=new ur(d.slice(va.length),n);if(m.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");s.push({fullPath:p,attributes:m,lineNumber:f,hasOnlyKeyPackets:!1})}else if(d.startsWith(Ra)){const f=new ur(d.slice(Ra.length),n),h=f.get("uri");if(h===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(f.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");const m=xt(i,h);s.push({fullPath:m,attributes:f,lineNumber:l,hasOnlyKeyPackets:!0})}else if(d.startsWith(Ba)){const f=new ur(d.slice(Ba.length),n);if(f.get("type")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(f.get("group-id")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let m=null;const b=f.get("uri");b!==null&&(m=xt(i,b)),a.push({fullPath:m,attributes:f,lineNumber:l})}else if(d!==Zd){if(d.startsWith(os)){const f=new $a(this,i,null,t);this.segmentedInputs=[f],this.hasMasterPlaylist=!1,this.trackBackings=await f.getTrackBackings();return}}}if(s.length>ff||a.length>hf)throw new Error("Unsupported M3U8 file; too many variant streams or media tags.");this.masterPlaylistVariables=n;const o=await Promise.all(s.map(async(l,d)=>{const f=[],h=l.attributes.get("codecs");let p;if(h)p=h.split(",").map(I=>I.trim());else{const E=await this.getSegmentedInputForPath(l.fullPath).getTrackBackings(),C=await Promise.all(E.map(async _=>({track:_,codec:await _.getCodec()})));p=await Promise.all(C.filter(_=>_.codec!==null).map(_=>_.track.getDecoderConfig().then(D=>D.codec)))}const m=l.attributes.get("video"),b=l.attributes.get("audio"),w=p.some(I=>Qe.includes(Je(I))),S=p.some(I=>Ge.includes(Je(I)));if(m!==null&&!w){const I=a.find(E=>{const C=E.attributes.get("group-id"),_=E.attributes.get("type");return C===m&&_.toLowerCase()==="video"});e:if(I){const E=I.attributes.get("uri");if(E===null)break e;const C=xt(i,E),q=(await this.getSegmentedInputForPath(C).getTrackBackings()).find(V=>V.getType()==="video");if(!q||await q.getCodec()===null)break e;const M=await q.getDecoderConfig().then(V=>(V==null?void 0:V.codec)??null);y(M!==null),p.push(M)}}if(b!==null&&!S){const I=a.find(E=>{const C=E.attributes.get("group-id"),_=E.attributes.get("type");return C===b&&_.toLowerCase()==="audio"});e:if(I){const E=I.attributes.get("uri");if(E===null)break e;const C=xt(i,E),q=(await this.getSegmentedInputForPath(C).getTrackBackings()).find(V=>V.getType()==="audio");if(!q||await q.getCodec()===null)break e;const M=await q.getDecoderConfig().then(V=>(V==null?void 0:V.codec)??null);y(M!==null),p.push(M)}}p=[...new Set(p)];let A=null,T=null;const k=l.attributes.getAsNumber("bandwidth");y(k!==null);const x=l.attributes.getAsNumber("average-bandwidth"),P=l.attributes.get("name");for(const I of p){const E=Je(I);if(E!==null){if(Qe.includes(E)){if(A!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");A=I;const C=l.attributes.get("video");if(C===null){const _=l.attributes.get("resolution");let D=null,q=null;if(_){const M=_.match(/^(\d+)x(\d+)$/);M&&(D=Number(M[1]),q=Number(M[2]))}f.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:De,lineNumber:l.lineNumber,fullPath:l.fullPath,fullCodecString:A,pairingMask:1n<<BigInt(d),peakBitrate:k,averageBitrate:x,name:P,hasOnlyKeyPackets:l.hasOnlyKeyPackets,info:{type:"video",width:D,height:q}})}else for(const _ of a){const D=_.attributes.get("group-id"),q=_.attributes.get("type");if(D!==C||q.toLowerCase()!=="video")continue;const M=_.attributes.get("resolution")??l.attributes.get("resolution");let V=null,G=null;if(M){const J=M.match(/^(\d+)x(\d+)$/);J&&(V=Number(J[1]),G=Number(J[2]))}f.push({id:-1,demuxer:this,backingTrack:null,default:wi(_.attributes),autoselect:wi(_.attributes)||Ya(_.attributes),languageCode:Za(_.attributes.get("language")),lineNumber:_.lineNumber,fullPath:_.fullPath??l.fullPath,fullCodecString:A,pairingMask:1n<<BigInt(d),peakBitrate:_.fullPath===null?k:null,averageBitrate:_.fullPath===null?x:null,name:_.attributes.get("name"),hasOnlyKeyPackets:l.hasOnlyKeyPackets,info:{type:"video",width:V,height:G}})}}else if(Ge.includes(E)){if(T!==null)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");T=I;const C=l.attributes.get("audio");if(C===null){const _=l.attributes.get("channels"),D=_!==null?Number(_.split("/")[0]):null;f.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:De,lineNumber:l.lineNumber,fullPath:l.fullPath,fullCodecString:T,pairingMask:1n<<BigInt(d),peakBitrate:k,averageBitrate:x,name:P,hasOnlyKeyPackets:l.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:D!==null&&Number.isInteger(D)&&D>0?D:null}})}else for(const _ of a){const D=_.attributes.get("group-id"),q=_.attributes.get("type");if(D!==C||q.toLowerCase()!=="audio")continue;const M=_.attributes.get("channels")??l.attributes.get("channels"),V=M!==null?Number(M.split("/")[0]):null;f.push({id:-1,demuxer:this,backingTrack:null,default:wi(_.attributes),autoselect:wi(_.attributes)||Ya(_.attributes),languageCode:Za(_.attributes.get("language")),lineNumber:_.lineNumber,fullPath:_.fullPath??l.fullPath,fullCodecString:T,pairingMask:1n<<BigInt(d),peakBitrate:_.fullPath===null?k:null,averageBitrate:_.fullPath===null?x:null,name:_.attributes.get("name"),hasOnlyKeyPackets:l.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:V!==null&&Number.isInteger(V)&&V>0?V:null}})}}}}return f})),c=[],u=l=>{const d=c.find(f=>f.fullPath===l.fullPath&&f.info.type===l.info.type);d?(d.pairingMask|=l.pairingMask,d.default||(d.default=l.default),d.autoselect||(d.autoselect=l.autoselect),d.lineNumber=Math.min(d.lineNumber,l.lineNumber),l.peakBitrate!==null&&(d.peakBitrate=Math.max(d.peakBitrate??-1/0,l.peakBitrate)),l.averageBitrate!==null&&(d.averageBitrate=Math.max(d.averageBitrate??-1/0,l.averageBitrate)),d.languageCode===De&&(d.languageCode=l.languageCode)):(l.id=c.length+1,c.push(l))};for(const l of o)for(const d of l)u(d);c.sort((l,d)=>l.lineNumber-d.lineNumber),this.trackBackings=[];for(const l of c)l.info.type==="video"?this.trackBackings.push(new Cc(l)):this.trackBackings.push(new Ec(l));this.internalTracks=c})())}async getTrackBackings(){return await this.readMetadata(),y(this.trackBackings),this.trackBackings}getMediaOffsetForDiscontinuity(e){let t=this.mediaOffsets.get(e);return t||(t=(async()=>{const i=this.getReferenceSegmentedInput();let n=await i.getFirstSegment();for(;n&&n.discontinuityNumber<e;)n=await i.getNextSegment(n,{});if(!n||n.discontinuityNumber!==e)throw new 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.`);const s=i.getInputForSegment(n),a=await i.getRawTimestampOffset(s)??0,o=await s.getTracks(),c=o.find(u=>u.type==="video")??o[0];if(!c)throw new Error("The reference playlist's segment contains no tracks.");return n.timestamp-(a+await c.getFirstTimestamp())})(),this.mediaOffsets.set(e,t),t)}getReferenceSegmentedInput(){if(!this.hasMasterPlaylist)return this.segmentedInputs[0];y(this.internalTracks);const e=this.internalTracks.filter(s=>!s.hasOnlyKeyPackets),t=e.filter(s=>s.info.type==="video"),i=t.length>0?t:e,n=Hi(i,s=>s.peakBitrate??1/0);return y(n!==-1),this.getSegmentedInputForPath(i[n].fullPath)}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(n=>n.path===e);if(t)return t;let i=null;return this.internalTracks&&(i=this.internalTracks.filter(s=>s.fullPath===e).map(s=>({id:s.id,type:s.info.type}))),t=new $a(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return gc}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class Ic{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??(this.hydrationPromise=(async()=>{const e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let t=null;const n=(await e.getTrackBackings()).filter(s=>s.getType()===this.getType());if(n.length===1)t=n[0];else if(this instanceof Cc){for(const s of n)if(await s.getCodec()===this.getCodec()){t=s;break}}else{y(this instanceof Ec);for(const s of n)if(await s.getCodec()===this.getCodec()){t=s;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t})())}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...kt,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){y(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}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)}}class Cc extends Ic{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Je(this.internalTrack.fullCodecString)}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 new Error("The codec in the playlist doesn't match the codec of the media data.");return this.backingVideoTrack.getDecoderConfig()}}class Ec extends Ic{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Je(this.internalTrack.fullCodecString)}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels!==null?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}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 new Error("The codec in the playlist doesn't match the codec of the media data.");return this.backingAudioTrack.getDecoderConfig()}}const wi=r=>{const e=r.get("default");if(e===null)return!1;const t=e.toUpperCase();if(t==="YES")return!0;if(t==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${e}".`)},Ya=r=>{const e=r.get("autoselect");if(e===null)return!1;const t=e.toUpperCase();if(t==="YES")return!0;if(t==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${e}".`)},Za=r=>{if(r===null)return De;const e=r.split("-")[0];return e||De};/*!
266
+ * Copyright (c) 2026-present, Vanilagy and contributors
267
+ *
268
+ * This Source Code Form is subject to the terms of the Mozilla Public
269
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
270
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
271
+ */class ot{constructor(){this._isIsobmff=!1}}class _c extends ot{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(F(t)&&(t=await t),!t)return null;t.skip(4);const i=be(t,4);return i!=="ftyp"&&i!=="styp"?null:be(t,4)}_createDemuxer(e){return new Es(e)}get supportsTimestampedMediaData(){return!0}}class pf extends _c{async _canReadInput(e){const t=await this._getMajorBrand(e);if(t!==null)return t!=="qt ";let i=0;for(let n=0;n<10;n++){let s=e._reader.requestSlice(i,8);if(F(s)&&(s=await s),!s)return!1;let a=U(s),o=8;if(a===1){let u=e._reader.requestSlice(i+8,8);if(F(u)&&(u=await u),!u)return!1;a=Oe(u),o=16}if(a<o)return!1;const c=be(s,4);if(c==="moof"||c==="sidx")return!0;if(c==="emsg"||c==="prft"||c==="free")i+=a;else return!1}return!1}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class gf extends _c{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class vc extends ot{async isSupportedEBMLOfDocType(e,t){let i=e._reader.requestSlice(0,at);if(F(i)&&(i=await i),!i)return!1;const n=sc(i);if(n===null||n<1||n>8||ee(i,n)!==B.EBML)return!1;const a=oc(i);if(typeof a!="number")return!1;let o=e._reader.requestSlice(i.filePos,a);if(F(o)&&(o=await o),!o)return!1;const c=i.filePos;for(;o.filePos<=c+a-We;){const u=nt(o);if(!u)break;const{id:l,size:d}=u,f=o.filePos;if(d===void 0||f+d>c+a||d>8&&l!==B.DocType)return!1;switch(l){case B.EBMLVersion:if(ee(o,d)!==1)return!1;break;case B.EBMLReadVersion:if(ee(o,d)!==1)return!1;break;case B.DocType:if(rr(o,d)!==t)return!1;break;case B.DocTypeVersion:if(ee(o,d)>4)return!1;break}o.filePos=f+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new pd(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}get supportsTimestampedMediaData(){return!0}}class bf extends vc{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class wf extends ot{async _canReadInput(e){let t=0;for(;;){let d=e._reader.requestSlice(t,He);if(F(d)&&(d=await d),!d)break;const f=wt(d);if(!f)break;t=d.filePos+f.size}const i=await ns(e._reader,t,t+4096);if(!i)return!1;const n=i.header,s=yo(n.mpegVersionId,n.channel);let a=e._reader.requestSlice(i.startPos+s,4);if(F(a)&&(a=await a),!a)return!1;const o=U(a);if(o===jn||o===ko)return!0;t=i.startPos+i.header.totalSize;const u=await ns(e._reader,t,t+vt);if(!u)return!1;const l=u.header;return!(n.channel!==l.channel||n.sampleRate!==l.sampleRate)}_createDemuxer(e){return new yd(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}get supportsTimestampedMediaData(){return!1}}class kf extends ot{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(F(t)&&(t=await t),!t)return!1;const i=be(t,4);return i!=="RIFF"&&i!=="RIFX"&&i!=="RF64"?!1:(t.skip(4),be(t,4)==="WAVE")}_createDemuxer(e){return new vd(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}get supportsTimestampedMediaData(){return!1}}class yf extends ot{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return F(t)&&(t=await t),t?be(t,4)==="OggS":!1}_createDemuxer(e){return new Ed(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}get supportsTimestampedMediaData(){return!0}}class Sf extends ot{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,He);if(F(n)&&(n=await n),!n)break;const s=wt(n);if(!s)break;t=n.filePos+s.size}let i=e._reader.requestSlice(t,4);return F(i)&&(i=await i),i?be(i,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}get supportsTimestampedMediaData(){return!1}_createDemuxer(e){return new Vd(e)}}class Af extends ot{async _canReadInput(e){let t=0;for(;;){let a=e._reader.requestSlice(t,He);if(F(a)&&(a=await a),!a)break;const o=wt(a);if(!o)break;t=a.filePos+o.size}let i=e._reader.requestSliceRange(t,ai,lr);if(F(i)&&(i=await i),!i)return!1;const n=oi(i);if(!n||(t+=n.frameLength,i=e._reader.requestSliceRange(t,ai,lr),F(i)&&(i=await i),!i))return!1;const s=oi(i);return s?n.objectType===s.objectType&&n.samplingFrequencyIndex===s.samplingFrequencyIndex&&n.channelConfiguration===s.channelConfiguration:!1}_createDemuxer(e){return new Bd(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}get supportsTimestampedMediaData(){return!1}}class Tf extends ot{async _canReadInput(e){const t=Le+16+1;let i=e._reader.requestSlice(0,t);if(F(i)&&(i=await i),!i)return!1;const n=X(i,t);return n[0]===71&&n[Le]===71||n[0]===71&&n[Le+16]===71?!0:n[4]===71&&n[4+Le+4]===71}_createDemuxer(e){return new Xd(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}get supportsTimestampedMediaData(){return!0}}class Rc extends ot{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(F(t)&&(t=await t),!t||!(be(t,7)==="#EXTM3U"))return!1;if(!(e._rootSource instanceof jt))throw new 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 mf(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return gc}get supportsTimestampedMediaData(){return!0}}const Bc=new pf,Fc=new gf,xf=new vc,Pf=new bf,Dc=new wf,If=new kf,Cf=new yf,Mc=new Af,Ef=new Sf,Oc=new Tf,Nc=new Rc,um=[Nc,Bc,Fc,xf,Pf,If,Cf,Ef,Dc,Mc,Oc],dm=[Nc,Bc,Fc,Dc,Mc,Oc],_f=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(`${e}, when provided, must be an object.`);if(r.isobmff!==void 0){if(!r.isobmff||typeof r.isobmff!="object")throw new TypeError(`${e}.isobmff, when provided, must be an object.`);if(r.isobmff.resolveKeyId!==void 0&&typeof r.isobmff.resolveKeyId!="function")throw new TypeError(`${e}.isobmff.resolveKeyId, when provided, must be a function.`)}if(r.hls!==void 0){if(!r.hls||typeof r.hls!="object")throw new TypeError(`${e}.hls, when provided, must be an object.`);if(r.hls.offsetTimestampsByDateTime!==void 0&&typeof r.hls.offsetTimestampsByDateTime!="boolean")throw new TypeError(`${e}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}};/*!
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
+ */const Bt=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.metadataOnly!==void 0&&typeof r.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(r.verifyKeyPackets!==void 0&&typeof r.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(r.verifyKeyPackets&&r.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(r.skipLiveWait!==void 0&&typeof r.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},bt=r=>{if(!Ht(r))throw new TypeError("timestamp must be a number.")},En=(r,e,t)=>t.verifyKeyPackets?e.then(async i=>{if(!i||i.type==="delta")return i;const n=await r.determinePacketType(i);return n&&(i.type=n),i}):e;class on{constructor(e){if(!(e instanceof hi))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(Bt(e),this._track.input._disposed)throw new Ce;return En(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Bt(e);const t=await this.getFirstPacket(e);return t?t.type==="key"?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(bt(e),Bt(t),this._track.input._disposed)throw new Ce;return En(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof ce))throw new TypeError("packet must be an EncodedPacket.");if(Bt(t),this._track.input._disposed)throw new Ce;return En(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(bt(e),Bt(t),this._track.input._disposed)throw new Ce;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let i=await this._track._backing.getKeyPacket(e,t);for(;i;){if(y(i.type==="key"),await this._track.determinePacketType(i)!=="delta")return i;let s=1/await this._track.getTimeResolution(),a;for(;a=await this._track._backing.getKeyPacket(i.timestamp-s,t),!(!a||a.timestamp<i.timestamp);)s*=2;i=a}return null}async getNextKeyPacket(e,t={}){if(!(e instanceof ce))throw new TypeError("packet must be an EncodedPacket.");if(Bt(t),this._track.input._disposed)throw new Ce;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let i=await this._track._backing.getNextKeyPacket(e,t);for(;i;){if(y(i.type==="key"),await this._track.determinePacketType(i)!=="delta")return i;i=await this._track._backing.getNextKeyPacket(i,t)}return null}packets(e,t,i={}){if(e!==void 0&&!(e instanceof ce))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!(i!=null&&i.metadataOnly))throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof ce))throw new TypeError("endPacket must be an EncodedPacket.");if(Bt(i),this._track.input._disposed)throw new Ce;const n=[];let{promise:s,resolve:a}=Se(),{promise:o,resolve:c}=Se(),u=!1,l=!1,d=null,f=!1;const h=[],p=()=>Math.max(2,h.length);(async()=>{let b=e??await this.getFirstPacket(i);for(;b&&!l&&!this._track.input._disposed&&!(t&&b.sequenceNumber>=(t==null?void 0:t.sequenceNumber));){if(n.length>p()){({promise:o,resolve:c}=Se()),await o;continue}n.push(b),a(),{promise:s,resolve:a}=Se(),b=await this.getNextPacket(b,i)}u=!0,a()})().catch(b=>{f||(d=b,f=!0,a())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new Ce;if(l)return{value:void 0,done:!0};if(f)throw d;if(n.length>0){const b=n.shift(),w=performance.now();for(h.push(w);h.length>0&&w-h[0]>=1e3;)h.shift();return c(),{value:b,done:!1}}else{if(u)return{value:void 0,done:!0};await s}}},async return(){return l=!0,c(),a(),{value:void 0,done:!0}},async throw(b){throw b},[Symbol.asyncIterator](){return this}}}}const Ja=4;class Ds{constructor(e,t){this.onSample=e,this.onError=t,this.onDequeue=null}}class zc{mediaSamplesInRange(e=-1/0,t=1/0,i){bt(e),bt(t);const n=[];let s=!1,a=null,{promise:o,resolve:c}=Se(),{promise:u,resolve:l}=Se(),d=!1,f=!1,h=!1,p=null,m=null,b=!1;const w={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{p=await this._createDecoder(_=>{if(l(),_.timestamp>=t&&(f=!0),f){_.close();return}a&&(_.timestamp>e?(n.push(a),s=!0):a.close()),_.timestamp>=e&&(n.push(_),s=!0),a=s?null:_,n.length>0&&(c(),{promise:o,resolve:c}=Se())},_=>{b||(m=_,b=!0,c())}),p.onDequeue=()=>l();const T=this._createPacketSink(),k=await this._getPreRollDuration(),x=await T.getPacket(e,w),P=await T.getKeyPacket(((x==null?void 0:x.timestamp)??e)-k,w)??await T.getFirstKeyPacket(w);let I=P;const C=T.packets(P??void 0,void 0,w);for(await C.next();I&&!f&&!this._track.input._disposed;){if(n.length+p.getDecodeQueueSize()>=Ja){({promise:u,resolve:l}=Se()),await u;continue}p.decode(I);const _=await C.next();if(_.done)break;I=_.value}await C.return(),!h&&!this._track.input._disposed&&await p.flush(),!s&&a&&(n.push(a),a=null),d=!0,c()})().catch(T=>{b||(m=T,b=!0,c())}).finally(()=>{p==null||p.close()});const S=this._track,A=()=>{a==null||a.close();for(const T of n)T.close()};return{async next(){for(;;){if(S.input._disposed)throw h=!0,f=!0,A(),new Ce;if(h)return{value:void 0,done:!0};if(b)throw h=!0,f=!0,A(),m;if(n.length>0){const T=n.shift();return l(),{value:T,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return h=!0,f=!0,l(),c(),A(),{value:void 0,done:!0}},async throw(T){throw T},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){ol(e);const i=al(e),n=[],s=[];let{promise:a,resolve:o}=Se(),{promise:c,resolve:u}=Se(),l=!1,d=!1,f=null,h=null,p=!1;const m=k=>{s.push(k),o(),{promise:a,resolve:o}=Se()};let b=null;const w=k=>{for(let x=0;x<k;x++)m(b&&(x<k-1?b.clone():b));k===0&&(b==null||b.close()),b=null},S={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{f=await this._createDecoder(M=>{if(u(),d){M.close();return}let V=0;for(;n.length>0&&M.timestamp-n[0]>1e-10;)V++,n.shift();w(V),b=M},M=>{p||(h=M,p=!0,o())}),f.onDequeue=()=>u();const k=this._createPacketSink(),x=await this._getPreRollDuration();let P=null,I=-1/0,E=null,C=null,_=-1;const D=async()=>{y(E),y(f);let M=C;for(M||(M=E,f.decode(M));M.sequenceNumber<_;){for(;s.length+f.getDecodeQueueSize()>=Ja&&!d;)({promise:c,resolve:u}=Se()),await c;if(d)break;const V=await k.getNextPacket(M,S);if(!V)throw new Error("Internal error: couldn't get next packet when one was expected.");f.decode(V),M=V}C=M},q=async()=>{y(f),await f.flush(),w(n.length),n.length=0};for await(const M of i){if(bt(M),d||this._track.input._disposed)break;const V=await k.getPacket(M,S);let G=V&&await k.getKeyPacket(V.timestamp-x,S);if(V&&!G){const J=await k.getFirstKeyPacket(S);J&&J.timestamp<=V.timestamp&&(G=J)}if(!V||!G){P&&await q(),m(null),P=null;continue}(!P||G.sequenceNumber>_+1||M<I)&&(P&&await q(),E=G,C=null,_=-1),n.push(M),_=Math.max(V.sequenceNumber,_),P=V,I=M,await D()}!d&&!this._track.input._disposed&&await q(),l=!0,o()})().catch(k=>{p||(h=k,p=!0,o())}).finally(()=>{f==null||f.close()});const A=this._track,T=()=>{b==null||b.close(),b=null;for(const k of s)k==null||k.close()};return{async next(){for(;;){if(A.input._disposed)throw d=!0,T(),new Ce;if(d)return{value:void 0,done:!0};if(p)throw d=!0,T(),h;if(s.length>0){const k=s.shift();return y(k!==void 0),u(),{value:k,done:!1}}else if(!l)await a;else return{value:void 0,done:!0}}},async return(){return d=!0,u(),o(),T(),{value:void 0,done:!0}},async throw(k){throw k},[Symbol.asyncIterator](){return this}}}}class vf extends Ds{constructor(e,t,i,n,s,a,o){var u,l,d,f;super(e,t),this.codec=i,this.decoderConfig=n,this.rotation=s,this.flip=a,this.timeResolution=o,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Wi,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;const c=ii.find(h=>h.supports(i,n));if(c)this.customDecoder=new c,this.customDecoder.codec=i,this.customDecoder.config=n,this.customDecoder.onSample=h=>{if(!(h instanceof Ie))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(h)},this.customDecoder.onError=h=>{t(h)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(h=>t(h));else{const h=m=>{if(this.alphaQueue.length>0){const b=this.alphaQueue.shift();y(b!==void 0),this.mergeAlpha(m,b)}else this.colorQueue.push(m)};if(ki()){if(i==="avc"&&this.decoderConfig.description){const m=Yi(ke(this.decoderConfig.description));if(m&&m.sequenceParameterSets.length>0){const b=dr(m.sequenceParameterSets[0]);b&&(b.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}),b.maxDecFrameBuffering!==0&&b.bitstreamRestrictionFlag!==1&&(m.sequenceParameterSets[0]=Js(b),this.decoderConfig={...this.decoderConfig,description:Io(m)}))}}ds(this.decoderConfig.colorSpace)||(this.decoderConfig={...this.decoderConfig,colorSpace:{primaries:((u=this.decoderConfig.colorSpace)==null?void 0:u.primaries)??"bt709",matrix:((l=this.decoderConfig.colorSpace)==null?void 0:l.matrix)??"bt709",transfer:((d=this.decoderConfig.colorSpace)==null?void 0:d.transfer)??"bt709",fullRange:((f=this.decoderConfig.colorSpace)==null?void 0:f.fullRange)??!1}})}const p=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:m=>{try{h(this.copyFrameIfNeeded(m))}catch(b){this.onError(b)}},error:m=>{m.stack=p,this.onError(m)}}),this.decoder.addEventListener("dequeue",()=>{var m;(m=this.onDequeue)==null||m.call(this)}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){var e;return this.customDecoder?this.customDecoderQueueSize:(y(this.decoder),Math.max(this.decoder.decodeQueueSize,((e=this.alphaDecoder)==null?void 0:e.decodeQueueSize)??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(t=>this.onError(t)).finally(()=>{var t;this.customDecoderQueueSize--,(t=this.onDequeue)==null||t.call(this)});else{if(y(this.decoder),_t()||js(this.inputTimestamps,e.timestamp,t=>t),ki()&&this.currentPacketIndex===0){if(this.codec==="avc"){const t=[];let i=!1;for(const s of To(e.data,this.decoderConfig)){const a=ri(e.data[s.offset]);if(i||(i=a>=1&&a<=5),a===Ae.AUD){if(i)break;t.length=0}a>=20&&a<=31||t.push(e.data.subarray(s.offset,s.offset+s.length))}if(!this.decoderConfig.description)for(let s=0;s<t.length;s++){const a=t[s];if(ri(a[0])!==Ae.SPS)continue;const o=dr(a);o&&o.maxDecFrameBuffering!==0&&o.bitstreamRestrictionFlag!==1&&(t[s]=Js(o));break}const n=zl(t,this.decoderConfig);e=new ce(n,e.type,e.timestamp,e.duration)}else if(this.codec==="hevc"){const t=Kl(e.data,this.decoderConfig);t&&(e=new ce(t,e.type,e.timestamp,e.duration))}}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||(this.merger=new Rf),!this.alphaDecoder){const i=s=>{if(this.colorQueue.length>0){const a=this.colorQueue.shift();y(a!==void 0),this.mergeAlpha(a,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const a=this.colorQueue.shift();y(a!==void 0),this.mergeAlpha(a,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},n=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{i(this.copyFrameIfNeeded(s))}catch(a){this.onError(a)}},error:s=>{s.stack=n,this.onError(s)}}),this.alphaDecoder.addEventListener("dequeue",()=>{var s;(s=this.onDequeue)==null||s.call(this)}),this.alphaDecoder.configure({...this.decoderConfig,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"}})}const t=tn(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=t==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(const t of Ri(e,this.decoderConfig)){const i=fr(e[t.offset]);if(i===ge.RASL_N||i===ge.RASL_R)return!0}return!1}sampleHandler(e){if(_t()){if(this.sampleQueue.length>0&&e.timestamp>=fe(this.sampleQueue).timestamp){for(const t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}js(this.sampleQueue,e,t=>t.timestamp)}else{const t=this.inputTimestamps.shift();y(t!==void 0),e.setTimestamp(t),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,t){const i=Se();this.mergeAlphaPromises.push(i.promise);const n={sample:null};this.finalSamples.push(n);try{if(!t)n.sample=new Ie(e);else{y(this.merger);const s=await this.merger.merge(e,t);n.sample=new Ie(s)}for(;this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){const s=this.finalSamples.shift();this.sampleHandler(s.sample)}}catch(s){Ci(this.finalSamples,n),this.onError(s)}finally{Ci(this.mergeAlphaPromises,i.promise),i.resolve()}}copyFrameIfNeeded(e){if(!ki()||!pl())return e;const t=e.visibleRect,i=t.width,n=t.height;if(!this.frameCopyContext){let o;if(typeof OffscreenCanvas<"u"?o=new OffscreenCanvas(i,n).getContext("2d",{alpha:!1}):o=document.createElement("canvas").getContext("2d",{alpha:!1}),!o)throw new Error("The '2d' canvas context is required to decode video on Chromium for Android.");this.frameCopyContext=o}const s=this.frameCopyContext.canvas;(s.width!==i||s.height!==n)&&(s.width=i,s.height=n),this.frameCopyContext.drawImage(e,0,0,i,n),this.flushing&&this.frameCopyContext.getImageData(0,0,1,1);const a=new VideoFrame(s,{timestamp:e.timestamp,duration:e.duration??void 0,displayWidth:e.displayWidth,displayHeight:e.displayHeight});return e.close(),a}async flush(){var e;if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(y(this.decoder),this.flushing=!0,await Promise.all([this.decoder.flush(),(e=this.alphaDecoder)==null?void 0:e.flush()]),this.flushing=!1,await Promise.all(this.mergeAlphaPromises),this.colorQueue.forEach(t=>t.close()),this.colorQueue.length=0,this.alphaQueue.forEach(t=>t==null?void 0:t.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),_t()){for(const t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){var e;this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(y(this.decoder),this.decoder.state!=="closed"&&this.decoder.close(),this.alphaDecoder&&this.alphaDecoder.state!=="closed"&&this.alphaDecoder.close(),this.colorQueue.forEach(t=>t.close()),this.colorQueue.length=0,this.alphaQueue.forEach(t=>t==null?void 0:t.close()),this.alphaQueue.length=0,(e=this.merger)==null||e.close());for(const t of this.sampleQueue)t.close();this.sampleQueue.length=0}}let _n=null;class Rf{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(this.workers.length===0){if(!_n){const o=new Blob([`(${Bf.toString()})()`],{type:"application/javascript"});_n=URL.createObjectURL(o)}const a=pe(navigator.hardwareConcurrency,1,4);for(let o=0;o<a;o++){const c=new Worker(_n);c.addEventListener("message",u=>{const l=u.data,d=this.pendingRequests.get(l.id);d&&(this.pendingRequests.delete(l.id),"error"in l?d.reject(new Error(l.error)):d.resolve(l.frame))}),c.addEventListener("error",u=>{const l=new Error(u.message||"Color/alpha merge worker error.");for(const d of this.pendingRequests.values())d.reject(l);this.pendingRequests.clear()}),this.workers.push(c)}}const i=this.nextRequestId++,n=Se();this.pendingRequests.set(i,n);const s=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,s.postMessage({id:i,color:e,alpha:t},{transfer:[e,t]}),n.promise}close(){for(const t of this.workers)t.terminate();this.workers.length=0;const e=new Error("Color/alpha merger closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}const Bf=()=>{let r=null,e=null,t=Promise.resolve();self.addEventListener("message",c=>{const{id:u,color:l,alpha:d}=c.data;t=t.then(async()=>{try{const f=await i(l,d);self.postMessage({id:u,frame:f},{transfer:[f]})}catch(f){self.postMessage({id:u,error:f.message})}finally{l.close(),d.close()}})});const i=async(c,u)=>{const l=c.format,d=u.format;if(!l||!d)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const f=l.includes("P10"),h=l.includes("P12"),p=d.includes("P10"),m=d.includes("P12");if(p!==f||m!==h)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${l}', alpha: '${d}').`);if(l==="RGBX"||l==="RGBA"||l==="BGRX"||l==="BGRA")return await n(c,u,l);if(l==="I420"||l==="I420P10"||l==="I420P12"||l==="I422"||l==="I422P10"||l==="I422P12"||l==="I444"||l==="I444P10"||l==="I444P12")return await s(c,u,l);if(l==="NV12")return await a(c,u);throw new Error(`CPU color/alpha merging does not support format '${l}'.`)},n=async(c,u,l)=>{var S,A;const d=((S=c.visibleRect)==null?void 0:S.width)??c.codedWidth,f=((A=c.visibleRect)==null?void 0:A.height)??c.codedHeight,h=d*f,p=new Uint8Array(h*4);await c.copyTo(p);const m=await o(u,d,f,1);for(let T=0,k=3;T<h;T++,k+=4)p[k]=m[T];const w={format:l==="RGBX"||l==="RGBA"?"RGBA":"BGRA",codedWidth:d,codedHeight:f,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[p.buffer]};return new VideoFrame(p,w)},s=async(c,u,l)=>{var q,M;const d=((q=c.visibleRect)==null?void 0:q.width)??c.codedWidth,f=((M=c.visibleRect)==null?void 0:M.height)??c.codedHeight,h=l.includes("P10"),p=l.includes("P12"),m=h||p?2:1;let b,w;l.startsWith("I420")?(b=Math.ceil(d/2),w=Math.ceil(f/2)):l.startsWith("I422")?(b=Math.ceil(d/2),w=f):(b=d,w=f);const S=d*f,A=b*w,T=S*m,k=A*m,x=S*m,P=T+2*k+x,I=new Uint8Array(P);await c.copyTo(I);const E=await o(u,d,f,m),C=T+2*k;I.set(E,C);const D={format:l.slice(0,4)+"A"+l.slice(4),codedWidth:d,codedHeight:f,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[I.buffer]};return new VideoFrame(I,D)},a=async(c,u)=>{var P,I;const l=((P=c.visibleRect)==null?void 0:P.width)??c.codedWidth,d=((I=c.visibleRect)==null?void 0:I.height)??c.codedHeight,f=l*d,h=Math.ceil(l/2),p=Math.ceil(d/2),m=h*p,b=c.allocationSize();(!e||e.byteLength!==b)&&(e=new Uint8Array(b)),await c.copyTo(e);const w=new Uint8Array(f+2*m+f);w.set(e.subarray(0,f),0);const S=f,A=f+m,T=f;for(let E=0;E<m;E++)w[S+E]=e[T+E*2],w[A+E]=e[T+E*2+1];const k=await o(u,l,d,1);w.set(k,f+2*m);const x={format:"I420A",codedWidth:l,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[w.buffer]};return new VideoFrame(w,x)},o=async(c,u,l,d)=>{const f=c.allocationSize();(!r||r.byteLength!==f)&&(r=new Uint8Array(f)),await c.copyTo(r);const h=c.format;if(h==="RGBA"||h==="BGRA"||h==="RGBX"||h==="BGRX"){const p=h==="RGBA"||h==="RGBX"?0:2,m=u*l;for(let b=0;b<m;b++)r[b]=r[b*4+p];return r.subarray(0,m)}else{const p=r.subarray(0,u*l*d);if(c.colorSpace.fullRange===!1){const m=h.includes("P12")?12:h.includes("P10")?10:8,b=16<<m-8,w=235<<m-8,S=(1<<m)-1,A=d===2?new Uint16Array(p.buffer,0,u*l):p;for(let T=0;T<A.length;T++){const k=Math.round((A[T]-b)*S/(w-b));A[T]=Math.min(Math.max(k,0),S)}}return p}}},Uc=r=>{if(!r||typeof r!="object")throw new TypeError("decoderOptions must be an object.");if(r.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(r.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(r.optimizeForLatency!==void 0&&typeof r.optimizeForLatency!="boolean")throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};class Ff extends zc{constructor(e,t={}){if(!(e instanceof cn))throw new TypeError("videoTrack must be an InputVideoTrack.");Uc(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!await this._track.canDecode())throw typeof VideoDecoder>"u"?new Error(qi("VideoDecoder")):new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.");const i=await this._track.getCodec(),n=await this._track.getRotation(),s=await this._track.getFlip();let a=await this._track.getDecoderConfig();const o=await this._track.getTimeResolution();return y(i&&a),a={...a,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new vf(e,t,i,a,n,s,o)}_createPacketSink(){return new on(this._track)}async _getPreRollDuration(){return 0}async getSample(e,t={}){bt(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class fm{constructor(e,t={}){if(this._rotation=0,this._flip=!1,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof cn))throw new TypeError("videoTrack must be an InputVideoTrack.");if(t&&typeof t!="object")throw new TypeError("options must be an object.");if(t.alpha!==void 0&&typeof t.alpha!="boolean")throw new TypeError("options.alpha, when provided, must be a boolean.");if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(t.fit!==void 0&&!["fill","contain","cover"].includes(t.fit))throw new 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 new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");if(t.crop!==void 0&&Fi(t.crop,"options."),t.poolSize!==void 0&&(typeof t.poolSize!="number"||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");t.decoderOptions!==void 0&&Uc(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new Ff(e,t.decoderOptions),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??(this._initPromise=(async()=>{const e=this._options,t=this._videoTrack,i=e.rotation??await t.getRotation(),n=e.flip??await t.getFlip(),s=await t.getSquarePixelWidth(),a=await t.getSquarePixelHeight(),[o,c]=i%180===0?[s,a]:[a,s];let u=e.crop;u&&(u=Jn(u,o,c));let[l,d]=u?[u.width,u.height]:[o,c];const f=l/d;e.width!==void 0&&e.height===void 0?(l=e.width,d=Math.round(l/f)):e.width===void 0&&e.height!==void 0?(d=e.height,l=Math.round(d*f)):e.width!==void 0&&e.height!==void 0&&(l=e.width,d=e.height),this._width=l,this._height=d,this._rotation=i,this._flip=n,this._crop=u})())}_videoSampleToWrappedCanvas(e){const t=this._width,i=this._height;let n=this._canvasPool[this._nextCanvasIndex],s=!1;n||(typeof document<"u"?(n=document.createElement("canvas"),n.width=t,n.height=i):n=new OffscreenCanvas(t,i),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=n),s=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const a=n.getContext("2d",{alpha:this._alpha||Wt()});y(a),e._drawWithFitAndMipmapping(n,a,{fit:this._fit,rotation:this._rotation,flip:this._flip,crop:this._crop,targetIsFresh:s,fillBlack:!this._alpha&&Wt()});const o={canvas:n,timestamp:e.timestamp,duration:e.duration};return e.close(),o}async getCanvas(e,t){bt(e),await this._ensureInit();const i=await this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)}async*canvases(e,t,i){await this._ensureInit(),yield*Ei(this._videoSampleSink.samples(e,t,i),n=>this._videoSampleToWrappedCanvas(n))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*Ei(this._videoSampleSink.samplesAtTimestamps(e,t),i=>i&&this._videoSampleToWrappedCanvas(i))}}class Df extends Ds{constructor(e,t,i,n){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Wi,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const s=i==="opus"&&n.description?ys(ke(n.description)).preSkip/mr:0,a=c=>{let u=c.timestamp;this.expectedFirstTimestamp!==null&&this.currentTimestamp===null&&(this.timestampOffset=this.expectedFirstTimestamp+s-u),u+=this.timestampOffset,(this.currentTimestamp===null||Math.abs(u-this.currentTimestamp)>=c.duration)&&(this.currentTimestamp=u);const l=this.currentTimestamp;if(this.currentTimestamp+=c.duration,c.numberOfFrames===0){c.close();return}const d=n.sampleRate;c.setTimestamp(Math.round(l*d)/d),e(c)},o=ni.find(c=>c.supports(i,n));if(o)this.customDecoder=new o,this.customDecoder.codec=i,this.customDecoder.config=n,this.customDecoder.onSample=c=>{if(!(c instanceof Te))throw new TypeError("The argument passed to onSample must be an AudioSample.");a(c)},this.customDecoder.onError=c=>{t(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(c=>t(c));else{const c=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:u=>{try{a(new Te(u))}catch(l){this.onError(l)}},error:u=>{u.stack=c,this.onError(u)}}),this.decoder.addEventListener("dequeue",()=>{var u;(u=this.onDequeue)==null||u.call(this)}),this.decoder.configure(n)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(y(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(t=>this.onError(t)).finally(()=>{var t;this.customDecoderQueueSize--,(t=this.onDequeue)==null||t.call(this)})):(y(this.decoder),this.expectedFirstTimestamp??(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(y(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(y(this.decoder),this.decoder.state!=="closed"&&this.decoder.close())}}class Mf extends Ds{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,y(Me.includes(i.codec)),this.codec=i.codec;const{dataType:n,sampleSize:s,littleEndian:a}=Vs(this.codec);switch(this.inputSampleSize=s,s){case 1:n==="unsigned"?this.readInputValue=(o,c)=>o.getUint8(c)-2**7:n==="signed"?this.readInputValue=(o,c)=>o.getInt8(c):n==="ulaw"?this.readInputValue=(o,c)=>Su(o.getUint8(c)):n==="alaw"?this.readInputValue=(o,c)=>Tu(o.getUint8(c)):y(!1);break;case 2:n==="unsigned"?this.readInputValue=(o,c)=>o.getUint16(c,a)-2**15:n==="signed"?this.readInputValue=(o,c)=>o.getInt16(c,a):y(!1);break;case 3:n==="unsigned"?this.readInputValue=(o,c)=>Li(o,c,a)-2**23:n==="signed"?this.readInputValue=(o,c)=>cl(o,c,a):y(!1);break;case 4:n==="unsigned"?this.readInputValue=(o,c)=>o.getUint32(c,a)-2**31:n==="signed"?this.readInputValue=(o,c)=>o.getInt32(c,a):n==="float"?this.readInputValue=(o,c)=>o.getFloat32(c,a):y(!1);break;case 8:n==="float"?this.readInputValue=(o,c)=>o.getFloat64(c,a):y(!1);break;default:ze(s),y(!1)}switch(s){case 1:n==="ulaw"||n==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(o,c,u)=>o.setInt16(c,u,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(o,c,u)=>o.setUint8(c,u+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(o,c,u)=>o.setInt16(c,u,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(o,c,u)=>o.setInt32(c,u<<8,!0);break;case 4:this.outputSampleSize=4,n==="float"?(this.outputFormat="f32",this.writeOutputValue=(o,c,u)=>o.setFloat32(c,u,!0)):(this.outputFormat="s32",this.writeOutputValue=(o,c,u)=>o.setInt32(c,u,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(o,c,u)=>o.setFloat32(c,u,!0);break;default:ze(s),y(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=Z(e.data),i=Math.floor(e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize),n=i*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(n),a=new DataView(s);for(let l=0;l<i*this.decoderConfig.numberOfChannels;l++){const d=l*this.inputSampleSize,f=l*this.outputSampleSize,h=this.readInputValue(t,d);this.writeOutputValue(a,f,h)}const o=i/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=o)&&(this.currentTimestamp=e.timestamp);const c=this.currentTimestamp;this.currentTimestamp+=o;const u=new Te({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:c});this.onSample(u)}async flush(){}close(){}}class Of extends zc{constructor(e){if(!(e instanceof ln))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw typeof AudioDecoder>"u"?new Error(qi("AudioDecoder")):new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.");const i=await this._track.getCodec(),n=await this._track.getDecoderConfig();return y(i&&n),Me.includes(n.codec)?new Mf(e,t,n):new Df(e,t,i,n)}_createPacketSink(){return new on(this._track)}async _getPreRollDuration(){const e=await this._track.getPreRollDuration();return y(e!==null),e}async getSample(e,t={}){bt(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class hm{constructor(e){if(!(e instanceof ln))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Of(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){bt(e);const i=await this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)}buffers(e,t,i){return Ei(this._audioSampleSink.samples(e,t,i),n=>this._audioSampleToWrappedArrayBuffer(n))}buffersAtTimestamps(e,t){return Ei(this._audioSampleSink.samplesAtTimestamps(e,t),i=>i&&this._audioSampleToWrappedArrayBuffer(i))}}/*!
278
+ * Copyright (c) 2026-present, Vanilagy and contributors
279
+ *
280
+ * This Source Code Form is subject to the terms of the Mozilla Public
281
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
282
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
283
+ */class hi{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof cn}isAudioTrack(){return this instanceof ln}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return de(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return de(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return de(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return de(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 de(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){const e=await this._backing.getFirstPacket({metadataOnly:!0});return(e==null?void 0:e.timestamp)??0}async computeDuration(e){const t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e}),i=((t==null?void 0:t.timestamp)??0)+((t==null?void 0:t.duration)??0);return _i(i,await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){const i=new on(this);let n=1/0,s=-1/0,a=0,o=0;for await(const c of i.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&c.timestamp>=s)break;n=Math.min(n,c.timestamp),s=Math.max(s,c.timestamp+c.duration),a++,o+=c.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(s-n)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(s-n)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof hi))throw new TypeError("other must be an InputTrack.");return this.input!==e.input||this===e?!1:(this._backing.getPairingMask()&e._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(Nt({filter:t=>t.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(Nt({filter:t=>t.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(Nt({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(Nt({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(Nt({filter:t=>t.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&(e=vn(e));const t=await this.input.getTracks();for(const i of t)if(this.canBePairedWith(i)&&(!e||await e(i)))return!0;return!1}hasPairableVideoTrack(e){return e&&(e=vn(e)),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&(e=vn(e)),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const de=(r,e,t)=>{if(F(r))throw new Error(`'${e}' is deprecated and not available synchronously for this track. Use the preferred '${t}()' instead.`);return r},vn=r=>{if(r!==void 0&&typeof r!="function")throw new TypeError("predicate, when provided, must be a function.");return r?e=>{const t=n=>{if(typeof n!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return n},i=r(e);return F(i)?i.then(t):t(i)}:void 0};class cn extends hi{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return de(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){var e,t;return await((t=(e=this._backing).getHasOnlyKeyPackets)==null?void 0:t.call(e))??await this._backing.getCodec()==="prores"}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return de(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return de(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getTransformationMatrix(){return this._backing.getTransformationMatrix()}async getRotation(){return gi(await this._backing.getTransformationMatrix())}get rotation(){return gi(de(this._backing.getTransformationMatrix(),"rotation","getRotation"))}async getFlip(){return lo(await this._backing.getTransformationMatrix())}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return de(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return de(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=eo(await this.getSquarePixelWidth()*await this.getCodedHeight(),await this.getSquarePixelHeight()*await this.getCodedWidth()))}get pixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=eo(de(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*de(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),de(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*de(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")))}async getDisplayWidth(){var i,n;const e=await((n=(i=this._backing).getMetadataDisplayWidth)==null?void 0:n.call(i));return e??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){var n,s;const e=(s=(n=this._backing).getMetadataDisplayWidth)==null?void 0:s.call(n);if(e!==void 0){const a=de(e,"displayWidth","getDisplayWidth");if(a!==null)return a}const i=gi(de(this._backing.getTransformationMatrix(),"displayWidth","getDisplayWidth"))%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return de(i,"displayWidth","getDisplayWidth")}async getDisplayHeight(){var i,n;const e=await((n=(i=this._backing).getMetadataDisplayHeight)==null?void 0:n.call(i));return e??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){var n,s;const e=(s=(n=this._backing).getMetadataDisplayHeight)==null?void 0:s.call(n);if(e!==void 0){const a=de(e,"displayHeight","getDisplayHeight");if(a!==null)return a}const i=gi(de(this._backing.getTransformationMatrix(),"displayHeight","getDisplayHeight"))%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return de(i,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pq"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){var i,n;const e=await((n=(i=this._backing).getMetadataCodecParameterString)==null?void 0:n.call(i));if(e!=null)return e;const t=await this._backing.getDecoderConfig();return(t==null?void 0:t.codec)??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();return y(t!==null),ii.some(n=>n.supports(t,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return j._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ce))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const t=await this.getCodec();if(t===null)return null;const i=await this.getDecoderConfig();return y(i),tn(t,i,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.targetPacketCount!==void 0&&(!Ht(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");const t=await this.getTimeResolution(),i=e.targetPacketCount??256,n=new on(this),s=[];let a=-1/0,o=0;for await(const C of n.packets(void 0,void 0,{metadataOnly:!0})){if(s.length>=i&&C.timestamp>=a)break;s.push(C.timestamp),a=Math.max(a,C.timestamp),o++}const c=new Float64Array(s.length);for(let C=0;C<s.length;C++)c[C]=Math.round(s[C]*t);c.sort();let u=1;for(let C=1;C<c.length;C++)c[C]!==c[u-1]&&(c[u++]=c[C]);if(u<2)return{underlyingFrameRate:null,bestGuessFrameRate:t,minFrameRate:t,maxFrameRate:t,averageFrameRate:t,medianFrameRate:t,frameRateIsConstant:!0,probedPacketCount:o};const l=c.subarray(0,u),d=Nf(l,t),f=d??t,h=d!==null?t/d:null,p=new Map;let m=1/0,b=-1/0,w=0;for(let C=1;C<u;C++){const _=l[C]-l[C-1],D=h!==null?Math.max(1,Math.round(_/h)):_;p.set(D,(p.get(D)??0)+1),m=Math.min(m,D),b=Math.max(b,D),w+=D}const S=u-1,A=[...p.keys()].sort((C,_)=>C-_),T=S-1>>1,k=S>>1;let x=0,P=0,I=0;for(const C of A)if(I+=p.get(C),x===0&&I>T&&(x=C),I>k){P=C;break}const E=(f/x+f/P)/2;return{underlyingFrameRate:d,bestGuessFrameRate:d!==null?d:zf(E),minFrameRate:f/b,maxFrameRate:f/m,averageFrameRate:f*S/w,medianFrameRate:E,frameRateIsConstant:d!==null&&m===1&&b===1,probedPacketCount:o}}}const eo=(r,e)=>r===0||e===0?{num:1,den:1}:ps({num:r,den:e});class ln extends hi{constructor(e,t){super(e,t)}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return de(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){var t,i;const e=await this._backing.getCodec();return await((i=(t=this._backing).getHasOnlyKeyPackets)==null?void 0:i.call(t))??(e===null||!jc.includes(e))}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return de(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return de(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){var i,n;const e=await((n=(i=this._backing).getMetadataCodecParameterString)==null?void 0:n.call(i));if(e!=null)return e;const t=await this._backing.getDecoderConfig();return(t==null?void 0:t.codec)??null}async getPreRollDuration(){const e=await this._backing.getCodec();if(e===null)return null;const t=await this._backing.getDecoderConfig();return y(t),ch(e,t)}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();return y(t!==null),ni.some(i=>i.supports(t,e))||Me.includes(e.codec)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return j._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ce))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const t=await this.getCodec();return t===null?null:Zl(t,e.data)}}const mm=r=>r??1/0,to=r=>-(r??-1/0),Vr=r=>-r,Lr=r=>{if(typeof r!="object"||!r)throw new TypeError("query must be an object.");if(r.filter!==void 0&&typeof r.filter!="function")throw new TypeError("query.filter, when provided, must be a function.");if(r.sortBy!==void 0&&typeof r.sortBy!="function")throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:r.filter?e=>{const t=n=>{if(typeof n!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return n},i=r.filter(e);return F(i)?i.then(t):t(i)}:void 0,sortBy:r.sortBy?e=>{const t=n=>{if(typeof n!="number"&&(!Array.isArray(n)||!n.every(s=>typeof s=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return n},i=r.sortBy(e);return F(i)?i.then(t):t(i)}:void 0}},Nt=(r,e)=>({filter:r!=null&&r.filter||e!=null&&e.filter?t=>{var s;const i=((s=r==null?void 0:r.filter)==null?void 0:s.call(r,t))??!0,n=a=>{var o;return a===!1?!1:((o=e==null?void 0:e.filter)==null?void 0:o.call(e,t))??!0};return F(i)?i.then(n):n(i)}:void 0,sortBy:r!=null&&r.sortBy||e!=null&&e.sortBy?t=>{var a,o;const i=((a=r==null?void 0:r.sortBy)==null?void 0:a.call(r,t))??[],n=((o=e==null?void 0:e.sortBy)==null?void 0:o.call(e,t))??[],s=(c,u)=>[...Array.isArray(c)?c:[c],...Array.isArray(u)?u:[u]];return F(i)||F(n)?Promise.all([i,n]).then(([c,u])=>s(c,u)):s(i,n)}:void 0}),Rn=async(r,e)=>{let t=r;if(e!=null&&e.filter){const a=r.map(c=>e.filter(c));if(a.some(c=>F(c))){const c=await Promise.all(a);t=r.filter((u,l)=>c[l])}else t=r.filter((c,u)=>a[u])}if(!(e!=null&&e.sortBy))return t;const i=t.map(a=>e.sortBy(a)),s=i.some(a=>F(a))?await Promise.all(i):i;return t.map((a,o)=>({track:a,sortValue:s[o]})).sort((a,o)=>{const c=Array.isArray(a.sortValue)?a.sortValue:[a.sortValue],u=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],l=Math.max(c.length,u.length);for(let d=0;d<l;d++){const f=c[d]??0,h=u[d]??0;if(f!==h)return f-h}return 0}).map(a=>a.track)},Nf=(r,e)=>{const n=1.000000001,s=1e3,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(r.length<2)return null;const o=new Float64Array(r.length-1);for(let P=1;P<r.length;P++){const I=r[P]-r[P-1];if(!(I>0))return null;o[P-1]=I}const c=o.slice();c.sort();let u=c[Math.floor(c.length*.05)];for(let P=0;P<6;P++){let I=0,E=0;for(const _ of o){const D=Math.max(1,Math.round(_/u));Math.abs(_-D*u)>=n||(I+=_,E+=D)}if(E===0)return null;const C=I/E;if(Math.abs(C-u)<=1e-12*Math.max(1,u)){u=C;break}u=C}let l=0,d=0,f=0;for(const P of o){const I=Math.max(1,Math.round(P/u));Math.abs(P-I*u)>=n||(l++,d+=P,f+=I)}if(l/o.length<.98)return null;u=d/f;const h=1/Math.min(f,s),p=Math.max(Number.EPSILON,u-h),m=u+h,b=e/m,w=e/p,S=e/u;let A=null,T=1/0;for(const P of a){if(P<b||P>w)continue;const I=Math.abs(P/S-1);I<T&&(A=P,T=I)}if(A===null){const P=ro(p,m,1e6),I=ro(b,w,1e6);if(I&&(!P||I.den<P.den||I.den===P.den&&I.num<=P.num))A=I.num/I.den;else if(P)A=e*P.den/P.num;else return null}const k=e/A;let x=0;for(const P of o){const I=Math.max(1,Math.round(P/k));Math.abs(P-I*k)<n&&x++}return x/o.length<.98?null:A},ro=(r,e,t)=>{for(let i=1;i<=t;i++){const n=Math.floor(r*i)+1;if(n/i<e)return ps({num:n,den:i})}return null},zf=r=>{const e=[23.976023976023978,29.970029970029973,59.940059940059946,119.88011988011989],t=[12,15,20,24,25,30,48,50,60,100,120,144,240],i=5e-4,n=.025;for(const o of e)if(Math.abs(o/r-1)<=i)return o;let s=r,a=1/0;for(const o of t){const c=Math.abs(o/r-1);c<=n&&c<a&&(s=o,a=c)}return s};/*!
284
+ * Copyright (c) 2026-present, Vanilagy and contributors
285
+ *
286
+ * This Source Code Form is subject to the terms of the Mozilla Public
287
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
288
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
289
+ */ms();const Uf=1,Vf=2;class Ms extends bs{get disposed(){return this._disposed}constructor(e){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(t=>!(t instanceof ot)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Xe||e.source instanceof Rs))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof Xe&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof Ms))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&_f(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof Xe?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){y(this._rootSource instanceof jt);const t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=Uf){const i=this._sourceCache.find(a=>a.cacheGroup===t&&Ha(a.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const n=this._sourceCachePromises.find(a=>a.cacheGroup===t&&Ha(a.request,e));if(n)return n.promise.then(a=>a.sourceRef.source.ref());const s=(async()=>{const a=await this._getSourceUncached(e);if(this._disposed)throw a.free(),new Ce;if(qr(this._sourceCache,d=>d.cacheGroup===t&&d.sourceRef.source._refCount===1)>=4){const d=Hi(this._sourceCache,h=>h.cacheGroup===t&&h.sourceRef.source._refCount===1?h.age:1/0);y(d!==-1);const f=this._sourceCache[d];this._sourceCache.splice(d,1),f.sourceRef.free(),Ci(this._sourceRefs,f.sourceRef)}this._sourceRefs.push(a);const u=this._sourceCachePromises.findIndex(d=>d.request===e);return y(u!==-1),this._sourceCachePromises.splice(u,1),{request:e,sourceRef:a,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:s}),s.then(a=>{const o=a.sourceRef.source.ref();return this._sourceCache.push(a),o})}_getDemuxer(){return this._demuxerPromise??(this._demuxerPromise=(async()=>{var e;this._reader=new xi(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(const t of this._formats)if(await t._canReadInput(this))return this._format=t,(e=this._onFormatDetermined)==null||e.call(this,t),t._createDemuxer(this);throw new io})())}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),y(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof io)return!1;throw e}}async getFirstTimestamp(e){e??(e=await this.getTracks());const t=e.filter(s=>s!==null);if(t.length===0)return 0;const i=await Promise.all(t.map(s=>s._backing.getFirstPacket({metadataOnly:!0}))),n=Math.min(...i.map(s=>(s==null?void 0:s.timestamp)??1/0));return n===1/0?0:n}async computeDuration(e,t){e??(e=await this.getTracks());const i=e.filter(s=>s!==null);if(i.length===0)return 0;const n=await Promise.all(i.map(s=>s.computeDuration(t)));return Math.max(...n)}async getDurationFromMetadata(e,t){e??(e=await this.getTracks());const i=e.filter(a=>a!==null),s=(await Promise.all(i.map(a=>a.getDurationFromMetadata(t)))).filter(a=>a!==null);return s.length===0?null:Math.max(...s)}async getTracks(e){e&&(e=Lr(e));const i=(await this._getTrackBackings()).map(n=>this._wrapBackingAsTrack(n));return Rn(i,e)}async getVideoTracks(e){e&&(e=Lr(e));const i=(await this.getTracks()).filter(n=>n.isVideoTrack());return Rn(i,e)}async getAudioTracks(e){e&&(e=Lr(e));const i=(await this.getTracks()).filter(n=>n.isAudioTrack());return Rn(i,e)}async getPrimaryVideoTrack(e){e&&(e=Lr(e));const t=Nt(e,{sortBy:async n=>[Vr((await n.getDisposition()).default),Vr(await n.hasPairableAudioTrack()),Vr(!await n.hasOnlyKeyPackets()),to(await n.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&(e=Lr(e));const t=await this.getPrimaryVideoTrack(),i=Nt(e,{sortBy:async s=>[Vr(!t||s.canBePairedWith(t)),Vr((await s.getDisposition()).default),to(await s.getBitrate())]});return(await this.getAudioTracks(i))[0]??null}async _getTrackBackings(){const e=await this._getDemuxer();return this._trackBackingsCache??(this._trackBackingsCache=await e.getTrackBackings())}_wrapBackingAsTrack(e){const t=this._backingToTrack.get(e);if(t)return t;const n=e.getType()==="video"?new cn(this,e):new ln(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(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}}class io extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class Ce extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}/*!
290
+ * Copyright (c) 2026-present, Vanilagy and contributors
291
+ *
292
+ * This Source Code Form is subject to the terms of the Mozilla Public
293
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
294
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
295
+ */class xi{constructor(e){this.source=e}get fileSize(){const e=this.source._getFileSize();if(e===void 0)throw new 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 Ce;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){const s=new Uint8Array(0);return new Ke(s,Z(s),0,e,e)}const i=e+t,n=this.source._read(e,i,yc,Sc);return F(n)?n.then(s=>s?new Ke(s.bytes,s.view,s.offset,e,i):null):n?new Ke(n.bytes,n.view,n.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new Ce;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,pe(this.fileSizeNonStrict-e,t,i));{const n=this.requestSlice(e,i),s=a=>a||(y(this.fileSizeNonStrict!==null),this.requestSlice(e,pe(this.fileSizeNonStrict-e,t,i)));return F(n)?n.then(s):s(n)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);const e=1024;return(async()=>{const t=[];let i=0;for(;;){if(t.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let a=this.requestSliceRange(i,0,e);if(F(a)&&(a=await a),!a||a.length===0)break;const o=X(a,a.length);t.push(o),i+=a.length}const n=new Uint8Array(i);let s=0;for(const a of t)n.set(a,s),s+=a.length;return new Ke(n,Z(n),0,0,i)})()}}class Ke{constructor(e,t,i,n,s){this.bytes=e,this.view=t,this.offset=i,this.start=n,this.end=s,this.bufferPos=n-i}static tempFromBytes(e){return new Ke(e,Z(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new Ke(this.bytes,this.view,this.offset,e,e+t)}}const Ue=(r,e)=>{if(e<0||r.filePos<r.start||r.filePos+e>r.end)throw new RangeError(`Tried reading [${r.filePos}, ${r.filePos+e}), but slice is [${r.start}, ${r.end}). This is likely an internal error, please report it alongside the file that caused it.`)},X=(r,e)=>{Ue(r,e);const t=r.bytes.subarray(r.bufferPos,r.bufferPos+e);return r.bufferPos+=e,t},K=r=>(Ue(r,1),r.view.getUint8(r.bufferPos++)),Wr=(r,e)=>{Ue(r,2);const t=r.view.getUint16(r.bufferPos,e);return r.bufferPos+=2,t},we=r=>{Ue(r,2);const e=r.view.getUint16(r.bufferPos,!1);return r.bufferPos+=2,e},dt=r=>{Ue(r,3);const e=Li(r.view,r.bufferPos,!1);return r.bufferPos+=3,e},cs=r=>{Ue(r,2);const e=r.view.getInt16(r.bufferPos,!1);return r.bufferPos+=2,e},Ct=(r,e)=>{Ue(r,4);const t=r.view.getUint32(r.bufferPos,e);return r.bufferPos+=4,t},U=r=>{Ue(r,4);const e=r.view.getUint32(r.bufferPos,!1);return r.bufferPos+=4,e},Ut=r=>{Ue(r,4);const e=r.view.getUint32(r.bufferPos,!0);return r.bufferPos+=4,e},Vt=r=>{Ue(r,4);const e=r.view.getInt32(r.bufferPos,!1);return r.bufferPos+=4,e},Lf=r=>{Ue(r,4);const e=r.view.getInt32(r.bufferPos,!0);return r.bufferPos+=4,e},no=(r,e)=>{let t,i;return e?(t=Ct(r,!0),i=Ct(r,!0)):(i=Ct(r,!1),t=Ct(r,!1)),i*4294967296+t},Oe=r=>{const e=U(r),t=U(r);return e*4294967296+t},Wf=r=>{const e=Vt(r),t=U(r);return e*4294967296+t},qf=r=>{const e=Ut(r);return Lf(r)*4294967296+e},Hf=r=>{Ue(r,4);const e=r.view.getFloat32(r.bufferPos,!1);return r.bufferPos+=4,e},Vc=r=>{Ue(r,8);const e=r.view.getFloat64(r.bufferPos,!1);return r.bufferPos+=8,e},be=(r,e)=>{Ue(r,e);let t="";for(let i=0;i<e;i++)t+=String.fromCharCode(r.bytes[r.bufferPos++]);return t},Lc=(r,e,t)=>_e.decode(X(r,e)).split(`
296
+ `).map(s=>s.trim()).filter(s=>{var a;return s.length>0&&!((a=t==null?void 0:t.ignore)!=null&&a.call(t,s))});/*!
297
+ * Copyright (c) 2026-present, Vanilagy and contributors
298
+ *
299
+ * This Source Code Form is subject to the terms of the Mozilla Public
300
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
301
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
302
+ */const ir=8,Kr=16,Tt=r=>{let e=U(r);const t=be(r,4);let i=8;e===1&&(e=Oe(r),i=16);const s=e-i;return s<0?null:{name:t,totalSize:e,headerSize:i,contentSize:s}},Mt=r=>Vt(r)/65536,Bn=r=>Vt(r)/1073741824,Fn=r=>{let e=0;for(let t=0;t<4;t++){e<<=7;const i=K(r);if(e|=i&127,(i&128)===0)break}return e},Wc=r=>{if(K(r)!==3)throw new Error("Invalid esds: expected ES_Descriptor.");Fn(r),r.skip(2);const t=K(r),i=(t&128)!==0,n=(t&64)!==0,s=(t&32)!==0;if(i&&r.skip(2),n){const d=K(r);r.skip(d)}if(s&&r.skip(2),K(r)!==4)throw new Error("Invalid esds: expected DecoderConfigDescriptor.");const o=Fn(r),c=r.filePos,u=K(r);r.skip(12);let l=null;if(o>r.filePos-c){if(K(r)!==5)throw new Error("Invalid esds: expected DecoderSpecificInfo.");const f=Fn(r);l=X(r,f)}return{objectTypeIndication:u,decoderSpecificInfo:l}},tt=r=>{let e=we(r);return r.skip(2),e=Math.min(e,r.remainingLength),_e.decode(X(r,e))},jf=r=>{const e=Tt(r);if(!e||e.name!=="data"||e.contentSize<8||r.remainingLength<8)return null;const t=U(r);r.skip(4);const i=X(r,e.contentSize-8);switch(t){case 1:return _e.decode(i);case 2:return new Qr("utf-16be").decode(i);case 13:return new Gr(i,"image/jpeg");case 14:return new Gr(i,"image/png");case 27:return new Gr(i,"image/bmp");default:return i}};/*!
303
+ * Copyright (c) 2026-present, Vanilagy and contributors
304
+ *
305
+ * This Source Code Form is subject to the terms of the Mozilla Public
306
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
307
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
308
+ */var Kf=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,n;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],t&&(n=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");n&&(i=function(){try{n.call(this)}catch(s){return Promise.reject(s)}}),r.stack.push({value:e,dispose:i,async:t})}else t&&r.stack.push({async:!0});return e},Xf=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var i,n=0;function s(){for(;i=e.stack.pop();)try{if(!i.async&&n===1)return n=0,e.stack.push(i),Promise.resolve().then(s);if(i.dispose){var a=i.dispose.call(i.value);if(i.async)return n|=2,Promise.resolve(a).then(s,function(o){return t(o),s()})}else n|=1}catch(o){t(o)}if(n===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=r,i.suppressed=e,i});class Os{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._nominalBitrate=null}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;const e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??(this._closingPromise=(async()=>{await this._flushAndClose(e),this._closed=!0})())}}class un extends Os{constructor(e){if(super(),!Qe.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${Qe.join(", ")}.`);this._codec=e}}const ls=(r,e)=>{if(r.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")};class pm extends un{constructor(e){super(e)}add(e,t){if(!(e instanceof ce))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),ls(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}}class Ns{setError(e){this.errorSet||(this.error=e,this.errorSet=!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=-1,this.emittedEncoderPackets=0,this.chunkTimestampsAreShiftedByDuration=!1,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new Wi,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,t,i){var s,a,o,c,u,l,d,f,h,p,m,b,w,S;const n=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();const A=this.encodingConfig,T=A.sizeChangeBehavior??"deny";let k=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(k=!0,T==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(((s=A.transform)==null?void 0:s.width)!==void 0||((a=A.transform)==null?void 0:a.height)!==void 0||((o=A.transform)==null?void 0:o.rotate)!==void 0||((c=A.transform)==null?void 0:c.flip)!==void 0||((u=A.transform)==null?void 0:u.crop)!==void 0||((l=A.transform)==null?void 0:l.force)===!0||k&&T!=="passThrough"){let E=(d=A.transform)==null?void 0:d.width,C=(f=A.transform)==null?void 0:f.height,_=((h=A.transform)==null?void 0:h.fit)??"fill";k&&T!=="passThrough"&&(y(this.outputWidth),y(this.outputHeight),y(T!=="deny"),E=this.outputWidth,C=this.outputHeight,_=T);const D=await e.transform({width:E,height:C,roundDimensionsTo:2,crop:(p=A.transform)==null?void 0:p.crop,rotate:(m=A.transform)==null?void 0:m.rotate,flip:(b=A.transform)==null?void 0:b.flip,fit:_,alpha:A.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=D.displayWidth,this.outputHeight=D.displayHeight),t&&e.close(),e=D,t=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);const I=(w=A.transform)==null?void 0:w.frameRate;if(I!==void 0){const E=e.timestamp+e.duration,C=Ks(e.timestamp,I);if(this.frameRateLastSample!==null)if(C<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=E;return}else await this.padFrameRate(C,i);e===n&&(e=e.clone(),t=!0),e.setTimestamp(C),e.setDuration(1/I),(S=this.frameRateLastSample)==null||S.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=C,this.frameRateLastEndTimestamp=E}await this.processAndEncode(e,i)}finally{t&&e.close()}}async processAndEncode(e,t){var s,a,o;const i=this.encodingConfig;let n;if((s=i.transform)!=null&&s.process){let c=i.transform.process(e);if(F(c)&&(c=await c),c===null)return;Array.isArray(c)||(c=[c]);const u=[];try{for(const l of c)l instanceof Ie?u.push(l):typeof VideoFrame<"u"&&l instanceof VideoFrame?u.push(new Ie(l)):u.push(new Ie(l,{timestamp:e.timestamp,duration:e.duration}))}catch(l){for(const d of u)d!==e&&d.close();for(const d of c)(d instanceof Ie&&d!==e||typeof VideoFrame<"u"&&d instanceof VideoFrame)&&d.close();throw l}n=u}else n=[e];try{for(const c of n){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(c),this.encoderInitialized||await this.ensureEncoderPromise),y(this.encoderInitialized),this.closed)break;this.encodersReclaimed&&this.recreateWebCodecsEncoders();const u=this.encodingConfig.keyFrameInterval??2,l=Math.floor(c.timestamp/u),d={...this.defaultEncodeOptions,...c.encodeOptions,...t},f={...d,keyFrame:d.keyFrame!==void 0?d.keyFrame:u===0||l!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=l,(o=(a=this.encodingConfig).onEncodedSample)==null||o.call(a,c),this.customEncoder){this.customEncoderQueueSize++;const h=c.clone(),p=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(h,f)).catch(m=>this.setError(m)).finally(()=>{this.customEncoderQueueSize--,h.close()});this.customEncoderQueueSize>=4&&await p}else{y(this.encoder);const h=c.toVideoFrame(),p=te(this.preciseTimings,h.timestamp,b=>b.microsecondTimestamp),m=p!==-1?this.preciseTimings[p]:null;if(m&&m.microsecondTimestamp===h.timestamp?(m.timestamp!==c.timestamp&&(m.timestampIsValid=!1),m.duration!==c.duration&&(m.durationIsValid=!1)):(this.preciseTimings.splice(p+1,0,{microsecondTimestamp:h.timestamp,timestamp:c.timestamp,duration:c.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(!!h.format&&!h.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(h,f)}finally{h.close()}}else{this.splitter||(this.splitter=new $f);const{colorFrame:w,alphaFrame:S}=await this.splitter.split(h);this.alphaFrameQueue.push(S);try{this.encoder.encode(w,f)}finally{w.close()}}else try{this.encoder.encode(h,f)}finally{h.close()}this.encoder.encodeQueueSize>=4&&await new Promise(b=>this.encoder.addEventListener("dequeue",b,{once:!0}))}await this.lastMuxerPromise}}finally{for(const c of n)c!==e&&c.close()}}async padFrameRate(e,t){const i=this.encodingConfig.transform.frameRate;y(this.frameRateLastSample);const n=Math.round((e-this.frameRateLastTimestamp)*i);for(let s=1;s<n;s++){const a={stack:[],error:void 0,hasError:!1};try{const o=Kf(a,this.frameRateLastSample.clone(),!1);o.setTimestamp(this.frameRateLastTimestamp+s/i),o.setDuration(1/i),await this.processAndEncode(o,t)}catch(o){a.error=o,a.hasError=!0}finally{Xf(a)}}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{var o,c,u;const t=nn(this.encodingConfig.quality,this.encodingConfig.bitrate);y(t!==void 0);const i=Ho({...this.encodingConfig,quality:t,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:(o=this.source._connectedTrack)==null?void 0:o.metadata.frameRate});let n=null,s;for(const l of i){const d=l.config;if((u=(c=this.encodingConfig).onEncoderConfig)==null||u.call(c,d),s=Di.find(h=>h.supports(this.encodingConfig.codec,d)),s){n=l;break}if(typeof VideoEncoder>"u")continue;if(d.alpha="discard",this.encodingConfig.alpha==="keep"&&(d.latencyMode="quality"),(d.width%2===1||d.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${d.width}x${d.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(d)).supported){n=l;break}}catch{}}if(!n){if(typeof VideoEncoder>"u")throw new Error(qi("VideoEncoder"));const l=i[0].config,d=i.map(({config:f,quantizer:h})=>h!==null?`quantizer ${h}`:`${f.bitrate} bps`);throw new Error(`This specific encoder configuration (${l.codec}, ${d.join(" / ")}, ${l.width}x${l.height}, hardware acceleration: ${l.hardwareAcceleration??"no-preference"}) is not supported in this environment. Consider using another codec or changing your video parameters.`)}const a=n.config;n.quantizer!==null?this.defaultEncodeOptions=Xo(this.encodingConfig.codec,n.quantizer):this.source._nominalBitrate=a.bitrate??null,s?(this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=a,this.customEncoder.onPacket=(l,d)=>{var f,h;if(!(l instanceof ce))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(d!==void 0&&(!d||typeof d!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");ls(this.source._connectedTrack,l),(h=(f=this.encodingConfig).onEncodedPacket)==null||h.call(f,l,d),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,l,d).catch(p=>{this.setError(p)})},this.customEncoder.onError=l=>{this.setError(l)},await this.customEncoder.init()):(this.encoderConfig=a,this.encodingConfig.codec==="avc"&&Wt()&&(this.chunkTimestampsAreShiftedByDuration=await Gf()),this.createWebCodecsEncoders()),y(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}createWebCodecsEncoders(){const e=this.encoderConfig;y(e);const t=[],i=[];let n=0,s=0;const a=(c,u)=>{if(gl(c)){this.encodersReclaimed=!0;return}c.stack=u,this.setError(c)},o=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(c,u)=>{if(!this.alphaEncoder){this.addPacket(c,null,u);return}const l=this.alphaFrameQueue.shift();y(l!==void 0),l?(this.alphaEncoder.encode(l,{...this.defaultEncodeOptions,keyFrame:c.type==="key"}),s++,l.close(),t.push({chunk:c,meta:u})):s===0?this.addPacket(c,null,u):(i.push(n+s),t.push({chunk:c,meta:u}))},error:c=>a(c,o)}),this.encoder.configure(e),this.encodingConfig.alpha==="keep"){const c=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(u,l)=>{s--;const d=t.shift();for(y(d!==void 0),this.addPacket(d.chunk,u,d.meta),n++;i.length>0&&i[0]===n;){i.shift();const f=t.shift();y(f!==void 0),this.addPacket(f.chunk,null,f.meta)}},error:u=>a(u,c)}),this.alphaEncoder.configure(e)}}addPacket(e,t,i){var d,f;const n={};if(t){const h=new Uint8Array(t.byteLength);t.copyTo(h),n.alpha=h}let s=ce.fromEncodedChunk(e,n);const a=this.encoderConfig;if(y(a),i!=null&&i.decoderConfig&&(i.decoderConfig.codec=fn({width:a.width,height:a.height,codec:this.encodingConfig.codec,codecDescription:i.decoderConfig.description?ke(i.decoderConfig.description):null,colorSpace:i.decoderConfig.colorSpace??null,avcType:a.codec.includes("avc1.")?1:a.codec.includes("avc3.")?3:null,avcCodecInfo:this.encodingConfig.codec==="avc"&&!i.decoderConfig.description?$i(s.data):null,hevcCodecInfo:this.encodingConfig.codec==="hevc"&&!i.decoderConfig.description?Ji(s.data):null,vp9CodecInfo:this.encodingConfig.codec==="vp9"?ks(s.data):null,av1CodecInfo:this.encodingConfig.codec==="av1"?en(s.data):null,proresFormat:null}),this.encodingConfig.codec==="avc"&&i.decoderConfig.description&&Wt())){const h=Yi(ke(i.decoderConfig.description));let p=h==null?void 0:h.sequenceParameterSets[0];if(p&&p[0]===p[1]){y(h),p=p.subarray(1);let m=h.pictureParameterSets[0];m&&(m=m.subarray(1));const b=Io({...h,sequenceParameterSets:[p],pictureParameterSets:m?[m]:[]});i.decoderConfig.description=b}}let o=e.timestamp;this.chunkTimestampsAreShiftedByDuration&&(o-=e.duration??0,s=s.clone({timestamp:o/1e6}));const c=te(this.preciseTimings,o,h=>h.microsecondTimestamp),u=c!==-1?this.preciseTimings[c]:null;let l=null;this.emittedEncoderPackets===0&&s.type==="delta"&&(i!=null&&i.decoderConfig)&&(l=tn(this.encodingConfig.codec,i.decoderConfig,s.data)),(u&&u.microsecondTimestamp===o||l!==null)&&(s=s.clone({timestamp:u!=null&&u.timestampIsValid?u.timestamp:void 0,duration:u!=null&&u.durationIsValid?u.duration:void 0,type:l??void 0})),ls(this.source._connectedTrack,s),(f=(d=this.encodingConfig).onEncodedPacket)==null||f.call(d,s,i),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,s,i).catch(h=>{this.setError(h)}),this.emittedEncoderPackets++}recreateWebCodecsEncoders(){y(this.encoder),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e==null?void 0:e.close()),this.alphaFrameQueue.length=0,this.encodersReclaimed=!1,this.lastMultipleOfKeyFrameInterval=-1,this.createWebCodecsEncoders()}async flushAndClose(e){var t,i,n;try{if(!e&&(this.checkForEncoderError(),this.frameRateLastSample)){const s=this.encodingConfig.transform.frameRate,a=Ks(this.frameRateLastEndTimestamp,s);await this.padFrameRate(a)}this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&!this.encodersReclaimed&&(await this.encoder.flush(),await((t=this.alphaEncoder)==null?void 0:t.flush()),await ar(25)))}finally{this.closed=!0,(i=this.frameRateLastSample)==null||i.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(s=>this.setError(s)):this.encoder&&(this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(s=>s==null?void 0:s.close()),this.alphaFrameQueue.length=0,(n=this.splitter)==null||n.close())}e||this.checkForEncoderError()}getQueueSize(){var e;return this.customEncoder?this.customEncoderQueueSize:((e=this.encoder)==null?void 0:e.encodeQueueSize)??0}checkForEncoderError(){if(this.errorSet)throw this.error}}let Qf=null;const Gf=()=>Qf??(Qf=(async()=>{let r=null;const e=new VideoEncoder({output:t=>{r??(r=t.timestamp)},error:()=>{}});try{e.configure({codec:"avc1.64001f",width:1280,height:720});const t=new VideoFrame(new Uint8Array(1280*720*1.5),{format:"I420",codedWidth:1280,codedHeight:720,timestamp:0,duration:500});e.encode(t,{keyFrame:!0}),t.close(),await e.flush()}catch{return!1}finally{e.state!=="closed"&&e.close()}return r===500})());let Dn=null;class $f{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!Dn){const n=new Blob([`(${Yf.toString()})()`],{type:"application/javascript"});Dn=URL.createObjectURL(n)}this.worker=new Worker(Dn),this.worker.addEventListener("message",n=>{const s=n.data,a=this.pendingRequests.get(s.id);a&&(this.pendingRequests.delete(s.id),"error"in s?a.reject(new Error(s.error)):a.resolve({colorFrame:s.colorFrame,alphaFrame:s.alphaFrame}))}),this.worker.addEventListener("error",n=>{const s=new Error(n.message||"Color/alpha splitter worker error.");for(const a of this.pendingRequests.values())a.reject(s);this.pendingRequests.clear()})}const t=this.nextRequestId++,i=Se();return this.pendingRequests.set(t,i),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),i.promise}close(){var t;(t=this.worker)==null||t.terminate(),this.worker=null;const e=new Error("Color/alpha splitter closed.");for(const i of this.pendingRequests.values())i.reject(e);this.pendingRequests.clear()}}const Yf=()=>{let r=null,e=Promise.resolve();self.addEventListener("message",s=>{const{id:a,sourceFrame:o}=s.data;e=e.then(async()=>{try{const{colorFrame:c,alphaFrame:u}=await t(o);self.postMessage({id:a,colorFrame:c,alphaFrame:u},{transfer:[c,u]})}catch(c){self.postMessage({id:a,error:c.message})}finally{o.close()}})});const t=async s=>{const a=s.format;if(!a)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");const o=s.allocationSize();if((!r||r.byteLength!==o)&&(r=new Uint8Array(o)),await s.copyTo(r),a==="RGBA"||a==="BGRA")return i(r,a,s);if(a==="I420A"||a==="I420AP10"||a==="I420AP12"||a==="I422A"||a==="I422AP10"||a==="I422AP12"||a==="I444A"||a==="I444AP10"||a==="I444AP12")return n(r,a,s);throw new Error(`CPU color/alpha splitting does not support format '${a}'.`)},i=(s,a,o)=>{var S,A;const c=((S=o.visibleRect)==null?void 0:S.width)??o.codedWidth,u=((A=o.visibleRect)==null?void 0:A.height)??o.codedHeight,l=c*u,d=Math.ceil(c/2),f=Math.ceil(u/2),h=l+d*f*2,p=new Uint8Array(h);for(let T=0,k=3;T<l;T++,k+=4)p[T]=s[k];p.fill(128,l);const m=new VideoFrame(s,{format:a==="RGBA"?"RGBX":"BGRX",codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0}),b={format:"I420",codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[p.buffer]},w=new VideoFrame(p,b);return{colorFrame:m,alphaFrame:w}},n=(s,a,o)=>{var he,le;const c=((he=o.visibleRect)==null?void 0:he.width)??o.codedWidth,u=((le=o.visibleRect)==null?void 0:le.height)??o.codedHeight,l=a.includes("P10"),d=a.includes("P12"),f=l||d?2:1;let h,p;a.startsWith("I420")?(h=Math.ceil(c/2),p=Math.ceil(u/2)):a.startsWith("I422")?(h=Math.ceil(c/2),p=u):(h=c,p=u);const m=c*u,b=h*p,w=m*f,S=b*f,A=m*f,T=w+S*2,k=a.replace("A",""),x=Math.ceil(c/2),P=Math.ceil(u/2),I=x*P,E=I*f,C=A+2*E,_=new Uint8Array(C),D=T;_.set(s.subarray(D,D+A),0);const q=A,M=l?512:d?2048:128;f===1?_.fill(M,q):new Uint16Array(_.buffer,q,2*I).fill(M);const V=l?"I420P10":d?"I420P12":"I420",G=new VideoFrame(s.subarray(0,T),{format:k,codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0}),J={format:V,codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[_.buffer]},ae=new VideoFrame(_,J);return{colorFrame:G,alphaFrame:ae}}};class gm extends un{constructor(e){Ts(e),super(e.codec),this._encoder=new Ns(this,e)}add(e,t){if(!(e instanceof Ie))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class bm extends un{constructor(e,t){if(!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");Ts(t),super(t.codec),this._encoder=new Ns(this,t),this._canvas=e}add(e,t=0,i){if(!Number.isFinite(e))throw new TypeError("timestamp must be a finite number.");if(!Number.isFinite(t)||t<0)throw new TypeError("duration must be a non-negative number.");const n=new Ie(this._canvas,{timestamp:e,duration:t});return this._encoder.add(n,!0,i)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class wm extends un{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,i={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");if(Ts(t),typeof i!="object"||!i)throw new TypeError("options must be an object.");if(i.frameRate!=null&&(typeof i.frameRate!="number"||i.frameRate<=0))throw new TypeError("options.frameRate, when provided, must be either a positive number or null.");if(i.timestampBase!==void 0&&i.timestampBase!=="synced-zero"&&i.timestampBase!=="zero"&&i.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");t={...t,latencyMode:"realtime"},super(t.codec),this._abortController=null,this._workerTrackId=null,this._workerListener=null,this._promiseWithResolvers=Se(),this._errorPromiseAccessed=!1,this._paused=!1,this._lastVideoFrame=null,this._timerHandle=null,this._videoElement=null,this._options=i,this._encoder=new Ns(this,t),this._track=e}async _start(){this._errorPromiseAccessed||j._warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");const e=this._options.frameRate!==void 0?this._options.frameRate:this._track.getSettings().frameRate??null;this._abortController=new AbortController;let t=null,i=null,n=0,s=!1,a=null,o=0;const c=()=>{if(y(e!==null),!this._lastVideoFrame)return;y(i!==null),y(t!==null);const d=performance.now();for(;d-i>1e3/e;){i+=1e3/e;const f=t+n/e,h=new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*f,duration:1e6/e});l(h,d)}};e!==null&&(this._timerHandle=Tl(c,4));const u=d=>{var f;if(e===null)l(d);else{const h=performance.now();this._lastVideoFrame?(c(),(f=this._lastVideoFrame)==null||f.close(),this._lastVideoFrame=d):(l(d.clone(),h),i=h,this._lastVideoFrame=d)}},l=(d,f=performance.now())=>{if(s){d.close();return}n++;const h=d.timestamp/1e6;if(this._paused){if(t!==null){if(a!==null&&this._options.timestampBase!=="unix"){const b=h-a;o-=b}a=h}d.close();return}if(t===null){t=h;let m;const b=this._options.timestampBase??"synced-zero";if(b==="unix")m=Date.now()/1e3;else if(b==="zero")m=0;else{const w=this._connectedTrack.output;w._firstMediaStreamTimestamp===null?(w._firstMediaStreamTimestamp=f/1e3,m=0):m=f/1e3-w._firstMediaStreamTimestamp}o=m-t}if(a=h,this._encoder.getQueueSize()>=8){d.close();return}const p=new Ie(d,{timestamp:h+o});this._encoder.add(p,!0).catch(m=>{var b;s=!0,(b=this._abortController)==null||b.abort(),this._promiseWithResolvers.reject(m),this._workerTrackId!==null&&Nn({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){const d=new MediaStreamTrackProcessor({track:this._track}),f=new WritableStream({write:u});d.readable.pipeTo(f,{signal:this._abortController.signal}).catch(h=>{h instanceof DOMException&&h.name==="AbortError"||this._promiseWithResolvers.reject(h)})}else if(await rh())this._workerTrackId=eh++,Nn({type:"videoTrack",trackId:this._workerTrackId,track:this._track}),this._workerListener=f=>{const h=f.data;h.type==="videoFrame"&&h.trackId===this._workerTrackId?u(h.videoFrame):h.type==="error"&&h.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(h.error)},Ze.addEventListener("message",this._workerListener);else if(e!==null){const f=document.createElement("video");f.style.position="fixed",f.style.left="-10000px",f.style.top="-10000px",f.style.width="1px",f.style.height="1px",f.style.opacity="0",f.style.pointerEvents="none",f.muted=!0,f.srcObject=new MediaStream([this._track]),document.body.appendChild(f),this._videoElement=f,f.addEventListener("loadeddata",()=>{if(s||!this._videoElement)return;const h=new VideoFrame(f,{timestamp:1e3*performance.now()});u(h),h.close()},{once:!0}),f.play().catch(h=>{s=!0,this._promiseWithResolvers.reject(h)})}else throw new Error("When no explicit frame rate is set, MediaStreamTrackProcessor is required; but it's not available in this environment.")}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){var t;try{this._abortController&&(this._abortController.abort(),this._abortController=null),this._timerHandle&&xl(this._timerHandle),(t=this._lastVideoFrame)==null||t.close(),this._videoElement&&(this._videoElement.srcObject=null,this._videoElement.remove(),this._videoElement=null),this._workerTrackId!==null&&(y(this._workerListener),Nn({type:"stopTrack",trackId:this._workerTrackId}),await new Promise(i=>{const n=s=>{const a=s.data;a.type==="trackStopped"&&a.trackId===this._workerTrackId&&(y(this._workerListener),Ze.removeEventListener("message",this._workerListener),Ze.removeEventListener("message",n),i())};Ze.addEventListener("message",n)}))}finally{await this._encoder.flushAndClose(e)}}}class dn extends Os{constructor(e){if(super(),!Ge.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${Ge.join(", ")}.`);this._codec=e}}class km extends dn{constructor(e){super(e)}add(e,t){if(!(e instanceof ce))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}}const Pi=2048;class zs{setError(e){this.errorSet||(this.error=e,this.errorSet=!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.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.pcmMeta=null,this.pcmStartTimestamp=0,this.pcmEmittedFrames=0,this.pcmReadBuffer=new ArrayBuffer(0),this.pcmScratchView=null,this.pcmScratchFrames=0,this.customEncoder=null,this.customEncoderCallSerializer=new Wi,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){var i,n;try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;const s=this.encodingConfig;((i=s.transform)==null?void 0:i.numberOfChannels)!==void 0||((n=s.transform)==null?void 0:n.sampleRate)!==void 0?(this.resampler||(this.resampler=new Xu({targetNumberOfChannels:s.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:s.transform.sampleRate??e.sampleRate,onSample:async o=>{await this.processAndEncode(o,!0)}})),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){var n,s;const i=this.encodingConfig;if(((n=i.transform)==null?void 0:n.sampleFormat)!==void 0&&Ou(e.format)!==i.transform.sampleFormat){const a=zu(e,i.transform.sampleFormat);t&&e.close(),e=a,t=!0}if((s=i.transform)!=null&&s.process)try{let a=i.transform.process(e);if(F(a)&&(a=await a),a===null)return;Array.isArray(a)||(a=[a]);try{for(const o of a)if(!(o instanceof Te))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");for(const o of a)await this.encodeSample(o,!0)}finally{for(const o of a)o instanceof Te&&o.close()}}finally{t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){var i,n;try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),y(this.encoderInitialized),this.closed)return;{const s=Math.round(e.timestamp*e.sampleRate),a=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=a;else{const o=s-this.lastEndSampleIndex;if(o>=64){const c=st(e.format),u=new Uint8Array(c*o*e.numberOfChannels);(e.format==="u8"||e.format==="u8-planar")&&u.fill(2**7);const l=new Te({data:u,format:e.format,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:o,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(l,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if((n=(i=this.encodingConfig).onEncodedSample)==null||n.call(i,e),this.customEncoder){this.customEncoderQueueSize++;const s=e.clone(),a=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(s)).catch(o=>this.setError(o)).finally(()=>{this.customEncoderQueueSize--,s.close()});this.customEncoderQueueSize>=4&&await a,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{y(this.encoder);const s=e.toAudioData();this.encoder.encode(s),s.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(a=>this.encoder.addEventListener("dequeue",a,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){y(this.outputSampleSize),y(this.writeOutputValue);const{numberOfChannels:i,numberOfFrames:n,sampleRate:s,timestamp:a}=e;this.pcmMeta||(this.pcmMeta={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:i,sampleRate:s}},this.pcmStartTimestamp=a);const o=e.format==="s32"||e.format==="s32-planar",c=o?"s32":"f32",u=o?1/2147483648:1,l=e.allocationSize({planeIndex:0,format:c});this.pcmReadBuffer.byteLength<l&&(this.pcmReadBuffer=new ArrayBuffer(l));const d=o?new Int32Array(this.pcmReadBuffer,0,l/4):new Float32Array(this.pcmReadBuffer,0,l/4);e.copyTo(d,{planeIndex:0,format:c}),t&&e.close();let f=0;for(;f<n;){this.pcmScratchView??(this.pcmScratchView=new DataView(new ArrayBuffer(Pi*i*this.outputSampleSize)));const h=Math.min(Pi-this.pcmScratchFrames,n-f),p=this.pcmScratchFrames*i,m=f*i;for(let b=0;b<h*i;b++)this.writeOutputValue(this.pcmScratchView,(p+b)*this.outputSampleSize,d[m+b]*u);this.pcmScratchFrames+=h,f+=h,this.pcmScratchFrames===Pi&&await this.emitPcmScratchPacket()}}async emitPcmScratchPacket(){var s,a,o;y(this.outputSampleSize),y(this.pcmScratchView),y((s=this.pcmMeta)==null?void 0:s.decoderConfig);const{numberOfChannels:e,sampleRate:t}=this.pcmMeta.decoderConfig,i=this.pcmScratchFrames*e*this.outputSampleSize,n=new ce(new Uint8Array(this.pcmScratchView.buffer,0,i),"key",this.pcmStartTimestamp+this.pcmEmittedFrames/t,this.pcmScratchFrames/t);this.pcmEmittedFrames+=this.pcmScratchFrames,this.pcmScratchView=null,this.pcmScratchFrames=0,(o=(a=this.encodingConfig).onEncodedPacket)==null||o.call(a,n,this.pcmMeta),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,n,this.pcmMeta)}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{var u,l;const{format:t,numberOfChannels:i,sampleRate:n,timestamp:s}=e,a=nn(this.encodingConfig.quality,this.encodingConfig.bitrate),o=Ko({numberOfChannels:i,sampleRate:n,...this.encodingConfig,quality:a});(l=(u=this.encodingConfig).onEncoderConfig)==null||l.call(u,o),this.source._nominalBitrate=o.bitrate??null;const c=Mi.find(d=>d.supports(this.encodingConfig.codec,o));if(c)this.customEncoder=new c,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=o,this.customEncoder.onPacket=(d,f)=>{var h,p;if(!(d instanceof ce))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(f!==void 0&&(!f||typeof f!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");(p=(h=this.encodingConfig).onEncodedPacket)==null||p.call(h,d,f),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,d,f).catch(m=>{this.setError(m)})},this.customEncoder.onError=d=>{this.setError(d)},await this.customEncoder.init();else if(Me.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error(qi("AudioEncoder"));let d;try{d=(await AudioEncoder.isConfigSupported(o)).supported??!1}catch{d=!1}if(!d)throw new Error(`This specific encoder configuration (${o.codec}, ${o.bitrate} bps, ${o.numberOfChannels} channels, ${o.sampleRate} Hz) is not supported in this environment. Consider using another codec or changing your audio parameters.`);const h=await Zf(this.encodingConfig.codec,o.codec)/o.sampleRate;let p=0;const m=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(b,w)=>{var A,T;if(w!=null&&w.decoderConfig&&(Hc(this.encodingConfig.codec,o,w.decoderConfig),this.encodingConfig.codec==="opus"&&w.decoderConfig.description)){const k=ke(w.decoderConfig.description);p=ys(k).preSkip/mr}let S=ce.fromEncodedChunk(b);S=S.clone({timestamp:_i(S.timestamp-h-p,o.sampleRate),duration:b.duration!=null?_i(S.duration,o.sampleRate):void 0}),Wt()&&(p=0),(T=(A=this.encodingConfig).onEncodedPacket)==null||T.call(A,S,w),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,S,w).catch(k=>{this.setError(k)})},error:b=>{b.stack=m,this.setError(b)}}),this.encoder.configure(o),this.encodingConfig.codec==="aac"&&_t()&&qc(this.encoder,t,i,n,s)}y(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;const e=this.encodingConfig.codec,{dataType:t,sampleSize:i,littleEndian:n}=Vs(e);switch(this.outputSampleSize=i,i){case 1:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint8(a,pe(Math.round(o*128)+128,0,255)):t==="signed"?this.writeOutputValue=(s,a,o)=>{s.setInt8(a,pe(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(s,a,o)=>{const c=pe(Math.round(o*32768),-32768,32767);s.setUint8(a,yu(c))}:t==="alaw"?this.writeOutputValue=(s,a,o)=>{const c=pe(Math.round(o*32768),-32768,32767);s.setUint8(a,Au(c))}:y(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint16(a,pe(Math.round(o*32768)+32768,0,65535),n):t==="signed"?this.writeOutputValue=(s,a,o)=>s.setInt16(a,pe(Math.round(o*32768),-32768,32767),n):y(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(s,a,o)=>hs(s,a,pe(Math.round(o*8388608)+8388608,0,16777215),n):t==="signed"?this.writeOutputValue=(s,a,o)=>ll(s,a,pe(Math.round(o*8388608),-8388608,8388607),n):y(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint32(a,pe(Math.round(o*2147483648)+2147483648,0,4294967295),n):t==="signed"?this.writeOutputValue=(s,a,o)=>s.setInt32(a,pe(Math.round(o*2147483648),-2147483648,2147483647),n):t==="float"?this.writeOutputValue=(s,a,o)=>s.setFloat32(a,o,n):y(!1);break;case 8:t==="float"?this.writeOutputValue=(s,a,o)=>s.setFloat64(a,o,n):y(!1);break;default:ze(i),y(!1)}}async flushAndClose(e){try{e||(this.checkForEncoderError(),this.resampler&&await this.resampler.finalize(),this.pcmScratchFrames>0&&await this.emitPcmScratchPacket()),this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&await this.encoder.flush())}finally{this.closed=!0,this.resampler=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(t=>this.setError(t)):this.encoder&&this.encoder.state!=="closed"&&this.encoder.close()}e||this.checkForEncoderError()}getQueueSize(){var e;return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:((e=this.encoder)==null?void 0:e.encodeQueueSize)??0}checkForEncoderError(){if(this.errorSet)throw this.error}}const Mn=new Map,Zf=(r,e)=>{let t=Mn.get(e);return t||(t=(async()=>{const s={codec:e,numberOfChannels:1,sampleRate:48e3,...$c(r)},a=4096,o=2*a,c="f32-planar",u=[];let l=null,d=null,f=-1/0,h=0,p=null;const m=new AudioEncoder({output:(S,A)=>{A!=null&&A.decoderConfig&&(l??(l=A.decoderConfig)),u.push(S)},error:S=>{p??(p=S)}}),b=new AudioDecoder({output:S=>{const A=new Float32Array(S.numberOfFrames);S.copyTo(A,{planeIndex:0,format:c}),S.close();for(let T=0;T<A.length;T++)A[T]>f&&(f=A[T],d=h+T);h+=A.length},error:S=>{p??(p=S)}});try{m.configure(s),r==="aac"&&_t()&&qc(m,c,1,48e3,0);const S=new Float32Array(1*o);S[a]=1;const A=new AudioData({data:S,format:c,numberOfChannels:1,numberOfFrames:o,sampleRate:48e3,timestamp:0});m.encode(A),A.close(),await m.flush(),y(l),Hc(r,s,l),b.configure(l);for(const T of u)b.decode(T);await b.flush()}catch(S){throw p??S}finally{m.state!=="closed"&&m.close(),b.state!=="closed"&&b.close()}y(d!==null);const w=Math.round(u[0].timestamp/1e6*48e3);return d-a+w})(),Mn.set(e,t),t.catch(()=>Mn.delete(e)),t)},qc=(r,e,t,i,n)=>{const a=st(e),o=new Uint8Array(a*1024*t);(e==="u8"||e==="u8-planar")&&o.fill(2**7);const c=new AudioData({data:o,format:e,numberOfChannels:t,numberOfFrames:1024,sampleRate:i,timestamp:Math.round(1e6*(n-1024/i))});r.encode(c),c.close()},Hc=(r,e,t)=>{if(r==="aac"){if(t.description&&t.description.byteLength>0&&ke(t.description)[0]===3){const{decoderSpecificInfo:n}=Wc(Ke.tempFromBytes(ke(t.description)));t.description=n??void 0}let i=!1;if(!t.description||t.description.byteLength<2?i=!0:i=Ki(ke(t.description)).objectType===0,i){const n=Number(fe(e.codec.split(".")));t.description=Cl({objectType:n,outputNumberOfChannels:t.numberOfChannels,outputSampleRate:t.sampleRate})}}};class ym extends dn{constructor(e){xs(e),super(e.codec),this._encoder=new zs(this,e)}add(e){if(!(e instanceof Te))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Sm extends dn{constructor(e,t={}){if(xs(e),typeof t!="object"||!t)throw new TypeError("options must be an object.");if(t.startTimestamp!==void 0&&!Number.isFinite(t.startTimestamp))throw new TypeError("options.startTimestamp, when provided, must be a finite number.");super(e.codec),this._encoder=new zs(this,e),this._accumulatedTime=t.startTimestamp??0}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const t=Te._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(const i of t)await this._encoder.add(i,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Am extends dn{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,i={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");if(xs(t),typeof i!="object"||!i)throw new TypeError("options must be an object.");if(i.timestampBase!==void 0&&i.timestampBase!=="synced-zero"&&i.timestampBase!=="zero"&&i.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");super(t.codec),this._abortController=null,this._audioContext=null,this._scriptProcessorNode=null,this._promiseWithResolvers=Se(),this._errorPromiseAccessed=!1,this._paused=!1,this._options=i,this._encoder=new zs(this,t),this._track=e}async _start(){this._errorPromiseAccessed||j._warn("Make sure not to ignore the `errorPromise` field on MediaStreamAudioTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let e=null,t=!1,i=null,n=0;const s=a=>{if(t){a.close();return}const o=a.timestamp;if(this._paused){if(e!==null){if(i!==null&&this._options.timestampBase!=="unix"){const u=o-i;n-=u}i=o}a.close();return}if(e===null){e=a.timestamp;let c;const u=this._options.timestampBase??"synced-zero";if(u==="unix")c=Date.now()/1e3;else if(u==="zero")c=0;else{const l=this._connectedTrack.output;l._firstMediaStreamTimestamp===null?(l._firstMediaStreamTimestamp=performance.now()/1e3,c=0):c=performance.now()/1e3-l._firstMediaStreamTimestamp}n=c-e}if(i=o,this._encoder.getQueueSize()>=8){a.close();return}a.setTimestamp(o+n),this._encoder.add(a,!0).catch(c=>{var u,l;t=!0,(u=this._abortController)==null||u.abort(),this._promiseWithResolvers.reject(c),(l=this._audioContext)==null||l.suspend()})};if(typeof MediaStreamTrackProcessor<"u"){const a=new MediaStreamTrackProcessor({track:this._track}),o=new WritableStream({write:c=>s(new Te(c))});a.readable.pipeTo(o,{signal:this._abortController.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||this._promiseWithResolvers.reject(c)})}else{const a=window.AudioContext||window.webkitAudioContext;this._audioContext=new a({sampleRate:this._track.getSettings().sampleRate});const o=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state==="suspended"&&await this._audioContext.resume(),o.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let c=0;this._scriptProcessorNode.onaudioprocess=u=>{const l=Te._fromAudioBuffer(u.inputBuffer,c);c+=u.inputBuffer.duration;for(const d of l)s(d)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){try{this._abortController&&(this._abortController.abort(),this._abortController=null),this._audioContext&&(y(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend())}finally{await this._encoder.flushAndClose(e)}}}const Jf=()=>{const r=(i,n)=>{n?self.postMessage(i,{transfer:n}):self.postMessage(i)};r({type:"support",supported:typeof MediaStreamTrackProcessor<"u"});const e=new Map,t=new Map;self.addEventListener("message",i=>{const n=i.data;switch(n.type){case"videoTrack":{t.set(n.trackId,n.track);const s=new MediaStreamTrackProcessor({track:n.track}),a=new WritableStream({write:c=>{if(!t.has(n.trackId)){c.close();return}r({type:"videoFrame",trackId:n.trackId,videoFrame:c},[c])}}),o=new AbortController;e.set(n.trackId,o),s.readable.pipeTo(a,{signal:o.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||r({type:"error",trackId:n.trackId,error:c})})}break;case"stopTrack":{const s=e.get(n.trackId);s&&(s.abort(),e.delete(n.trackId));const a=t.get(n.trackId);a==null||a.stop(),t.delete(n.trackId),r({type:"trackStopped",trackId:n.trackId})}break;default:ze(n)}})};let eh=0,Ze=null;const th=()=>{const r=new Blob([`(${Jf.toString()})()`],{type:"application/javascript"}),e=URL.createObjectURL(r);Ze=new Worker(e)};let On=null;const rh=async()=>On!==null?On:(Ze||th(),new Promise(r=>{y(Ze);const e=t=>{const i=t.data;i.type==="support"&&(On=i.supported,Ze.removeEventListener("message",e),r(i.supported))};Ze.addEventListener("message",e)})),Nn=(r,e)=>{y(Ze),Ze.postMessage(r)};class ih extends Os{constructor(e){if(super(),!ci.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${ci.join(", ")}.`);this._codec=e}}class Tm extends ih{constructor(e){super(e),this._error=null,this._errorSet=!1,this._lastMuxerPromise=Promise.resolve(),this._parser=new wu({codec:e,output:(t,i)=>{this._lastMuxerPromise=this._connectedTrack.output._muxer.addSubtitleCue(this._connectedTrack,t,i).catch(n=>{this._setError(n)})}})}add(e){if(typeof e!="string")throw new TypeError("text must be a string.");return this._checkForError(),this._ensureValidAdd(),this._parser.parse(e),this._lastMuxerPromise}_setError(e){this._errorSet||(this._error=e,this._errorSet=!0)}_checkForError(){if(this._errorSet)throw this._error}async _flushAndClose(e){e||this._checkForError()}}/*!
309
+ * Copyright (c) 2026-present, Vanilagy and contributors
310
+ *
311
+ * This Source Code Form is subject to the terms of the Mozilla Public
312
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
313
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
314
+ */const Qe=["avc","hevc","vp9","av1","vp8","prores"],Me=["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"],nh=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts","truehd"],Ge=[...nh,...Me],ci=["webvtt"],jc=["truehd"],zi=[{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}],so=[{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}],Et=[{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}],ao=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],oo=".01.01.01.01.00",co=".0.110.01.01.01.0",Lt=["ap4x","ap4h","apch","apcn","apcs","apco"],Ui=["dtsc","dtsh","dtsl","dtse"],sh=[{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}],Kc=(r,e,t,i,n)=>{if(r==="avc"){const s=_t(),a=s?66:100,o=Math.ceil(e/16)*Math.ceil(t/16),c=zi.find(h=>o<=h.maxMacroblocks&&i<=h.maxBitrate)??fe(zi),u=c?c.level:0,l=a.toString(16).padStart(2,"0"),d=s?"40":"00",f=u.toString(16).padStart(2,"0");return`avc1.${l}${d}${f}`}else if(r==="hevc"){const c=e*t,u=so.find(d=>c<=d.maxPictureSize&&i<=d.maxBitrate)??fe(so);return`hev1.1.6.${u.tier}${u.level}.B0`}else{if(r==="vp8")return"vp8";if(r==="vp9"){const a=e*t;return`vp09.00.${(Et.find(u=>a<=u.maxPictureSize&&i<=u.maxBitrate)??fe(Et)).level.toString().padStart(2,"0")}.08`}else if(r==="av1"){const a=e*t,o=ao.find(l=>a<=l.maxPictureSize&&i<=l.maxBitrate)??fe(ao);return`av01.0.${o.level.toString().padStart(2,"0")}${o.tier}.08`}else if(r==="prores"){const a=Math.pow(e*t/2073600,.95),o=sh.filter(l=>l.alpha===n);let c=o[0].fourCc,u=1/0;for(const{fourCc:l,bitrate:d}of o){const f=Math.abs(d*a-i);f<u&&(u=f,c=l)}return c}else ze(r)}throw new TypeError(`Unhandled codec '${String(r)}'.`)},xm=r=>{const e=r.split("."),t=Number(e[1]),i=Number(e[2]),n=Number(e[3]),s=e[4]?Number(e[4]):1;return[1,1,t,2,1,i,3,1,n,4,1,s]},Pm=r=>{const e=r.split("."),n=(1<<7)+1,s=Number(e[1]),a=e[2],o=Number(a.slice(0,-1)),c=(s<<5)+o,u=a.slice(-1)==="H"?1:0,l=Number(e[3]),d=l===8?0:1,f=l===12?1:0,h=e[4]?Number(e[4]):0,p=e[5]?Number(e[5][0]):1,m=e[5]?Number(e[5][1]):1,b=e[5]?Number(e[5][2]):0,w=(u<<7)+(d<<6)+(f<<5)+(h<<4)+(p<<3)+(m<<2)+b;return[n,c,w,0]},fn=r=>{const{codec:e,codecDescription:t,colorSpace:i,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:c}=r;if(e==="avc"){if(y(r.avcType!==null),n){const u=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${r.avcType}.${Jr(u)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${r.avcType}.${Jr(t.subarray(1,4))}`}else if(e==="hevc"){let u,l,d,f,h,p;if(s)u=s.generalProfileSpace,l=s.generalProfileIdc,d=Hs(s.generalProfileCompatibilityFlags),f=s.generalTierFlag,h=s.generalLevelIdc,p=[...s.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const b=Z(t),w=b.getUint8(1);u=w>>6&3,l=w&31,d=Hs(b.getUint32(2)),f=w>>5&1,h=b.getUint8(12),p=[];for(let S=0;S<6;S++)p.push(b.getUint8(6+S))}let m="hev1.";for(m+=["","A","B","C"][u]+l,m+=".",m+=d.toString(16).toUpperCase(),m+=".",m+=f===0?"L":"H",m+=h;p.length>0&&p[p.length-1]===0;)p.pop();return p.length>0&&(m+=".",m+=p.map(b=>b.toString(16).toUpperCase()).join(".")),m}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){const S=r.width*r.height;let A=fe(Et).level;for(const T of Et)if(S<=T.maxPictureSize){A=T.level;break}return`vp09.00.${A.toString().padStart(2,"0")}.08`}const u=a.profile.toString().padStart(2,"0"),l=a.level.toString().padStart(2,"0"),d=a.bitDepth.toString().padStart(2,"0"),f=a.chromaSubsampling.toString().padStart(2,"0"),h=a.colourPrimaries.toString().padStart(2,"0"),p=a.transferCharacteristics.toString().padStart(2,"0"),m=a.matrixCoefficients.toString().padStart(2,"0"),b=a.videoFullRangeFlag.toString().padStart(2,"0");let w=`vp09.${u}.${l}.${d}.${f}`;return w+=`.${h}.${p}.${m}.${b}`,w.endsWith(oo)&&(w=w.slice(0,-oo.length)),w}else if(e==="av1"){if(!o){const T=r.width*r.height;let k=fe(Et).level;for(const x of Et)if(T<=x.maxPictureSize){k=x.level;break}return`av01.0.${k.toString().padStart(2,"0")}M.08`}const u=o.profile,l=o.level.toString().padStart(2,"0"),d=o.tier?"H":"M",f=o.bitDepth.toString().padStart(2,"0"),h=o.monochrome?"1":"0",p=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0);let m,b,w,S;vo(o)?(m=o.colourPrimaries,b=o.transferCharacteristics,w=o.matrixCoefficients,S=o.videoFullRangeFlag):(m=i!=null&&i.primaries?li[i.primaries]:1,b=i!=null&&i.transfer?ui[i.transfer]:1,w=i!=null&&i.matrix?di[i.matrix]:1,S=i!=null&&i.fullRange?1:0);let A=`av01.${u}.${l}${d}.${f}`;return A+=`.${h}.${p.toString().padStart(3,"0")}`,A+=`.${m.toString().padStart(2,"0")}`,A+=`.${b.toString().padStart(2,"0")}`,A+=`.${w.toString().padStart(2,"0")}`,A+=`.${S}`,A.endsWith(co)&&(A=A.slice(0,-co.length)),A}else{if(e==="prores")return c??"apch";e!==null&&ze(e)}}throw new TypeError(`Unhandled codec '${e}'.`)},Xc=r=>{var e,t,i,n,s,a;switch(r.codec){case"avc":{let o=(e=r.avcCodecInfo)==null?void 0:e.sequenceParameterSets[0];if(!o&&r.codecDescription&&(o=(t=Yi(r.codecDescription))==null?void 0:t.sequenceParameterSets[0]),o){const c=dr(o);if(c)return{primaries:ht[c.colourPrimaries],transfer:mt[c.transferCharacteristics],matrix:pt[c.matrixCoefficients],fullRange:!!c.fullRangeFlag}}}break;case"hevc":{let o=(n=(i=r.hevcCodecInfo)==null?void 0:i.arrays.find(c=>c.nalUnitType===ge.SPS_NUT))==null?void 0:n.nalUnits[0];if(!o&&r.codecDescription&&(o=(a=(s=Eo(r.codecDescription))==null?void 0:s.arrays.find(c=>c.nalUnitType===ge.SPS_NUT))==null?void 0:a.nalUnits[0]),o){const c=Zi(o);if(c)return{primaries:ht[c.colourPrimaries],transfer:mt[c.transferCharacteristics],matrix:pt[c.matrixCoefficients],fullRange:!!c.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(r.vp9CodecInfo)return{primaries:ht[r.vp9CodecInfo.colourPrimaries],transfer:mt[r.vp9CodecInfo.transferCharacteristics],matrix:pt[r.vp9CodecInfo.matrixCoefficients],fullRange:!!r.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(r.av1CodecInfo)return{primaries:ht[r.av1CodecInfo.colourPrimaries],transfer:mt[r.av1CodecInfo.transferCharacteristics],matrix:pt[r.av1CodecInfo.matrixCoefficients],fullRange:!!r.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(r.proresCodecInfo)return{primaries:ht[r.proresCodecInfo.colourPrimaries],transfer:mt[r.proresCodecInfo.transferCharacteristics],matrix:pt[r.proresCodecInfo.matrixCoefficients],fullRange:r.proresCodecInfo.fullRange};break}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},Qc=(r,e,t)=>{if(r==="aac")return e>=2&&t<=24e3?"mp4a.40.29":t<=24e3?"mp4a.40.5":"mp4a.40.2";if(r==="mp3")return"mp3";if(r==="opus")return"opus";if(r==="vorbis")return"vorbis";if(r==="flac")return"flac";if(r==="ac3")return"ac-3";if(r==="eac3")return"ec-3";if(r==="dts")return"dtsc";if(r==="truehd")return"mlpa";if(Me.includes(r))return r;throw new TypeError(`Unhandled codec '${r}'.`)},Us=r=>{const{codec:e,codecDescription:t,aacCodecInfo:i,dtsFormat:n}=r;if(e==="aac"){if(!i)throw new TypeError("AAC codec info must be provided.");if(i.isMpeg2)return"mp4a.67";{let s;return i.objectType!==null?s=i.objectType:s=Ki(t).objectType,`mp4a.40.${s}`}}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e==="ac3")return"ac-3";if(e==="eac3")return"ec-3";if(e==="dts")return n??"dtsc";if(e==="truehd")return"mlpa";if(e&&Me.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},ah=r=>{},oh=r=>{switch(r.codec){case"flac":{const e=vi("ZkxhQ4AAACIQABAAAAYtACWtCsRC8AANRBhVFucAcYu5ASE2m1Dxv8tw");return r.sampleRate>=1<<20||r.numberOfChannels>8?!1:(e[18]=r.sampleRate>>>12,e[19]=r.sampleRate>>>4,e[20]=(r.sampleRate&15)<<4|r.numberOfChannels-1<<1,e)}case"vorbis":{const e=vi("Ah7/AgF2b3JiaXMAAAAAAoC7AAAAAAAAgLUBAAAAAAC4AQN2b3JiaXMNAAAATGF2ZjU4Ljc2LjEwMAgAAAAMAAAAbGFuZ3VhZ2U9dW5kGQAAAGhhbmRsZXJfbmFtZT1Tb3VuZEhhbmRsZXIWAAAAdmVuZG9yX2lkPVswXVswXVswXVswXSAAAABlbmNvZGVyPUxhdmM1OC4xMzQuMTAwIGxpYnZvcmJpcxAAAABtYWpvcl9icmFuZD1pc29tEQAAAG1pbm9yX3ZlcnNpb249NTEyIgAAAGNvbXBhdGlibGVfYnJhbmRzPWlzb21pc28yYXZjMW1wNDEmAAAAREVTQ1JJUFRJT049TWFkZSB3aXRoIFJlbW90aW9uIDQuMC4yNzgBBXZvcmJpcyVCQ1YBAEAAACRzGCpGpXMWhBAaQlAZ4xxCzmvsGUJMEYIcMkxbyyVzkCGkoEKIWyiB0JBVAABAAACHQXgUhIpBCCGEJT1YkoMnPQghhIg5eBSEaUEIIYQQQgghhBBCCCGERTlokoMnQQgdhOMwOAyD5Tj4HIRFOVgQgydB6CCED0K4moOsOQghhCQ1SFCDBjnoHITCLCiKgsQwuBaEBDUojILkMMjUgwtCiJqDSTX4GoRnQXgWhGlBCCGEJEFIkIMGQcgYhEZBWJKDBjm4FITLQagahCo5CB+EIDRkFQCQAACgoiiKoigKEBqyCgDIAAAQQFEUx3EcyZEcybEcCwgNWQUAAAEACAAAoEiKpEiO5EiSJFmSJVmSJVmS5omqLMuyLMuyLMsyEBqyCgBIAABQUQxFcRQHCA1ZBQBkAAAIoDiKpViKpWiK54iOCISGrAIAgAAABAAAEDRDUzxHlETPVFXXtm3btm3btm3btm3btm1blmUZCA1ZBQBAAAAQ0mlmqQaIMAMZBkJDVgEACAAAgBGKMMSA0JBVAABAAACAGEoOogmtOd+c46BZDppKsTkdnEi1eZKbirk555xzzsnmnDHOOeecopxZDJoJrTnnnMSgWQqaCa0555wnsXnQmiqtOeeccc7pYJwRxjnnnCateZCajbU555wFrWmOmkuxOeecSLl5UptLtTnnnHPOOeecc84555zqxekcnBPOOeecqL25lpvQxTnnnE/G6d6cEM4555xzzjnnnHPOOeecIDRkFQAABABAEIaNYdwpCNLnaCBGEWIaMulB9+gwCRqDnELq0ehopJQ6CCWVcVJKJwgNWQUAAAIAQAghhRRSSCGFFFJIIYUUYoghhhhyyimnoIJKKqmooowyyyyzzDLLLLPMOuyssw47DDHEEEMrrcRSU2011lhr7jnnmoO0VlprrbVSSimllFIKQkNWAQAgAAAEQgYZZJBRSCGFFGKIKaeccgoqqIDQkFUAACAAgAAAAABP8hzRER3RER3RER3RER3R8RzPESVREiVREi3TMjXTU0VVdWXXlnVZt31b2IVd933d933d+HVhWJZlWZZlWZZlWZZlWZZlWZYgNGQVAAACAAAghBBCSCGFFFJIKcYYc8w56CSUEAgNWQUAAAIACAAAAHAUR3EcyZEcSbIkS9IkzdIsT/M0TxM9URRF0zRV0RVdUTdtUTZl0zVdUzZdVVZtV5ZtW7Z125dl2/d93/d93/d93/d93/d9XQdCQ1YBABIAADqSIymSIimS4ziOJElAaMgqAEAGAEAAAIriKI7jOJIkSZIlaZJneZaomZrpmZ4qqkBoyCoAABAAQAAAAAAAAIqmeIqpeIqoeI7oiJJomZaoqZoryqbsuq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq4LhIasAgAkAAB0JEdyJEdSJEVSJEdygNCQVQCADACAAAAcwzEkRXIsy9I0T/M0TxM90RM901NFV3SB0JBVAAAgAIAAAAAAAAAMybAUy9EcTRIl1VItVVMt1VJF1VNVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVN0zRNEwgNWQkAkAEAkBBTLS3GmgmLJGLSaqugYwxS7KWxSCpntbfKMYUYtV4ah5RREHupJGOKQcwtpNApJq3WVEKFFKSYYyoVUg5SIDRkhQAQmgHgcBxAsixAsiwAAAAAAAAAkDQN0DwPsDQPAAAAAAAAACRNAyxPAzTPAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAA0DwP8DwR8EQRAAAAAAAAACzPAzTRAzxRBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAAsDwP8EQR0DwRAAAAAAAAACzPAzxRBDzRAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEOAAABBgIRQasiIAiBMAcEgSJAmSBM0DSJYFTYOmwTQBkmVB06BpME0AAAAAAAAAAAAAJE2DpkHTIIoASdOgadA0iCIAAAAAAAAAAAAAkqZB06BpEEWApGnQNGgaRBEAAAAAAAAAAAAAzzQhihBFmCbAM02IIkQRpgkAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAGHAAAAgwoQwUGrIiAIgTAHA4imUBAIDjOJYFAACO41gWAABYliWKAABgWZooAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAYcAAACDChDBQashIAiAIAcCiKZQHHsSzgOJYFJMmyAJYF0DyApgFEEQAIAAAocAAACLBBU2JxgEJDVgIAUQAABsWxLE0TRZKkaZoniiRJ0zxPFGma53meacLzPM80IYqiaJoQRVE0TZimaaoqME1VFQAAUOAAABBgg6bE4gCFhqwEAEICAByKYlma5nmeJ4qmqZokSdM8TxRF0TRNU1VJkqZ5niiKommapqqyLE3zPFEURdNUVVWFpnmeKIqiaaqq6sLzPE8URdE0VdV14XmeJ4qiaJqq6roQRVE0TdNUTVV1XSCKpmmaqqqqrgtETxRNU1Vd13WB54miaaqqq7ouEE3TVFVVdV1ZBpimaaqq68oyQFVV1XVdV5YBqqqqruu6sgxQVdd1XVmWZQCu67qyLMsCAAAOHAAAAoygk4wqi7DRhAsPQKEhKwKAKAAAwBimFFPKMCYhpBAaxiSEFEImJaXSUqogpFJSKRWEVEoqJaOUUmopVRBSKamUCkIqJZVSAADYgQMA2IGFUGjISgAgDwCAMEYpxhhzTiKkFGPOOScRUoox55yTSjHmnHPOSSkZc8w556SUzjnnnHNSSuacc845KaVzzjnnnJRSSuecc05KKSWEzkEnpZTSOeecEwAAVOAAABBgo8jmBCNBhYasBABSAQAMjmNZmuZ5omialiRpmud5niiapiZJmuZ5nieKqsnzPE8URdE0VZXneZ4oiqJpqirXFUXTNE1VVV2yLIqmaZqq6rowTdNUVdd1XZimaaqq67oubFtVVdV1ZRm2raqq6rqyDFzXdWXZloEsu67s2rIAAPAEBwCgAhtWRzgpGgssNGQlAJABAEAYg5BCCCFlEEIKIYSUUggJAAAYcAAACDChDBQashIASAUAAIyx1lprrbXWQGettdZaa62AzFprrbXWWmuttdZaa6211lJrrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmstpZRSSimllFJKKaWUUkoppZRSSgUA+lU4APg/2LA6wknRWGChISsBgHAAAMAYpRhzDEIppVQIMeacdFRai7FCiDHnJKTUWmzFc85BKCGV1mIsnnMOQikpxVZjUSmEUlJKLbZYi0qho5JSSq3VWIwxqaTWWoutxmKMSSm01FqLMRYjbE2ptdhqq7EYY2sqLbQYY4zFCF9kbC2m2moNxggjWywt1VprMMYY3VuLpbaaizE++NpSLDHWXAAAd4MDAESCjTOsJJ0VjgYXGrISAAgJACAQUooxxhhzzjnnpFKMOeaccw5CCKFUijHGnHMOQgghlIwx5pxzEEIIIYRSSsaccxBCCCGEkFLqnHMQQgghhBBKKZ1zDkIIIYQQQimlgxBCCCGEEEoopaQUQgghhBBCCKmklEIIIYRSQighlZRSCCGEEEIpJaSUUgohhFJCCKGElFJKKYUQQgillJJSSimlEkoJJYQSUikppRRKCCGUUkpKKaVUSgmhhBJKKSWllFJKIYQQSikFAAAcOAAABBhBJxlVFmGjCRcegEJDVgIAZAAAkKKUUiktRYIipRikGEtGFXNQWoqocgxSzalSziDmJJaIMYSUk1Qy5hRCDELqHHVMKQYtlRhCxhik2HJLoXMOAAAAQQCAgJAAAAMEBTMAwOAA4XMQdAIERxsAgCBEZohEw0JweFAJEBFTAUBigkIuAFRYXKRdXECXAS7o4q4DIQQhCEEsDqCABByccMMTb3jCDU7QKSp1IAAAAAAADADwAACQXAAREdHMYWRobHB0eHyAhIiMkAgAAAAAABcAfAAAJCVAREQ0cxgZGhscHR4fICEiIyQBAIAAAgAAAAAggAAEBAQAAAAAAAIAAAAEBA=="),t=Z(e);return t.setUint8(15,r.numberOfChannels),t.setUint32(16,r.sampleRate,!0),e}default:return}},ch=(r,e)=>{switch(r){case"aac":{if(!e.description)return 1024/e.sampleRate;const t=Ki(ke(e.description));if(t.coreSampleRate===null)throw new Error("Invalid AAC sampling frequency index.");return t.frameLength/t.coreSampleRate}case"opus":return lh;case"mp3":{const{sampleRate:t,numberOfChannels:i}=e,n=t>=32e3,s=n?1152:576,a=n?32e3:8e3,o=n?511:255,c=n?i===1?17:32:i===1?9:17,l=Math.floor(s/8*a/t)-vt-c;return(1+Math.ceil(o/l))*s/t}case"vorbis":{y(e.description);const t=ke(e.description);let i=1,n=2;for(;n>0;)t[i++]<255&&n--;return(1<<(t[i+28]>>4))/2/e.sampleRate}case"ac3":case"eac3":return 256/e.sampleRate;case"dts":return 512/e.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:ze(r),y(!1)}},Im=(r,e)=>{switch(r){case"aac":return 1024;case"opus":return .02*e;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 Pi;default:ze(r),y(!1)}},mr=48e3,lh=.4,Gc=/^pcm-([usf])(\d+)(be)?$/,Vs=r=>{if(y(Me.includes(r)),r==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(r==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=Gc.exec(r);y(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";const i=Number(e[2])/8,n=e[3]!=="be",s=r==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:i,littleEndian:n,silentValue:s}},Je=r=>r.startsWith("avc1")||r.startsWith("avc3")?"avc":r.startsWith("hev1")||r.startsWith("hvc1")?"hevc":r==="vp8"?"vp8":r.startsWith("vp09")?"vp9":r.startsWith("av01")?"av1":Lt.includes(r)?"prores":r==="mp3"||r==="mp4a.69"||r==="mp4a.6B"||r==="mp4a.6b"||r==="mp4a.40.34"?"mp3":r.startsWith("mp4a.40.")||r==="mp4a.67"?"aac":r==="opus"||r==="Opus"?"opus":r==="vorbis"?"vorbis":r==="flac"?"flac":r==="ac-3"||r==="ac3"?"ac3":r==="ec-3"||r==="eac3"?"eac3":Ui.includes(r)?"dts":r==="mlpa"?"truehd":r==="ulaw"?"ulaw":r==="alaw"?"alaw":Gc.test(r)?r:r==="webvtt"?"webvtt":null,uh=r=>r==="avc"?{avc:{format:"avc"}}:r==="hevc"?{hevc:{format:"hevc"}}:{},$c=r=>r==="aac"?{aac:{format:"aac"}}:r==="opus"?{opus:{format:"opus"}}:{},dh=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Lt],fh=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,hh=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,mh=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,ph=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Cm=(r,e)=>{if(!r)throw new TypeError("Video chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Video chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!dh.some(t=>r.decoderConfig.codec.startsWith(t)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(r.decoderConfig.codedWidth)||r.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(r.decoderConfig.codedHeight)||r.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(r.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectWidth)||r.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectHeight)||r.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectWidth!==void 0!=(r.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(r.decoderConfig.description!==void 0&&!hr(r.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.colorSpace!==void 0){const{colorSpace:t}=r.decoderConfig;if(typeof t!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const i=Object.keys(li);if(t.primaries!=null&&!i.includes(t.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${i.join(", ")}.`);const n=Object.keys(ui);if(t.transfer!=null&&!n.includes(t.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${n.join(", ")}.`);const s=Object.keys(di);if(t.matrix!=null&&!s.includes(t.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${s.join(", ")}.`);if(t.fullRange!=null&&typeof t.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(r.decoderConfig.codec.startsWith("avc1")||r.decoderConfig.codec.startsWith("avc3")){if(!fh.test(r.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(r.decoderConfig.codec.startsWith("hev1")||r.decoderConfig.codec.startsWith("hvc1")){if(!hh.test(r.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(r.decoderConfig.codec.startsWith("vp8")){if(r.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(r.decoderConfig.codec.startsWith("vp09")){if(!mh.test(r.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(r.decoderConfig.codec.startsWith("av01")){if(!ph.test(r.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')}else if(Lt.some(t=>r.decoderConfig.codec.startsWith(t))&&!Lt.some(t=>r.decoderConfig.codec===t))throw new TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${Lt.join(", ")}.`);if(e!==null&&Je(r.decoderConfig.codec)!==e)throw new TypeError(`Video chunk metadata decoder configuration codec string '${r.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},gh=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts","mlpa"],Em=(r,e)=>{if(!r)throw new TypeError("Audio chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!gh.some(t=>r.decoderConfig.codec.startsWith(t)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(r.decoderConfig.sampleRate)||r.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(r.decoderConfig.numberOfChannels)||r.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(r.decoderConfig.description!==void 0&&!hr(r.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.codec.startsWith("mp4a")&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(r.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("mp3")||r.decoderConfig.codec.startsWith("mp4a")){if(r.decoderConfig.codec!=="mp3"&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(r.decoderConfig.codec.startsWith("opus")){if(r.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(r.decoderConfig.description&&r.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(r.decoderConfig.codec.startsWith("vorbis")){if(r.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!r.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("flac")){if(r.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!r.decoderConfig.description||r.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("ac-3")||r.decoderConfig.codec.startsWith("ac3")){if(r.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(r.decoderConfig.codec.startsWith("ec-3")||r.decoderConfig.codec.startsWith("eac3")){if(r.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if(r.decoderConfig.codec.startsWith("dts")){if(!Ui.includes(r.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${Ui.join(", ")}.`)}else if(r.decoderConfig.codec.startsWith("mlpa")){if(r.decoderConfig.codec!=="mlpa")throw new TypeError('Audio chunk metadata decoder configuration codec string for TrueHD must be "mlpa".')}else if((r.decoderConfig.codec.startsWith("pcm")||r.decoderConfig.codec.startsWith("ulaw")||r.decoderConfig.codec.startsWith("alaw"))&&!Me.includes(r.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Me.join(", ")}).`);if(e!==null&&Je(r.decoderConfig.codec)!==e)throw new TypeError(`Audio chunk metadata decoder configuration codec string '${r.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},_m=r=>{if(!r)throw new TypeError("Subtitle metadata must be provided.");if(typeof r!="object")throw new TypeError("Subtitle metadata must be an object.");if(!r.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof r.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof r.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};export{$i as $,Vi as A,re as B,fe as C,Th as D,Pm as E,or as F,li as G,Zl as H,nm as I,Oo as J,Uh as K,ru as L,di as M,Jl as N,ys as O,Me as P,Un as Q,Gr as R,_t as S,ui as T,De as U,Ol as V,bs as W,Se as X,Qu as Y,Gu as Z,Cm as _,y as a,Ae as a$,Io as a0,Ji as a1,Mh as a2,Ph as a3,ps as a4,oi as a5,qt as a6,ji as a7,Cl as a8,_m as a9,ra as aA,yh as aB,j as aC,od as aD,Zc as aE,yo as aF,Rl as aG,ko as aH,jn as aI,At as aJ,El as aK,vl as aL,ws as aM,_l as aN,xd as aO,Td as aP,Yl as aQ,xa as aR,pe as aS,dc as aT,xh as aU,sm as aV,Le as aW,Wd as aX,Yi as aY,Eo as aZ,ri as a_,Qi as aa,Po as ab,ai as ac,lr as ad,lh as ae,mr as af,$l as ag,Vh as ah,Kr as ai,ir as aj,im as ak,B as al,ad as am,dd as an,Be as ao,ch as ap,cd as aq,gi as ar,Xr as as,sd as at,Ih as au,wo as av,kl as aw,hd as ax,xm as ay,_i as az,Fh as b,xc as b$,fr as b0,ge as b1,xo as b2,Ao as b3,hs as b4,am as b5,Nh as b6,zh as b7,Fe as b8,St as b9,on as bA,nn as bB,Zh as bC,gm as bD,Ff as bE,Lu as bF,ym as bG,Of as bH,st as bI,Te as bJ,Im as bK,Fi as bL,Mc as bM,um as bN,Af as bO,hm as bP,Sm as bQ,Or as bR,zc as bS,cm as bT,om as bU,fm as bV,bm as bW,_h as bX,Hu as bY,Ku as bZ,nf as b_,gc as ba,Ch as bb,xt as bc,pm as bd,km as be,Gt as bf,ve as bg,Pl as bh,Qe as bi,nh as bj,ci as bk,jc as bl,Ht as bm,Ge as bn,F as bo,un as bp,ce as bq,dn as br,ih as bs,vh as bt,ho as bu,Bh as bv,Ms as bw,rl as bx,Jn as by,Eh as bz,Z as c,Iu as c$,qu as c0,ju as c1,Ef as c2,Tc as c3,Sf as c4,Nc as c5,dm as c6,Rc as c7,ln as c8,Ce as c9,lf as cA,Pc as cB,Xe as cC,Rs as cD,lm as cE,Tm as cF,io as cG,Ac as cH,Yn as cI,Ie as cJ,Tn as cK,Rt as cL,If as cM,Pf as cN,kf as cO,bf as cP,mm as cQ,Wh as cR,Vo as cS,Uo as cT,$h as cU,Is as cV,Cs as cW,Ps as cX,to as cY,Cu as cZ,qh as c_,ot as ca,hi as cb,cn as cc,_c as cd,rt as ce,xf as cf,Dc as cg,Bc as ch,Oc as ci,vc as cj,Os as ck,Am as cl,wm as cm,wf as cn,pf as co,Tf as cp,Cf as cq,yf as cr,jt as cs,Fc as ct,Qh as cu,Kh as cv,Xh as cw,Gh as cx,jh as cy,gf as cz,Ye as d,Yh as d0,Wu as d1,Vu as d2,Jh as d3,em as d4,Vr as d5,tm as d6,rm as d7,Hh as d8,Oh as e,Ke as f,Dd as g,Od as h,Nd as i,Lh as j,wh as k,Ii as l,Rh as m,el as n,Jc as o,Ki as p,ze as q,X as r,tl as s,ke as t,mo as u,Em as v,Dh as w,fs as x,kh as y,Vs as z};