@hyperframes/studio 0.9.45 → 0.9.47
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.
- package/dist/assets/{hyperframes-player-C7JtYIRD.js → hyperframes-player-DTdMXCCs.js} +1 -1
- package/dist/assets/{index-C7EGuz1n.js → index-CdtV6F8j.js} +121 -121
- package/dist/assets/index-DA5GM2Mj.js +469 -0
- package/dist/assets/pausedVideoDecoder-B4OsoiOL.js +1 -0
- package/dist/{chunk-FQ3VRKMC.js → chunk-5ZHKYODQ.js} +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.html +1 -1
- package/dist/index.js +569 -534
- package/dist/{keys-CaWcxUST.d.ts → keys-B163OjLN.d.ts} +1 -0
- package/dist/keys.d.ts +1 -1
- package/dist/keys.js +1 -1
- package/package.json +9 -9
- package/src/captions/hooks/useCaptionSync.test.ts +45 -0
- package/src/captions/hooks/useCaptionSync.ts +8 -3
- package/src/hooks/gsapMutationClient.ts +6 -2
- package/src/hooks/useDomEditCommitsHelpers.test.ts +16 -0
- package/src/hooks/useDomEditCommitsHelpers.ts +3 -1
- package/src/hooks/useElementLifecycleOps.ts +1 -0
- package/src/hooks/useFreezeFrame.test.ts +9 -0
- package/src/hooks/useFreezeFrame.ts +3 -1
- package/src/hooks/useGroupCommits.ts +3 -0
- package/src/hooks/useTimelineDeleteOps.test.tsx +26 -0
- package/src/hooks/useTimelineDeleteOps.ts +3 -1
- package/src/player/components/ShortcutsPanel.test.tsx +75 -0
- package/src/player/components/ShortcutsPanel.tsx +20 -4
- package/src/player/components/studioKeyDefaults.ts +1 -0
- package/src/player/components/studioShortcuts.ts +1 -0
- package/src/player/lib/mediabunnyHevcSps.test.ts +169 -0
- package/src/utils/studioSaveDiagnostics.test.ts +10 -0
- package/src/utils/studioSaveDiagnostics.ts +10 -0
- package/src/utils/timelineCompositionInsert.ts +3 -1
- package/dist/assets/codec-DQ7n-U_9.js +0 -314
- package/dist/assets/index-CByWY7fK.js +0 -150
- package/dist/assets/pausedVideoDecoder-Bnvo9NIs.js +0 -1
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
import{n as an}from"./index-CdtV6F8j.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 w(i){if(!i)throw new Error("Assertion failed.")}const Ml=Math.PI/180,Ea=180/Math.PI,Ir=i=>{const e=(i%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${i}.`)},cs=[1,0,0,0,1,0,0,0,1],Dl=(i,e,t)=>{const[r,s,,n,a]=i,o=Math.abs(r)*e+Math.abs(n)*t,c=Math.abs(s)*e+Math.abs(a)*t;return vr(vr(tc(-e/2,-t/2),i),tc(o/2,c/2))},es=i=>{const[e,t]=i,r=Math.atan2(t,zl(i)?-e:e);return Ir(Ia(r*Ea,90))},zl=i=>{const[e,t,,r,s]=i;return e*s-t*r<0},mo=i=>{const e=i*Ml,t=Math.round(Math.cos(e)),r=Math.round(Math.sin(e));return[t,r,0,-r,t,0,0,0,1]},tc=(i,e)=>[1,0,0,0,1,0,i,e,1],Ol=(i,e)=>[i,0,0,0,e,0,0,0,1],vr=(i,e)=>{const t=new Array(9);for(let r=0;r<3;r++)for(let s=0;s<3;s++)t[3*r+s]=i[3*r]*e[s]+i[3*r+1]*e[3+s]+i[3*r+2]*e[6+s];return t},Ul=(i,e,t,r)=>({rotation:Ir(i+(e?-t:t)),flip:e!==r}),Te=i=>i&&i[i.length-1],gi=i=>i>=0&&i<2**32,Nl=i=>i>=-2147483648&&i<2**31,j=i=>{let e=0;for(;i.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return 2**e-1+i.readBits(e)},or=(i,e)=>{const t=e+1,r=Math.floor(Math.log2(t));i.writeBits(r,0),i.writeBits(1,1),i.writeBits(r,t-2**r)},mi=i=>{const e=j(i);return e%2===0?-(e/2):(e+1)/2},me=i=>i.constructor===Uint8Array?i:ArrayBuffer.isView(i)?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i),ie=i=>i.constructor===DataView?i:ArrayBuffer.isView(i)?new DataView(i.buffer,i.byteOffset,i.byteLength):new DataView(i),df=typeof globalThis.TextEncoder<"u"?globalThis.TextEncoder:class{constructor(){this.encoding="utf-8"}encode(e=""){const t=new Uint8Array(3*e.length);let r=0;for(let s=0;s<e.length;s++){let n=e.charCodeAt(s);if(n<128)t[r++]=n;else if(n<2048)t[r++]=192|n>>6,t[r++]=128|n&63;else if(n<55296||n>57343)t[r++]=224|n>>12,t[r++]=128|n>>6&63,t[r++]=128|n&63;else{const a=s+1<e.length?e.charCodeAt(s+1):0;n<56320&&a>=56320&&a<=57343?(n=65536+(n-55296<<10)+(a-56320),s++,t[r++]=240|n>>18,t[r++]=128|n>>12&63,t[r++]=128|n>>6&63,t[r++]=128|n&63):(t[r++]=239,t[r++]=191,t[r++]=189)}}return t.slice(0,r)}},Sr=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?me(e):new Uint8Array(0),r=[];if(this.encoding==="utf-8"){let n=t.length>=3&&t[0]===239&&t[1]===187&&t[2]===191?3:0;for(;n<t.length;){const a=t[n];if(a<128){r.push(a),n++;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{r.push(65533),n++;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=n+d<t.length?t[n+d]:0;if(f<u||f>l)break;c=c<<6|f&63,u=128,l=191}n+=d,d<=o?r.push(65533):c>=65536?(c-=65536,r.push(55296|c>>10,56320|c&1023)):r.push(c)}}else{const n=this.encoding==="utf-16le",a=n?255:254,o=n?254:255;let c=t.length>=2&&t[0]===a&&t[1]===o?2:0;for(;c+1<t.length;){const u=n?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?n?t[c]|t[c+1]<<8:t[c]<<8|t[c+1]:-1;l>=56320&&l<=57343?(r.push(u,l),c+=2):(r.push(65533),c+1===t.length&&c++)}else u>=56320&&u<=57343?r.push(65533):r.push(u)}c<t.length&&r.push(65533)}let s="";for(let n=0;n<r.length;n+=8192)s+=String.fromCharCode(...r.slice(n,n+8192));return s}},nt=new Sr,ff=new Sr("utf-8",{fatal:!0}),ge=new df,ri=i=>{for(let e=0;e<i.length;e++)if(i.charCodeAt(e)>255)return!1;return!0},po=i=>Object.fromEntries(Object.entries(i).map(([e,t])=>[t,e])),Ui={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},di=po(Ui),Ni={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},fi=po(Ni),Vi={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},hi=po(Vi),go=i=>!!i&&!!i.primaries&&!!i.transfer&&!!i.matrix&&i.fullRange!=null,Vl=i=>!i||i.primaries==null&&i.transfer==null&&i.matrix==null&&i.fullRange==null,Wl={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},Ur=i=>i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer||ArrayBuffer.isView(i);class Jt{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e;const t=new Promise(s=>{let n=!1;e=()=>{n||(s(),this.pending--,n=!0)}}),r=this.currentPromise;return this.currentPromise=t,this.pending++,await r,e}}const hf=/^[0-9a-fA-F]+$/,ls=i=>[...i].map(e=>e.toString(16).padStart(2,"0")).join(""),mf=i=>{w(i.length%2===0);const e=new Uint8Array(i.length/2);for(let t=0;t<i.length;t+=2)e[t/2]=parseInt(i.slice(t,t+2),16);return e},ic=i=>(i=i>>1&1431655765|(i&1431655765)<<1,i=i>>2&858993459|(i&858993459)<<2,i=i>>4&252645135|(i&252645135)<<4,i=i>>8&16711935|(i&16711935)<<8,i=i>>16&65535|(i&65535)<<16,i>>>0),As=(i,e,t)=>{let r=0,s=i.length-1,n=-1;for(;r<=s;){const a=r+s>>1,o=t(i[a]);o===e?(n=a,s=a-1):o<e?r=a+1:s=a-1}return n},de=(i,e,t)=>{let r=0,s=i.length-1,n=-1;for(;r<=s;){const a=r+(s-r+1)/2|0;t(i[a])<=e?(n=a,r=a+1):s=a-1}return n},rc=(i,e,t)=>{const r=de(i,t(e),t);i.splice(r+1,0,e)},Ae=()=>{let i,e;return{promise:new Promise((r,s)=>{i=r,e=s}),resolve:i,reject:e}},on=(i,e)=>{const t=i.indexOf(e);t!==-1&&i.splice(t,1)},Ll=(i,e)=>{for(let t=i.length-1;t>=0;t--)if(e(i[t]))return i[t]},Br=(i,e)=>{for(let t=i.length-1;t>=0;t--)if(e(i[t]))return t;return-1},pf=async function*(i){Symbol.iterator in i?yield*i[Symbol.iterator]():yield*i[Symbol.asyncIterator]()},gf=i=>{if(!(Symbol.iterator in i)&&!(Symbol.asyncIterator in i))throw new TypeError("Argument must be an iterable or async iterable.")},xe=i=>{throw new Error(`Unexpected value: ${i}`)},En=(i,e,t)=>{const r=i.getUint8(e),s=i.getUint8(e+1),n=i.getUint8(e+2);return t?r|s<<8|n<<16:r<<16|s<<8|n},wf=(i,e,t)=>En(i,e,t)<<8>>8,In=(i,e,t,r)=>{t=t>>>0,t=t&16777215,r?(i.setUint8(e,t&255),i.setUint8(e+1,t>>>8&255),i.setUint8(e+2,t>>>16&255)):(i.setUint8(e,t>>>16&255),i.setUint8(e+1,t>>>8&255),i.setUint8(e+2,t&255))},yf=(i,e,t,r)=>{t=Be(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),In(i,e,t,r)},bf=(i,e,t,r)=>{t=Math.trunc(t),i.setUint32(e+0,t,!0),i.setInt32(e+4,Math.floor(t/2**32),!0)},cn=(i,e)=>({async next(){const t=await i.next();if(t.done)return{value:void 0,done:!0};try{return{value:e(t.value),done:!1}}catch(r){throw await i.return(),r}},return(){return i.return()},throw(t){return i.throw(t)},[Symbol.asyncIterator](){return this}}),Be=(i,e,t)=>Math.max(e,Math.min(t,i)),kf=(i,e,t)=>i+(e-i)*t,Hl=(i,e)=>i-Math.floor(i/e)*e,et="und",Zt=i=>{const e=Math.round(i);return Math.abs(i/e-1)<10*Number.EPSILON?e:i},Ia=(i,e)=>Math.round(i/e)*e,tr=(i,e)=>Math.round(i*e)/e,Js=(i,e)=>Math.floor(i/e)*e,sc=(i,e)=>Math.floor(i*e)/e,Tf=i=>{let e=0;for(;i;)e++,i>>=1;return e},va=i=>{let e=0;for(;i!==0;)i&=i-1,e++;return e},Sf=/^[a-z]{3}$/,us=i=>Sf.test(i),Bi=1e6*(1+Number.EPSILON),$n=(i,e)=>{const t={...i,...e};if(i.headers||e.headers){const r=i.headers?Ba(i.headers):{},s=e.headers?Ba(e.headers):{},n={...r};Object.entries(s).forEach(([a,o])=>{const c=Object.keys(n).find(u=>u.toLowerCase()===a.toLowerCase());c&&delete n[c],n[a]=o}),t.headers=n}return t},Ba=i=>{if(i instanceof Headers){const e={};return i.forEach((t,r)=>{e[r]=t}),e}if(Array.isArray(i)){const e={};return i.forEach(([t,r])=>{e[t]=r}),e}return i},nc=async(i,e,t,r,s)=>{let n=0;for(;;)try{return await i(e,t)}catch(a){if(s())throw a;n++;const o=r(n,a,e);if(o===null)throw a;if(K._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),s())throw a}},Af=(i,e)=>{const t=i<0?-1:1;i=Math.abs(i);let r=0,s=1,n=1,a=0,o=i;for(;;){const c=Math.floor(o),u=c*n+r,l=c*a+s;if(l>e)return{num:t*n,den:a};if(r=n,s=a,n=u,a=l,o=1/(o-c),!isFinite(o))break}return{num:t*n,den:a}};class vn{constructor(){this.currentPromise=Promise.resolve()}call(e){const t=this.currentPromise.then(e);return this.currentPromise=t.catch(()=>{}),t}}let Qn=null;const wi=()=>{var i;return Qn!==null?Qn:Qn=!!(typeof navigator<"u"&&((i=navigator.vendor)!=null&&i.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)))};let Gn=null;const ir=()=>{var i;return Gn!==null?Gn:Gn=typeof navigator<"u"&&((i=navigator.userAgent)==null?void 0:i.includes("Firefox"))};let Xn=null;const ts=()=>{var i;return Xn!==null?Xn:Xn=!!(typeof navigator<"u"&&((i=navigator.vendor)!=null&&i.includes("Google Inc")||/Chrome/.test(navigator.userAgent)))};let Yn=null;const xf=()=>{if(Yn!==null)return Yn;if(typeof navigator>"u")return null;const i=/\bChrome\/(\d+)/.exec(navigator.userAgent);return i?Yn=Number(i[1]):null};let Zn=null;const Pf=()=>Zn!==null?Zn:Zn=typeof navigator<"u"&&/Android/.test(navigator.userAgent),Bn=i=>typeof globalThis.isSecureContext<"u"&&!globalThis.isSecureContext?`${i} 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.`:`${i} is not available in this environment.`,Cf=i=>i instanceof DOMException&&i.name==="QuotaExceededError"&&/reclaimed/i.test(i.message),_f=(async()=>{})().constructor,D=i=>i instanceof _f||i instanceof Promise?!0:typeof(i==null?void 0:i.then)=="function",pr=(i,e)=>i!==-1?i:e,Fa=(i,e,t,r)=>i<=r&&t<=e,Nr=function*(i){for(const e in i){const t=i[e];t!==void 0&&(yield{key:e,value:t})}},Ef=i=>{switch(i.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}},ln=i=>{let e;try{e=atob(i)}catch{throw new Error("Invalid base64 string.")}const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t},If=i=>{let e="";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return btoa(e)},ql=(i,e)=>{if(i.length!==e.length)return!1;for(let t=0;t<i.length;t++)if(i[t]!==e[t])return!1;return!0},wo=()=>{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},ut=i=>typeof i=="number"&&!Number.isNaN(i),st=(i,e)=>{if(/^(?:[a-z][a-z0-9+.-]*:\/\/|(?:data|blob):)/i.test(e))return e;if(i.includes("://")){const u=i.search(/[?#]/);u!==-1&&(i=i.slice(0,u))}const t=e.search(/[?#]/),r=t===-1?"":e.slice(t);t!==-1&&(e=e.slice(0,t));let s;if(e==="")s=i;else if(e.startsWith("/")){const u=i.indexOf("://");if(u===-1)s=e;else if(e.startsWith("//"))s=i.slice(0,u+1)+e;else{const l=i.indexOf("/",u+3);l===-1?s=i+e:s=i.slice(0,l)+e}}else{const u=i.indexOf("://"),l=i.lastIndexOf("/");u!==-1&&l===u+2?s=i+"/"+e:l===-1?s=e:s=i.slice(0,l+1)+e}let n="";const a=s.indexOf("://");if(a!==-1){const u=s.indexOf("/",a+3);u!==-1&&(n=s.slice(0,u),s=s.slice(u))}const o=s.split("/"),c=[];for(const u of o)u===".."?c.length===0||c[c.length-1]===".."?c.push(".."):(c.length!==1||c[0]!=="")&&c.pop():u!=="."&&c.push(u);return n+c.join("/")+r},vf=(i,e)=>{const t=i.indexOf("#"),r=t===-1?i:i.slice(0,t),s=r.indexOf("?");return s===-1?null:new URLSearchParams(r.slice(s+1)).get(e)},is=(i,e)=>{let t=0;for(let r=0;r<i.length;r++)e(i[r])&&t++;return t},Fn=(i,e)=>{let t=-1,r=1/0;for(let s=0;s<i.length;s++){const n=e(i[s]);(t===-1||n<r)&&(r=n,t=s)}return t},Bf=(i,e)=>{let t=-1,r=-1/0;for(let s=0;s<i.length;s++){const n=e(i[s]);(t===-1||n>r)&&(r=n,t=s)}return t},xs=i=>{w(Number.isInteger(i.num)),w(Number.isInteger(i.den)),w(i.den!==0);let e=Math.abs(i.num),t=Math.abs(i.den);for(;t!==0;){const s=e%t;e=t,t=s}const r=e||1;return{num:i.num/r,den:i.den/r}},Ff=(i,e)=>{if(typeof i!="object"||!i)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(i.left)||i.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(i.top)||i.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(i.width)||i.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(i.height)||i.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)};let Hr,Rf=1;const ac=new Map,yo=new Map,jl=()=>typeof window>"u",Mf=()=>{const i=new Map,e=new Map;self.onmessage=t=>{const r=t.data;switch(r.type){case"set-timeout":{const s=setTimeout(()=>{i.delete(r.timerId),self.postMessage({type:"fire",timerId:r.timerId})},r.delay);i.set(r.timerId,s)}break;case"set-interval":{const s=setInterval(()=>{self.postMessage({type:"fire",timerId:r.timerId})},r.delay);e.set(r.timerId,s)}break;case"clear-timeout":{const s=i.get(r.timerId);s!==void 0&&(clearTimeout(s),i.delete(r.timerId))}break;case"clear-interval":{const s=e.get(r.timerId);s!==void 0&&(clearInterval(s),e.delete(r.timerId))}break}}},Kl=()=>{if(Hr)return Hr;const i=`(${Mf.toString()})();`,e=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));return Hr=new Worker(e),URL.revokeObjectURL(e),Hr.onmessage=t=>{const r=t.data,s=ac.get(r.timerId);if(s){ac.delete(r.timerId),s();return}const n=yo.get(r.timerId);n&&n()},Hr},Df=(i,e)=>{if(jl())return{id:setInterval(i,e)};const t=Rf++;return yo.set(t,()=>{i()}),Kl().postMessage({type:"set-interval",timerId:t,delay:e}),{id:t}},zf=i=>{if(jl()){clearInterval(i.id);return}w(typeof i.id=="number"),yo.delete(i.id),Kl().postMessage({type:"clear-interval",timerId:i.id})},Ar=i=>new Promise(e=>setTimeout(e,i)),Fi=i=>Array.isArray(i)?i:[i];class Ps{constructor(){this._listeners=new Map}on(e,t,r){this._listeners.has(e)||this._listeners.set(e,new Set);const s={fn:t,once:(r==null?void 0:r.once)??!1};return this._listeners.get(e).add(s),()=>{var n;(n=this._listeners.get(e))==null||n.delete(s)}}_emit(...e){const[t,r]=e,s=this._listeners.get(t);if(s){for(const n of[...s])if(s.has(n)){n.once&&s.delete(n);try{n.fn(r)}catch(a){console.error(a)}}}}}const cr=i=>Math.ceil(i/2)*2;class i0{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(()=>on(this._queue,t)).catch(()=>this._errored=!0)}async flush(){await Promise.all(this._queue)}}const $l=i=>i!==null&&typeof i=="object"&&Object.getPrototypeOf(i)===Object.prototype&&Object.values(i).every(e=>typeof e=="string"),un=(i,e=0,t=1)=>{const r=new Date(0);return r.setUTCFullYear(i,e,t),r},Of=/^(\d{4})(?:-(\d{2})(?:-(\d{2})(?:[T ](\d{2})(?::(\d{2})(?::(\d{2})(?:\.(\d+))?)?)?)?)?)?(?:Z|([+-])(\d{2})(?::?(\d{2}))?)?$/,Fr=i=>{const e=Of.exec(i);if(!e)return null;const[,t,r="01",s="01",n="00",a="00",o="00",c="",u="+",l="00",d="00"]=e,f=`${t}-${r}-${s}T${n}:${a}:${o}`,h=new Date(`${f}.${c.padEnd(3,"0").slice(0,3)}Z`);if(Number.isNaN(h.getTime())||!h.toISOString().startsWith(f)||Number(l)>23||Number(d)>59)return null;const p=(u==="-"?-1:1)*(60*Number(l)+Number(d));return h.setTime(h.getTime()-6e4*p),h};/*!
|
|
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 jt;(function(i){i[i.Silent=0]="Silent",i[i.Errors=1]="Errors",i[i.Warnings=2]="Warnings",i[i.Info=3]="Info"})(jt||(jt={}));class K{constructor(){}static get level(){return K._level}static set level(e){if(e!==jt.Silent&&e!==jt.Errors&&e!==jt.Warnings&&e!==jt.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");K._level=e}static get _emitter(){return K._emitterInstance??(K._emitterInstance=new Ps)}static on(e,t,r){return K._emitter.on(e,t,r)}static _error(...e){K._emitter._emit("error",e),K._level>=jt.Errors&&console.error(...e)}static _warn(...e){K._emitter._emit("warn",e),K._level>=jt.Warnings&&console.warn(...e)}static _info(...e){K._emitter._emit("info",e),K._level>=jt.Info&&console.info(...e)}}K._level=jt.Info;K._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 xr{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 bo{constructor(e,t,r,s){if(this.data=e,this.mimeType=t,this.name=r,this.description=s,!(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(r!==void 0&&typeof r!="string")throw new TypeError("name, when provided, must be a string.");if(s!==void 0&&typeof s!="string")throw new TypeError("description, when provided, must be a string.")}}const Ra=i=>{if(!i||typeof i!="object")throw new TypeError("tags must be an object.");if(i.title!==void 0&&typeof i.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(i.description!==void 0&&typeof i.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(i.artist!==void 0&&typeof i.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(i.album!==void 0&&typeof i.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(i.albumArtist!==void 0&&typeof i.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(i.trackNumber!==void 0&&(!Number.isInteger(i.trackNumber)||i.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(i.tracksTotal!==void 0&&(!Number.isInteger(i.tracksTotal)||i.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(i.discNumber!==void 0&&(!Number.isInteger(i.discNumber)||i.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(i.discsTotal!==void 0&&(!Number.isInteger(i.discsTotal)||i.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(i.genre!==void 0&&typeof i.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(i.date!==void 0&&(!(i.date instanceof Date)||Number.isNaN(i.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(i.creationTime!==void 0&&i.creationTime!==null&&(!(i.creationTime instanceof Date)||Number.isNaN(i.creationTime.getTime())))throw new TypeError("tags.creationTime, when provided, must be a valid Date or null.");if(i.beatsPerMinute!==void 0&&(!Number.isInteger(i.beatsPerMinute)||i.beatsPerMinute<=0))throw new TypeError("tags.beatsPerMinute, when provided, must be a positive integer.");if(i.lyrics!==void 0&&typeof i.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(i.images!==void 0){if(!Array.isArray(i.images))throw new TypeError("tags.images, when provided, must be an array.");for(const e of i.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(e.name!==void 0&&typeof e.name!="string")throw new TypeError("Each image.name, when provided, must be a string.");if(e.description!==void 0&&typeof e.description!="string")throw new TypeError("Each image.description, when provided, must be a string.")}}if(i.comment!==void 0&&typeof i.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(i.raw!==void 0){if(!i.raw||typeof i.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(const e of Object.values(i.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 xr)&&!(e instanceof bo)&&!$l(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.")}},ds=i=>i.title===void 0&&i.description===void 0&&i.artist===void 0&&i.album===void 0&&i.albumArtist===void 0&&i.trackNumber===void 0&&i.tracksTotal===void 0&&i.discNumber===void 0&&i.discsTotal===void 0&&i.genre===void 0&&i.beatsPerMinute===void 0&&i.date===void 0&&i.lyrics===void 0&&(!i.images||i.images.length===0)&&i.comment===void 0&&(i.raw===void 0||Object.keys(i.raw).length===0),Si={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},Uf=i=>{if(!i||typeof i!="object")throw new TypeError("disposition must be an object.");if(i.default!==void 0&&typeof i.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(i.primary!==void 0&&typeof i.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(i.forced!==void 0&&typeof i.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(i.original!==void 0&&typeof i.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(i.commentary!==void 0&&typeof i.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(i.hearingImpaired!==void 0&&typeof i.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(i.visuallyImpaired!==void 0&&typeof i.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 oe{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,r=7-(this.pos&7),s=(t&1<<r)>>r;return this.pos++,s}readBits(e){if(e===1)return this.readBit();let t=0;for(let r=0;r<e;r++)t=2*t+this.readBit();return t}writeBits(e,t){const r=this.pos+e;for(let s=this.pos;s<r;s++){const n=Math.floor(s/8);let a=this.bytes[n];const o=7-(s&7),c=Math.floor(t/2**(r-s-1))&1;a&=~(1<<o),a|=c<<o,this.bytes[n]=a}this.pos=r}copyBits(e,t){let r=0;for(r;r<e-7;r+=8)this.writeBits(8,t.readBits(8));const s=e-r;s>0&&this.writeBits(s,t.readBits(s))}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 oe(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 Ot=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Vr=[-1,1,2,3,4,5,6,8],Nf=[1,2,3,4,6,7,17,19,20,21,22],nr=i=>{if(!i||i.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new oe(i),t=Jn(e),{frequencyIndex:r,sampleRate:s}=ea(e),n=e.readBits(4);let a=null;n>=1&&n<=7&&(a=Vr[n]);let o=t,c=!1,u=s;(t===5||t===29)&&(c=t===29,u=ea(e).sampleRate,o=Jn(e),o===22&&e.skipBits(4));let l=1024,d=null;if(Nf.includes(o)&&(l=e.readBits(1)?960:1024,n===0&&(e.readBits(1)&&e.skipBits(14),e.skipBits(1),d=Zl(e),a=Cs(d))),t!==5&&t!==29)for(;e.getBitsLeft()>15;){const f=e.pos;if(e.readBits(11)!==695){e.pos=f+1;continue}Jn(e)===5&&e.readBits(1)&&(u=ea(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:r,channelConfiguration:n,coreSampleRate:s,outputSampleRate:u,outputNumberOfChannels:c&&a===1?2:a,frameLength:l,programConfigElement:d}},Jn=i=>{const e=i.readBits(5);return e===31?32+i.readBits(6):e},ea=i=>{const e=i.readBits(4);return e===15?{frequencyIndex:e,sampleRate:i.readBits(24)}:{frequencyIndex:e,sampleRate:e<Ot.length?Ot[e]:null}},Rn=i=>{const e=i.objectType===5||i.objectType===29,t=i.objectType===29,r=e?i.outputSampleRate/2:i.outputSampleRate,s=t?1:i.outputNumberOfChannels,n=i.programConfigElement?0:Vr.indexOf(s);if(n===-1)throw new TypeError(`Unsupported number of channels: ${i.outputNumberOfChannels}`);let a=16;i.objectType>=32&&(a+=6),Ma(r)===15&&(a+=24),e&&(a+=9,Ma(i.outputSampleRate)===15&&(a+=24));const o=Math.ceil(a/8)+(i.programConfigElement?Gl(i.programConfigElement):0),c=new Uint8Array(o),u=new oe(c);return oc(u,i.objectType),cc(u,r),u.writeBits(4,n),e&&(cc(u,i.outputSampleRate),oc(u,2)),u.writeBits(3,0),i.programConfigElement&&Xl(u,i.programConfigElement),c.subarray(0,Math.ceil(u.pos/8))},oc=(i,e)=>{e<32?i.writeBits(5,e):(i.writeBits(5,31),i.writeBits(6,e-32))},cc=(i,e)=>{const t=Ma(e);i.writeBits(4,t),t===15&&i.writeBits(24,e)},Ma=i=>{const e=Ot.indexOf(i);return e===-1?15:e},Ql=i=>{const{coreObjectType:e,frequencyIndex:t,frameLength:r}=i;let{channelConfiguration:s,programConfigElement:n}=i;if(e<1||e>4)throw new Error(`AAC object type ${e} can't be stored in ADTS.`);if(t>=Ot.length)throw new Error(`AAC sampling frequency index ${t} can't be stored in ADTS.`);if(s===11||s===12){const u={isCpe:!0,tagSelect:1};n={elementInstanceTag:0,objectType:e-1,samplingFrequencyIndex:t,frontElements:[{isCpe:!1,tagSelect:0},{isCpe:!0,tagSelect:0}],sideElements:s===12?[u]:[],backElements:s===11?[u,{isCpe:!1,tagSelect:1}]:[{isCpe:!0,tagSelect:2}],lfeElementTags:[0],assocDataElementTags:[],ccElements:[],monoMixdownElementNumber:null,stereoMixdownElementNumber:null,matrixMixdown:null,comment:new Uint8Array(0)},s=0}if(s>7)throw new Error(`AAC channel configuration ${s} can't be stored in ADTS.`);if(r!==1024)throw new Error(`AAC frame length ${r} can't be stored in ADTS.`);let a=new Uint8Array(7+(n?Gl(n):0));const o=new oe(a),c=e-1;return o.writeBits(12,4095),o.writeBits(1,0),o.writeBits(2,0),o.writeBits(1,1),o.writeBits(2,c),o.writeBits(4,t),o.writeBits(1,0),o.writeBits(3,s),o.writeBits(1,0),o.writeBits(1,0),o.writeBits(1,0),o.writeBits(1,0),o.skipBits(13),o.writeBits(11,2047),o.writeBits(2,0),n&&(o.pos=56,o.writeBits(3,5),Xl(o,n),a=a.subarray(0,o.pos/8)),{header:a,bitstream:o}},Gl=i=>64+i.comment.byteLength,Xl=(i,e)=>{i.writeBits(4,e.elementInstanceTag),i.writeBits(2,e.objectType),i.writeBits(4,e.samplingFrequencyIndex),i.writeBits(4,e.frontElements.length),i.writeBits(4,e.sideElements.length),i.writeBits(4,e.backElements.length),i.writeBits(2,e.lfeElementTags.length),i.writeBits(3,e.assocDataElementTags.length),i.writeBits(4,e.ccElements.length),i.writeBits(1,+(e.monoMixdownElementNumber!==null)),e.monoMixdownElementNumber!==null&&i.writeBits(4,e.monoMixdownElementNumber),i.writeBits(1,+(e.stereoMixdownElementNumber!==null)),e.stereoMixdownElementNumber!==null&&i.writeBits(4,e.stereoMixdownElementNumber),i.writeBits(1,+(e.matrixMixdown!==null)),e.matrixMixdown&&(i.writeBits(2,e.matrixMixdown.index),i.writeBits(1,+e.matrixMixdown.pseudoSurroundEnabled));for(const t of[...e.frontElements,...e.sideElements,...e.backElements])i.writeBits(1,+t.isCpe),i.writeBits(4,t.tagSelect);for(const t of[...e.lfeElementTags,...e.assocDataElementTags])i.writeBits(4,t);for(const t of e.ccElements)i.writeBits(1,+t.isIndependentlySwitched),i.writeBits(4,t.tagSelect);i.pos=8*Math.ceil(i.pos/8),i.writeBits(8,e.comment.byteLength),i.bytes.set(e.comment,i.pos/8),i.pos+=8*e.comment.byteLength},Yl=(i,e)=>{if(e>=2**13)throw new Error(`AAC frame too large for ADTS (${e} bytes, at most ${2**13-1} allowed).`);i.pos=30,i.writeBits(13,e)},Rr=i=>{const e=new oe(i);if(e.readBits(3)!==5)return null;const t=Zl(e),r=e.pos/8;if(r>i.byteLength)throw new Error("Invalid ADTS frame: its program config element extends past the end of the frame.");return{programConfigElement:t,size:r}},Zl=i=>{const e=i.readBits(4),t=i.readBits(2),r=i.readBits(4),s=i.readBits(4),n=i.readBits(4),a=i.readBits(4),o=i.readBits(2),c=i.readBits(3),u=i.readBits(4),l=i.readBits(1)?i.readBits(4):null,d=i.readBits(1)?i.readBits(4):null,f=i.readBits(1)?{index:i.readBits(2),pseudoSurroundEnabled:!!i.readBits(1)}:null,h=T=>Array.from({length:T},()=>({isCpe:!!i.readBits(1),tagSelect:i.readBits(4)})),p=h(s),m=h(n),g=h(a),y=Array.from({length:o},()=>i.readBits(4)),b=Array.from({length:c},()=>i.readBits(4)),S=Array.from({length:u},()=>({isIndependentlySwitched:!!i.readBits(1),tagSelect:i.readBits(4)}));i.pos=8*Math.ceil(i.pos/8);const A=i.readBits(8),x=i.bytes.slice(i.pos/8,i.pos/8+A);return i.pos+=8*A,{elementInstanceTag:e,objectType:t,samplingFrequencyIndex:r,frontElements:p,sideElements:m,backElements:g,lfeElementTags:y,assocDataElementTags:b,ccElements:S,monoMixdownElementNumber:l,stereoMixdownElementNumber:d,matrixMixdown:f,comment:x}},Cs=i=>[...i.frontElements,...i.sideElements,...i.backElements].reduce((t,r)=>t+(r.isCpe?2:1),i.lfeElementTags.length);/*!
|
|
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 Yt=4,dn=529,Jl=[44100,48e3,32e3],Da=[-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],fs=1483304551,Mn=1231971951,Vf=1447187017,za=(i,e,t,r,s)=>e===0?0:e===1?Math.floor(144*t/(r<<i))+s:e===2?Math.floor(144*t/r)+s:(Math.floor(12*t/r)+s)*4,Wf=(i,e,t,r)=>e===0?0:e===1?144*t/(r<<i):e===2?144*t/r:12*t/r*4,Dn=(i,e)=>i===3?e===3?21:36:e===3?13:21,Mr=(i,e)=>{const t=i>>>24,r=i>>>16&255,s=i>>>8&255,n=i&255;if(t!==255&&r!==255&&s!==255&&n!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((r&224)!==224)return{header:null,bytesAdvanced:1};let a=0,o=0;r&16?a=r&8?0:1:(a=1,o=1);const c=r>>3&3,u=r>>1&3,l=s>>4&15,d=s>>2&3;if(c===1||d===3)return{header:null,bytesAdvanced:1};const f=s>>1&1,h=n>>6&3,p=n>>4&3,m=n>>3&1,g=n>>2&1,y=n&3,b=Da[a*16*4+u*16+l];if(b===-1)return{header:null,bytesAdvanced:1};const S=b*1e3,A=Jl[d]>>a+o,x=za(a,u,S,A,f);if(e!==null&&e<x)return{header:null,bytesAdvanced:1};let T;return c===3?T=u===3?384:1152:u===3?T=384:u===2?T=1152:T=576,{header:{totalSize:x,mpegVersionId:c,lowSamplingFrequency:a,layer:u,bitrate:S,frequencyIndex:d,sampleRate:A,channel:h,modeExtension:p,copyright:m,original:g,emphasis:y,audioSamplesInFrame:T},bytesAdvanced:1}},Lf=i=>{let e=127,t=0,r=i;for(;(e^2147483647)!==0;)t=r&~e,t<<=1,t|=r&e,e=(e+1<<8)-1,r=t;return t},fn=i=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=i&e,e>>=8;return t};var Gt;(function(i){i[i.FrameCount=1]="FrameCount",i[i.FileSize=2]="FileSize",i[i.Toc=4]="Toc",i[i.Quality=8]="Quality"})(Gt||(Gt={}));const hs=i=>i===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 zn=[48e3,44100,32e3],eu=[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 Hf=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 qf="1.66.0",Pr=`Mediabunny v${qf}`;/*!
|
|
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 Ve;(function(i){i[i.NON_IDR_SLICE=1]="NON_IDR_SLICE",i[i.SLICE_DPA=2]="SLICE_DPA",i[i.SLICE_DPB=3]="SLICE_DPB",i[i.SLICE_DPC=4]="SLICE_DPC",i[i.IDR=5]="IDR",i[i.SEI=6]="SEI",i[i.SPS=7]="SPS",i[i.PPS=8]="PPS",i[i.AUD=9]="AUD",i[i.SPS_EXT=13]="SPS_EXT"})(Ve||(Ve={}));var ke;(function(i){i[i.RASL_N=8]="RASL_N",i[i.RASL_R=9]="RASL_R",i[i.BLA_W_LP=16]="BLA_W_LP",i[i.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",i[i.VPS_NUT=32]="VPS_NUT",i[i.SPS_NUT=33]="SPS_NUT",i[i.PPS_NUT=34]="PPS_NUT",i[i.AUD_NUT=35]="AUD_NUT",i[i.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",i[i.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(ke||(ke={}));const Wr=function*(i){let e=0,t=-1;for(;e<i.length-2;){const r=i.indexOf(0,e);if(r===-1||r>=i.length-2)break;e=r;let s=0;if(e+3<i.length&&i[e+1]===0&&i[e+2]===0&&i[e+3]===1?s=4:i[e+1]===0&&i[e+2]===1&&(s=3),s===0){e++;continue}t!==-1&&e>t&&(yield{offset:t,length:e-t}),t=e+s,e=t}t!==-1&&t<i.length&&(yield{offset:t,length:i.length-t})},ko=function*(i,e){let t=0;const r=new DataView(i.buffer,i.byteOffset,i.byteLength);for(;t+e<=i.length;){let s;e===1?s=r.getUint8(t):e===2?s=r.getUint16(t,!1):e===3?s=En(r,t,!1):(w(e===4),s=r.getUint32(t,!1)),t+=e,yield{offset:t,length:s},t+=s}},tu=(i,e)=>{if(e.description){const s=(me(e.description)[4]&3)+1;return ko(i,s)}else return Wr(i)},rr=i=>i&31,On=i=>{const e=new Uint8Array(i.length),t=i.length;let r=0;for(let s=0;s<t;s++)s+2<t&&i[s]===0&&i[s+1]===0&&i[s+2]===3?(e[r++]=0,e[r++]=0,s+=2):e[r++]=i[s];return e.subarray(0,r)},jf=i=>{const e=[];let t=0;for(const r of i)t===2&&r<=3&&(e.push(3),t=0),e.push(r),t=r===0?t+1:0;return new Uint8Array(e)},ta=new Uint8Array([0,0,0,1]),hn=i=>{const e=i.reduce((s,n)=>s+ta.byteLength+n.byteLength,0),t=new Uint8Array(e);let r=0;for(const s of i)t.set(ta,r),r+=ta.byteLength,t.set(s,r),r+=s.byteLength;return t},To=(i,e)=>{const t=i.reduce((n,a)=>n+e+a.byteLength,0),r=new Uint8Array(t);let s=0;for(const n of i){const a=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(e){case 1:a.setUint8(s,n.byteLength);break;case 2:a.setUint16(s,n.byteLength,!1);break;case 3:In(a,s,n.byteLength,!1);break;case 4:a.setUint32(s,n.byteLength,!1);break}s+=e,r.set(n,s),s+=n.byteLength}return r},Kf=(i,e)=>{if(e.description){const s=(me(e.description)[4]&3)+1;return To(i,s)}else return hn(i)},_s=i=>{try{const e=[],t=[],r=[];for(const o of Wr(i)){const c=i.subarray(o.offset,o.offset+o.length),u=rr(c[0]);u===Ve.SPS&&e.length<31?e.push(c):u===Ve.PPS&&t.length<255?t.push(c):u===Ve.SPS_EXT&&r.length<255&&r.push(c)}if(e.length===0||t.length===0)return null;const s=e[0],n=Zi(s);if(!n)return null;const a=Ao(n.profileIdc);return{configurationVersion:1,avcProfileIndication:n.profileIdc,profileCompatibility:n.constraintFlags,avcLevelIndication:n.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:t,chromaFormat:a?n.chromaFormatIdc:null,bitDepthLumaMinus8:a?n.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?n.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?r:null}}catch(e){return K._error("Error building AVC Decoder Configuration Record:",e),null}},So=i=>{const e=[];e.push(i.configurationVersion),e.push(i.avcProfileIndication),e.push(i.profileCompatibility),e.push(i.avcLevelIndication),e.push(252|i.lengthSizeMinusOne&3),e.push(224|i.sequenceParameterSets.length&31);for(const t of i.sequenceParameterSets){const r=t.byteLength;e.push(r>>8),e.push(r&255);for(let s=0;s<r;s++)e.push(t[s])}e.push(i.pictureParameterSets.length);for(const t of i.pictureParameterSets){const r=t.byteLength;e.push(r>>8),e.push(r&255);for(let s=0;s<r;s++)e.push(t[s])}if(Ao(i.avcProfileIndication)&&i.chromaFormat!==null){w(i.bitDepthLumaMinus8!==null),w(i.bitDepthChromaMinus8!==null),w(i.sequenceParameterSetExt!==null),e.push(252|i.chromaFormat&3),e.push(248|i.bitDepthLumaMinus8&7),e.push(248|i.bitDepthChromaMinus8&7),e.push(i.sequenceParameterSetExt.length);for(const t of i.sequenceParameterSetExt){const r=t.byteLength;e.push(r>>8),e.push(r&255);for(let s=0;s<r;s++)e.push(t[s])}}return new Uint8Array(e)},Es=i=>{try{const e=ie(i);let t=0;const r=e.getUint8(t++),s=e.getUint8(t++),n=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(i.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(i.subarray(t,t+p)),t+=p}const f={configurationVersion:r,avcProfileIndication:s,profileCompatibility:n,avcLevelIndication:a,lengthSizeMinusOne:o,sequenceParameterSets:u,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if(Ao(s)&&t+4<=i.length){const h=e.getUint8(t++)&3,p=e.getUint8(t++)&7,m=e.getUint8(t++)&7,g=e.getUint8(t++);f.chromaFormat=h,f.bitDepthLumaMinus8=p,f.bitDepthChromaMinus8=m;const y=[];for(let b=0;b<g;b++){const S=e.getUint16(t,!1);t+=2,y.push(i.subarray(t,t+S)),t+=S}f.sequenceParameterSetExt=y}return f}catch(e){return K._error("Error deserializing AVC Decoder Configuration Record:",e),null}},Ao=i=>i!==66&&i!==77&&i!==88,iu={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}},Zi=i=>{try{const e=On(i),t=new oe(e);if(t.skipBits(1),t.skipBits(2),t.readBits(5)!==7)return null;const s=t.readAlignedByte(),n=t.readAlignedByte(),a=t.readAlignedByte();j(t);let o=1,c=0,u=0,l=0;if((s===100||s===110||s===122||s===244||s===44||s===83||s===86||s===118||s===128||s===138||s===139||s===134||s===135||s===144)&&(o=j(t),o===3&&(l=t.readBits(1)),c=j(t),u=j(t),t.skipBits(1),t.readBits(1))){for(let L=0;L<(o!==3?8:12);L++)if(t.readBits(1)){const re=L<6?16:64;let Y=8,se=8;for(let pe=0;pe<re;pe++){if(se!==0){const he=mi(t);se=(Y+he+256)%256}Y=se===0?Y:se}}}j(t);const d=j(t);if(d===0)j(t);else if(d===1){t.skipBits(1),mi(t),mi(t);const U=j(t);for(let L=0;L<U;L++)mi(t)}const f=j(t);t.skipBits(1);const h=j(t),p=j(t),m=t.readBits(1);m||t.skipBits(1);const g=16*(h+1),y=16*(2-m)*(p+1);let b=g,S=y;if(t.skipBits(1),t.readBits(1)){const U=j(t),L=j(t),Q=j(t),re=j(t);let Y,se;if((l===0?o:0)===0)Y=1,se=2-m;else{const he=o===3?1:2,Pe=o===1?2:1;Y=he,se=Pe*(2-m)}b-=Y*(U+L),S-=se*(Q+re)}if(b<=0||S<=0)return null;let x=2,T=2,P=2,C=0,_={num:1,den:1},I=null,v=null,R=null,F=null;const H=t.pos;if(t.readBits(1)){if(t.readBits(1)){const he=t.readBits(8);if(he===255)_={num:t.readBits(16),den:t.readBits(16)};else{const Pe=iu[he];Pe&&(_=Pe)}}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),C=t.readBits(1),t.readBits(1)&&(x=t.readBits(8),T=t.readBits(8),P=t.readBits(8))),t.readBits(1)&&(j(t),j(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));const se=t.readBits(1);se&&lc(t);const pe=t.readBits(1);pe&&lc(t),(se||pe)&&t.skipBits(1),t.skipBits(1),R=t.pos,F=t.readBits(1),F&&(t.skipBits(1),j(t),j(t),j(t),j(t),I=Math.min(j(t),16),v=Math.min(j(t),16))}if(I===null){w(v===null);const U=n&16;if((s===44||s===86||s===100||s===110||s===122||s===244)&&U)I=0,v=0;else{const L=h+1,Q=p+1,re=(2-m)*Q,Y=a===11&&U&&(s===66||s===77||s===88),se=xn.find(he=>he.level>=(Y?10:a))??Te(xn),pe=Math.min(Math.floor(se.maxDpbMbs/(L*re)),16);I=pe,v=Math.min(Math.max(pe,f),16)}}return w(v!==null),{emulationUnpreventedBytes:e,profileIdc:s,constraintFlags:n,levelIdc:a,frameMbsOnlyFlag:m,chromaFormatIdc:o,bitDepthLumaMinus8:c,bitDepthChromaMinus8:u,codedWidth:g,codedHeight:y,displayWidth:b,displayHeight:S,pixelAspectRatio:_,colourPrimaries:x,matrixCoefficients:P,transferCharacteristics:T,fullRangeFlag:C,numReorderFrames:I,maxDecFrameBuffering:v,vuiParametersFlagBitOffset:H,bitstreamRestrictionFlagBitOffset:R,bitstreamRestrictionFlag:F}}catch(e){return K._error("Error parsing AVC SPS:",e),null}},lc=i=>{const e=j(i);i.skipBits(4),i.skipBits(4);for(let t=0;t<=e;t++)j(i),j(i),i.skipBits(1);i.skipBits(5),i.skipBits(5),i.skipBits(5),i.skipBits(5)},uc=i=>{w(i.bitstreamRestrictionFlag!==1);const e=new Uint8Array(i.emulationUnpreventedBytes.byteLength+64),t=new oe(i.emulationUnpreventedBytes),r=new oe(e);i.bitstreamRestrictionFlag===null?(r.copyBits(i.vuiParametersFlagBitOffset,t),r.writeBits(1,1),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0)):(w(i.bitstreamRestrictionFlagBitOffset!==null),r.copyBits(i.bitstreamRestrictionFlagBitOffset,t)),r.writeBits(1,1),r.writeBits(1,1),or(r,2),or(r,1),or(r,16),or(r,16),or(r,i.numReorderFrames),or(r,i.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const s=r.pos/8;return w(Number.isInteger(s)),jf(e.subarray(0,s))},$f=(i,e)=>{if(e.description){const s=(me(e.description)[21]&3)+1;return To(i,s)}else return hn(i)},mn=(i,e)=>{if(e.description){const s=(me(e.description)[21]&3)+1;return ko(i,s)}else return Wr(i)},zi=i=>i>>1&63,Un=i=>{try{const e=new oe(On(i));e.skipBits(16),e.readBits(4);const t=e.readBits(3),r=e.readBits(1),{general_profile_space:s,general_tier_flag:n,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:u}=Qf(e,t);j(e);const l=j(e);let d=0;l===3&&(d=e.readBits(1));const f=j(e),h=j(e);let p=f,m=h;if(e.readBits(1)){const F=j(e),H=j(e),O=j(e),U=j(e);let L=1,Q=1;const re=d===0?l:0;re===1?(L=2,Q=2):re===2&&(L=2,Q=1),p-=(F+H)*L,m-=(O+U)*Q}if(p<=0||m<=0)return null;const g=j(e),y=j(e),b=j(e),A=e.readBits(1)?0:t;let x=0;for(let F=A;F<=t;F++)j(e),x=j(e),j(e);j(e),j(e),j(e),j(e),j(e),j(e),e.readBits(1)&&e.readBits(1)&&Gf(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),j(e),j(e),e.skipBits(1));const T=j(e);if(Xf(e,T),e.readBits(1)){const F=j(e);for(let H=0;H<F;H++)e.skipBits(b+4),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let P=2,C=2,_=2,I=0,v=0,R={num:1,den:1};if(e.readBits(1)){const F=Zf(e,t);R=F.pixelAspectRatio,P=F.colourPrimaries,C=F.transferCharacteristics,_=F.matrixCoefficients,I=F.fullRangeFlag,v=F.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,pixelAspectRatio:R,colourPrimaries:P,transferCharacteristics:C,matrixCoefficients:_,fullRangeFlag:I,maxDecFrameBuffering:Math.min(x+1,16),spsMaxSubLayersMinus1:t,spsTemporalIdNestingFlag:r,generalProfileSpace:s,generalTierFlag:n,generalProfileIdc:a,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:u,chromaFormatIdc:l,bitDepthLumaMinus8:g,bitDepthChromaMinus8:y,minSpatialSegmentationIdc:v}}catch(e){return K._error("Error parsing HEVC SPS:",e),null}},Is=i=>{try{const e=[],t=[],r=[],s=[],n=[];for(const d of Wr(i)){const f=i.subarray(d.offset,d.offset+d.length),h=zi(f[0]);h===ke.VPS_NUT&&e.length<65535?e.push(f):h===ke.SPS_NUT&&t.length<65535?t.push(f):h===ke.PPS_NUT&&r.length<65535?r.push(f):h===ke.PREFIX_SEI_NUT&&s.length<65535?s.push(f):h===ke.SUFFIX_SEI_NUT&&n.length<65535&&n.push(f)}if(t.length===0||r.length===0)return null;const o=Un(t[0]);if(!o)return null;let c=0;if(r.length>0){const d=r[0],f=new oe(On(d));f.skipBits(16),j(f),j(f),f.skipBits(1),f.skipBits(1),f.skipBits(3),f.skipBits(1),f.skipBits(1),j(f),j(f),mi(f),f.skipBits(1),f.skipBits(1),f.readBits(1)&&j(f),mi(f),mi(f),f.skipBits(1),f.skipBits(1),f.skipBits(1),f.skipBits(1);const h=f.readBits(1),p=f.readBits(1);!h&&!p?c=0:h&&!p?c=2:!h&&p?c=3:c=0}const u=[...e.length?[{arrayCompleteness:1,nalUnitType:ke.VPS_NUT,nalUnits:e}]:[],...t.length?[{arrayCompleteness:1,nalUnitType:ke.SPS_NUT,nalUnits:t}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:ke.PPS_NUT,nalUnits:r}]:[],...s.length?[{arrayCompleteness:0,nalUnitType:ke.PREFIX_SEI_NUT,nalUnits:s}]:[],...n.length?[{arrayCompleteness:0,nalUnitType:ke.SUFFIX_SEI_NUT,nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:o.generalProfileSpace,generalTierFlag:o.generalTierFlag,generalProfileIdc:o.generalProfileIdc,generalProfileCompatibilityFlags:o.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:o.generalConstraintIndicatorFlags,generalLevelIdc:o.generalLevelIdc,minSpatialSegmentationIdc:o.minSpatialSegmentationIdc,parallelismType:c,chromaFormatIdc:o.chromaFormatIdc,bitDepthLumaMinus8:o.bitDepthLumaMinus8,bitDepthChromaMinus8:o.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:o.spsMaxSubLayersMinus1+1,temporalIdNested:o.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:u}}catch(e){return K._error("Error building HEVC Decoder Configuration Record:",e),null}},Qf=(i,e)=>{const t=i.readBits(2),r=i.readBits(1),s=i.readBits(5);let n=0;for(let l=0;l<32;l++)n=n<<1|i.readBits(1);const a=new Uint8Array(6);for(let l=0;l<6;l++)a[l]=i.readBits(8);const o=i.readBits(8),c=[],u=[];for(let l=0;l<e;l++)c.push(i.readBits(1)),u.push(i.readBits(1));if(e>0)for(let l=e;l<8;l++)i.skipBits(2);for(let l=0;l<e;l++)c[l]&&i.skipBits(88),u[l]&&i.skipBits(8);return{general_profile_space:t,general_tier_flag:r,general_profile_idc:s,general_profile_compatibility_flags:n,general_constraint_indicator_flags:a,general_level_idc:o}},Gf=i=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!i.readBits(1))j(i);else{const s=Math.min(64,1<<4+(e<<1));e>1&&mi(i);for(let n=0;n<s;n++)mi(i)}},Xf=(i,e)=>{const t=[];for(let r=0;r<e;r++)t[r]=Yf(i,r,e,t)},Yf=(i,e,t,r)=>{let s=0,n=0,a=0;if(e!==0&&(n=i.readBits(1)),n){if(e===t){const c=j(i);a=e-(c+1)}else a=e-1;i.readBits(1),j(i);const o=r[a]??0;for(let c=0;c<=o;c++)(i.readBits(1)||i.readBits(1))&&s++}else{const o=j(i),c=j(i);for(let u=0;u<o;u++)j(i),i.readBits(1);for(let u=0;u<c;u++)j(i),i.readBits(1);s=o+c}return s},Zf=(i,e)=>{let t=2,r=2,s=2,n=0,a=0,o={num:1,den:1};if(i.readBits(1)){const c=i.readBits(8);if(c===255)o={num:i.readBits(16),den:i.readBits(16)};else{const u=iu[c];u&&(o=u)}}return i.readBits(1)&&i.readBits(1),i.readBits(1)&&(i.readBits(3),n=i.readBits(1),i.readBits(1)&&(t=i.readBits(8),r=i.readBits(8),s=i.readBits(8))),i.readBits(1)&&(j(i),j(i)),i.readBits(1),i.readBits(1),i.readBits(1),i.readBits(1)&&(j(i),j(i),j(i),j(i)),i.readBits(1)&&(i.readBits(32),i.readBits(32),i.readBits(1)&&j(i),i.readBits(1)&&Jf(i,!0,e)),i.readBits(1)&&(i.readBits(1),i.readBits(1),i.readBits(1),a=j(i),j(i),j(i),j(i),j(i)),{pixelAspectRatio:o,colourPrimaries:t,transferCharacteristics:r,matrixCoefficients:s,fullRangeFlag:n,minSpatialSegmentationIdc:a}},Jf=(i,e,t)=>{let r=!1,s=!1,n=!1;r=i.readBits(1)===1,s=i.readBits(1)===1,(r||s)&&(n=i.readBits(1)===1,n&&(i.readBits(8),i.readBits(5),i.readBits(1),i.readBits(5)),i.readBits(4),i.readBits(4),n&&i.readBits(4),i.readBits(5),i.readBits(5),i.readBits(5));for(let a=0;a<=t;a++){const o=i.readBits(1)===1;let c=!0;o||(c=i.readBits(1)===1);let u=!1;c?j(i):u=i.readBits(1)===1;let l=1;u||(l=j(i)+1),r&&dc(i,l,n),s&&dc(i,l,n)}},dc=(i,e,t)=>{for(let r=0;r<e;r++)j(i),j(i),t&&(j(i),j(i)),i.readBits(1)},eh=i=>{const e=[];e.push(i.configurationVersion),e.push((i.generalProfileSpace&3)<<6|(i.generalTierFlag&1)<<5|i.generalProfileIdc&31),e.push(i.generalProfileCompatibilityFlags>>>24&255),e.push(i.generalProfileCompatibilityFlags>>>16&255),e.push(i.generalProfileCompatibilityFlags>>>8&255),e.push(i.generalProfileCompatibilityFlags&255),e.push(...i.generalConstraintIndicatorFlags),e.push(i.generalLevelIdc&255),e.push(240|i.minSpatialSegmentationIdc>>8&15),e.push(i.minSpatialSegmentationIdc&255),e.push(252|i.parallelismType&3),e.push(252|i.chromaFormatIdc&3),e.push(248|i.bitDepthLumaMinus8&7),e.push(248|i.bitDepthChromaMinus8&7),e.push(i.avgFrameRate>>8&255),e.push(i.avgFrameRate&255),e.push((i.constantFrameRate&3)<<6|(i.numTemporalLayers&7)<<3|(i.temporalIdNested&1)<<2|i.lengthSizeMinusOne&3),e.push(i.arrays.length&255);for(const t of i.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 r of t.nalUnits){e.push(r.length>>8&255),e.push(r.length&255);for(let s=0;s<r.length;s++)e.push(r[s])}}return new Uint8Array(e)},xo=i=>{try{const e=ie(i);let t=0;const r=e.getUint8(t++),s=e.getUint8(t++),n=s>>6&3,a=s>>5&1,o=s&31,c=e.getUint32(t,!1);t+=4;const u=i.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,g=e.getUint16(t,!1);t+=2;const y=e.getUint8(t++),b=y>>6&3,S=y>>3&7,A=y>>2&1,x=y&3,T=e.getUint8(t++),P=[];for(let C=0;C<T;C++){const _=e.getUint8(t++),I=_>>7&1,v=_&63,R=e.getUint16(t,!1);t+=2;const F=[];for(let H=0;H<R;H++){const O=e.getUint16(t,!1);t+=2,F.push(i.subarray(t,t+O)),t+=O}P.push({arrayCompleteness:I,nalUnitType:v,nalUnits:F})}return{configurationVersion:r,generalProfileSpace:n,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:u,generalLevelIdc:l,minSpatialSegmentationIdc:d,parallelismType:f,chromaFormatIdc:h,bitDepthLumaMinus8:p,bitDepthChromaMinus8:m,avgFrameRate:g,constantFrameRate:b,numTemporalLayers:S,temporalIdNested:A,lengthSizeMinusOne:x,arrays:P}}catch(e){return K._error("Error deserializing HEVC Decoder Configuration Record:",e),null}};var ot;(function(i){i[i.audAllowed=0]="audAllowed",i[i.beforeFirstVcl=1]="beforeFirstVcl",i[i.afterFirstVcl=2]="afterFirstVcl",i[i.eoBitstreamAllowed=3]="eoBitstreamAllowed",i[i.noMoreDataAllowed=4]="noMoreDataAllowed"})(ot||(ot={}));const th=(i,e)=>{const t=new Set;let r=ot.audAllowed;for(const n of mn(i,e)){if(r===ot.noMoreDataAllowed){t.add(n.offset);continue}const a=zi(i[n.offset]);if(r===ot.eoBitstreamAllowed&&a!==37){t.add(n.offset);continue}let o=!1;a===35?r>ot.audAllowed?o=!0:r=ot.beforeFirstVcl:a<=31?r>ot.afterFirstVcl?o=!0:r=ot.afterFirstVcl:a===36?r!==ot.afterFirstVcl?o=!0:r=ot.eoBitstreamAllowed:a===37?r<ot.afterFirstVcl?o=!0:r=ot.noMoreDataAllowed:a===32||a===33||a===34||a===39||a>=41&&a<=44||a>=48&&a<=55?r>ot.beforeFirstVcl?o=!0:r=ot.beforeFirstVcl:(a===38||a===40||a>=45&&a<=47||a>=56&&a<=63)&&r<ot.afterFirstVcl&&(o=!0),o&&t.add(n.offset)}if(t.size===0)return null;const s=[];for(const n of mn(i,e))t.has(n.offset)||s.push(i.subarray(n.offset,n.offset+n.length));return $f(s,e)},ih={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}},Po=i=>{const e=new oe(i);if(e.readBits(2)!==2)return null;const r=e.readBits(1),n=(e.readBits(1)<<1)+r;if(n===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let u=8;n>=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),n===1||n===3){const C=e.readBits(1),_=e.readBits(1);d=!C&&!_?3:C&&!_?2:1,e.skipBits(1)}else d=1;else d=3,f=1,(n===1||n===3)&&e.skipBits(1);const h=e.readBits(16),p=e.readBits(16),m=h+1,g=p+1,y=m*g;let b=Te(zr).level;for(const P of zr)if(y<=P.maxPictureSize){b=P.level;break}const S=ih[l],A=(S==null?void 0:S.colourPrimaries)??2,x=(S==null?void 0:S.transferCharacteristics)??2,T=(S==null?void 0:S.matrixCoefficients)??2;return{profile:n,level:b,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:A,transferCharacteristics:x,matrixCoefficients:T}},rh=i=>i.colourPrimaries!==2||i.transferCharacteristics!==2||i.matrixCoefficients!==2,ru=function*(i){const e=new oe(i),t=()=>{let r=0;for(let s=0;s<8;s++){const n=e.readAlignedByte();if(r+=(n&127)*2**(s*7),!(n&128))break;if(s===7&&n&128)return null}return r>2**32-1?null:r};for(;e.getBitsLeft()>=8;){e.skipBits(1);const r=e.readBits(4),s=e.readBits(1),n=e.readBits(1);e.skipBits(1),s&&e.skipBits(8);let a;if(n){const o=t();if(o===null)return;a=o}else a=Math.floor(e.getBitsLeft()/8);w(e.pos%8===0),yield{type:r,data:i.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},ms=i=>{for(const{type:e,data:t}of ru(i)){if(e!==1)continue;const r=new oe(t),s=r.readBits(3);r.readBits(1);const n=r.readBits(1);let a=0,o=0,c=0;if(n)a=r.readBits(5);else{const _=r.readBits(1);let I=0;if(_){if(r.skipBits(32),r.skipBits(32),r.readBits(1)){let H=0;for(;H<32&&!r.readBits(1);)H++;H<32&&r.skipBits(H)}I=r.readBits(1),I&&(c=r.readBits(5),r.skipBits(32),r.skipBits(5),r.skipBits(5))}const v=r.readBits(1),R=r.readBits(5);for(let F=0;F<=R;F++){r.skipBits(12);const H=r.readBits(5);if(F===0&&(a=H),H>7){const O=r.readBits(1);F===0&&(o=O)}if(I&&r.readBits(1)){const U=c+1;r.skipBits(U),r.skipBits(U),r.skipBits(1)}v&&r.readBits(1)&&r.skipBits(4)}}const u=r.readBits(4),l=r.readBits(4),d=u+1;r.skipBits(d);const f=l+1;r.skipBits(f);let h=0;if(n?h=0:h=r.readBits(1),h&&(r.skipBits(4),r.skipBits(3)),r.skipBits(1),r.skipBits(1),r.skipBits(1),!n){r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const _=r.readBits(1);_&&(r.skipBits(1),r.skipBits(1));const I=r.readBits(1);let v=0;I?v=2:v=r.readBits(1),v>0&&(r.readBits(1)||r.skipBits(1)),_&&r.skipBits(3)}r.skipBits(1),r.skipBits(1),r.skipBits(1);const p=r.readBits(1);let m=8;s===2&&p?m=r.readBits(1)?12:10:s<=2&&(m=p?10:8);let g=0;s!==1&&(g=r.readBits(1));let y=2,b=2,S=2;r.readBits(1)&&(y=r.readBits(8),b=r.readBits(8),S=r.readBits(8));let x=0,T=1,P=1,C=0;return g?x=r.readBits(1):y===1&&b===13&&S===0?(x=1,T=0,P=0):(x=r.readBits(1),s===0?(T=1,P=1):s===1?(T=0,P=0):m===12?(T=r.readBits(1),P=T?r.readBits(1):0):(T=1,P=0),T&&P&&(C=r.readBits(2))),{profile:s,level:a,tier:o,bitDepth:m,monochrome:g,chromaSubsamplingX:T,chromaSubsamplingY:P,chromaSamplePosition:C,videoFullRangeFlag:x,colourPrimaries:y,transferCharacteristics:b,matrixCoefficients:S}}return null},su=i=>i.colourPrimaries!==2||i.transferCharacteristics!==2||i.matrixCoefficients!==2,nu=i=>{if(i.length<28)return null;const t=ie(i);return t.getUint32(4)!==1768124518||t.getUint16(8)<20?null:{fullRange:!1,colourPrimaries:t.getUint8(22),transferCharacteristics:t.getUint8(23),matrixCoefficients:t.getUint8(24)}},vs=i=>{if(i.byteLength<19)throw new Error("Invalid Opus identification header: too short.");const e=ie(i),t=e.getUint8(9),r=e.getUint16(10,!0),s=e.getUint32(12,!0),n=e.getInt16(16,!0),a=e.getUint8(18);let o=null;return a&&(o=i.subarray(19)),{outputChannelCount:t,preSkip:r,inputSampleRate:s,outputGain:n,channelMappingFamily:a,channelMappingTable:o}},sh=[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],au=i=>{const e=i[0]>>3,t=i[0]&3;let r;return t===0?r=1:t===1||t===2?r=2:r=i[1]&63,{durationInSamples:sh[e]*r}},ou=i=>{if(i.length<7)throw new Error("Setup header is too short.");if(i[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...i.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");const t=i.length,r=new Uint8Array(t);for(let d=0;d<t;d++)r[d]=i[t-1-d];const s=new oe(r);let n=0;for(;s.getBitsLeft()>97;)if(s.readBits(1)===1){n=s.pos;break}if(n===0)throw new Error("Invalid Setup header: framing bit not found.");let a=0,o=!1,c=0;for(;s.getBitsLeft()>=97;){const d=s.pos,f=s.readBits(8),h=s.readBits(16),p=s.readBits(16);if(f>63||h!==0||p!==0){s.pos=d;break}if(s.skipBits(1),a++,a>64)break;s.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;s.pos=0,s.skipBits(n);const l=Array(u).fill(0);for(let d=u-1;d>=0;d--)s.skipBits(40),l[d]=s.readBits(1);return{modeBlockflags:l}},Nn=(i,e,t)=>{switch(i){case"avc":{for(const r of tu(t,e)){const s=t[r.offset],n=rr(s);if(n>=Ve.NON_IDR_SLICE&&n<=Ve.SLICE_DPC)return"delta";if(n===Ve.IDR)return"key";if(n===Ve.SEI&&!ts()){const a=t.subarray(r.offset,r.offset+r.length),o=On(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 oe(o);f.pos=8*c;let h=-1;try{h=j(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 r of mn(t,e)){const s=zi(t[r.offset]);if(s<ke.BLA_W_LP)return"delta";if(s<=ke.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{const r=new oe(t);if(r.readBits(2)!==2)return null;const s=r.readBits(1);return(r.readBits(1)<<1)+s===3&&r.skipBits(1),r.readBits(1)?null:r.readBits(1)===0?"key":"delta"}case"av1":{let r=!1;for(const{type:s,data:n}of ru(t))if(s===1){const a=new oe(n);a.skipBits(4),r=!!a.readBits(1)}else if(s===3||s===6||s===7){if(r)return"key";const a=new oe(n);if(a.readBits(1))return null;const c=a.readBits(2),u=a.readBits(1);return c===0&&u===1?"key":"delta"}return null}case"prores":return"key";default:xe(i),w(!1)}},nh=(i,e)=>{if(i==="vp8")return e[0]>>4&1;if(i==="vp9"){const t=s=>{const n=new oe(s);n.skipBits(2);const a=n.readBits(1),o=n.readBits(1);return a===1&&o===1&&n.skipBits(1),n.readBits(1)===1?!0:(n.skipBits(1),n.readBits(1)===1)},r=e[e.length-1];if((r&224)===192){const s=(r&7)+1,n=(r>>3&3)+1,a=e.length-(2+s*n);if(e[a]===r){let o=0,c=0;for(let u=0;u<s;u++){let l=0;for(let d=0;d<n;d++)l+=e[a+1+u*n+d]*2**(8*d);t(e.subarray(c,c+l))&&o++,c+=l}return o}}return t(e)?1:0}return 1},Co=(i,e)=>i==="truehd"?(e.byteLength>=8?ie(e).getUint32(4):null)===Hf?"key":"delta":"key";var yi;(function(i){i[i.STREAMINFO=0]="STREAMINFO",i[i.VORBIS_COMMENT=4]="VORBIS_COMMENT",i[i.PICTURE=6]="PICTURE"})(yi||(yi={}));const Oa=(i,e)=>{var o,c;const t=ie(i);let r=0;if(i.length<4)return;const s=t.getUint32(r,!0);r+=4;const n=nt.decode(i.subarray(r,r+s));if(r+=s,s>0&&(e.raw??(e.raw={}),(o=e.raw).vendor??(o.vendor=n)),r+4>i.length)return;const a=t.getUint32(r,!0);r+=4;for(let u=0;u<a&&!(r+4>i.length);u++){const l=t.getUint32(r,!0);r+=4;const d=nt.decode(i.subarray(r,r+l));r+=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("/"),g=Number.parseInt(m[0],10),y=m[1]&&Number.parseInt(m[1],10);Number.isInteger(g)&&g>0&&(e.trackNumber??(e.trackNumber=g)),y&&Number.isInteger(y)&&y>0&&(e.tracksTotal??(e.tracksTotal=y))}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("/"),g=Number.parseInt(m[0],10),y=m[1]&&Number.parseInt(m[1],10);Number.isInteger(g)&&g>0&&(e.discNumber??(e.discNumber=g)),y&&Number.isInteger(y)&&y>0&&(e.discsTotal??(e.discsTotal=y))}break;case"DISCTOTAL":{const m=Number.parseInt(p,10);Number.isInteger(m)&&m>0&&(e.discsTotal??(e.discsTotal=m))}break;case"DATE":{const m=Fr(p);m&&(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=ln(p),g=ie(m),y=g.getUint32(0,!1),b=g.getUint32(4,!1),S=nt.decode(m.subarray(8,8+b)),A=g.getUint32(8+b,!1),x=nt.decode(m.subarray(12+b,12+b+A)),T=g.getUint32(b+A+28),P=m.subarray(b+A+32,b+A+32+T);e.images??(e.images=[]),e.images.push({data:P,mimeType:S,kind:y===3?"coverFront":y===4?"coverBack":"unknown",name:void 0,description:x||void 0})}catch{}break}}},Ua=(i,e,t)=>{var h;const r=[i],s=ge.encode(Pr);let n=new Uint8Array(4+s.length),a=new DataView(n.buffer);a.setUint32(0,s.length,!0),n.set(s,4),r.push(n);const o=[],c=(p,m)=>{const g=`${p}=${m}`,y=ge.encode(g);n=new Uint8Array(4+y.length),a=new DataView(n.buffer),a.setUint32(0,y.length,!0),n.set(y,4),r.push(n),o.push(p)};for(const{key:p,value:m}of Nr(e))switch(p){case"title":c("TITLE",m);break;case"description":c("DESCRIPTION",m);break;case"artist":c("ARTIST",m);break;case"album":c("ALBUM",m);break;case"albumArtist":c("ALBUMARTIST",m);break;case"genre":c("GENRE",m);break;case"date":c("DATE",m.toISOString().slice(0,10));break;case"comment":c("COMMENT",m);break;case"lyrics":c("LYRICS",m);break;case"trackNumber":c("TRACKNUMBER",m.toString());break;case"tracksTotal":c("TRACKTOTAL",m.toString());break;case"discNumber":c("DISCNUMBER",m.toString());break;case"discsTotal":c("DISCTOTAL",m.toString());break;case"beatsPerMinute":c("BPM",m.toString());break;case"images":{if(!t)break;for(const g of m){const y=g.kind==="coverFront"?3:g.kind==="coverBack"?4:0,b=new Uint8Array(g.mimeType.length);for(let P=0;P<g.mimeType.length;P++)b[P]=g.mimeType.charCodeAt(P);const S=ge.encode(g.description??""),A=new Uint8Array(8+b.length+4+S.length+16+4+g.data.length),x=ie(A);x.setUint32(0,y,!1),x.setUint32(4,b.length,!1),A.set(b,8),x.setUint32(8+b.length,S.length,!1),A.set(S,12+b.length),x.setUint32(28+b.length+S.length,g.data.length,!1),A.set(g.data,32+b.length+S.length);const T=If(A);c("METADATA_BLOCK_PICTURE",T)}}break;case"raw":break;case"creationTime":break;default:xe(p)}if(e.raw)for(const p in e.raw){const m=e.raw[p]??e.raw[p.toLowerCase()];if(!(p==="vendor"||m==null||o.includes(p))&&!(p==="METADATA_BLOCK_PICTURE"&&!t&&(((h=e.images)==null?void 0:h.length)??0)>0)){if(typeof m=="string")c(p,m);else if(Array.isArray(m)&&m.every(y=>typeof y=="string"))for(const y of m)c(p,y)}}const u=new Uint8Array(4);ie(u).setUint32(0,o.length,!0),r.splice(2,0,u);const l=r.reduce((p,m)=>p+m.length,0),d=new Uint8Array(l);let f=0;for(const p of r)d.set(p,f),f+=p.length;return d},_o=[2,1,2,3,3,4,4,5],cu=i=>{if(i.length<7||i[0]!==11||i[1]!==119)return null;const e=new oe(i);e.skipBits(16),e.skipBits(16);const t=e.readBits(2);if(t===3)return null;const r=e.readBits(6),s=e.readBits(5);if(s>8)return null;const n=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(r/2);return{fscod:t,bsid:s,bsmod:n,acmod:a,lfeon:o,bitRateCode:c}},ah=[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],oh=1536,Vs=new Uint8Array([5,4,65,67,45,51]),Ws=new Uint8Array([5,4,69,65,67,51]),Eo=[1,2,3,6],lu=i=>{if(i.length<6||i[0]!==11||i[1]!==119)return null;const e=new oe(i);e.skipBits(16);const t=e.readBits(2);if(e.skipBits(3),t!==0&&t!==2)return null;const r=e.readBits(11),s=e.readBits(2);let n=0,a;s===3?(n=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=Eo[a];let d;s<3?d=zn[s]/1e3:d=eu[n]/1e3;const f=Math.round((r+1)*d/(l*16)),h=0;let p=0,m=0,g=2*(r+1);for(;g+2<=i.length&&(e.seekToByte(g),!(e.readBits(16)!==2935||e.readBits(2)!==1));){e.skipBits(3);const b=e.readBits(11);e.skipBits(4);const S=e.readBits(3);if(e.skipBits(11),e.readBits(1)&&e.skipBits(8),S===0&&(e.skipBits(5),e.readBits(1)&&e.skipBits(8)),e.readBits(1)){const A=e.readBits(16);for(let x=0;x<8;x++)A&1<<10-x&&(m|=1<<x);A&2&&(m|=256)}p++,g+=2*(b+1)}return{dataRate:f,substreams:[{fscod:s,fscod2:n,bsid:u,bsmod:h,acmod:o,lfeon:c,numDepSub:p,chanLoc:m}]}},uu=i=>{const e=[];let t=0;for(;t<i.length;){if(t+6>i.length||i[t]!==11||i[t+1]!==119)return null;const r=i[t+2]>>6,s=(i[t+2]&7)<<8|i[t+3],a=i[t+4]>>6===3?3:i[t+4]>>4&3,o=i[t+5]>>3,c=2*(s+1);if(o<=10||t+c>i.length)return null;if(r===1){const u=Te(e);if(!u)return null;u.size+=c}else e.push({offset:t,size:c,blockCount:Eo[a]});t+=c}return e},ch=i=>{if(i.length<2)return null;const e=new oe(i),t=e.readBits(13),r=e.readBits(3),s=[];for(let n=0;n<=r&&!(Math.ceil(e.pos/8)+3>i.length);n++){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),s.push({fscod:a,fscod2:null,bsid:o,bsmod:c,acmod:u,lfeon:l,numDepSub:d,chanLoc:f})}return s.length===0?null:{dataRate:t,substreams:s}},du=i=>{const e=i.substreams[0];return w(e),e.fscod<3?zn[e.fscod]:e.fscod2!==null&&e.fscod2<3?eu[e.fscod2]:null},fu=i=>{const e=i.substreams[0];w(e);let t=_o[e.acmod]+e.lfeon;if(e.numDepSub>0){const r=[2,2,1,1,2,2,2,1,1];for(let s=0;s<9;s++)e.chanLoc&1<<s&&(t+=r[s])}return t},lh=1683496997,en=18,Na=10,uh=4096,fc=32,Io=20,dh=8,fh=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],hh=[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],mh=[16,16,20,20,0,24,24,0],pn=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],ph=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],gh=8,wh=44646,yh=[32e3,44100,48e3,0],bh=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],hu=[512,1024,2048,4096],vo=i=>{const e=pu(i),t=ie(i);let r=e?Math.ceil(e.frameSize/4)*4:0,s=null;for(;r+4<=i.length&&t.getUint32(r)===lh;){const a=tn(i.subarray(r));if(!a)break;s??(s=a),r+=a.frameSize}if(e)return{frameSize:s?r:e.frameSize,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,sampleCount:e.sampleCount,channelLayout:e.channelLayout,pcmResolution:e.pcmResolution,bitRate:e.bitRate,core:e,hasExtensions:s!==null};if(!(s!=null&&s.asset))return null;const{asset:n}=s;return{frameSize:r,sampleRate:n.sampleRate,numberOfChannels:n.numberOfChannels,sampleCount:n.sampleCount,channelLayout:n.channelLayout,pcmResolution:n.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},mu=i=>{const e=vo(i);return e!=null&&e.core?e.hasExtensions?"dtsh":"dtsc":null},pu=i=>{if(i.length<en||i[0]!==127||i[1]!==254||i[2]!==128||i[3]!==1)return null;const e=new oe(i);if(e.skipBits(32),e.skipBits(1),e.readBits(5)!==fc-1)return null;const t=e.readBits(1),r=e.readBits(7)+1;if(r%dh!==0)return null;const s=e.readBits(14)+1;if(s<96)return null;const n=e.readBits(6);if(n>=pn.length)return null;const a=fh[e.readBits(4)];if(a===0)return null;const o=hh[e.readBits(5)];if(e.readBits(1)!==0)return null;e.skipBits(4);const c=e.readBits(3),u=e.readBits(1);e.skipBits(1);const l=e.readBits(2);if(l===3)return null;e.skipBits(1),t&&e.skipBits(16),e.skipBits(7);const d=mh[e.readBits(3)];if(d===0)return null;const f=l!==0;return{frameSize:s,sampleRate:a,numberOfChannels:pn[n]+(f?1:0),sampleCount:r*fc,channelLayout:ph[n]|(f?gh:0),amode:n,lfePresent:f,bitRate:o,pcmResolution:d,extAudioId:u?c:null}},tn=i=>{if(i.length<Na||i[0]!==100||i[1]!==88||i[2]!==32||i[3]!==37)return null;const e=new oe(i);e.skipBits(32),e.skipBits(8);const t=e.readBits(2),r=e.readBits(1),s=8+4*r,n=16+4*r;e.skipBits(s);const a=e.readBits(n)+1,o={frameSize:a,asset:null};if(!e.readBits(1))return o;const c=yh[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 y=0;y<l;y++)f.push(e.readBits(t+1));for(const y of f)e.skipBits(8*va(y));if(e.readBits(1)){e.skipBits(2);const y=e.readBits(2)+1<<2,b=e.readBits(2)+1;e.skipBits(b*y)}for(let y=0;y<d;y++)e.skipBits(n);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=bh[e.readBits(4)],m=e.readBits(8)+1;let g=0;if(e.readBits(1)&&(m>2&&e.skipBits(1),m>6&&e.skipBits(1),e.readBits(1))){const y=e.readBits(2)+1<<2;g=e.readBits(y)}return c===0||e.getBitsLeft()<0?o:{frameSize:a,asset:{sampleRate:p,numberOfChannels:m,sampleCount:Math.round(u*p/c),channelLayout:g,pcmResolution:h}}},kh=i=>{if(i.length<Io)return null;const e=ie(i),t=e.getUint32(0);if(t===0)return null;const r=new oe(i);r.seekToByte(13);const s=r.readBits(2);r.skipBits(5);const n=r.readBits(1),a=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);const o=r.readBits(16);let c=null;return o!==0?c=Ah(o):a<pn.length&&(c=pn[a]+n),{sampleRate:t,maxBitrate:e.getUint32(4),avgBitrate:e.getUint32(8),pcmSampleDepth:i[12],sampleCount:hu[s],channelLayout:o,numberOfChannels:c}},Th={0:2,2:4,6:3},Sh=i=>{var n,a;const e=new Uint8Array(Io),t=ie(e);t.setUint32(0,i.sampleRate),t.setUint32(4,i.bitRate),t.setUint32(8,i.bitRate),e[12]=i.pcmResolution;let r=0;if(i.core&&!i.hasExtensions){const{extAudioId:o}=i.core;r=o===null?1:Th[o]??0}const s=new oe(e);return s.seekToByte(13),s.writeBits(2,Math.max(hu.indexOf(i.sampleCount),0)),s.writeBits(5,r),s.writeBits(1,(n=i.core)!=null&&n.lfePresent?1:0),s.writeBits(6,((a=i.core)==null?void 0:a.amode)??0),s.writeBits(14,i.core?i.core.frameSize-1:0),s.writeBits(1,0),s.writeBits(3,0),s.writeBits(16,i.channelLayout),s.writeBits(1,0),s.writeBits(1,0),s.writeBits(1,0),s.writeBits(5,0),e},Ah=i=>va(i)+va(i&wh);/*!
|
|
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 qr=/(?:(.+?)\n)?((?:\d{2,}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2,}:)?\d{2}:\d{2}.\d{3})/g,xh=/^WEBVTT(.|\n)*?\n{2}/,gn=/<(?:(\d{2,}):)?(\d{2}):(\d{2}).(\d{3})>/g;class Ph{constructor(e){this.preambleText=null,this.preambleEmitted=!1,this.options=e}parse(e){e=e.replaceAll(`\r
|
|
68
|
+
`,`
|
|
69
|
+
`).replaceAll("\r",`
|
|
70
|
+
`),qr.lastIndex=0;let t;if(!this.preambleText){if(e.charCodeAt(0)===65279&&(e=e.slice(1)),!xh.test(e))throw new Error("WebVTT preamble incorrect.");t=qr.exec(e);const r=e.slice(0,(t==null?void 0:t.index)??e.length).trimEnd();if(!r)throw new Error("No WebVTT preamble provided.");this.preambleText=r,t&&(e=e.slice(t.index),qr.lastIndex=0)}for(;t=qr.exec(e);){const r=e.slice(0,t.index),s=t[1],n=t.index+t[0].length,a=e.indexOf(`
|
|
71
|
+
`,n),o=a===-1?e.length:a+1,c=e.slice(n,o).trim();let u=e.indexOf(`
|
|
72
|
+
|
|
73
|
+
`,n);u===-1&&(u=e.length);const l=Va(t[2]),f=Va(t[3])-l,h=e.slice(o,u).trim();e=e.slice(u).trimStart(),qr.lastIndex=0;const p={timestamp:l/1e3,duration:f/1e3,text:h,identifier:s,settings:c,notes:r},m={};this.preambleEmitted||(m.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(p,m)}}}const Ch=/(?:(\d{2,}):)?(\d{2}):(\d{2}).(\d{3})/,Va=i=>{const e=Ch.exec(i);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])},gu=i=>{const e=Math.round(1e3*i),t=Math.floor(e/(3600*1e3)),r=Math.floor(e%(3600*1e3)/(60*1e3)),s=Math.floor(e%(60*1e3)/1e3),n=e%1e3;return t.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+":"+s.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 _h=i=>{let r=i>>2,s=4096,n=0,a=12,o=0;for(r<0&&(r=-r,n=128),r+=33,r>8191&&(r=8191);(r&s)!==s&&a>=5;)s>>=1,a--;return o=r>>a-4&15,~(n|a-5<<4|o)&255},Eh=i=>{let t=0,r=0,s=~i;s&128&&(s&=-129,t=-1),r=((s&240)>>4)+5;const n=(1<<r|(s&15)<<r-4|1<<r-5)-33;return(t===0?n:-n)<<2},Ih=i=>{let t=2048,r=0,s=11,n=0,a=i>>3;for(a<0?a=-a-1:r=128,a>4095&&(a=4095);(a&t)!==t&&s>=5;)t>>=1,s--;return n=a>>(s===4?1:s-4)&15,(r|s-4<<4|n)^85},vh=i=>{let e=0,t=0,r=i^85;r&128&&(r&=-129,e=-1),t=((r&240)>>4)+4;let s=0;return t!==4?s=1<<t|(r&15)<<t-4|1<<t-5:s=r<<1|1,(e===0?-s:s)<<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 Wa=new Map,La=new Map,Bh=(i,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&&Dt(e.codec)!==i)throw new TypeError(`options.codec, when provided, must match the specified codec (${i}).`);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&&!Ur(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.")},Fh=(i,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&&Dt(e.codec)!==i)throw new TypeError(`options.codec, when provided, must match the specified codec (${i}).`);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&&!Ur(e.description))throw new TypeError("options.description, when provided, must be a buffer source.")},r0=async i=>Oe.includes(i)?wu(i):Ke.includes(i)?yu(i):!1,wu=async(i,e={})=>{if(!Oe.includes(i))return!1;Bh(i,e);const t=e.codedWidth??1280,r=e.codedHeight??720,s={...e,codedWidth:t,codedHeight:r,codec:e.codec??zd(i,t,r,1e6,!1)};s.description??(s.description=Gp());const n=bu(s),a=Wa.get(n);if(a)return a;const o=(async()=>ws.some(u=>u.supports(i,s))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(s)).supported===!0)();return Wa.set(n,o),o},yu=async(i,e={})=>{if(!Ke.includes(i))return!1;Fh(i,e);const t={...e,numberOfChannels:e.numberOfChannels??2,sampleRate:e.sampleRate??48e3,codec:e.codec??Nd(i)};if(t.description===void 0){const a=Xp(t);if(a===!1)return!1;t.description=a}const r=bu(t),s=La.get(r);if(s)return s;const n=(async()=>ys.some(o=>o.supports(i,t))||je.includes(i)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(t)).supported===!0)();return La.set(r,n),n},bu=i=>JSON.stringify({...i,description:i.description&&[...me(i.description)]}),s0=async()=>{const[i,e]=await Promise.all([Rh(),Mh()]);return[...i,...e]},Rh=async(i=Oe,e)=>{const t=await Promise.all(i.map(r=>wu(r,e)));return i.filter((r,s)=>t[s])},Mh=async(i=Ke,e)=>{const t=await Promise.all(i.map(r=>yu(r,e)));return i.filter((r,s)=>t[s])};/*!
|
|
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 Dh=function(i,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,s;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],t&&(s=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");s&&(r=function(){try{s.call(this)}catch(n){return Promise.reject(n)}}),i.stack.push({value:e,dispose:r,async:t})}else t&&i.stack.push({async:!0});return e},zh=(function(i){return function(e){function t(a){e.error=e.hasError?new i(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var r,s=0;function n(){for(;r=e.stack.pop();)try{if(!r.async&&s===1)return s=0,e.stack.push(r),Promise.resolve().then(n);if(r.dispose){var a=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(a).then(n,function(o){return t(o),n()})}else s|=1}catch(o){t(o)}if(s===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return n()}})(typeof SuppressedError=="function"?SuppressedError:function(i,e,t){var r=new Error(t);return r.name="SuppressedError",r.error=i,r.suppressed=e,r});wo();let hc=-1/0,mc=-1/0,yt=null;typeof FinalizationRegistry<"u"&&(yt=new FinalizationRegistry(i=>{const e=performance.now();i.type==="video"?(e-hc>=1e3&&(K._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."),hc=e),typeof VideoFrame<"u"&&i.data instanceof VideoFrame&&i.data.close()):(e-mc>=1e3&&(K._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."),mc=e),typeof AudioData<"u"&&i.data instanceof AudioData&&i.data.close())}));class Hi{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Ha=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Oh=new Set(Ha);class Je{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(Bi*this.timestamp)}get microsecondDuration(){return Math.trunc(Bi*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){var r,s,n,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||!Oh.has(t.format))throw new TypeError("init.format must be one of: "+Ha.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 p of t.layout){if(!p||typeof p!="object"||Array.isArray(p))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(p.offset)||p.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(p.stride)||p.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}const h=gs(t.format).length;if(t.layout.length!==h)throw new TypeError(`init.layout must have ${h} entries for format ${t.format}.`)}if(t.visibleRect!==void 0&&ra(t.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??Nh(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:((r=t.visibleRect)==null?void 0:r.left)??0,top:((s=t.visibleRect)==null?void 0:s.top)??0,width:((n=t.visibleRect)==null?void 0:n.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?me(e):me(e).slice(),this._layout=d,this.colorSpace=new ia(f)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(e.codedWidth===0)throw new TypeError("data must not be a closed 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&&ra(t.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 ia({primaries:d!==null&&d in Ui?d:null,transfer:f!==null&&f in Ni?f:null,matrix:h!==null&&h in Vi?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&&ra(t.visibleRect),typeof VideoFrame<"u")return new Je(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Bi),duration:Math.trunc((t.duration??0)*Bi)||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:ir(),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 ia({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof Hi){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.format=e.getFormat(),this.format!==null&&!Ha.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(),this._data=e,e._referenceCount++}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=(t==null?void 0:t.encodeOptions)??{},this.pixelAspectRatio=xs({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),yt==null||yt.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return w(this._data!==null),this._data instanceof Hi?new Je(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):Kr(this._data)?new Je(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(w(this._layout),new Je(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 Je(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||(yt==null||yt.unregister(this),this._data instanceof Hi?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Kr(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(wc(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 Kr(this._data)?this._data.allocationSize(e):yc(this,e).allocationSize}async copyTo(e,t={}){if(!Ur(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(wc(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(w(this._data!==null),Kr(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 Hi){const u={stack:[],error:void 0,hasError:!1};try{const l=Dh(u,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip},t.colorSpace??"srgb"),!1);if(!(l instanceof Je))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{zh(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();try{return await u.copyTo(e,t)}finally{u.close()}}const r=yc(this,t);w(this.format);const s=me(e);if(s.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${s.byteLength}`);const n=gs(this.format);let a;if(this._data instanceof Hi){let u=this._data.getDataPlanes();if(D(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)w(this._layout),w(this._layout.length===n.length),a=this._layout.map((u,l)=>{const d=Math.ceil((this.visibleRect.top+this.visibleRect.height)/n[l].heightDivisor);return{data:this._data.subarray(u.offset,u.offset+u.stride*d),stride:u.stride}});else{const l=this._data.getContext("2d");w(l);const d=l.getImageData(0,0,this.codedWidth,this.codedHeight);a=[{data:me(d.data),stride:4*this.codedWidth}]}const o=[],c=n.length;for(let u=0;u<c;u++){const l=r.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,g={offset:p,stride:l.destinationStride};for(let y=0;y<l.sourceHeight;y++){if(h+m>f.byteLength)throw new Error("Source buffer OOB read.");if(p+m>s.byteLength)throw new Error("Destination buffer OOB write.");const b=f.subarray(h,h+m);s.set(b,p),h+=d,p+=l.destinationStride}o.push(g)}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){const d=r.computedLayouts[0];for(let f=0;f<d.sourceHeight;f++){const h=d.destinationOffset+f*d.destinationStride,p=h+d.sourceWidthBytes;for(let m=h;m<p;m+=4){if(u){const g=s[m],y=s[m+2];s[m]=y,s[m+2]=g}l&&(s[m+3]=255)}}}}return o}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(w(this._data!==null),this._data instanceof Hi){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(D(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),r=new Uint8Array(t);let s=0;const n=[];for(const a of e)r.set(a.data,s),n.push(s),s+=a.data.byteLength;return new VideoFrame(r,{format:this.format,layout:e.map((a,o)=>({offset:n[o],stride:a.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return Kr(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(w(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.visibleRect.left+this.visibleRect.width,codedHeight:this.visibleRect.top+this.visibleRect.height,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:{x:this.visibleRect.left,y:this.visibleRect.top,width:this.visibleRect.width,height:this.visibleRect.height},displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,r,s,n,a,o,c,u){let l=0,d=0,f=this.displayWidth,h=this.displayHeight,p=0,m=0,g=this.displayWidth,y=this.displayHeight;if(a!==void 0?(l=t,d=r,f=s,h=n,p=a,m=o,c!==void 0?(g=c,y=u):(g=f,y=h)):(p=t,m=r,s!==void 0&&(g=s,y=n)),!(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(g)||g<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<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 b=this.toCanvasImageSource();e.save();const S=p+g/2,A=m+y/2;e.translate(S,A),this.flip&&e.scale(-1,1),e.rotate(this.rotation*Math.PI/180);const x=this.rotation%180===0?1:g/y;e.scale(1/x,x),e.drawImage(b,l,d,f,h,-g/2,-y/2,g,y),e.restore()}drawWithFit(e,t){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&&ps(t.crop,"options.");const r=e.canvas.width,s=e.canvas.height,n=t.rotation??this.rotation,a=t.flip??this.flip,[o,c]=n%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let u=t.crop;u&&(u=wn(u,o,c));let l,d,f,h;const{sx:p,sy:m,sWidth:g,sHeight:y}=this._unmapSourceRegion((u==null?void 0:u.left)??0,(u==null?void 0:u.top)??0,(u==null?void 0:u.width)??o,(u==null?void 0:u.height)??c,n,a);if(t.fit==="fill")l=0,d=0,f=r,h=s;else{const[A,x]=u?[u.width,u.height]:[o,c],T=t.fit==="contain"?Math.min(r/A,s/x):Math.max(r/A,s/x);f=A*T,h=x*T,l=(r-f)/2,d=(s-h)/2}const b=this.toCanvasImageSource();e.save();const S=n%180===0?1:f/h;e.translate(r/2,s/2),a&&e.scale(-1,1),e.rotate(n*Math.PI/180),e.scale(1/S,S),e.translate(-r/2,-s/2),e.drawImage(b,p,m,g,y,l,d,f,h),e.restore()}_unmapSourceRegion(e,t,r,s,n,a){return a&&(e=(n%180===0?this.squarePixelWidth:this.squarePixelHeight)-e-r),n===90?[e,t,r,s]=[t,this.squarePixelHeight-e-r,s,r]:n===180?[e,t]=[this.squarePixelWidth-e-r,this.squarePixelHeight-t-s]:n===270&&([e,t,r,s]=[this.squarePixelWidth-t-s,e,s,r]),{sx:e,sy:t,sWidth:r,sHeight:s}}_drawWithFitAndMipmapping(e,t,r){const s=e.width,n=e.height,[a,o]=r.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],c=r.crop?r.crop.width:a,u=r.crop?r.crop.height:o;let l=0;2*s<c&&2*n<u&&(l=Math.floor(Math.log2(Math.min(c/s,u/n))));const d=s*2**l,f=n*2**l,{canvas:h,context:p,isNew:m}=l>0?gc(d,f):{canvas:e,context:t,isNew:r.targetIsFresh};p.imageSmoothingQuality="high",r.fillBlack?(p.fillStyle="black",p.fillRect(0,0,d,f)):m||p.clearRect(0,0,d,f),this.drawWithFit(p,{fit:r.fit,rotation:r.rotation,flip:r.flip,crop:r.crop}),p.globalCompositeOperation="copy";for(let g=l;g>1;g--){const y=s*2**g,b=n*2**g;p.drawImage(h,0,0,y,b,0,0,y/2,b/2)}p.globalCompositeOperation="source-over",l>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(h,0,0,2*s,2*n,0,0,s,n),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(w(this._data!==null),this._data instanceof Hi||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&&ps(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:r}=Ul(this.rotation,this.flip,e.rotate??0,e.flip??!1),[s,n]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let a=e.crop;a&&(a=wn(a,s,n));const o=a?a.width:s,c=a?a.height:n,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=Ia(l,e.roundDimensionsTo??1),d=Ia(d,e.roundDimensionsTo??1);const f={width:l,height:d,fit:e.fit??"fill",rotation:t,flip:r,crop:a??{left:0,top:0,width:s,height:n},alpha:e.alpha??"keep"};for(const g of qa){let y=g(this,f);if(D(y)&&(y=await y),y!==null)return y}const{canvas:h,context:p,isNew:m}=gc(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 Je(h,{timestamp:this.timestamp,duration:this.duration,rotation:0,flip:!1,encodeOptions:this.encodeOptions})}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 qa=[],n0=i=>{qa.includes(i)||qa.push(i)},Uh=3,jr=[];let pc=0;const gc=(i,e)=>{for(const s of jr)if(s.canvas.width===i&&s.canvas.height===e)return s.age=pc++,{canvas:s.canvas,context:s.context,isNew:!1};let t;if(typeof OffscreenCanvas<"u")t=new OffscreenCanvas(i,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=i,t.height=e}const r=t.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return jr.length>=Uh&&jr.splice(Fn(jr,s=>s.age),1),jr.push({canvas:t,context:r,age:pc++}),{canvas:t,context:r,isNew:!0}};class ia{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(Ui);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(", ")}.`);const r=Object.keys(Ni);if(e.transfer!=null&&!r.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${r.join(", ")}.`);const s=Object.keys(Vi);if(e.matrix!=null&&!s.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${s.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 Kr=i=>typeof VideoFrame<"u"&&i instanceof VideoFrame,wn=(i,e,t)=>{const r=Math.min(i.left,e),s=Math.min(i.top,t),n=Math.min(i.width,e-r),a=Math.min(i.height,t-s);return w(n>=0),w(a>=0),{left:r,top:s,width:n,height:a}},ps=(i,e)=>{if(!i||typeof i!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(i.left)||i.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(i.top)||i.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(i.width)||i.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(i.height)||i.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},ra=i=>{if(Ff(i,"init.visibleRect"),i.width===0||i.height===0)throw new TypeError("init.visibleRect must not be empty.")},wc=i=>{if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.colorSpace!==void 0&&!["display-p3","srgb"].includes(i.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(i.format!==void 0&&typeof i.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(i.layout!==void 0){if(!Array.isArray(i.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const e of i.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(i.rect!==void 0){if(!i.rect||typeof i.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(i.rect.x!==void 0&&(!Number.isInteger(i.rect.x)||i.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(i.rect.y!==void 0&&(!Number.isInteger(i.rect.y)||i.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(i.rect.width!==void 0&&(!Number.isInteger(i.rect.width)||i.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(i.rect.height!==void 0&&(!Number.isInteger(i.rect.height)||i.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},Nh=(i,e,t)=>{const r=gs(i),s=[];let n=0;for(const a of r){const o=Math.ceil(e/a.widthDivisor),c=Math.ceil(t/a.heightDivisor),u=o*a.sampleBytes,l=u*c;s.push({offset:n,stride:u}),n+=l}return s},gs=i=>{const e=(t,r,s,n,a)=>{const o=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:r,widthDivisor:s,heightDivisor:n},{sampleBytes:r,widthDivisor:s,heightDivisor:n}];return a&&o.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),o};switch(i){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:xe(i),w(!1)}},yc=(i,e)=>{const t={x:i.visibleRect.left,y:i.visibleRect.top,width:i.visibleRect.width,height:i.visibleRect.height},r=e.rect,s=Vh(t,r,i.visibleRect.left+i.visibleRect.width,i.visibleRect.top+i.visibleRect.height,i.format),n=e.layout;let a;if(!e.format||e.format===i.format)a=i.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(e.format))a=e.format;else throw new Error("NotSupportedError: Invalid destination format.");return Lh(s,a,n)},Vh=(i,e,t,r,s)=>{const n={...i};if(e!==void 0){if(!e.width||!e.height)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)>r)throw new TypeError("visibleRect exceeds codedHeight.");n.x=e.x||0,n.y=e.y||0,n.width=e.width||0,n.height=e.height||0}if(!Wh(s,n))throw new TypeError("visibleRect alignment is invalid for the format.");return n},Wh=(i,e)=>{if(i===null)return!0;const t=gs(i);for(let r=0;r<t.length;r++){const s=t[r],n=s.widthDivisor,a=s.heightDivisor;if((e.x||0)%n!==0||(e.y||0)%a!==0)return!1}return!0},Lh=(i,e,t)=>{const r=gs(e),s=r.length;if(t!==void 0&&t.length!==s)throw new TypeError(`Layout must have ${s} planes.`);let n=0;const a=[],o=[];for(let c=0;c<s;c++){const u=r[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(i.y||0)/f),h.sourceHeight=Math.ceil(Math.trunc(i.height||0)/f),h.sourceLeftBytes=Math.floor(Math.trunc(i.x||0)/d)*l,h.sourceWidthBytes=Math.ceil(Math.trunc(i.width||0)/d)*l,t!==void 0){const g=t[c];if(g.stride<h.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);h.destinationOffset=g.offset,h.destinationStride=g.stride}else h.destinationOffset=n,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),n=Math.max(n,m);for(let g=0;g<c;g++){const y=a[g];if(!(o[c]<=y.destinationOffset||o[g]<=h.destinationOffset))throw new TypeError("Planes overlap.")}a.push(h)}return{allocationSize:n,computedLayouts:a}},Ls=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class $r{constructor(){this._referenceCount=0}}class qe{get microsecondTimestamp(){return Math.trunc(Bi*this.timestamp)}get microsecondDuration(){return Math.trunc(Bi*this.duration)}constructor(e){if(this._closed=!1,Qr(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 $r){if(this.format=e.getFormat(),!Ls.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,this._data=e,e._referenceCount++}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Ls.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/(Mt(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 r;if(e.data instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e.data instanceof SharedArrayBuffer)r=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))r=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");const s=this.numberOfFrames*this.numberOfChannels*Mt(this.format);if(r.byteLength<s)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=e._doNotCopy?r:r.slice()}yt==null||yt.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&&!Ls.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,r=e.frameOffset??0;if(r>0&&r>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const s=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-r;if(s>this.numberOfFrames-r)throw new RangeError("frameCount out of range");const n=Mt(t),a=Qi(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?s:s*this.numberOfChannels)*n}copyTo(e,t){if(!Ur(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&&!Ls.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:r,frameCount:s,frameOffset:n}=t;let{planeIndex:a}=t,o=this.format;const c=r??this.format;if(!c)throw new Error("Destination format not determined");const u=this.numberOfFrames,l=this.numberOfChannels,d=n??0;if(d>0&&d>=u)throw new RangeError("frameOffset out of range");const f=s!==void 0?s:u-d;if(f>u-d)throw new RangeError("frameCount out of range");const h=Mt(c),p=Qi(c);if(p&&a>=l)throw new RangeError("planeIndex out of range");if(!p&&a!==0)throw new RangeError("planeIndex out of range");const g=(p?f:f*l)*h;if(e.byteLength<g)throw new RangeError("Destination buffer is too small");const y=ie(e),b=Tu(c);if(Qr(this._data))if(wi()&&l>2&&c!==o){qh(this._data,y,o,c,l,a,d,f);return}else try{this._data.copyTo(e,{planeIndex:a,frameOffset:d,frameCount:f,format:c});return}catch(C){if(c==="f32-planar")throw C;o="f32-planar"}const S=ku(o),A=Mt(o),x=Qi(o);let T;if(this._data instanceof $r){const C=_=>{const I=this._data.getDataPlane(_);if(!(I instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const v=u*A*(x?1:l);if(I.byteLength!==v)throw new TypeError(`Data plane ${_} has invalid size. Expected exactly ${v} bytes, got ${I.byteLength} bytes.`);return I};if(x)if(p)T=C(a),a=0;else{T=new Uint8Array(u*A*l);for(let _=0;_<l;_++){const I=C(_);T.set(I,_*u*A)}}else T=C(0)}else if(this._data instanceof Uint8Array)T=this._data;else if(w(o==="f32-planar"),p)T=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:a})),this._data.copyTo(T,{format:"f32-planar",planeIndex:a}),a=0;else{T=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:0})*l);for(let C=0;C<l;C++)this._data.copyTo(T.subarray(C*u*A,(C+1)*u*A),{format:"f32-planar",planeIndex:C})}const P=ie(T);for(let C=0;C<f;C++)if(p){const _=C*h;let I;x?I=(a*u+(C+d))*A:I=((C+d)*l+a)*A;const v=S(P,I);b(y,_,v)}else for(let _=0;_<l;_++){const v=(C*l+_)*h;let R;x?R=(_*u+(C+d))*A:R=((C+d)*l+_)*A;const F=S(P,R);b(y,v,F)}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof $r){const e=new qe(this._data);return e.setTimestamp(this.timestamp),e}else if(Qr(this._data)){const e=new qe(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new qe({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data,_doNotCopy:!0})}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 r=t-e,s=Mt(this.format);let n;if(Qi(this.format)){const a=r*s;if(n=new Uint8Array(a*this.numberOfChannels),r>0)for(let o=0;o<this.numberOfChannels;o++)this.copyTo(n.subarray(o*a,(o+1)*a),{planeIndex:o,format:this.format,frameOffset:e,frameCount:r})}else n=new Uint8Array(r*this.numberOfChannels*s),r>0&&this.copyTo(n,{planeIndex:0,format:this.format,frameOffset:e,frameCount:r});return new qe({data:n,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate,_doNotCopy:!0})}close(){this._closed||(yt==null||yt.unregister(this),this._data instanceof $r?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Qr(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 $r?this._createAudioDataFromData():Qr(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(Qi(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(new Uint8Array(t,r*e,e),{planeIndex:r,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 r=0;r<this.numberOfChannels;r++)this.copyTo(t,{planeIndex:r,format:"f32-planar"}),e.copyToChannel(t,r);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 r=48e3*5,s=e.numberOfChannels,n=e.sampleRate,a=e.length,o=Math.floor(r/s);let c=0,u=a;for(;u>0;){const l=Math.min(o,u),d=new Float32Array(s*l);for(let f=0;f<s;f++)e.copyFromChannel(d.subarray(f*l,(f+1)*l),f,c);yield new qe({format:"f32-planar",sampleRate:n,numberOfFrames:l,numberOfChannels:s,timestamp:t+c/n,data:d,_doNotCopy:!0}),c+=l,u-=l}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const r=48e3*5,s=e.numberOfChannels,n=e.sampleRate,a=e.length,o=Math.floor(r/s);let c=0,u=a;const l=[];for(;u>0;){const d=Math.min(o,u),f=new Float32Array(s*d);for(let p=0;p<s;p++)e.copyFromChannel(f.subarray(p*d,(p+1)*d),p,c);const h=new qe({format:"f32-planar",sampleRate:n,numberOfFrames:d,numberOfChannels:s,timestamp:t+c/n,data:f,_doNotCopy:!0});l.push(h),c+=d,u-=d}return l}}const Mt=i=>{switch(i){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")}},Qi=i=>{switch(i){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},ku=i=>{switch(i){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)}},Tu=i=>{switch(i){case"u8":case"u8-planar":return(e,t,r)=>e.setUint8(t,Be(Math.round(r*128)+128,0,255));case"s16":case"s16-planar":return(e,t,r)=>e.setInt16(t,Be(Math.round(r*32768),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,r)=>e.setInt32(t,Be(Math.round(r*2147483648),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,r)=>e.setFloat32(t,r,!0)}},Qr=i=>typeof AudioData<"u"&&i instanceof AudioData,Hh=i=>{switch(i){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return i}},qh=(i,e,t,r,s,n,a,o)=>{const c=ku(t),u=Tu(r),l=Mt(t),d=Mt(r),f=Qi(t);if(Qi(r))if(f){const p=new ArrayBuffer(o*l),m=ie(p);i.copyTo(p,{planeIndex:n,frameOffset:a,frameCount:o,format:t});for(let g=0;g<o;g++){const y=g*l,b=g*d,S=c(m,y);u(e,b,S)}}else{const p=new ArrayBuffer(o*s*l),m=ie(p);i.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let g=0;g<o;g++){const y=(g*s+n)*l,b=g*d,S=c(m,y);u(e,b,S)}}else if(f){const p=o*l,m=new ArrayBuffer(p),g=ie(m);for(let y=0;y<s;y++){i.copyTo(m,{planeIndex:y,frameOffset:a,frameCount:o,format:t});for(let b=0;b<o;b++){const S=b*l,A=(b*s+y)*d,x=c(g,S);u(e,A,x)}}}else{const p=new ArrayBuffer(o*s*l),m=ie(p);i.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let g=0;g<o;g++)for(let y=0;y<s;y++){const b=g*s+y,S=b*l,A=b*d,x=c(m,S);u(e,A,x)}}},jh=(i,e)=>{const t=i.allocationSize({format:e,planeIndex:0}),r=new ArrayBuffer(t);return i.copyTo(r,{format:e,planeIndex:0}),new qe({data:r,format:e,numberOfChannels:i.numberOfChannels,sampleRate:i.sampleRate,timestamp:i.timestamp,duration:i.duration,_doNotCopy:!0})};/*!
|
|
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 ja=new Map,Ka=new Map,Bo=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!Oe.includes(i.codec))throw new TypeError(`Invalid video codec '${i.codec}'. Must be one of: ${Oe.join(", ")}.`);const e=i.bitrate;if(i.quality===void 0&&e===void 0)throw new TypeError("config.quality must be provided.");if(i.quality!==void 0&&e!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(i.quality!==void 0&&!(i.quality instanceof Me))throw new TypeError("config.quality, when provided, must be a Quality.");if(e!==void 0&&!(e instanceof Me)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(i.keyFrameInterval!==void 0&&(!Number.isFinite(i.keyFrameInterval)||i.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(i.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(i.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(i.transform!==void 0){if(typeof i.transform!="object"||!i.transform)throw new TypeError("config.transform, when provided, must be an object.");if(i.transform.width!==void 0&&(!Number.isInteger(i.transform.width)||i.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(i.transform.height!==void 0&&(!Number.isInteger(i.transform.height)||i.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(i.transform.fit!==void 0&&!["fill","contain","cover"].includes(i.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(i.transform.width!==void 0&&i.transform.height!==void 0&&i.transform.fit===void 0&&!["fill","contain","cover"].includes(i.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(i.transform.fit!==void 0&&["fill","contain","cover"].includes(i.sizeChangeBehavior)&&i.transform.fit!==i.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(i.transform.rotate!==void 0&&![0,90,180,270].includes(i.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(i.transform.flip!==void 0&&typeof i.transform.flip!="boolean")throw new TypeError("config.transform.flip, when provided, must be a boolean.");if(i.transform.crop!==void 0&&ps(i.transform.crop,"config.transform."),i.transform.alpha!==void 0&&!["keep","discard"].includes(i.transform.alpha))throw new TypeError("config.transform.alpha, when provided, must be 'keep' or 'discard'.");if(i.transform.process!==void 0&&typeof i.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(i.transform.frameRate!==void 0&&(!Number.isFinite(i.transform.frameRate)||i.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(i.transform.force!==void 0&&typeof i.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(i.onEncoderConfig!==void 0&&typeof i.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(i.onEncodedSample!==void 0&&typeof i.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");Su(i.codec,i)},Su=(i,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&&Dt(e.fullCodecString)!==i)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${i}).`);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.")},Au=i=>{const e=i.bitrateMode,t=i.quality._toVideoRateControl(i.codec,i.width,i.height,e),r=(n,a,o)=>({codec:i.fullCodecString??zd(i.codec,i.width,i.height,o,i.alpha==="keep"),width:i.width,height:i.height,displayWidth:i.squarePixelWidth,displayHeight:i.squarePixelHeight,bitrate:n,bitrateMode:a,alpha:i.alpha??"discard",framerate:i.framerate,latencyMode:i.latencyMode,hardwareAcceleration:i.hardwareAcceleration,scalabilityMode:i.scalabilityMode,contentHint:i.contentHint,...Zp(i.codec)}),s=[];return t.quantizer!==null&&s.push({config:r(void 0,"quantizer",t.bitrate),quantizer:t.quantizer}),t.bitrateMode!=="quantizer"&&s.push({config:r(t.bitrate,t.bitrateMode,t.bitrate),quantizer:null}),w(s.length>0),s},Fo=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!Ke.includes(i.codec))throw new TypeError(`Invalid audio codec '${i.codec}'. Must be one of: ${Ke.join(", ")}.`);const e=i.bitrate;if(i.quality===void 0&&e===void 0&&!(je.includes(i.codec)||i.codec==="flac"||i.codec==="truehd"))throw new TypeError("config.quality must be provided for compressed audio codecs.");if(i.quality!==void 0&&e!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(i.quality!==void 0&&!(i.quality instanceof Me))throw new TypeError("config.quality, when provided, must be a Quality.");if(e!==void 0&&!(e instanceof Me)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(i.transform!==void 0){if(typeof i.transform!="object"||!i.transform)throw new TypeError("config.transform, when provided, must be an object.");if(i.transform.numberOfChannels!==void 0&&(!Number.isInteger(i.transform.numberOfChannels)||i.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(i.transform.sampleRate!==void 0&&(!Number.isInteger(i.transform.sampleRate)||i.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(i.transform.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(i.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(i.transform.process!==void 0&&typeof i.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.")}if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(i.onEncoderConfig!==void 0&&typeof i.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(i.onEncodedSample!==void 0&&typeof i.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");xu(i.codec,i)},xu=(i,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&&Dt(e.fullCodecString)!==i)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${i}).`)},Pu=i=>{var t,r;const e=i.bitrateMode;return{codec:i.fullCodecString??Nd(i.codec),numberOfChannels:i.numberOfChannels,sampleRate:i.sampleRate,bitrate:(t=i.quality)==null?void 0:t._toAudioBitrate(i.codec,i.numberOfChannels),bitrateMode:((r=i.quality)==null?void 0:r._bitrateMode)??e,...Hd(i.codec)}};class Me{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"?!Object.prototype.hasOwnProperty.call(bc,e.quality):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"?bc[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,r,s){const n=Kh[e];let a=null,o=this._bitrateMode??s??"variable";if(this._quantizer!==void 0){if(n)if(this._quantizer<n.min||this._quantizer>n.max){if(this._bitrate===void 0)throw new Error(`Quantizer ${this._quantizer} is out of range for codec '${e}'; must be between ${n.min} and ${n.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&&n&&!this._preferBitrate&&(w(this._quality!==void 0),a=Be(Math.round(kf(n.worst,n.best,this._quality)),n.min,n.max));let c;if(this._bitrate!==void 0)c=this._bitrate;else{let u=this._quality;u===void 0&&(w(a!==null&&n),u=Be((a-n.worst)/(n.best-n.worst),0,1)),c=kc(e,t,r,sa(u))}return{quantizer:a,bitrate:c,bitrateMode:o}}_toVideoBitrate(e,t,r){return this._bitrate!==void 0?this._bitrate:(w(this._quality!==void 0),kc(e,t,r,sa(this._quality)))}_toAudioBitrate(e,t){if(je.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 r=sa(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 a=n*r;return(e==="opus"||e==="vorbis")&&(a*=t/2),e==="aac"?a=[96e3,128e3,16e4,192e3].reduce((c,u)=>Math.abs(u-a)<Math.abs(c-a)?u:c):e==="opus"||e==="vorbis"?a=Math.max(6e3,a):e==="mp3"&&(a=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((c,u)=>Math.abs(u-a)<Math.abs(c-a)?u:c)),Math.round(a/1e3)*1e3}}const bc={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},Kh={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:(xf()??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}},sa=i=>.3*Math.exp(2.5538*i),kc=(i,e,t,r)=>{const s=e*t,n=1920*1080,a=3e6,o=Math.pow(s/n,.95),c=a*o,u={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:22e7/a},d=c*u[i]*r;return Math.ceil(d/1e3)*1e3},Cu=(i,e)=>{if(i==="avc")return{avc:{quantizer:e}};if(i==="hevc")return{hevc:{quantizer:e}};if(i==="vp9")return{vp9:{quantizer:e}};if(i==="av1")return{av1:{quantizer:e}};w(!1)},a0=new Me("very-low"),o0=new Me("low"),c0=new Me("medium"),l0=new Me("high"),u0=new Me("very-high"),d0=i=>{if(Oe.includes(i))return Ro(i);if(Ke.includes(i))return Mo(i);if(vt.includes(i))return Do(i);throw new TypeError(`Unknown codec '${i}'.`)},Ro=async(i,e={})=>{const{width:t=1280,height:r=720,quality:s,bitrate:n,frameRate:a,...o}=e;if(!Oe.includes(i))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("height must be a positive integer.");if(s!==void 0&&!(s instanceof Me))throw new TypeError("quality, when provided, must be a Quality.");if(s!==void 0&&n!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(n!==void 0&&!(n instanceof Me)&&(!Number.isInteger(n)||n<=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.");Su(i,o);const c=Dr(s,n)??new Me("medium");let u;try{u=Au({codec:i,width:t,height:r,quality:c,framerate:a,...o,alpha:"discard"})}catch{return!1}const l=JSON.stringify(u),d=ja.get(l);if(d)return d;const f=(async()=>{for(const{config:p}of u)if(yn.some(m=>m.supports(i,p)))return!0;if(typeof VideoEncoder>"u"||(t%2===1||r%2===1)&&(i==="avc"||i==="hevc"))return!1;for(const{config:p,quantizer:m}of u){try{if(!(await VideoEncoder.isConfigSupported(p)).supported)continue}catch{continue}if(!ir()||await new Promise(async y=>{const b=new VideoEncoder({output:()=>{},error:()=>y(!1)});try{b.configure(p);const S=new Uint8Array(t*r*4),A=new VideoFrame(S,{format:"RGBA",codedWidth:t,codedHeight:r,timestamp:0});b.encode(A,m!==null?Cu(i,m):void 0),A.close(),await b.flush(),y(!0)}catch{y(!1)}finally{b.state!=="closed"&&b.close()}}))return!0}return!1})();return ja.set(l,f),f},Mo=async(i,e={})=>{const{numberOfChannels:t=2,sampleRate:r=48e3,quality:s,bitrate:n,...a}=e;if(!Ke.includes(i))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("sampleRate must be a positive integer.");if(s!==void 0&&!(s instanceof Me))throw new TypeError("quality, when provided, must be a Quality.");if(s!==void 0&&n!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(n!==void 0&&!(n instanceof Me)&&(!Number.isInteger(n)||n<=0))throw new TypeError("bitrate must be a positive integer.");xu(i,a);const o=Dr(s,n)??new Me("medium"),c=Pu({codec:i,numberOfChannels:t,sampleRate:r,quality:o,...a}),u=JSON.stringify(c),l=Ka.get(u);if(l)return l;const d=(async()=>{if(bn.some(f=>f.supports(i,c))||je.includes(i))return!0;if(typeof AudioEncoder>"u")return!1;try{return(await AudioEncoder.isConfigSupported(c)).supported===!0}catch{return!1}})();return Ka.set(u,d),d},Dr=(i,e)=>{if(i!==void 0)return i;if(e!==void 0)return e instanceof Me?e:new Me({bitrate:e})},Do=async i=>!!vt.includes(i),f0=async()=>{const[i,e,t]=await Promise.all([$h(),$a(),Qh()]);return[...i,...e,...t]},$h=async(i=Oe,e)=>{const t=await Promise.all(i.map(r=>Ro(r,e)));return i.filter((r,s)=>t[s])},$a=async(i=Ke,e)=>{const t=await Promise.all(i.map(r=>Mo(r,e)));return i.filter((r,s)=>t[s])},Qh=async(i=vt)=>{const e=await Promise.all(i.map(Do));return i.filter((t,r)=>e[r])},Gh=async(i,e)=>{for(const t of i)if(await Ro(t,e))return t;return null},h0=async(i,e)=>{for(const t of i)if(await Mo(t,e))return t;return null},m0=async i=>{for(const e of i)if(await Do(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 Xh{static supports(e,t){return!1}}class Yh{static supports(e,t){return!1}}class Zh{static supports(e,t){return!1}}class Jh{static supports(e,t){return!1}}const ws=[],ys=[],yn=[],bn=[],p0=i=>{if(i.prototype instanceof Xh){const e=i;if(ws.includes(e)){K._warn("Video decoder already registered.");return}ws.push(e),Wa.clear()}else if(i.prototype instanceof Yh){const e=i;if(ys.includes(e)){K._warn("Audio decoder already registered.");return}ys.push(e),La.clear()}else throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},g0=i=>{if(i.prototype instanceof Zh){const e=i;if(yn.includes(e)){K._warn("Video encoder already registered.");return}yn.push(e),ja.clear()}else if(i.prototype instanceof Jh){const e=i;if(bn.includes(e)){K._warn("Audio encoder already registered.");return}bn.push(e),Ka.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 mt=new Uint8Array(0);class Ce{constructor(e,t,r,s,n=-1,a,o){if(this.data=e,this.type=t,this.timestamp=r,this.duration=s,this.sequenceNumber=n,e===mt&&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(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(s)||s<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))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===mt}get microsecondTimestamp(){return Math.trunc(Bi*this.timestamp)}get microsecondDuration(){return Math.trunc(Bi*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 r=new Uint8Array(e.byteLength);return e.copyTo(r),new Ce(r,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){var t;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,((t=e==null?void 0:e.data)==null?void 0:t.byteLength)??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 em{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(){w(this.sourceNumberOfChannels!==null);const e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(r,s)=>r[s*e]:e===1&&t===4?this.channelMixer=(r,s,n)=>r[s*e]*+(n<2):e===1&&t===6?this.channelMixer=(r,s,n)=>r[s*e]*+(n===2):e===2&&t===1?this.channelMixer=(r,s)=>{const n=s*e;return .5*(r[n]+r[n+1])}:e===2&&t===4?this.channelMixer=(r,s,n)=>n<2?r[s*e+n]:0:e===2&&t===6?this.channelMixer=(r,s,n)=>n<2?r[s*e+n]:0:e===4&&t===1?this.channelMixer=(r,s)=>{const n=s*e;return .25*(r[n]+r[n+1]+r[n+2]+r[n+3])}:e===4&&t===2?this.channelMixer=(r,s,n)=>{const a=s*e;return .5*(r[a+n]+r[a+n+2])}:e===4&&t===6?this.channelMixer=(r,s,n)=>{const a=s*e;return n<2?r[a+n]:n===2||n===3?0:r[a+n-2]}:e===6&&t===1?this.channelMixer=(r,s)=>{const n=s*e;return Math.SQRT1_2*(r[n]+r[n+1])+r[n+2]+.5*(r[n+4]+r[n+5])}:e===6&&t===2?this.channelMixer=(r,s,n)=>{const a=s*e;return r[a+n]+Math.SQRT1_2*(r[a+2]+r[a+n+4])}:e===6&&t===4?this.channelMixer=(r,s,n)=>{const a=s*e;return n<2?r[a+n]+Math.SQRT1_2*r[a+2]:r[a+n+2]}:this.channelMixer=(r,s,n)=>n<e?r[s*e+n]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){const r=new Float32Array(t);r.set(this.tempSourceBuffer),this.tempSourceBuffer=r}}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()}w(this.startTime!==null);const t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);const r=e.allocationSize({planeIndex:0,format:"f32"}),s=new Float32Array(this.tempSourceBuffer.buffer,0,r/4);e.copyTo(s,{planeIndex:0,format:"f32"});const n=Math.round((e.timestamp-this.startTime)*this.sourceSampleRate),a=n+e.numberOfFrames,o=Math.floor((n-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;w(l<this.bufferCapacityInFrames);const d=u*this.sourceSampleRate/this.targetSampleRate-n,f=Math.floor(d),h=Math.ceil(d),p=d-f;for(let m=0;m<this.targetNumberOfChannels;m++){let g=0,y=0;f>=0&&f<e.numberOfFrames&&(g=this.channelMixer(s,f,m)),h>=0&&h<e.numberOfFrames&&(y=this.channelMixer(s,h,m));const b=g+p*(y-g),S=l*this.targetNumberOfChannels+m;this.outputBuffer[S]+=b}this.maxWrittenFrame===null?this.maxWrittenFrame=l:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,l)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;w(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 r=new qe({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t,_doNotCopy:!0});await this.onSample(r),this.outputBuffer.copyWithin(0,this.bufferSizeInSamples),this.outputBuffer.fill(0,this.outputBuffer.length-this.bufferSizeInSamples),this.maxWrittenFrame=this.maxWrittenFrame>=this.bufferSizeInFrames?this.maxWrittenFrame-this.bufferSizeInFrames:null}async finalize(){for(;this.maxWrittenFrame!==null;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames}}/*!
|
|
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 Ai{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 _u=2082844800,Eu=i=>{let t=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isQuickTime?"quicktime":"mp4");if(i.codecStrings.length>0){const r=[...new Set(i.codecStrings)];t+=`; codecs="${r.join(", ")}"`}return t},Iu=i=>{if(i.length<24)throw new Error("Invalid pssh box: too small.");const e=ie(i);let t=0;const r=e.getUint8(t);t+=1,t+=3;const s=ls(i.subarray(t,t+16));t+=16;let n=null;if(r>0){const o=e.getUint32(t);if(t+=4,t+16*o+4>i.length)throw new Error("Invalid pssh box: key ID count exceeds box size.");if(o>0){n=[];for(let c=0;c<o;c++)n.push(ls(i.subarray(t,t+16))),t+=16}}const a=e.getUint32(t);return t+=4,{systemId:s,keyIds:n,data:i.slice(t,t+a)}},vu=(i,e)=>{if(i.systemId!==e.systemId||!ql(i.data,e.data))return!1;const t=i.keyIds,r=e.keyIds;return!t||!r?t===r:t.length===r.length&&t.every((s,n)=>s===r[n])};/*!
|
|
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 Kt=16,si=new Uint32Array(256),gr=new Uint32Array(256),wr=new Uint32Array(256),yr=new Uint32Array(256),br=new Uint32Array(256),it=new Uint32Array(256),Bu=new Uint32Array(10);let Fu=!1;const tm=()=>{const i=new Uint8Array(256),e=new Uint8Array(256),t=new Uint8Array(256);for(let n=0,a=1;n<256;n++)t[n]=a,e[a]=n,a=a^a<<1^(a&128?283:0);const r=(n,a)=>n&&a?t[(e[n]+e[a])%255]:0;i[0]=99;for(let n=1;n<256;n++){const a=t[255-e[n]];let o=a^a<<1^a<<2^a<<3^a<<4;o=o>>>8^o&255^99,i[n]=o}for(let n=0;n<256;n++){const a=i[n],o=i.indexOf(n);si[n]=a<<24|a<<16|a<<8|a,it[n]=o<<24|o<<16|o<<8|o;const c=r(o,14),u=r(o,9),l=r(o,13),d=r(o,11),f=c<<24|u<<16|l<<8|d;gr[n]=f,wr[n]=f>>>8|f<<24,yr[n]=f>>>16|f<<16,br[n]=f>>>24|f<<8}let s=1;for(let n=0;n<10;n++)Bu[n]=s<<24,s=s<<1^(s&128?283:0);Fu=!0};class Ru{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Kt/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Kt),this.out=new Uint8Array(Kt),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){w(e.byteLength===16),w(t.byteLength===16),Fu||tm();const r=new DataView(e.buffer,e.byteOffset,e.byteLength),s=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=r.getUint32(0,!1),this.roundkey[1]=r.getUint32(4,!1),this.roundkey[2]=r.getUint32(8,!1),this.roundkey[3]=r.getUint32(12,!1),this.iv[0]=s.getUint32(0,!1),this.iv[1]=s.getUint32(4,!1),this.iv[2]=s.getUint32(8,!1),this.iv[3]=s.getUint32(12,!1);for(let n=4;n<44;n+=4){const a=this.roundkey[n-1];this.roundkey[n]=this.roundkey[n-4]^si[a>>>16&255]&4278190080^si[a>>>8&255]&16711680^si[a>>>0&255]&65280^si[a>>>24&255]&255^Bu[n/4-1],this.roundkey[n+1]=this.roundkey[n-3]^this.roundkey[n],this.roundkey[n+2]=this.roundkey[n-2]^this.roundkey[n+1],this.roundkey[n+3]=this.roundkey[n-1]^this.roundkey[n+2]}for(let n=0,a=40;n<a;n+=4,a-=4)for(let o=0;o<4;o++){const c=this.roundkey[n+o];this.roundkey[n+o]=this.roundkey[a+o],this.roundkey[a+o]=c}for(let n=4;n<40;n+=4)for(let a=0;a<4;a++){const o=this.roundkey[n+a];this.roundkey[n+a]=gr[si[o>>>24&255]&255]^wr[si[o>>>16&255]&255]^yr[si[o>>>8&255]&255]^br[si[o>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],r=this.inView.getUint32(8,!1)^this.roundkey[2],s=this.inView.getUint32(12,!1)^this.roundkey[3];const n=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 y=1;y<10;y++){const b=y*4;u=gr[e>>>24]^wr[s>>>16&255]^yr[r>>>8&255]^br[t&255]^this.roundkey[b],l=gr[t>>>24]^wr[e>>>16&255]^yr[s>>>8&255]^br[r&255]^this.roundkey[b+1],d=gr[r>>>24]^wr[t>>>16&255]^yr[e>>>8&255]^br[s&255]^this.roundkey[b+2],f=gr[s>>>24]^wr[r>>>16&255]^yr[t>>>8&255]^br[e&255]^this.roundkey[b+3],e=u,t=l,r=d,s=f}const h=it[e>>>24&255]&4278190080^it[s>>>16&255]&16711680^it[r>>>8&255]&65280^it[t>>>0&255]&255^this.roundkey[40],p=it[t>>>24&255]&4278190080^it[e>>>16&255]&16711680^it[s>>>8&255]&65280^it[r>>>0&255]&255^this.roundkey[41],m=it[r>>>24&255]&4278190080^it[t>>>16&255]&16711680^it[e>>>8&255]&65280^it[s>>>0&255]&255^this.roundkey[42],g=it[s>>>24&255]&4278190080^it[r>>>16&255]&16711680^it[t>>>8&255]&65280^it[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,g^this.iv[3],!1),this.iv[0]=n,this.iv[1]=a,this.iv[2]=o,this.iv[3]=c}}const im=(i,e,t)=>{let r=!1,s=!1,n=0;const a=2**16,o=16,c=new Ru,u=()=>{s||(s=!0,t())};return new ReadableStream({pull:async l=>{try{r||(c.init(await e()),r=!0);const d=a+o;let f=i.requestSliceRange(n,0,d);if(D(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),g=new Uint8Array(p);for(let y=0;y<p;y+=16)c.in.set(m.subarray(y,y+16)),c.decrypt(),g.set(c.out,y);if(p<h)l.enqueue(g),n+=p;else{const y=g[p-1];if(y===0||y>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const b=g.subarray(0,p-y);l.enqueue(b),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 Tc=[2,1,1,2,2,2,2,1,1,2,2,1,1],rm=64;class zo extends Ai{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=cs,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=new Map,this.psshBoxes=[],this.currentFragment=null,this.isReadingTraf=!1,this.currentFragmentTrackState=null,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(r=>r.getDecoderConfig().then(s=>(s==null?void 0:s.codec)??null)));return Eu({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(r=>{var s;return((s=r.info)==null?void 0:s.type)==="video"}),hasAudio:this.tracks.some(r=>{var s;return((s=r.info)==null?void 0:s.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,r=!1;for(;;){let s=this.reader.requestSliceRange(e,Xt,Di);if(D(s)&&(s=await s),!s)break;const n=e,a=_i(s);if(!a)break;if((a.name==="ftyp"||a.name==="styp")&&s.remainingLength>=4){const o=Ie(s,4);this.isQuickTime=o==="qt "}else if(a.name==="moov"){let o=this.reader.requestSlice(s.filePos,a.contentSize);if(D(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>n+a.totalSize,r=!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,r=!0;break}e=n+a.totalSize}if(!r&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),t){w(this.reader.fileSize!==null);let s=this.reader.requestSlice(this.reader.fileSize-4,4);D(s)&&(s=await s),w(s);const n=q(s),a=this.reader.fileSize-n;if(a>=0&&a<=this.reader.fileSize-Di){let o=this.reader.requestSliceRange(a,Xt,Di);if(D(o)&&(o=await o),o){const c=_i(o);if(c&&c.name==="mfra"){let u=this.reader.requestSlice(o.filePos,c.contentSize);D(u)&&(u=await u),u&&this.readContiguousBoxes(u)}}}}for(const s of this.tracks){const n=s.fragmentLookupTable;n.sort((o,c)=>o.timestamp-c.timestamp);let a=0;for(const o of n)(a===0||o.timestamp!==n[a-1].timestamp)&&(n[a++]=o);n.length=a}})())}async copyMetadataFromInitInput(e){const t=await e._getDemuxer();if(t.constructor!==zo)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 r of t.tracks){const s={id:r.id,demuxer:this,trackBacking:null,disposition:r.disposition,timescale:r.timescale,durationInMediaTimescale:r.durationInMediaTimescale,durationInMovieTimescale:r.durationInMovieTimescale,matrix:r.matrix,internalCodecId:r.internalCodecId,name:r.name,languageCode:r.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],fragmentPositionCache:[],editListPreviousSegmentDurations:r.editListPreviousSegmentDurations,editListOffset:r.editListOffset,encryptionInfo:r.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:r.maxBitrate,avgBitrate:r.avgBitrate,info:r.info};if(r.trackBacking){if(w(s.info),s.info.type==="video"&&s.info.width!==-1){const n=s;s.trackBacking=new Sc(n),this.tracks.push(s),this.idToTrack.set(s.id,s)}else if(s.info.type==="audio"&&s.info.numberOfChannels!==-1){const n=s;s.trackBacking=new Ac(n),this.tracks.push(s),this.idToTrack.set(s.id,s)}}}}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;w(this.moovSlice);const r=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e;try{this.traverseBox(r)}catch(l){throw e.sampleTable=null,l}finally{this.currentTrack=null}const s=Te(t.sampleTimingEntries),n=de(t.sampleToChunk,t.chunkOffsets.length-1,l=>l.startChunkIndex),a=t.sampleToChunk[n];if(t.sampleCount=Math.min(t.sampleCount,s?s.startIndex+s.count:0,a?a.startSampleIndex+(t.chunkOffsets.length-a.startChunkIndex)*a.samplesPerChunk:0),Cc(t.sampleTimingEntries,t.sampleCount),Cc(t.sampleCompositionTimeOffsets,t.sampleCount),((c=e.info)==null?void 0:c.type)==="audio"&&e.info.codec&&je.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0&&t.sampleTimingEntries.length>0){w(((u=e.info)==null?void 0:u.type)==="audio");const l=Bt(e.info.codec),d=[],f=[];for(let h=0;h<t.sampleToChunk.length;h++){const p=t.sampleToChunk[h],m=t.sampleToChunk[h+1],g=Math.min(m?m.startChunkIndex:1/0,t.chunkOffsets.length)-p.startChunkIndex,y=f.length;for(let b=0;b<g;b++){const S=p.startSampleIndex+b*p.samplesPerChunk,A=S+p.samplesPerChunk,x=de(t.sampleTimingEntries,S,O=>O.startIndex),T=t.sampleTimingEntries[x],P=de(t.sampleTimingEntries,A,O=>O.startIndex),C=t.sampleTimingEntries[P],_=T.startDecodeTimestamp+(S-T.startIndex)*T.delta,v=C.startDecodeTimestamp+(A-C.startIndex)*C.delta-_,R=Te(d);R&&R.delta===v?R.count++:d.push({startIndex:f.length,startDecodeTimestamp:_,count:1,delta:v});const H=Math.round(v*e.info.sampleRate/e.timescale)*l.sampleSize*e.info.numberOfChannels;f.push(H)}p.startSampleIndex=y,p.samplesPerChunk=1}t.sampleTimingEntries=d,t.sampleSizes=f,t.sampleCount=f.length}if(t.sampleCompositionTimeOffsets.length>0){const l=t.sampleCompositionTimeOffsets,d=Te(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(b=>b.count>0),p=t.sampleTimingEntries;let m=0;const g=b=>{for(;m+1<p.length&&p[m+1].startIndex<=b;)m++;const S=p[m];return S.startDecodeTimestamp+(b-S.startIndex)*S.delta};for(const b of h){const S=b.startIndex+b.count-1;b.startTimestamp=g(b.startIndex)+b.offset,b.lastTimestamp=g(S)+b.offset}h.sort((b,S)=>b.startTimestamp-S.startTimestamp||b.startIndex-S.startIndex);let y=-1/0;for(const b of h)y=Math.max(y,b.lastTimestamp),b.maxLastTimestamp=y;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}readFragment(e){var r;if(((r=this.lastReadFragment)==null?void 0:r.moofOffset)===e)return this.lastReadFragment.promise;const t=(async()=>{let s=this.reader.requestSliceRange(e,Xt,Di);D(s)&&(s=await s),w(s);const n=_i(s);w((n==null?void 0:n.name)==="moof");let a=this.reader.requestSlice(e,n.totalSize);if(D(a)&&(a=await a),!a)return null;this.traverseBox(a);const o=this.currentFragment;w(o&&o.moofOffset===e),this.currentFragment=null,this.fragmentSummaries.set(e,{moofSize:o.moofSize,trackIds:new Set(o.trackData.keys())});for(const[,c]of o.trackData){const u=c.track,{fragmentPositionCache:l}=u;if(!c.startTimestampIsFinal){const p=As(u.fragmentLookupTable,o.moofOffset,y=>y.moofOffset),m=u.fragmentLookupTable[p];if(m&&c.trunSampleCounts.length>=m.trunNumber&&c.trunSampleCounts[m.trunNumber-1]>=m.sampleNumber){let y=0;for(let A=1;A<m.trunNumber;A++)y+=c.trunSampleCounts[A-1];y+=m.sampleNumber-1;const b=c.samples[y];w(b);const S=m.timestamp-b.presentationTimestamp;Hs(c,S)}else{const y=de(l,o.moofOffset-1,b=>b.moofOffset);if(y!==-1){const b=l[y];Hs(c,b.endDecodeTimestamp)}else{const b=Te(this.getSampleTableForTrack(u).sampleTimingEntries);if(b){const{startDecodeTimestamp:S,count:A,delta:x}=b;Hs(c,S+A*x)}}}c.startTimestampIsFinal=!0}const d=de(l,c.startTimestamp,p=>p.startTimestamp),f=l[d],h=l[d+1];if((!f||f.moofOffset<o.moofOffset)&&(!h||h.moofOffset>o.moofOffset)&&l.splice(d+1,0,{moofOffset:o.moofOffset,startTimestamp:c.startTimestamp,endDecodeTimestamp:c.endDecodeTimestamp,hasKeyFrame:c.firstKeyFrameTimestamp!==null}),c.encryptionAuxInfo&&u.encryptionInfo){const p=await Ou(this.reader,u.encryptionInfo,c.encryptionAuxInfo);for(let m=0;m<Math.min(c.samples.length,p.length);m++){const g=p[m];c.samples[m].encryption=g}}}return o})();return this.lastReadFragment={moofOffset:e,promise:t},t.catch(()=>{var s;((s=this.lastReadFragment)==null?void 0:s.promise)===t&&(this.lastReadFragment=null)}),t}readContiguousBoxes(e){if(this.boxNestingDepth===rm)throw new Error("Invalid file: boxes are nested too deeply.");const t=e.filePos;this.boxNestingDepth++;try{for(;e.filePos-t<=e.length-Xt&&this.traverseBox(e););}finally{this.boxNestingDepth--}}*iterateContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-Xt;){const r=e.filePos,s=_i(e);if(!s)break;yield{boxInfo:s,slice:e},e.filePos=r+s.totalSize}}traverseBox(e){var a,o,c,u,l,d,f,h,p,m,g,y,b,S,A,x,T,P,C,_,I,v,R,F,H,O,U,L,Q,re,Y,se,pe,he,Pe,We,tt,$e,ve,Qe,Ge,_e,Xe,St,xi,Li,Pi,ii,Lr,N,ne,Ee,Ye,At,Ft,dt;const t=e.filePos,r=_i(e);if(!r)return!1;const s=e.filePos,n=t+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes(e.slice(s,r.contentSize));break;case"mvhd":{const k=Z(e);e.skip(3);let B;if(k===1?(B=ft(e),e.skip(8),this.movieTimescale=q(e),this.movieDurationInTimescale=ft(e)):(B=q(e),e.skip(4),this.movieTimescale=q(e),this.movieDurationInTimescale=q(e)),B!==0&&(this.metadataTags.creationTime=new Date(1e3*(B-_u))),this.movieTimescale===0)throw new Error("Invalid mvhd box: timescale must not be 0.");e.skip(16),this.movieMatrix=xc(e)}break;case"trak":{if(this.currentFragment||this.currentTrack)break;const k={id:-1,demuxer:this,trackBacking:null,disposition:{...Si,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,matrix:cs,internalCodecId:null,name:null,languageCode:et,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:null,avgBitrate:null};if(this.currentTrack=k,this.readContiguousBoxes(e.slice(s,r.contentSize)),k.id!==-1&&k.timescale!==-1&&k.info!==null&&k.sampleTableByteOffset!==-1){if(k.info.type==="video"&&k.info.width!==-1){const B=k;k.trackBacking=new Sc(B),this.tracks.push(k),this.idToTrack.set(k.id,k)}else if(k.info.type==="audio"&&k.info.numberOfChannels!==-1){const B=k;k.trackBacking=new Ac(B),this.tracks.push(k),this.idToTrack.set(k.id,k)}}this.currentTrack=null}break;case"tkhd":{const k=this.currentTrack;if(!k||this.currentFragment)break;const B=Z(e),V=!!(ai(e)&1);if(k.disposition.default=V,B===0)e.skip(8),k.id=q(e),e.skip(4),k.durationInMovieTimescale=q(e);else if(B===1)e.skip(16),k.id=q(e),e.skip(4),k.durationInMovieTimescale=ft(e);else throw new Error(`Incorrect track header version ${B}.`);e.skip(16);const $=xc(e);k.matrix=vr($,this.movieMatrix)}break;case"elst":{const k=this.currentTrack;if(!k)break;const B=Z(e);e.skip(3);let M=!1,V=0;const $=q(e);for(let W=0;W<$;W++){const G=B===1?ft(e):q(e),te=B===1?Bp(e):Yi(e),ce=Ki(e);if(M){K._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(te===-1){V+=G;continue}if(ce!==1){K._warn("Unsupported edit list entry: media rate must be 1.");break}k.editListPreviousSegmentDurations=V,k.editListOffset=te,M=!0}}break;case"mdhd":{const k=this.currentTrack;if(!k)break;const B=Z(e);if(e.skip(3),B===0?(e.skip(8),k.timescale=q(e),k.durationInMediaTimescale=q(e)):B===1&&(e.skip(16),k.timescale=q(e),k.durationInMediaTimescale=ft(e)),k.durationInMediaTimescale===2**(B===1?64:32)-1&&(k.durationInMediaTimescale=-1),k.timescale===0)throw new Error("Invalid mdhd box: timescale must not be 0.");let M=De(e);if(M>0){k.languageCode="";for(let V=0;V<3;V++)k.languageCode=String.fromCharCode(96+(M&31))+k.languageCode,M>>=5;us(k.languageCode)||(k.languageCode=et)}}break;case"hdlr":{const k=this.currentTrack;if(!k)break;e.skip(8);const B=Ie(e,4);B==="vide"?k.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...Wl},avcType:null,avcCodecInfo:null,hevcType:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:B==="soun"&&(k.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const k=this.currentTrack;if(!k)break;k.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(s,r.contentSize))}break;case"stsd":{const k=this.currentTrack;if(!k||k.info===null||k.sampleTable)break;const B=Z(e);e.skip(3);const M=q(e);for(let V=0;V<M;V++){const $=e.filePos,W=_i(e);if(!W)break;k.internalCodecId=W.name;const G=W.name.toLowerCase();if(k.info.type==="video"){e.skip(24),k.info.width=De(e),k.info.height=De(e),k.info.squarePixelWidth=k.info.width,k.info.squarePixelHeight=k.info.height,e.skip(50),k.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,$+W.totalSize-e.filePos));const te=G==="encv"?k.frmaCodecString:G;k.frmaCodecString=null,te==="avc1"||te==="avc3"?(k.info.codec="avc",k.info.avcType=te==="avc1"?1:3):te==="hvc1"||te==="hev1"?(k.info.codec="hevc",k.info.hevcType=te):te==="vp08"?k.info.codec="vp8":te==="vp09"?k.info.codec="vp9":te==="av01"?k.info.codec="av1":er.includes(G)?(k.info.codec="prores",k.info.proresFormat=G):te===null?K._warn("Unknown encrypted video codec due to missing frma box."):K._warn(`Unsupported video codec (sample entry type '${W.name}').`)}else{e.skip(8);const te=De(e);e.skip(6);let ce=De(e),ue=De(e);e.skip(4);let Ue=q(e)/65536,Ne=null;B===0&&te>0&&(te===1?(e.skip(4),ue=8*q(e),e.skip(8)):te===2&&(e.skip(4),Ue=vd(e),ce=q(e),e.skip(4),ue=q(e),Ne=q(e),e.skip(8))),k.info.numberOfChannels=ce,k.info.sampleRate=Ue||k.timescale,k.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,$+W.totalSize-e.filePos));const we=G==="enca"?k.frmaCodecString:G;if(k.frmaCodecString=null,we!=="mp4a")if(we===".mp3")k.info.codec="mp3";else if(we==="opus")k.info.codec="opus",k.info.sampleRate=Wi;else if(we==="flac")k.info.codec="flac";else if(we==="ulaw")k.info.codec="ulaw";else if(we==="alaw")k.info.codec="alaw";else if(we==="ac-3")k.info.codec="ac3";else if(we==="ec-3")k.info.codec="eac3";else if(Cn.includes(we))k.info.codec="dts",k.info.dtsFormat=we;else if(we==="mlpa")k.info.codec="truehd";else if(we==="twos")ue===8?k.info.codec="pcm-s8":ue===16?k.info.codec=k.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(K._warn(`Unsupported sample size ${ue} for codec 'twos'.`),k.info.codec=null);else if(we==="sowt")ue===8?k.info.codec="pcm-s8":ue===16?k.info.codec="pcm-s16":(K._warn(`Unsupported sample size ${ue} for codec 'sowt'.`),k.info.codec=null);else if(we==="raw ")k.info.codec="pcm-u8";else if(we==="in24")k.info.codec=k.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(we==="in32")k.info.codec=k.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(we==="fl32")k.info.codec=k.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(we==="fl64")k.info.codec=k.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(we==="ipcm"){const ye=k.info.pcmSampleSize;k.info.pcmLittleEndian?ye===16?k.info.codec="pcm-s16":ye===24?k.info.codec="pcm-s24":ye===32?k.info.codec="pcm-s32":(K._warn(`Invalid ipcm sample size ${ye}.`),k.info.codec=null):ye===16?k.info.codec="pcm-s16be":ye===24?k.info.codec="pcm-s24be":ye===32?k.info.codec="pcm-s32be":(K._warn(`Invalid ipcm sample size ${ye}.`),k.info.codec=null)}else if(we==="fpcm"){const ye=k.info.pcmSampleSize;k.info.pcmLittleEndian?ye===32?k.info.codec="pcm-f32":ye===64?k.info.codec="pcm-f64":(K._warn(`Invalid fpcm sample size ${ye}.`),k.info.codec=null):ye===32?k.info.codec="pcm-f32be":ye===64?k.info.codec="pcm-f64be":(K._warn(`Invalid fpcm sample size ${ye}.`),k.info.codec=null)}else if(we==="lpcm"&&Ne!==null){const ye=ue+7>>3,Le=!!(Ne&1),gt=!!(Ne&2),wt=Ne&4?-1:0;ue>0&&ue<=64&&(Le?ue===32?k.info.codec=gt?"pcm-f32be":"pcm-f32":ue===64&&(k.info.codec=gt?"pcm-f64be":"pcm-f64"):wt&1<<ye-1?ye===1?k.info.codec="pcm-s8":ye===2?k.info.codec=gt?"pcm-s16be":"pcm-s16":ye===3?k.info.codec=gt?"pcm-s24be":"pcm-s24":ye===4&&(k.info.codec=gt?"pcm-s32be":"pcm-s32"):ye===1&&(k.info.codec="pcm-u8")),k.info.codec===null&&K._warn("Unsupported PCM format.")}else we===null?K._warn("Unknown encrypted audio codec due to missing frma box."):K._warn(`Unsupported audio codec (sample entry type '${W.name}').`)}e.filePos=$+W.totalSize}}break;case"frma":{const k=this.currentTrack;if(!k)break;const M=Ie(e,4).toLowerCase();k.frmaCodecString=M}break;case"schm":{const k=this.currentTrack;if(!k)break;e.skip(4);const B=Ie(e,4);B==="cenc"||B==="cens"||B==="cbcs"?k.encryptionInfo={scheme:B,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:K._warn(`Unsupported encryption scheme '${B}'.`)}break;case"tenc":{const k=this.currentTrack;if(!k||!k.encryptionInfo)break;const B=Z(e);e.skip(3),e.skip(1);const M=Z(e);if(B>0?(k.encryptionInfo.defaultCryptByteBlock=M>>4,k.encryptionInfo.defaultSkipByteBlock=M&15):(k.encryptionInfo.defaultCryptByteBlock=0,k.encryptionInfo.defaultSkipByteBlock=0),k.encryptionInfo.defaultIsProtected=Z(e)!==0,k.encryptionInfo.defaultPerSampleIvSize=Z(e),k.encryptionInfo.defaultKid=ls(X(e,16)),k.encryptionInfo.defaultPerSampleIvSize>16)throw new Error("Invalid tenc box: IV size must not exceed 16 bytes.");if(k.encryptionInfo.defaultIsProtected&&k.encryptionInfo.defaultPerSampleIvSize===0){const V=Z(e);if(V>16)throw new Error("Invalid tenc box: IV size must not exceed 16 bytes.");const $=new Uint8Array(16);$.set(X(e,V),0),k.encryptionInfo.defaultConstantIv=$}}break;case"avcC":{const k=this.currentTrack;if(!k||((a=k.info)==null?void 0:a.type)!=="video"||r.contentSize===0)break;k.info.codecDescription=X(e,r.contentSize);const B=(o=Es(k.info.codecDescription))==null?void 0:o.sequenceParameterSets[0],M=B&&Zi(B);M&&Pc(k,M.pixelAspectRatio)}break;case"hvcC":{const k=this.currentTrack;if(!k||((c=k.info)==null?void 0:c.type)!=="video"||r.contentSize===0)break;k.info.codecDescription=X(e,r.contentSize);const B=(l=(u=xo(k.info.codecDescription))==null?void 0:u.arrays.find(V=>V.nalUnitType===ke.SPS_NUT))==null?void 0:l.nalUnits[0],M=B&&Un(B);M&&Pc(k,M.pixelAspectRatio)}break;case"vpcC":{const k=this.currentTrack;if(!k||((d=k.info)==null?void 0:d.type)!=="video")break;e.skip(4);const B=Z(e),M=Z(e),V=Z(e),$=V>>4,W=V>>1&7,G=V&1,te=Z(e),ce=Z(e),ue=Z(e);k.info.vp9CodecInfo={profile:B,level:M,bitDepth:$,chromaSubsampling:W,videoFullRangeFlag:G,colourPrimaries:te,transferCharacteristics:ce,matrixCoefficients:ue}}break;case"av1C":{const k=this.currentTrack;if(!k||((f=k.info)==null?void 0:f.type)!=="video")break;e.skip(1);const B=Z(e),M=B>>5,V=B&31,$=Z(e),W=$>>7,G=$>>6&1,te=$>>5&1,ce=$>>4&1,ue=$>>3&1,Ue=$>>2&1,Ne=$&3,we=M===2&&G?te?12:10:G?10:8;e.skip(1);const ye=X(e,r.contentSize-4),Le=ms(ye);k.info.av1CodecInfo={profile:M,level:V,tier:W,bitDepth:we,monochrome:ce,chromaSubsamplingX:ue,chromaSubsamplingY:Ue,chromaSamplePosition:Ne,videoFullRangeFlag:(Le==null?void 0:Le.videoFullRangeFlag)??0,colourPrimaries:(Le==null?void 0:Le.colourPrimaries)??2,transferCharacteristics:(Le==null?void 0:Le.transferCharacteristics)??2,matrixCoefficients:(Le==null?void 0:Le.matrixCoefficients)??2}}break;case"colr":{const k=this.currentTrack;if(!k||((h=k.info)==null?void 0:h.type)!=="video")break;const B=Ie(e,4);if(B!=="nclx"&&B!=="nclc")break;const M=De(e),V=De(e),$=De(e);let W;B==="nclx"&&(W=!!(Z(e)&128)),k.info.colorSpace={primaries:di[M],transfer:fi[V],matrix:hi[$],fullRange:W}}break;case"pasp":{const k=this.currentTrack;if(!k||((p=k.info)==null?void 0:p.type)!=="video")break;const B=q(e),M=q(e);B>0&&M>0&&(k.info.squarePixelWidth=k.info.width,k.info.squarePixelHeight=k.info.height,B>M?k.info.squarePixelWidth=Math.round(k.info.width*B/M):k.info.squarePixelHeight=Math.round(k.info.height*M/B))}break;case"btrt":{const k=this.currentTrack;if(!k)break;e.skip(4);const B=q(e),M=q(e);k.maxBitrate=B>0?B:null,k.avgBitrate=M>0?M:null}break;case"wave":this.readContiguousBoxes(e.slice(s,r.contentSize));break;case"esds":{const k=this.currentTrack;if(!k||((m=k.info)==null?void 0:m.type)!=="audio")break;e.skip(4);const{objectTypeIndication:B,decoderSpecificInfo:M}=Fd(e);if(B===64||B===103?(k.info.codec="aac",k.info.aacCodecInfo={isMpeg2:B===103,objectType:null}):B===105||B===107?k.info.codec="mp3":B===221?k.info.codec="vorbis":B===169?k.info.codec="dts":K._warn(`Unsupported audio codec (objectTypeIndication ${B}) - discarding track.`),M&&(k.info.codecDescription=M,k.info.codec==="aac")){const V=nr(k.info.codecDescription);V.outputNumberOfChannels!==null&&(k.info.numberOfChannels=V.outputNumberOfChannels),V.outputSampleRate!==null&&(k.info.sampleRate=V.outputSampleRate)}}break;case"enda":{const k=this.currentTrack;if(!k||((g=k.info)==null?void 0:g.type)!=="audio")break;k.info.pcmLittleEndian=!!(De(e)&255)}break;case"pcmC":{const k=this.currentTrack;if(!k||((y=k.info)==null?void 0:y.type)!=="audio")break;e.skip(4);const B=Z(e);k.info.pcmLittleEndian=!!(B&1),k.info.pcmSampleSize=Z(e)}break;case"srat":{const k=this.currentTrack;if(!k||((b=k.info)==null?void 0:b.type)!=="audio")break;e.skip(4),k.info.sampleRate=q(e)}break;case"dOps":{const k=this.currentTrack;if(!k||((S=k.info)==null?void 0:S.type)!=="audio")break;e.skip(1);const B=Z(e),M=De(e),V=q(e),$=co(e),W=Z(e),G=W!==0?X(e,r.contentSize-11):new Uint8Array(0),te=new Uint8Array(19+G.byteLength),ce=new DataView(te.buffer);ce.setUint32(0,1332770163,!1),ce.setUint32(4,1214603620,!1),ce.setUint8(8,1),ce.setUint8(9,B),ce.setUint16(10,M,!0),ce.setUint32(12,V,!0),ce.setInt16(16,$,!0),ce.setUint8(18,W),te.set(G,19),k.info.codecDescription=te,k.info.numberOfChannels=B}break;case"dfLa":{const k=this.currentTrack;if(!k||((A=k.info)==null?void 0:A.type)!=="audio")break;e.skip(4);const B=127,M=128,V=e.filePos;for(;e.filePos<n;){const ce=Z(e),ue=ai(e);if((ce&B)===yi.STREAMINFO){e.skip(10);const Ne=q(e),we=Ne>>>12,ye=(Ne>>9&7)+1;k.info.sampleRate=we,k.info.numberOfChannels=ye,e.skip(20)}else e.skip(ue);if(ce&M)break}const $=e.filePos;e.filePos=V;const W=X(e,$-V),G=new Uint8Array(4+W.byteLength);new DataView(G.buffer).setUint32(0,1716281667,!1),G.set(W,4),k.info.codecDescription=G}break;case"dac3":{const k=this.currentTrack;if(!k||((x=k.info)==null?void 0:x.type)!=="audio")break;const B=X(e,3),M=new oe(B),V=M.readBits(2);M.skipBits(8);const $=M.readBits(3),W=M.readBits(1);V<3&&(k.info.sampleRate=zn[V]),k.info.numberOfChannels=_o[$]+W}break;case"dec3":{const k=this.currentTrack;if(!k||((T=k.info)==null?void 0:T.type)!=="audio")break;const B=X(e,r.contentSize),M=ch(B);if(!M){K._warn("Invalid dec3 box contents, ignoring.");break}const V=du(M);V!==null&&(k.info.sampleRate=V),k.info.numberOfChannels=fu(M)}break;case"ddts":{const k=this.currentTrack;if(!k||((P=k.info)==null?void 0:P.type)!=="audio")break;const B=X(e,Math.min(r.contentSize,Io)),M=kh(B);if(!M){K._warn("Invalid ddts box contents, ignoring.");break}k.info.sampleRate=M.sampleRate,M.numberOfChannels!==null&&(k.info.numberOfChannels=M.numberOfChannels)}break;case"dmlp":{const k=this.currentTrack;if(!k||((C=k.info)==null?void 0:C.type)!=="audio")break;const B=q(e),M=B>>>28;if(M===15){K._warn("Invalid dmlp box contents, ignoring.");break}k.info.sampleRate=(M&8?44100:48e3)<<(M&7);const V=B>>>15&31,W=B&8191||V;let G=0;for(let te=0;te<Tc.length;te++)W&1<<te&&(G+=Tc[te]);k.info.numberOfChannels=G}break;case"stts":{const k=this.currentTrack;if(!k||!k.sampleTable)break;e.skip(4);const B=q(e);let M=0,V=0;for(let $=0;$<B;$++){const W=q(e),G=q(e);k.sampleTable.sampleTimingEntries.push({startIndex:M,startDecodeTimestamp:V,count:W,delta:G}),M+=W,V+=W*G}}break;case"ctts":{const k=this.currentTrack;if(!k||!k.sampleTable)break;e.skip(4);const B=q(e);let M=0;for(let V=0;V<B;V++){const $=q(e),W=Yi(e);k.sampleTable.sampleCompositionTimeOffsets.push({startIndex:M,count:$,offset:W,startTimestamp:-1,lastTimestamp:-1,maxLastTimestamp:-1}),M+=$}}break;case"stsz":{const k=this.currentTrack;if(!k||!k.sampleTable)break;e.skip(4);const B=q(e),M=q(e);if(B===0)for(let V=0;V<M;V++){const $=q(e);k.sampleTable.sampleSizes.push($)}else k.sampleTable.sampleSizes.push(B);k.sampleTable.sampleCount=M}break;case"stz2":{const k=this.currentTrack;if(!k||!k.sampleTable)break;e.skip(4),e.skip(3);const B=Z(e),M=q(e);if(B!==4&&B!==8&&B!==16)throw new Error(`Invalid stz2 box: unsupported field size ${B}.`);const V=X(e,Math.ceil(M*B/8)),$=new oe(V);for(let W=0;W<M;W++){const G=$.readBits(B);k.sampleTable.sampleSizes.push(G)}k.sampleTable.sampleCount=M}break;case"stss":{const k=this.currentTrack;if(!k||!k.sampleTable)break;e.skip(4),k.sampleTable.keySampleIndices=[];const B=q(e);for(let M=0;M<B;M++){const V=q(e)-1;k.sampleTable.keySampleIndices.push(V)}k.sampleTable.keySampleIndices.sort((M,V)=>M-V),k.sampleTable.keySampleIndices[0]!==0&&k.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const k=this.currentTrack;if(!k||!k.sampleTable)break;e.skip(4);const B=q(e);let M=0;for(let $=0;$<B;$++){const W=q(e)-1,G=q(e),te=q(e),ce=Te(k.sampleTable.sampleToChunk);if(ce&&W<=ce.startChunkIndex){M++;continue}k.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:W,samplesPerChunk:G,sampleDescriptionIndex:te})}M>0&&K._warn(`Skipped ${M} invalid stsc entries whose chunk indices weren't strictly increasing.`);let V=0;for(let $=0;$<k.sampleTable.sampleToChunk.length;$++)if(k.sampleTable.sampleToChunk[$].startSampleIndex=V,$<k.sampleTable.sampleToChunk.length-1){const G=k.sampleTable.sampleToChunk[$+1].startChunkIndex-k.sampleTable.sampleToChunk[$].startChunkIndex;V+=G*k.sampleTable.sampleToChunk[$].samplesPerChunk}}break;case"stco":{const k=this.currentTrack;if(!k||!k.sampleTable)break;e.skip(4);const B=q(e);for(let M=0;M<B;M++){const V=q(e);k.sampleTable.chunkOffsets.push(V)}}break;case"co64":{const k=this.currentTrack;if(!k||!k.sampleTable)break;e.skip(4);const B=q(e);for(let M=0;M<B;M++){const V=ft(e);k.sampleTable.chunkOffsets.push(V)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(s,r.contentSize));break;case"mehd":{const k=Z(e);e.skip(3);const B=k===1?ft(e):q(e);this.movieDurationInTimescale=B}break;case"trex":{e.skip(4);const k=q(e),B=q(e),M=q(e),V=q(e),$=q(e);this.fragmentTrackDefaults.set(k,{trackId:k,defaultSampleDescriptionIndex:B,defaultSampleDuration:M,defaultSampleSize:V,defaultSampleFlags:$})}break;case"tfra":{const k=Z(e);e.skip(3);const B=q(e),M=this.idToTrack.get(B);if(!M)break;const V=q(e),$=(V&48)>>4,W=(V&12)>>2,G=V&3,te=[Z,De,ai,q],ce=te[$],ue=te[W],Ue=te[G],Ne=q(e);for(let we=0;we<Ne;we++){const ye=k===1?ft(e):q(e),Le=k===1?ft(e):q(e);ce(e);const gt=ue(e),wt=Ue(e);gt>=1&&wt>=1&&M.fragmentLookupTable.push({timestamp:ye,moofOffset:Le,trunNumber:gt,sampleNumber:wt})}}break;case"moof":{if(this.currentFragment)break;this.currentFragment={moofOffset:t,moofSize:r.totalSize,implicitBaseDataOffset:t,trackData:new Map,psshBoxes:[],sampleCount:0};try{this.readContiguousBoxes(e.slice(s,r.contentSize))}catch(k){throw this.currentFragment=null,k}finally{this.currentTrack=null,this.currentFragmentTrackState=null}}break;case"traf":{if(!this.currentFragment||this.isReadingTraf)break;this.isReadingTraf=!0;try{this.readContiguousBoxes(e.slice(s,r.contentSize))}finally{this.isReadingTraf=!1}const k=this.currentFragmentTrackState;if(this.currentFragmentTrackState=null,this.currentTrack){w(k);const B=this.currentFragment.trackData.get(this.currentTrack.id);e:if(B){if(B.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break e}B.presentationTimestamps=B.samples.map(($,W)=>({presentationTimestamp:$.presentationTimestamp,sampleIndex:W})).sort(($,W)=>$.presentationTimestamp-W.presentationTimestamp);for(let $=0;$<B.presentationTimestamps.length;$++){const W=B.presentationTimestamps[$],G=B.samples[W.sampleIndex];if(B.firstKeyFrameTimestamp===null&&G.isKeyFrame&&(B.firstKeyFrameTimestamp=G.presentationTimestamp),$<B.presentationTimestamps.length-1){const ce=B.presentationTimestamps[$+1].presentationTimestamp-W.presentationTimestamp;G.duration=ce}}const M=B.samples[B.presentationTimestamps[0].sampleIndex],V=B.samples[Te(B.presentationTimestamps).sampleIndex];B.startTimestamp=M.presentationTimestamp,B.endTimestamp=V.presentationTimestamp+V.duration,B.endDecodeTimestamp=k.currentTimestamp,k.startTimestamp!==null&&(Hs(B,k.startTimestamp),B.startTimestampIsFinal=!0),k.encryptionAuxInfo&&!B.samples[0].encryption&&(B.encryptionAuxInfo=k.encryptionAuxInfo)}this.currentTrack=null}}break;case"pssh":{if((_=this.input._formatOptions.isobmff)!=null&&_._suppressPsshParsing)break;const k=Iu(X(e,r.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(k):this.currentTrack||this.psshBoxes.push(k)}break;case"tfhd":{if(!this.currentFragment||!this.isReadingTraf||this.currentFragmentTrackState)break;e.skip(1);const k=ai(e),B=!!(k&1),M=!!(k&2),V=!!(k&8),$=!!(k&16),W=!!(k&32),G=!!(k&65536),te=!!(k&131072),ce=q(e),ue=this.fragmentTrackDefaults.get(ce),Ue={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,currentOffset:null,currentTimestamp:0};this.currentFragmentTrackState=Ue,B?Ue.baseDataOffset=ft(e):te&&(Ue.baseDataOffset=this.currentFragment.moofOffset),M&&(Ue.sampleDescriptionIndex=q(e)),V&&(Ue.defaultSampleDuration=q(e)),$&&(Ue.defaultSampleSize=q(e)),W&&(Ue.defaultSampleFlags=q(e)),G&&(Ue.defaultSampleDuration=0);const Ne=this.idToTrack.get(ce);if(!Ne)break;if(this.currentFragment.trackData.has(ce)){K._warn(`Multiple traf boxes for track ${ce} in the same moof box; ignoring the samples of all but the first.`);break}this.currentTrack=Ne}break;case"tfdt":{if(!this.currentFragmentTrackState)break;const k=Z(e);e.skip(3);const B=k===0?q(e):ft(e);this.currentFragmentTrackState.startTimestamp=B}break;case"trun":{const k=this.currentFragmentTrackState;if(!k||!this.currentFragment)break;const B=this.currentTrack;e.skip(1);const M=ai(e),V=!!(M&1),$=!!(M&4),W=!!(M&256),G=!!(M&512),te=!!(M&1024),ce=!!(M&2048),ue=q(e),{defaultSampleDuration:Ue,defaultSampleSize:Ne,defaultSampleFlags:we}=k;if(ue>0&&(!W&&Ue===null||!G&&Ne===null||!te&&we===null))throw new Error("Invalid trun box: sample values are missing and there are no defaults.");if(this.currentFragment.sampleCount+=ue,this.currentFragment.sampleCount>2**20)throw new Error("Too many (> 2^20) samples in fragment.");let ye=null;V&&(ye=Yi(e));let Le=null;$&&(Le=q(e));let gt=ye!==null?k.baseDataOffset+ye:k.currentOffset??k.baseDataOffset,wt=null;B&&(wt=this.currentFragment.trackData.get(B.id)??null,wt||(wt={track:B,startTimestamp:0,endTimestamp:0,endDecodeTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,trunSampleCounts:[],encryptionAuxInfo:null},this.currentFragment.trackData.set(B.id,wt)),wt.trunSampleCounts.push(ue));for(let Kn=0;Kn<ue;Kn++){let Os;W?Os=q(e):Os=Ue;let Us;G?Us=q(e):Us=Ne;let Ns;te?Ns=q(e):Ns=we,Kn===0&&Le!==null&&(Ns=Le);let ec=0;ce&&(ec=Yi(e)),wt==null||wt.samples.push({presentationTimestamp:k.currentTimestamp+ec,duration:Os,byteOffset:gt,byteSize:Us,isKeyFrame:!(Ns&65536),encryption:null}),gt+=Us,k.currentTimestamp+=Os}k.currentOffset=gt,this.currentFragment.implicitBaseDataOffset=gt}break;case"saiz":{const k=this.currentTrack;if(!k||!k.encryptionInfo)break;if(e.skip(1),ai(e)&1){const G=Ie(e,4),te=q(e);if(G!==k.encryptionInfo.scheme||te!==0)break}const M=Z(e),V=q(e);let $=null;M===0&&V>0&&($=X(e,V));const W=_c(k,this.currentFragmentTrackState);W.defaultSampleInfoSize=M,W.sampleSizes=$,W.sampleCount=V}break;case"saio":{const k=this.currentTrack;if(!k||!k.encryptionInfo)break;const B=Z(e);if(ai(e)&1){const G=Ie(e,4),te=q(e);if(G!==k.encryptionInfo.scheme||te!==0)break}const V=q(e);if(V===0)break;V>1&&K._warn("Multiple saio entries are not supported; using the first offset only.");let $=B===0?q(e):Number(ft(e));this.currentFragment&&(w(this.currentFragmentTrackState),$+=this.currentFragmentTrackState.baseDataOffset);const W=_c(k,this.currentFragmentTrackState);W.offset=$}break;case"senc":{const k=this.currentTrack;if(!k||!k.encryptionInfo)break;const B=(I=this.currentFragment)==null?void 0:I.trackData.get(k.id);if(!B)break;e.skip(1);const V=!!(ai(e)&2),$=q(e),W=k.encryptionInfo.defaultPerSampleIvSize;if(W===null)throw new Error("Invalid file: encrypted track is missing its tenc box.");for(let G=0;G<Math.min($,B.samples.length);G++){const te=new Uint8Array(16);if(W>0)te.set(X(e,W),0);else if(k.encryptionInfo.defaultConstantIv)te.set(k.encryptionInfo.defaultConstantIv,0);else throw new Error("Invalid file: encrypted sample has no IV.");let ce=null;if(V){const Ue=De(e);ce=[];for(let Ne=0;Ne<Ue;Ne++){const we=De(e),ye=q(e);ce.push({clearLen:we,protectedLen:ye})}}const ue=B.samples[G];ue.encryption={iv:te,subsamples:ce}}}break;case"udta":{const k=this.iterateContiguousBoxes(e.slice(s,r.contentSize));for(const{boxInfo:B,slice:M}of k){if(B.name!=="meta"&&!this.currentTrack){const V=M.filePos;(v=this.metadataTags).raw??(v.raw={}),B.name[0]==="©"?(R=this.metadataTags.raw)[F=B.name]??(R[F]=xt(M)):(H=this.metadataTags.raw)[O=B.name]??(H[O]=X(M,B.contentSize)),M.filePos=V}switch(B.name){case"meta":M.skip(-B.headerSize),this.traverseBox(M);break;case"©nam":this.currentTrack?this.currentTrack.name=xt(M):(U=this.metadataTags).title??(U.title=xt(M));break;case"name":this.currentTrack?this.currentTrack.name=nt.decode(X(M,B.contentSize)):(L=this.metadataTags).title??(L.title=xt(M));break;case"©des":this.currentTrack||((Q=this.metadataTags).description??(Q.description=xt(M)));break;case"©ART":this.currentTrack||((re=this.metadataTags).artist??(re.artist=xt(M)));break;case"©alb":this.currentTrack||((Y=this.metadataTags).album??(Y.album=xt(M)));break;case"albr":this.currentTrack||((se=this.metadataTags).albumArtist??(se.albumArtist=xt(M)));break;case"©gen":this.currentTrack||((pe=this.metadataTags).genre??(pe.genre=xt(M)));break;case"©day":if(!this.currentTrack){const V=Fr(xt(M));V&&((he=this.metadataTags).date??(he.date=V))}break;case"©cmt":this.currentTrack||((Pe=this.metadataTags).comment??(Pe.comment=xt(M)));break;case"©lyr":this.currentTrack||((We=this.metadataTags).lyrics??(We.lyrics=xt(M)));break}}}break;case"meta":{if(this.currentTrack)break;const B=q(e)!==0;this.currentMetadataKeys=new Map,B?this.readContiguousBoxes(e.slice(s,r.contentSize)):this.readContiguousBoxes(e.slice(s+4,r.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const k=q(e);for(let B=0;B<k;B++){const M=q(e);if(M<8)throw new Error("Invalid keys box: key size must be at least 8.");e.skip(4);const V=nt.decode(X(e,M-8));this.currentMetadataKeys.set(B+1,V)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const k=this.iterateContiguousBoxes(e.slice(s,r.contentSize));for(const{boxInfo:B,slice:M}of k){let V=B.name;const $=(V.charCodeAt(0)<<24)+(V.charCodeAt(1)<<16)+(V.charCodeAt(2)<<8)+V.charCodeAt(3);this.currentMetadataKeys.has($)&&(V=this.currentMetadataKeys.get($));const W=Mp(M);switch((tt=this.metadataTags).raw??(tt.raw={}),($e=this.metadataTags.raw)[V]??($e[V]=W),V){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":typeof W=="string"&&((ve=this.metadataTags).title??(ve.title=W));break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof W=="string"&&((Qe=this.metadataTags).description??(Qe.description=W));break;case"©ART":case"com.apple.quicktime.artist":case"artist":typeof W=="string"&&((Ge=this.metadataTags).artist??(Ge.artist=W));break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":typeof W=="string"&&((_e=this.metadataTags).album??(_e.album=W));break;case"aART":case"album_artist":typeof W=="string"&&((Xe=this.metadataTags).albumArtist??(Xe.albumArtist=W));break;case"©cmt":case"com.apple.quicktime.comment":case"comment":typeof W=="string"&&((St=this.metadataTags).comment??(St.comment=W));break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof W=="string"&&((xi=this.metadataTags).genre??(xi.genre=W));break;case"©lyr":case"lyrics":typeof W=="string"&&((Li=this.metadataTags).lyrics??(Li.lyrics=W));break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof W=="string"){const G=Fr(W);G&&((Pi=this.metadataTags).date??(Pi.date=G))}break;case"tmpo":if(W instanceof Uint8Array&&W.length>=2){const G=ie(W).getInt16(0,!1);G>0&&((ii=this.metadataTags).beatsPerMinute??(ii.beatsPerMinute=G))}break;case"covr":case"com.apple.quicktime.artwork":W instanceof xr?((Lr=this.metadataTags).images??(Lr.images=[]),this.metadataTags.images.push({data:W.data,kind:"coverFront",mimeType:W.mimeType})):W instanceof Uint8Array&&((N=this.metadataTags).images??(N.images=[]),this.metadataTags.images.push({data:W,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof W=="string"){const G=W.split("/"),te=Number.parseInt(G[0],10),ce=G[1]&&Number.parseInt(G[1],10);Number.isInteger(te)&&te>0&&((ne=this.metadataTags).trackNumber??(ne.trackNumber=te)),ce&&Number.isInteger(ce)&&ce>0&&((Ee=this.metadataTags).tracksTotal??(Ee.tracksTotal=ce))}break;case"trkn":if(W instanceof Uint8Array&&W.length>=6){const G=ie(W),te=G.getUint16(2,!1),ce=G.getUint16(4,!1);te>0&&((Ye=this.metadataTags).trackNumber??(Ye.trackNumber=te)),ce>0&&((At=this.metadataTags).tracksTotal??(At.tracksTotal=ce))}break;case"disc":case"disk":if(W instanceof Uint8Array&&W.length>=6){const G=ie(W),te=G.getUint16(2,!1),ce=G.getUint16(4,!1);te>0&&((Ft=this.metadataTags).discNumber??(Ft.discNumber=te)),ce>0&&((dt=this.metadataTags).discsTotal??(dt.discsTotal=ce))}break}}}break}return e.filePos=n,!0}}class Mu{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap,this.nextEac3Frames=new WeakMap}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let r=0;for(const s of e.tracks)if(s.trackBacking.getType()===t&&r++,s===this.internalTrack)break;return r}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||e.demuxer.isFragmented&&e.demuxer.getSampleTableForTrack(e).sampleCount>0)return null;w(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.fetchFirstFragmentedPacket(!1,e)}mapTimestampIntoTimescale(e){return Zt(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const r=this.mapTimestampIntoTimescale(e),s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Qa(s,r),a=await this.fetchPacketForSampleIndex(n,t,r);if(!this.internalTrack.demuxer.isFragmented)return a;const o=await this.performFragmentedLookup(null,c=>{const u=c.trackData.get(this.internalTrack.id);if(!u)return{sampleIndex:-1,correctSampleFound:!1};const l=de(u.presentationTimestamps,r,h=>h.presentationTimestamp),d=l!==-1?u.presentationTimestamps[l].sampleIndex:-1,f=l!==-1&&r<u.endTimestamp;return{sampleIndex:d,correctSampleFound:f}},r,r,t);return!a||!o?a??o:a.timestamp>o.timestamp?a:o}async getNextPacket(e,t){const r=this.nextEac3Frames.get(e);if(r)return r;const s=this.packetToSampleIndex.get(e);if(s!==void 0){const a=await this.fetchPacketForSampleIndex(s+1,t);return a||!this.internalTrack.demuxer.isFragmented?a:this.fetchFirstFragmentedPacket(!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,a=>{if(a===n.fragment){const o=a.trackData.get(this.internalTrack.id);if(n.sampleIndex+1<o.samples.length)return{sampleIndex:n.sampleIndex+1,correctSampleFound:!0}}else if(a.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 r=this.mapTimestampIntoTimescale(e),s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=sm(s,r),a=await this.fetchPacketForSampleIndex(n,t,r);if(!this.internalTrack.demuxer.isFragmented)return a;const o=await this.performFragmentedLookup(null,c=>{const u=c.trackData.get(this.internalTrack.id);if(!u)return{sampleIndex:-1,correctSampleFound:!1};const l=Br(u.presentationTimestamps,h=>u.samples[h.sampleIndex].isKeyFrame&&h.presentationTimestamp<=r),d=l!==-1?u.presentationTimestamps[l].sampleIndex:-1,f=l!==-1&&r<u.endTimestamp;return{sampleIndex:d,correctSampleFound:f}},r,r,t,!0);return!a||!o?a??o:a.timestamp>o.timestamp?a:o}async getNextKeyPacket(e,t){const r=this.nextEac3Frames.get(e);if(r)return r;const s=this.packetToSampleIndex.get(e);if(s!==void 0){const a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),o=om(a,s),c=await this.fetchPacketForSampleIndex(o,t);return c||!this.internalTrack.demuxer.isFragmented?c:this.fetchFirstFragmentedPacket(!0,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,a=>{if(a===n.fragment){const o=a.trackData.get(this.internalTrack.id);for(let c=n.sampleIndex+1;c<o.samples.length;c++)if(o.samples[c].isKeyFrame)return{sampleIndex:c,correctSampleFound:!0}}else{const o=a.trackData.get(this.internalTrack.id);if(o&&o.firstKeyFrameTimestamp!==null){const c=o.samples.findIndex(u=>u.isKeyFrame);return w(c!==-1),{sampleIndex:c,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}fetchFirstFragmentedPacket(e,t){return this.performFragmentedLookup(null,r=>{const s=r.trackData.get(this.internalTrack.id),n=(s==null?void 0:s.samples.findIndex(a=>!e||a.isKeyFrame))??-1;return{sampleIndex:n,correctSampleFound:n!==-1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t,r=-1/0){var l,d;if(e===-1)return null;const s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=nm(s,e);if(!n)return null;let a;if(t.metadataOnly&&((l=this.internalTrack.info)==null?void 0:l.codec)!=="eac3")a=mt;else{let f=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);if(D(f)&&(f=await f),!f)return null;if(a=X(f,n.sampleSize),this.internalTrack.encryptionInfo){let h=null;if(this.internalTrack.encryptionAuxInfo){const p=await Ou(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<p.length&&(h=p[e])}h??(h=Ec(this.internalTrack.encryptionInfo)),h&&(a=await Ic(this.internalTrack,h,a,null))}}const o=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=n.duration/this.internalTrack.timescale,u=new Ce(a,n.isKeyFrame?"key":"delta",o,c,e,n.sampleSize);return((d=this.internalTrack.info)==null?void 0:d.codec)==="eac3"?this.splitEac3Sample(u,t,r,this.packetToSampleIndex,e):(this.packetToSampleIndex.set(u,e),u)}async fetchPacketInFragment(e,t,r,s){var d,f;if(t===-1)return null;const a=e.trackData.get(this.internalTrack.id).samples[t];w(a);let o;if(r.metadataOnly&&((d=this.internalTrack.info)==null?void 0:d.codec)!=="eac3")o=mt;else{let h=this.internalTrack.demuxer.reader.requestSlice(a.byteOffset,a.byteSize);if(D(h)&&(h=await h),!h)return null;if(o=X(h,a.byteSize),this.internalTrack.encryptionInfo){const p=a.encryption??Ec(this.internalTrack.encryptionInfo);p&&(o=await Ic(this.internalTrack,p,o,e))}}const c=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,u=a.duration/this.internalTrack.timescale,l=new Ce(o,a.isKeyFrame?"key":"delta",c,u,e.moofOffset+t,a.byteSize);return((f=this.internalTrack.info)==null?void 0:f.codec)==="eac3"?this.splitEac3Sample(l,r,s,this.packetToFragmentLocation,{fragment:e,sampleIndex:t}):(this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:t}),l)}async performFragmentedLookup(e,t,r,s,n,a=!1){var m,g;const{demuxer:o,fragmentLookupTable:c,fragmentPositionCache:u}=this.internalTrack;let l=null,d=-1;if(e){const{sampleIndex:y,correctSampleFound:b}=t(e);if(b)return this.fetchPacketInFragment(e,y,n,r);y!==-1&&(l=e,d=y)}let f=de(c,r,y=>y.timestamp),h=de(u,r,y=>y.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 y=Math.max(((m=c[f])==null?void 0:m.moofOffset)??0,((g=u[h])==null?void 0:g.moofOffset)??0)||null;let b,S=null;e?y===null||e.moofOffset>=y?(b=e.moofOffset+e.moofSize,S=e):b=y:b=y??0;const A=S?S.moofOffset:b;for(;b<p;){if(S){const _=S.trackData.get(this.internalTrack.id);if(_&&_.startTimestamp>s)break;S=null}const x=o.fragmentSummaries.get(b);if(x&&!x.trackIds.has(this.internalTrack.id)){b+=x.moofSize;continue}let T=o.reader.requestSliceRange(b,Xt,Di);if(D(T)&&(T=await T),!T)break;const P=b,C=_i(T);if(!C)break;if(C.name==="moof"){if(S=await o.readFragment(P),!S)break;const{sampleIndex:_,correctSampleFound:I}=t(S);if(I)return this.fetchPacketInFragment(S,_,n,r);_!==-1&&(l=S,d=_)}b=P+C.totalSize}if(y===null||l&&l.moofOffset>=y)break;p=A,e=null}return l?this.fetchPacketInFragment(l,d,n,r):null}splitEac3Sample(e,t,r,s,n){const a=this.internalTrack.info;w((a==null?void 0:a.type)==="audio");const o=uu(e.data)??[{offset:0,size:e.data.byteLength,blockCount:6}],c=(r-this.internalTrack.editListOffset)/this.internalTrack.timescale;let u=null,l=null,d=0;for(let f=0;f<o.length;f++){const h=o[f],p=e.timestamp+256*d/a.sampleRate,m=o.length===1?e.duration:256*h.blockCount/a.sampleRate,g=new Ce(t.metadataOnly?mt:e.data.subarray(h.offset,h.offset+h.size),"key",p,m,8*e.sequenceNumber+f,h.size);s.set(g,n),l&&this.nextEac3Frames.set(l,g),(f===0||p<=c)&&(u=g),l=g,d+=h.blockCount}return w(u),u}}class Sc extends Mu{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,r,s,n;const e=await this.getDecoderConfig();return e?{primaries:(t=e.colorSpace)==null?void 0:t.primaries,transfer:(r=e.colorSpace)==null?void 0:r.transfer,matrix:(s=e.colorSpace)==null?void 0:s.matrix,fullRange:(n=e.colorSpace)==null?void 0:n.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,r,s,n;if(this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription){const a=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=a&&_s(a.data)}else if(this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription){const a=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=a&&Is(a.data)}else if(this.internalTrack.info.codec==="vp9"&&(!this.internalTrack.info.vp9CodecInfo||!rh(this.internalTrack.info.vp9CodecInfo))){const a=await this.getFirstPacket({}),o=a&&Po(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||!su(this.internalTrack.info.av1CodecInfo))){const a=await this.getFirstPacket({}),o=a&&ms(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&&nu(a.data)}if(!go(this.internalTrack.info.colorSpace)){const a=Ud(this.internalTrack.info);(t=this.internalTrack.info.colorSpace).primaries??(t.primaries=a.primaries),(r=this.internalTrack.info.colorSpace).transfer??(r.transfer=a.transfer),(s=this.internalTrack.info.colorSpace).matrix??(s.matrix=a.matrix),(n=this.internalTrack.info.colorSpace).fullRange??(n.fullRange=a.fullRange)}const e={codec:jn(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 Ac extends Mu{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&&mu(e.data)}return{codec:Xo(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const Qa=(i,e)=>{if(i.sortedCompositionTimeOffsets)return Du(i,e,!1);{const t=de(i.sampleTimingEntries,e,s=>s.startDecodeTimestamp);if(t===-1)return-1;const r=i.sampleTimingEntries[t];return r.delta===0?r.startIndex+r.count-1:r.startIndex+Math.min(Math.floor((e-r.startDecodeTimestamp)/r.delta),r.count-1)}},sm=(i,e)=>{if(!i.keySampleIndices)return Qa(i,e);if(i.sortedCompositionTimeOffsets)return Du(i,e,!0);{const t=Qa(i,e),r=de(i.keySampleIndices,t,s=>s);return i.keySampleIndices[r]??-1}},nm=(i,e)=>{if(e>=i.sampleCount)return null;const t=de(i.sampleTimingEntries,e,g=>g.startIndex),r=i.sampleTimingEntries[t];let n=r.startDecodeTimestamp+(e-r.startIndex)*r.delta;const a=de(i.sampleCompositionTimeOffsets,e,g=>g.startIndex),o=i.sampleCompositionTimeOffsets[a];o&&e-o.startIndex<o.count&&(n+=o.offset);const c=i.sampleSizes[Math.min(e,i.sampleSizes.length-1)],u=de(i.sampleToChunk,e,g=>g.startSampleIndex),l=i.sampleToChunk[u],d=l.startChunkIndex+Math.floor((e-l.startSampleIndex)/l.samplesPerChunk),f=i.chunkOffsets[d],h=l.startSampleIndex+(d-l.startChunkIndex)*l.samplesPerChunk;let p=f;i.sampleSizes.length===1?p+=c*(e-h):p+=i.cumulativeSampleSizes[e]-i.cumulativeSampleSizes[h];let m=r.delta;if(i.sortedCompositionTimeOffsets){const g=am(i,e,n);g!==null&&(m=g-n)}return{presentationTimestamp:n,duration:m,sampleOffset:p,sampleSize:c,chunkOffset:f,isKeyFrame:i.keySampleIndices?As(i.keySampleIndices,e,g=>g)!==-1:!0}},Du=(i,e,t)=>{const r=i.sortedCompositionTimeOffsets;let s=-1,n=-1/0;const a=de(r,e,o=>o.startTimestamp);for(let o=a;o>=0;o--){const c=r[o];if(c.maxLastTimestamp<n)break;let u=c.lastTimestamp<=e?c.startIndex+c.count-1:zu(i,c,(d,f)=>f>e)-1;if(t){const d=de(i.keySampleIndices,u,f=>f);u=i.keySampleIndices[d]??-1}if(u<c.startIndex)continue;const l=Oo(i,u)+c.offset;(l>n||l===n&&u>s)&&(s=u,n=l)}return s},am=(i,e,t)=>{var a;const r=i.sortedCompositionTimeOffsets,s=de(r,t,o=>o.startTimestamp);let n=((a=r[s+1])==null?void 0:a.startTimestamp)??null;for(let o=s;o>=0;o--){const c=r[o];if(c.maxLastTimestamp<t)break;const u=zu(i,c,(d,f)=>f>t||f===t&&d>e);if(u===c.startIndex+c.count)continue;const l=Oo(i,u)+c.offset;(n===null||l<n)&&(n=l)}return n},zu=(i,e,t)=>{let r=e.startIndex,s=e.startIndex+e.count;for(;r<s;){const n=Math.floor((r+s)/2);t(n,Oo(i,n)+e.offset)?s=n:r=n+1}return r},Oo=(i,e)=>{const t=de(i.sampleTimingEntries,e,s=>s.startIndex),r=i.sampleTimingEntries[t];return r.startDecodeTimestamp+(e-r.startIndex)*r.delta},om=(i,e)=>{if(!i.keySampleIndices)return e+1;const t=de(i.keySampleIndices,e,r=>r);return i.keySampleIndices[t+1]??-1},Hs=(i,e)=>{i.startTimestamp+=e,i.endTimestamp+=e,i.endDecodeTimestamp+=e;for(const t of i.samples)t.presentationTimestamp+=e;for(const t of i.presentationTimestamps)t.presentationTimestamp+=e},xc=i=>[Ki(i),Ki(i),da(i),Ki(i),Ki(i),da(i),Ki(i),Ki(i),da(i)],Pc=(i,e)=>{const t=i.info;if(t.type!=="video")return;const{num:r,den:s}=e;!(r>0&&s>0)||r===s||(r>s?(t.squarePixelWidth=Math.round(t.width*r/s),t.squarePixelHeight=t.height):(t.squarePixelWidth=t.width,t.squarePixelHeight=Math.round(t.height*s/r)))},Cc=(i,e)=>{for(;i.length>0&&Te(i).startIndex>=e;)i.pop();const t=Te(i);t&&(t.count=Math.min(t.count,e-t.startIndex))},_c=(i,e)=>e?e.encryptionAuxInfo??(e.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}):i.encryptionAuxInfo??(i.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}),Ou=async(i,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 r=0;if(t.defaultSampleInfoSize>0)r=t.defaultSampleInfoSize*t.sampleCount;else{w(t.sampleSizes);for(let o=0;o<t.sampleCount;o++)r+=t.sampleSizes[o]}let s=i.requestSlice(t.offset,r);if(D(s)&&(s=await s),!s)throw new Error("Failed to read auxiliary encryption info.");const n=e.defaultPerSampleIvSize;if(n===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(n>0)u.set(X(s,n),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>n){const d=De(s);l=[];for(let f=0;f<d;f++){const h=De(s),p=q(s);l.push({clearLen:h,protectedLen:p})}}a.push({iv:u,subsamples:l})}return t.resolved=a,a},Ec=i=>i.defaultConstantIv?{iv:i.defaultConstantIv,subsamples:null}:null,Ic=async(i,e,t,r)=>{var c;w(i.encryptionInfo);const s=i.encryptionInfo;if(s.defaultKid===null)throw new Error("Invalid file: encrypted track is missing its tenc box.");const n=s.defaultKid;let a;const o=i.demuxer.decryptionKeyCache.get(n);if(o)a=await o;else{if(!((c=i.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=i.demuxer.psshBoxes;if(r){l=[...l,...r.psshBoxes].filter(f=>f.keyIds===null||f.keyIds.includes(n));for(let f=0;f<l.length-1;f++)for(let h=f+1;h<l.length;h++)vu(l[f],l[h])&&(l.splice(h,1),h--)}const d=await i.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:n,psshBoxes:l});if(!(typeof d=="string"&&d.length===32&&hf.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:mf(d)})();i.demuxer.decryptionKeyCache.set(n,u),a=await u}return s.scheme==="cenc"||s.scheme==="cens"?cm(a,s,e,t):lm(a,s,e,t)},cm=async(i,e,t,r)=>{const s=new Uint8Array(16);s.set(t.iv,0);const n=await crypto.subtle.importKey("raw",i,{name:"AES-CTR"},!1,["decrypt"]),a=async p=>{const m=await crypto.subtle.decrypt({name:"AES-CTR",counter:s,length:64},n,p);return new Uint8Array(m)};if(!t.subsamples)return a(r);w(e.defaultCryptByteBlock!==null&&e.defaultSkipByteBlock!==null);const o=Uu(t.subsamples,e.defaultCryptByteBlock,e.defaultSkipByteBlock,r.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(r.subarray(m.offset,m.offset+m.length),l),l+=m.length;const d=await a(u),f=new Uint8Array(r);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},lm=(i,e,t,r)=>{const s=new Ru;s.init({key:i,iv:t.iv});const n=e.defaultCryptByteBlock,a=e.defaultSkipByteBlock;if(w(n!==null&&a!==null),!t.subsamples){const l=new Uint8Array(r),d=Math.floor(r.length/16);for(let f=0;f<d;f++){const h=f*16;s.in.set(r.subarray(h,h+16)),s.decrypt(),l.set(s.out,h)}return l}if(n===0&&a===0)throw new Error("cbcs with subsamples requires pattern encryption.");const o=new Uint8Array(r),c=Uu(t.subsamples,n,a,r.length),u=new DataView(t.iv.buffer,t.iv.byteOffset,16);for(const l of c){s.iv[0]=u.getUint32(0,!1),s.iv[1]=u.getUint32(4,!1),s.iv[2]=u.getUint32(8,!1),s.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;s.in.set(r.subarray(p,p+16)),s.decrypt(),o.set(s.out,p)}}}return o},Uu=(i,e,t,r)=>{const s=[],n=e!==0||t!==0;let a=0;for(const o of i){if(a+o.clearLen+o.protectedLen>r)throw new Error("Invalid encryption info: subsamples exceed the sample size.");a+=o.clearLen;const c=[];if(!n)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}s.push({perSubsample:c})}return s};/*!
|
|
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 Gi{constructor(e){this.value=e}}class kn{constructor(e){this.value=e}}class Uo{constructor(e){this.value=e}}class oi{constructor(e){this.value=e}}var E;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Duration=17545]="Duration",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.DateUTC=17505]="DateUTC",i[i.Title=31657]="Title",i[i.MuxingApp=19840]="MuxingApp",i[i.WritingApp=22337]="WritingApp",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.TrackNumber=215]="TrackNumber",i[i.TrackUID=29637]="TrackUID",i[i.TrackType=131]="TrackType",i[i.FlagEnabled=185]="FlagEnabled",i[i.FlagDefault=136]="FlagDefault",i[i.FlagForced=21930]="FlagForced",i[i.FlagOriginal=21934]="FlagOriginal",i[i.FlagHearingImpaired=21931]="FlagHearingImpaired",i[i.FlagVisualImpaired=21932]="FlagVisualImpaired",i[i.FlagCommentary=21935]="FlagCommentary",i[i.FlagLacing=156]="FlagLacing",i[i.MaxBlockAdditionID=21998]="MaxBlockAdditionID",i[i.Name=21358]="Name",i[i.Language=2274716]="Language",i[i.LanguageBCP47=2274717]="LanguageBCP47",i[i.CodecID=134]="CodecID",i[i.CodecPrivate=25506]="CodecPrivate",i[i.CodecDelay=22186]="CodecDelay",i[i.SeekPreRoll=22203]="SeekPreRoll",i[i.DefaultDuration=2352003]="DefaultDuration",i[i.Video=224]="Video",i[i.PixelWidth=176]="PixelWidth",i[i.PixelHeight=186]="PixelHeight",i[i.DisplayWidth=21680]="DisplayWidth",i[i.DisplayHeight=21690]="DisplayHeight",i[i.DisplayUnit=21682]="DisplayUnit",i[i.StereoMode=21432]="StereoMode",i[i.AlphaMode=21440]="AlphaMode",i[i.Audio=225]="Audio",i[i.SamplingFrequency=181]="SamplingFrequency",i[i.OutputSamplingFrequency=30901]="OutputSamplingFrequency",i[i.Channels=159]="Channels",i[i.BitDepth=25188]="BitDepth",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.Block=161]="Block",i[i.BlockAdditions=30113]="BlockAdditions",i[i.BlockMore=166]="BlockMore",i[i.BlockAdditional=165]="BlockAdditional",i[i.BlockAddID=238]="BlockAddID",i[i.BlockDuration=155]="BlockDuration",i[i.ReferenceBlock=251]="ReferenceBlock",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.Colour=21936]="Colour",i[i.MatrixCoefficients=21937]="MatrixCoefficients",i[i.TransferCharacteristics=21946]="TransferCharacteristics",i[i.Primaries=21947]="Primaries",i[i.Range=21945]="Range",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPoseYaw=30323]="ProjectionPoseYaw",i[i.ProjectionPosePitch=30324]="ProjectionPosePitch",i[i.ProjectionPoseRoll=30325]="ProjectionPoseRoll",i[i.Attachments=423732329]="Attachments",i[i.AttachedFile=24999]="AttachedFile",i[i.FileDescription=18046]="FileDescription",i[i.FileName=18030]="FileName",i[i.FileMediaType=18016]="FileMediaType",i[i.FileData=18012]="FileData",i[i.FileUID=18094]="FileUID",i[i.Chapters=272869232]="Chapters",i[i.Tags=307544935]="Tags",i[i.Tag=29555]="Tag",i[i.Targets=25536]="Targets",i[i.TargetTypeValue=26826]="TargetTypeValue",i[i.TargetType=25546]="TargetType",i[i.TagTrackUID=25541]="TagTrackUID",i[i.TagEditionUID=25545]="TagEditionUID",i[i.TagChapterUID=25540]="TagChapterUID",i[i.TagAttachmentUID=25542]="TagAttachmentUID",i[i.SimpleTag=26568]="SimpleTag",i[i.TagName=17827]="TagName",i[i.TagLanguage=17530]="TagLanguage",i[i.TagString=17543]="TagString",i[i.TagBinary=17541]="TagBinary",i[i.ContentEncodings=28032]="ContentEncodings",i[i.ContentEncoding=25152]="ContentEncoding",i[i.ContentEncodingOrder=20529]="ContentEncodingOrder",i[i.ContentEncodingScope=20530]="ContentEncodingScope",i[i.ContentCompression=20532]="ContentCompression",i[i.ContentCompAlgo=16980]="ContentCompAlgo",i[i.ContentCompSettings=16981]="ContentCompSettings",i[i.ContentEncryption=20533]="ContentEncryption"})(E||(E={}));const Nu=[E.EBML,E.Segment],bs=[E.SeekHead,E.Info,E.Cluster,E.Tracks,E.Cues,E.Attachments,E.Chapters,E.Tags],rn=[...Nu,...bs],Tn=i=>i<256?1:i<65536?2:i<1<<24?3:i<2**32?4:i<2**40?5:6,Ga=i=>i<1n<<8n?1:i<1n<<16n?2:i<1n<<24n?3:i<1n<<32n?4:i<1n<<40n?5:i<1n<<48n?6:i<1n<<56n?7:8,Xa=i=>i>=-64&&i<64?1:i>=-8192&&i<8192?2:i>=-1048576&&i<1<<20?3:i>=-134217728&&i<1<<27?4:i>=-17179869184&&i<2**34?5:6,Ci=i=>{if(i<127)return 1;if(i<16383)return 2;if(i<(1<<21)-1)return 3;if(i<(1<<28)-1)return 4;if(i<2**35-1)return 5;if(i<2**42-1)return 6;throw new Error("EBML varint size not supported "+i)};class um{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=Tn(e)){let r=0;switch(t){case 6:this.helperView.setUint8(r++,e/2**40|0);case 5:this.helperView.setUint8(r++,e/2**32|0);case 4:this.helperView.setUint8(r++,e>>24);case 3:this.helperView.setUint8(r++,e>>16);case 2:this.helperView.setUint8(r++,e>>8);case 1:this.helperView.setUint8(r++,e);break;default:throw new Error("Bad unsigned int size "+t)}this.writer.write(this.helper.subarray(0,r))}writeUnsignedBigInt(e,t=Ga(e)){let r=0;for(let s=t-1;s>=0;s--)this.helperView.setUint8(r++,Number(e>>BigInt(s*8)&0xffn));this.writer.write(this.helper.subarray(0,r))}writeSignedInt(e,t=Xa(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=Ci(e)){if(e>=2**(7*t)-1)throw new Error(`EBML variable-size integer ${e} doesn't fit into ${t} bytes.`);let r=0;switch(t){case 1:this.helperView.setUint8(r++,128|e);break;case 2:this.helperView.setUint8(r++,64|e>>8),this.helperView.setUint8(r++,e);break;case 3:this.helperView.setUint8(r++,32|e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 4:this.helperView.setUint8(r++,16|e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 5:this.helperView.setUint8(r++,8|e/2**32&7),this.helperView.setUint8(r++,e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 6:this.helperView.setUint8(r++,4|e/2**40&3),this.helperView.setUint8(r++,e/2**32|0),this.helperView.setUint8(r++,e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;default:throw new Error("Bad EBML varint size "+t)}this.writer.write(this.helper.subarray(0,r))}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))if(e.size===void 0)this.writeVarInt(Ya(e.data)),this.dataOffsets.set(e,this.writer.getPos()),this.writeEBML(e.data);else{const t=this.writer.getPos(),r=e.size===-1?1:e.size;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+r);const s=this.writer.getPos();if(this.dataOffsets.set(e,s),this.writeEBML(e.data),e.size!==-1){const n=this.writer.getPos()-s,a=this.writer.getPos();this.writer.seek(t),this.writeVarInt(n,r),this.writer.seek(a)}}else if(typeof e.data=="number"){const t=e.size??Tn(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data=="bigint"){const t=e.size??Ga(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 Gi)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof kn)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof Uo){const t=e.size??Xa(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof oi){const t=ge.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else xe(e.data)}}const Ya=i=>{if(i===null)return 0;if(i instanceof Uint8Array)return i.byteLength;if(Array.isArray(i))return i.reduce((r,s)=>r+Ya(s),0);let e,t;return Array.isArray(i.data)?(e=Ya(i.data),t=i.size===void 0?Ci(e):i.size===-1?1:i.size):typeof i.data=="number"?(e=i.size??Tn(i.data),t=Ci(e)):typeof i.data=="bigint"?(e=i.size??Ga(i.data),t=Ci(e)):typeof i.data=="string"?(e=i.data.length,t=Ci(e)):i.data instanceof Uint8Array?(e=i.data.byteLength,t=i.size??Ci(e)):i.data instanceof Gi?(e=4,t=1):i.data instanceof kn?(e=8,t=1):i.data instanceof Uo?(e=i.size??Xa(i.data.value),t=Ci(e)):(w(i.data instanceof oi),e=ge.encode(i.data.value).length,t=Ci(e)),Tn(i.id)+t+e},Vu=Date.UTC(2001,0,1),Wu=8,Pt=2,ui=2*Wu,Lu=i=>{if(i.remainingLength<1)return null;const e=Z(i);if(i.skip(-1),e===0)return null;let t=1,r=128;for(;(e&r)===0;)t++,r>>=1;return i.remainingLength<t?null:t},rs=i=>{if(i.remainingLength<1)return null;const e=Z(i);if(e===0)return null;let t=1,r=128;for(;(e&r)===0;)t++,r>>=1;if(i.remainingLength<t-1)return null;let s=e&r-1;for(let n=1;n<t;n++)s*=256,s+=Z(i);return s},le=(i,e)=>{if(e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let r=0;r<e;r++)t*=256,t+=Z(i);return t},Hu=(i,e)=>{if(e>8)throw new Error("Bad unsigned int size "+e);let t=0n;for(let r=0;r<e;r++)t<<=8n,t+=BigInt(Z(i));return t},dm=(i,e)=>e===0?0n:BigInt.asIntN(8*e,Hu(i,e)),qu=i=>{const e=Lu(i);return e===null||i.remainingLength<e?null:le(i,e)},ju=i=>{const e=i.filePos,t=rs(i);if(t===null)return null;const r=i.filePos-e;if(t!==2**(7*r)-1)return t},$t=i=>{w(i.remainingLength>=Pt);const e=qu(i);if(e===null)return null;const t=ju(i);return t===null?null:{id:e,size:t}},kr=(i,e)=>{const t=X(i,e);let r="";for(let s=0;s<e&&t[s]!==0;s++)r+=String.fromCharCode(t[s]);return r},lr=(i,e)=>{const t=X(i,e);let r=0;for(;r<e&&t[r]!==0;)r+=1;return nt.decode(t.subarray(0,r))},ur=(i,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?Rp(i):vd(i)},Za=async(i,e,t,r)=>{const s=new Set(t);let n=e;for(;r===null||n<r;){let a=i.requestSliceRange(n,Pt,ui);if(D(a)&&(a=await a),!a)break;const o=$t(a);if(!o)break;if(s.has(o.id))return{pos:n,found:!0};ni(o.size),n=a.filePos+o.size}return{pos:r!==null&&r>n?r:n,found:!1}},Ku=async(i,e,t,r)=>{const n=new Set(t);let a=e;for(;a<r;){let o=i.requestSliceRange(a,0,Math.min(65536,r-a));if(D(o)&&(o=await o),!o||o.length===0)break;const c=Math.max(o.length-Wu,1);for(let u=0;u<c;u++){o.filePos=a;const l=qu(o);if(l!==null&&n.has(l))return a;a++}}return null},rt={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 ni(i){if(i===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 $u=i=>{let t=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isWebM?"webm":"x-matroska");if(i.codecStrings.length>0){const r=[...new Set(i.codecStrings.filter(Boolean))];t+=`; codecs="${r.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 ci;(function(i){i[i.None=0]="None",i[i.Xiph=1]="Xiph",i[i.FixedSize=2]="FixedSize",i[i.Ebml=3]="Ebml"})(ci||(ci={}));var ns;(function(i){i[i.Block=1]="Block",i[i.Private=2]="Private",i[i.Next=4]="Next"})(ns||(ns={}));var as;(function(i){i[i.Zlib=0]="Zlib",i[i.Bzlib=1]="Bzlib",i[i.lzo1x=2]="lzo1x",i[i.HeaderStripping=3]="HeaderStripping"})(as||(as={}));const na=[{id:E.SeekHead,flag:"seekHeadSeen"},{id:E.Info,flag:"infoSeen"},{id:E.Tracks,flag:"tracksSeen"},{id:E.Cues,flag:"cuesSeen"}],Qu=10*2**20,fm=64;class hm extends Ai{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentProjection=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.claimedSeekTargets=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(r=>r.getDecoderConfig().then(s=>(s==null?void 0:s.codec)??null)));return $u({isWebM:this.isWebM,hasVideo:this.segments.some(r=>r.tracks.some(s=>{var n;return((n=s.info)==null?void 0:n.type)==="video"})),hasAudio:this.segments.some(r=>r.tracks.some(s=>{var n;return((n=s.info)==null?void 0:n.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,Pt,ui);if(D(t)&&(t=await t),!t)break;const r=$t(t);if(!r)break;const s=r.id;let n=r.size;const a=t.filePos;if(s===E.EBML){ni(n);let o=this.reader.requestSlice(a,n);if(D(o)&&(o=await o),!o)break;this.readContiguousElements(o)}else if(s===E.Segment){if(await this.readSegment(a,n),n===void 0||this.reader.fileSize===null)break}else if(s===E.Cluster){if(this.reader.fileSize===null)break;n===void 0&&(n=(await Za(this.reader,a,rn,this.reader.fileSize)).pos-a);const o=Te(this.segments);o&&(o.elementEndPos=a+n)}ni(n),e=a+n}})())}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 r=e;const s=new Set;for(;this.currentSegment.elementEndPos===null||r<this.currentSegment.elementEndPos;){let o=this.reader.requestSliceRange(r,Pt,ui);if(D(o)&&(o=await o),!o)break;const c=r,u=$t(o);if(!u||!bs.includes(u.id)&&u.id!==E.Void){const p=await Ku(this.reader,c+1,bs,Math.min(this.currentSegment.elementEndPos??1/0,c+Qu));if(p){r=p;continue}else break}const{id:l,size:d}=u,f=o.filePos,h=na.findIndex(p=>p.id===l);if(h!==-1){const p=na[h].flag;this.currentSegment[p]=!0,l===E.SeekHead&&s.add(c-e),ni(d);let m=this.reader.requestSlice(f,d);D(m)&&(m=await m),m&&this.readContiguousElements(m)}else if(l===E.Tags||l===E.Attachments){l===E.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,ni(d);let p=this.reader.requestSlice(f,d);D(p)&&(p=await p),p&&this.readContiguousElements(p)}else if(l===E.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(d===void 0)break;r=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!==E.SeekHead||s.has(c.segmentPosition)||(s.add(c.segmentPosition),!this.claimSeekTarget(e+c.segmentPosition)))continue;let u=this.reader.requestSliceRange(e+c.segmentPosition,Pt,ui);if(D(u)&&(u=await u),!u)continue;const l=$t(u);if(!l||l.id!==E.SeekHead)continue;const{size:d}=l;ni(d);let f=this.reader.requestSlice(u.filePos,d);D(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=na.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,Pt,ui);if(D(u)&&(u=await u),!u)continue;const l=$t(u);if(!l)continue;const{id:d,size:f}=l;if(d!==c.id)continue;ni(f),this.currentSegment[c.flag]=!0;let h=this.reader.requestSlice(u.filePos,f);D(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 n=null,a=-1/0;for(const o of this.currentSegment.tracks)o.cuePoints.length>a&&(a=o.cuePoints.length,n=o);for(const o of this.currentSegment.tracks)o.cuePoints.length===0&&(o.cuePoints=n.cuePoints);this.currentSegment=null}async readCluster(e,t){var d,f;if(((d=t.lastReadCluster)==null?void 0:d.elementStartPos)===e)return t.lastReadCluster;let r=this.reader.requestSliceRange(e,Pt,ui);D(r)&&(r=await r),w(r);const s=e,n=$t(r);w(n);const a=n.id;w(a===E.Cluster);let o=n.size;const c=r.filePos;o===void 0&&(o=(await Za(this.reader,c,rn,t.elementEndPos)).pos-c);let u=this.reader.requestSliceRange(c,0,o);D(u)&&(u=await u);const l={segment:t,elementStartPos:s,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(u){this.currentCluster=l;try{const h=this.readContiguousElements(u,rn);l.elementEndPos=h}finally{this.currentCluster=null,this.currentBlock=null}}for(const[,h]of l.trackData){const p=h.track;w(h.blocks.length>0);let m=!1;for(let T=0;T<h.blocks.length;T++){const P=h.blocks[T];P.timestamp+=l.timestamp,m||(m=P.lacing!==ci.None)}h.presentationTimestamps=h.blocks.map((T,P)=>({timestamp:T.timestamp,blockIndex:P})).sort((T,P)=>T.timestamp-P.timestamp);for(let T=0;T<h.presentationTimestamps.length;T++){const P=h.presentationTimestamps[T],C=h.blocks[P.blockIndex];if(T<h.presentationTimestamps.length-1){const _=h.presentationTimestamps[T+1];C.duration=_.timestamp-C.timestamp}else C.duration===0&&p.defaultDuration!=null&&C.lacing===ci.None&&(C.duration=Math.round(p.defaultDuration))}if(m&&(h.blocks=this.expandLacedBlocks(h.blocks,p),h.presentationTimestamps=h.blocks.map((T,P)=>({timestamp:T.timestamp,blockIndex:P})).sort((T,P)=>T.timestamp-P.timestamp)),((f=p.info)==null?void 0:f.type)==="audio"&&p.info.codec){const T=An.includes(p.info.codec);for(const P of h.blocks)(P.decoded||!T)&&(P.isKeyFrame=Co(p.info.codec,P.data)==="key")}const g=h.presentationTimestamps.find(T=>h.blocks[T.blockIndex].isKeyFrame);g&&(h.firstKeyFrameTimestamp=g.timestamp);const y=h.blocks[h.presentationTimestamps[0].blockIndex],b=h.blocks[Te(h.presentationTimestamps).blockIndex];h.startTimestamp=y.timestamp,h.endTimestamp=b.timestamp+b.duration;const S=de(p.clusterPositionCache,h.startTimestamp,T=>T.startTimestamp),A=p.clusterPositionCache[S],x=p.clusterPositionCache[S+1];(!A||A.elementStartPos<s)&&(!x||x.elementStartPos>s)&&p.clusterPositionCache.splice(S+1,0,{elementStartPos:l.elementStartPos,startTimestamp:h.startTimestamp,hasKeyFrame:h.firstKeyFrameTimestamp!==null})}return t.lastReadCluster=l,t.clusterSummaries.set(e,{elementEndPos:l.elementEndPos,trackIds:new Set(l.trackData.keys())}),l}getTrackDataInCluster(e,t){let r=e.trackData.get(t);if(!r){const s=e.segment.idToTrack.get(t);if(!s)return null;r={track:s,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,r)}return r}expandLacedBlocks(e,t){const r=[];for(const s of e){if(s.lacing===ci.None){r.push(s);continue}const n=at.tempFromBytes(s.data);if(n.length===0)throw new Error("Invalid laced block: no data.");const a=[],o=Z(n)+1;switch(s.lacing){case ci.Xiph:{let u=0;for(let l=0;l<o-1;l++){let d=0;for(;n.bufferPos<n.length;){const f=Z(n);if(d+=f,f<255){a.push(d),u+=d;break}}}a.push(n.length-(n.bufferPos+u))}break;case ci.FixedSize:{const u=n.length-1,l=Math.floor(u/o);for(let d=0;d<o;d++)a.push(l)}break;case ci.Ebml:{if(o===1){a.push(n.length-n.bufferPos);break}const u=rs(n);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=n.bufferPos,p=rs(n);if(p===null)throw new Error("Invalid EBML lacing: bad frame size.");const m=p,y=(1<<(n.bufferPos-h)*7-1)-1,b=m-y;l+=b,a.push(l),d+=l}a.push(n.length-(n.bufferPos+d))}break;default:w(!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=s.duration||Math.round(o*(t.defaultDuration??0));for(let u=0;u<o;u++){const l=a[u],d=X(n,l),f=Math.floor(c*u/o),h=Math.floor(c*(u+1)/o);r.push({timestamp:s.timestamp+f,duration:h-f,isKeyFrame:s.isKeyFrame,data:d,lacing:ci.None,decoded:s.decoded,postProcessed:!1,mainAdditional:s.mainAdditional})}}return r}async loadSegmentMetadata(e){for(const t of e.seekEntries){if(!(t.id===E.Tags&&!e.tagsSeen)){if(!(t.id===E.Attachments&&!e.attachmentsSeen))continue}if(!this.claimSeekTarget(e.dataStartPos+t.segmentPosition))continue;let r=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,Pt,ui);if(D(r)&&(r=await r),!r)continue;const s=$t(r);if(!s||s.id!==t.id)continue;const{size:n}=s;ni(n);let a=this.reader.requestSlice(r.filePos,n);if(D(a)&&(a=await a),a){w(!this.currentSegment),this.currentSegment=e;try{this.readContiguousElements(a)}finally{this.currentSegment=null}}t.id===E.Tags?e.tagsSeen=!0:t.id===E.Attachments&&(e.attachmentsSeen=!0)}}claimSeekTarget(e){return this.claimedSeekTargets.has(e)?!1:(this.claimedSeekTargets.add(e),!0)}readContiguousElements(e,t){if(this.elementNestingDepth===fm)throw new Error("Invalid file: elements are nested too deeply.");this.elementNestingDepth++;try{for(;e.remainingLength>=Pt;){const r=e.filePos;if(!this.traverseElement(e,t))return r}return e.filePos}finally{this.elementNestingDepth--}}traverseElement(e,t){var o,c,u,l,d,f,h,p,m,g,y,b,S,A,x,T,P,C,_,I,v,R,F,H,O,U,L,Q,re,Y,se,pe,he,Pe,We,tt,$e,ve,Qe,Ge,_e,Xe,St,xi,Li,Pi,ii,Lr;const r=$t(e);if(!r||t&&t.includes(r.id))return!1;const{id:s,size:n}=r,a=e.filePos;if(ni(n),a+n>e.end)return!1;switch(s){case E.DocType:this.isWebM=kr(e,n)==="webm";break;case E.Seek:{if(!this.currentSegment)break;const N={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(N),this.readContiguousElements(e.slice(a,n)),(N.id===-1||N.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case E.SeekID:{const N=(o=this.currentSegment)==null?void 0:o.seekEntries[this.currentSegment.seekEntries.length-1];if(!N)break;N.id=le(e,n)}break;case E.SeekPosition:{const N=(c=this.currentSegment)==null?void 0:c.seekEntries[this.currentSegment.seekEntries.length-1];if(!N)break;N.segmentPosition=le(e,n)}break;case E.TimestampScale:{if(!this.currentSegment)break;const N=n===0?1e6:le(e,n);if(N===0)throw new Error("Invalid TimestampScale element: must not be 0.");this.currentSegment.timestampScale=N,this.currentSegment.timestampFactor=1e9/N}break;case E.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=ur(e,n)}break;case E.DateUTC:{if(!this.currentSegment)break;const N=dm(e,n);this.currentSegment.metadataTags.creationTime=new Date(Vu+Number(N/1000000n))}break;case E.Title:{if(!this.currentSegment)break;(u=this.currentSegment.metadataTags).title??(u.title=lr(e,n))}break;case E.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...Si,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,n)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(N=>{var ne;return((ne=N.data)==null?void 0:ne.type)!=="decompress"||N.scope!==ns.Block||N.data.algorithm!==as.HeaderStripping})&&(K._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentSegment.idToTrack.has(this.currentTrack.id)&&(K._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 N=this.currentTrack.codecId.indexOf("/"),ne=N===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,N);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height;let Ee=this.currentTrack.info.displayWidth,Ye=this.currentTrack.info.displayHeight;const At=this.currentTrack.info.stereoMode;if(Ee!==null&&[1,8,9,11].includes(At)&&(Ee*=2),Ye!==null&&[2,3,6,7].includes(At)&&(Ye*=2),this.currentTrack.info.displayUnit===0&&(Ee??(Ee=this.currentTrack.info.width),Ye??(Ye=this.currentTrack.info.height)),this.currentTrack.info.displayUnit!==4&&Ee!==null&&Ye!==null){const dt=Ee*this.currentTrack.info.height,k=Ye*this.currentTrack.info.width;dt>0&&k>0&&(dt>k?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*dt/k):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*k/dt))}if(this.currentTrack.codecId===rt.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===rt.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(ne===rt.vp8)this.currentTrack.info.codec="vp8";else if(ne===rt.vp9)this.currentTrack.info.codec="vp9";else if(ne===rt.av1)this.currentTrack.info.codec="av1";else if(ne===rt.prores){const dt=this.currentTrack.codecPrivate?nt.decode(this.currentTrack.codecPrivate):"";er.includes(dt)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=dt)}const Ft=this.currentTrack;this.currentTrack.trackBacking=new mm(Ft),this.currentSegment.tracks.push(this.currentTrack),this.currentSegment.idToTrack.set(this.currentTrack.id,this.currentTrack)}else if(this.currentTrack.info.type==="audio"){if(this.currentTrack.info.outputSampleRate!==null&&(this.currentTrack.info.sampleRate=this.currentTrack.info.outputSampleRate),ne===rt.aac){if(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,!this.currentTrack.codecPrivate&&this.currentTrack.codecId!==rt.aac){const Ye=this.currentTrack.codecId.split("/")[2]??"",At=["MAIN","LC","SSR","LTP"].indexOf(Ye)+1;if(At===0)throw new Error(`Unknown Matroska AAC codec ID '${this.currentTrack.codecId}'.`);const Ft=this.currentTrack.codecId.endsWith("/SBR");Ft&&this.currentTrack.info.outputSampleRate===null&&(this.currentTrack.info.sampleRate*=2),this.currentTrack.info.codecDescription=Rn({objectType:Ft?5:At,outputSampleRate:this.currentTrack.info.sampleRate,outputNumberOfChannels:this.currentTrack.info.numberOfChannels,programConfigElement:null})}}else this.currentTrack.codecId===rt.mp3?this.currentTrack.info.codec="mp3":ne===rt.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Wi):ne===rt.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):ne===rt.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):ne===rt.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):ne===rt.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):ne===rt.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")):ne===rt.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 Ee=this.currentTrack;this.currentTrack.trackBacking=new pm(Ee),this.currentSegment.tracks.push(this.currentTrack),this.currentSegment.idToTrack.set(this.currentTrack.id,this.currentTrack)}}this.currentTrack=null}break;case E.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=le(e,n)}break;case E.TrackType:{if(!this.currentTrack)break;const N=le(e,n);N===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:0,stereoMode:0,squarePixelWidth:-1,squarePixelHeight:-1,horizontalScale:1,verticalScale:1,rotation:0,codec:null,codecDescription:null,colorSpace:{...Wl},alphaMode:!1,proresFormat:null}:N===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,outputSampleRate:null,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case E.FlagEnabled:{if(!this.currentTrack)break;(n===0?1:le(e,n))||(this.currentTrack=null)}break;case E.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=n===0||!!le(e,n)}break;case E.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!le(e,n)}break;case E.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!le(e,n)}break;case E.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!le(e,n)}break;case E.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!le(e,n)}break;case E.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!le(e,n)}break;case E.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=kr(e,n)}break;case E.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=X(e,n)}break;case E.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=le(e,n)}break;case E.CodecDelay:{if(!this.currentTrack)break;this.currentTrack.codecDelayNs=le(e,n)}break;case E.Name:{if(!this.currentTrack)break;this.currentTrack.name=lr(e,n)}break;case E.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=n===0?"eng":kr(e,n),us(this.currentTrack.languageCode)||(this.currentTrack.languageCode=et)}break;case E.LanguageBCP47:{if(!this.currentTrack)break;const ne=kr(e,n).split("-")[0];ne?this.currentTrack.languageCode=ne:this.currentTrack.languageCode=et,this.currentTrack.hasLanguageBcp47=!0}break;case E.Video:{if(((d=(l=this.currentTrack)==null?void 0:l.info)==null?void 0:d.type)!=="video")break;this.readContiguousElements(e.slice(a,n))}break;case E.PixelWidth:{if(((h=(f=this.currentTrack)==null?void 0:f.info)==null?void 0:h.type)!=="video")break;this.currentTrack.info.width=le(e,n)}break;case E.PixelHeight:{if(((m=(p=this.currentTrack)==null?void 0:p.info)==null?void 0:m.type)!=="video")break;this.currentTrack.info.height=le(e,n)}break;case E.DisplayWidth:{if(((y=(g=this.currentTrack)==null?void 0:g.info)==null?void 0:y.type)!=="video")break;this.currentTrack.info.displayWidth=le(e,n)}break;case E.DisplayHeight:{if(((S=(b=this.currentTrack)==null?void 0:b.info)==null?void 0:S.type)!=="video")break;this.currentTrack.info.displayHeight=le(e,n)}break;case E.DisplayUnit:{if(((x=(A=this.currentTrack)==null?void 0:A.info)==null?void 0:x.type)!=="video")break;this.currentTrack.info.displayUnit=le(e,n)}break;case E.StereoMode:{if(((P=(T=this.currentTrack)==null?void 0:T.info)==null?void 0:P.type)!=="video")break;this.currentTrack.info.stereoMode=le(e,n)}break;case E.AlphaMode:{if(((_=(C=this.currentTrack)==null?void 0:C.info)==null?void 0:_.type)!=="video")break;this.currentTrack.info.alphaMode=le(e,n)===1}break;case E.Colour:{if(((v=(I=this.currentTrack)==null?void 0:I.info)==null?void 0:v.type)!=="video")break;this.readContiguousElements(e.slice(a,n))}break;case E.MatrixCoefficients:{if(((F=(R=this.currentTrack)==null?void 0:R.info)==null?void 0:F.type)!=="video")break;const N=n===0?2:le(e,n),ne=hi[N];this.currentTrack.info.colorSpace.matrix=ne}break;case E.Range:{if(((O=(H=this.currentTrack)==null?void 0:H.info)==null?void 0:O.type)!=="video")break;const N=le(e,n);this.currentTrack.info.colorSpace.fullRange=N===1||N===2?N===2:void 0}break;case E.TransferCharacteristics:{if(((L=(U=this.currentTrack)==null?void 0:U.info)==null?void 0:L.type)!=="video")break;const N=n===0?2:le(e,n),ne=fi[N];this.currentTrack.info.colorSpace.transfer=ne}break;case E.Primaries:{if(((re=(Q=this.currentTrack)==null?void 0:Q.info)==null?void 0:re.type)!=="video")break;const N=n===0?2:le(e,n),ne=di[N];this.currentTrack.info.colorSpace.primaries=ne}break;case E.Projection:{if(((se=(Y=this.currentTrack)==null?void 0:Y.info)==null?void 0:se.type)!=="video")break;const N=this.currentTrack.info,ne={type:0,yaw:0,pitch:0,roll:0};if(this.currentProjection=ne,this.readContiguousElements(e.slice(a,n)),this.currentProjection=null,ne.type!==0)break;const Ee=Ye=>{try{return Math.round(Math.cos(Ir(Ye)*Ml))}catch{return 1}};N.horizontalScale=Ee(ne.yaw),N.verticalScale=Ee(ne.pitch);try{N.rotation=Ir(-ne.roll)}catch{}}break;case E.ProjectionType:{if(!this.currentProjection)break;this.currentProjection.type=le(e,n)}break;case E.ProjectionPoseYaw:{if(!this.currentProjection)break;this.currentProjection.yaw=ur(e,n)}break;case E.ProjectionPosePitch:{if(!this.currentProjection)break;this.currentProjection.pitch=ur(e,n)}break;case E.ProjectionPoseRoll:{if(!this.currentProjection)break;this.currentProjection.roll=ur(e,n)}break;case E.Audio:{if(((he=(pe=this.currentTrack)==null?void 0:pe.info)==null?void 0:he.type)!=="audio")break;this.readContiguousElements(e.slice(a,n))}break;case E.SamplingFrequency:{if(((We=(Pe=this.currentTrack)==null?void 0:Pe.info)==null?void 0:We.type)!=="audio")break;const N=n===0?8e3:ur(e,n);if(!(N>0)||!Number.isFinite(N))throw new Error("Invalid SamplingFrequency element: must be a positive, finite number.");this.currentTrack.info.sampleRate=N}break;case E.OutputSamplingFrequency:{if((($e=(tt=this.currentTrack)==null?void 0:tt.info)==null?void 0:$e.type)!=="audio")break;const N=ur(e,n);if(!(N>0)||!Number.isFinite(N))throw new Error("Invalid OutputSamplingFrequency element: must be a positive, finite number.");this.currentTrack.info.outputSampleRate=N}break;case E.Channels:{if(((Qe=(ve=this.currentTrack)==null?void 0:ve.info)==null?void 0:Qe.type)!=="audio")break;const N=n===0?1:le(e,n);if(N===0)throw new Error("Invalid Channels element: must not be 0.");this.currentTrack.info.numberOfChannels=N}break;case E.BitDepth:{if(((_e=(Ge=this.currentTrack)==null?void 0:Ge.info)==null?void 0:_e.type)!=="audio")break;this.currentTrack.info.bitDepth=le(e,n)}break;case E.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,n)),this.currentCueTime=null}break;case E.CueTime:this.currentCueTime=le(e,n);break;case E.CueTrackPositions:{if(this.currentCueTime===null||!this.currentSegment)break;const N={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(N),this.readContiguousElements(e.slice(a,n)),(N.trackId===-1||N.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case E.CueTrack:{const N=(Xe=this.currentSegment)==null?void 0:Xe.cuePoints[this.currentSegment.cuePoints.length-1];if(!N)break;N.trackId=le(e,n)}break;case E.CueClusterPosition:{const N=(St=this.currentSegment)==null?void 0:St.cuePoints[this.currentSegment.cuePoints.length-1];if(!N)break;w(this.currentSegment),N.clusterPosition=this.currentSegment.dataStartPos+le(e,n)}break;case E.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=le(e,n)}break;case E.SimpleBlock:{if(!this.currentCluster)break;const N=e.slice(a,n),ne=rs(N);if(ne===null||N.remainingLength<3)break;const Ee=this.getTrackDataInCluster(this.currentCluster,ne);if(!Ee)break;const Ye=co(N),At=Z(N),Ft=At>>1&3,dt=!!(At&128),k=X(N,N.remainingLength),B=Ee.track.decodingInstructions.length>0;Ee.blocks.push({timestamp:Ye,duration:0,isKeyFrame:dt,data:k,lacing:Ft,decoded:!B,postProcessed:!1,mainAdditional:null})}break;case E.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,n)),this.currentBlock=null}break;case E.Block:{if(!this.currentCluster)break;const N=e.slice(a,n),ne=rs(N);if(ne===null||N.remainingLength<3)break;const Ee=this.getTrackDataInCluster(this.currentCluster,ne);if(!Ee)break;const Ye=co(N),Ft=Z(N)>>1&3,dt=X(N,N.remainingLength),k=Ee.track.decodingInstructions.length>0;this.currentBlock={timestamp:Ye,duration:0,isKeyFrame:!0,data:dt,lacing:Ft,decoded:!k,postProcessed:!1,mainAdditional:null},Ee.blocks.push(this.currentBlock)}break;case E.BlockAdditions:this.readContiguousElements(e.slice(a,n));break;case E.BlockMore:{const N=this.currentBlock;if(!N)break;const ne={addId:1,data:null};this.currentBlockAdditional=ne,this.readContiguousElements(e.slice(a,n)),ne.data&&ne.addId===1&&(N.mainAdditional=ne.data),this.currentBlockAdditional=null}break;case E.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=X(e,n)}break;case E.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=n===0?1:le(e,n)}break;case E.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=le(e,n)}break;case E.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case E.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,n));break;case E.Targets:this.readContiguousElements(e.slice(a,n));break;case E.TargetTypeValue:(n===0?50:le(e,n))!==50&&(this.currentTagTargetIsMovie=!1);break;case E.TagTrackUID:case E.TagEditionUID:case E.TagChapterUID:case E.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case E.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,n))}break;case E.TagName:this.currentSimpleTagName=lr(e,n);break;case E.TagString:{if(!this.currentSimpleTagName)break;const N=lr(e,n);this.processTagValue(this.currentSimpleTagName,N)}break;case E.TagBinary:{if(!this.currentSimpleTagName)break;const N=X(e,n);this.processTagValue(this.currentSimpleTagName,N)}break;case E.AttachedFile:{if(!this.currentSegment||this.currentAttachedFile)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,n));const N=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(N.raw??(N.raw={}),N.raw[this.currentAttachedFile.fileUid.toString()]=new bo(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),(xi=this.currentAttachedFile.fileMediaType)!=null&&xi.startsWith("image/")&&this.currentAttachedFile.fileData){const ne=this.currentAttachedFile.fileName;let Ee="unknown";if(ne){const Ye=ne.toLowerCase();Ye.startsWith("cover.")?Ee="coverFront":Ye.startsWith("back.")&&(Ee="coverBack")}N.images??(N.images=[]),N.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:Ee,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case E.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=Hu(e,n)}break;case E.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=lr(e,n)}break;case E.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=kr(e,n)}break;case E.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=X(e,n)}break;case E.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=lr(e,n)}break;case E.ContentEncodings:{const N=this.currentTrack;if(!N)break;this.readContiguousElements(e.slice(a,n)),N.decodingInstructions.sort((ne,Ee)=>Ee.order-ne.order)}break;case E.ContentEncoding:{const N=this.currentTrack;if(!N)break;const ne={order:0,scope:ns.Block,data:null};this.currentDecodingInstruction=ne,this.readContiguousElements(e.slice(a,n)),ne.data&&N.decodingInstructions.push(ne),this.currentDecodingInstruction=null}break;case E.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=le(e,n)}break;case E.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=n===0?ns.Block:le(e,n)}break;case E.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:as.Zlib,settings:null},this.readContiguousElements(e.slice(a,n))}break;case E.ContentCompAlgo:{if(((Pi=(Li=this.currentDecodingInstruction)==null?void 0:Li.data)==null?void 0:Pi.type)!=="decompress")break;this.currentDecodingInstruction.data.algorithm=le(e,n)}break;case E.ContentCompSettings:{if(((Lr=(ii=this.currentDecodingInstruction)==null?void 0:ii.data)==null?void 0:Lr.type)!=="decompress")break;this.currentDecodingInstruction.data.settings=X(e,n)}break;case E.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+n,!0}decodeBlockData(e,t){w(e.decodingInstructions.length>0);let r=t;for(const s of e.decodingInstructions)switch(w(s.data),s.data.type){case"decompress":switch(s.data.algorithm){case as.HeaderStripping:if(s.data.settings&&s.data.settings.length>0){const n=s.data.settings,a=new Uint8Array(n.length+r.length);a.set(n,0),a.set(r,n.length),r=a}break}break}return r}processTagValue(e,t){var s,n;if(!((s=this.currentSegment)!=null&&s.metadataTags))return;const r=this.currentSegment.metadataTags;if(r.raw??(r.raw={}),(n=r.raw)[e]??(n[e]=t),typeof t=="string")switch(e.toLowerCase()){case"title":r.title??(r.title=t);break;case"description":r.description??(r.description=t);break;case"artist":r.artist??(r.artist=t);break;case"album":r.album??(r.album=t);break;case"album_artist":r.albumArtist??(r.albumArtist=t);break;case"genre":r.genre??(r.genre=t);break;case"bpm":{const a=Number.parseInt(t,10);Number.isInteger(a)&&a>0&&(r.beatsPerMinute??(r.beatsPerMinute=a))}break;case"comment":r.comment??(r.comment=t);break;case"lyrics":r.lyrics??(r.lyrics=t);break;case"date":{const a=Fr(t);a&&(r.date??(r.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&&(r.trackNumber??(r.trackNumber=o)),c&&Number.isInteger(c)&&c>0&&(r.tracksTotal??(r.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&&(r.discNumber??(r.discNumber=o)),c&&Number.isInteger(c)&&c>0&&(r.discsTotal??(r.discsTotal=c))}break}}getDurationFromMetadata(e){if(e.duration<=0)return null;const t=Math.min(...e.tracks.map(r=>r.codecDelay));return(e.duration-t)/e.timestampFactor}}class Gu{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let r=0;for(const s of e.segments)for(const n of s.tracks)if(n.trackBacking.getType()===t&&r++,n===this.internalTrack)return r;w(!1)}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 Zt(e*this.internalTrack.segment.timestampFactor)+this.internalTrack.codecDelay}async getPacket(e,t){const r=this.intoTimescale(e);return this.performClusterLookup(null,s=>{const n=s.trackData.get(this.internalTrack.id);if(!n)return{blockIndex:-1,correctBlockFound:!1};const a=de(n.presentationTimestamps,r,u=>u.timestamp),o=a!==-1?n.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&r<n.endTimestamp;return{blockIndex:o,correctBlockFound:c}},r,r,t)}async getNextPacket(e,t){const r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,s=>{if(s===r.cluster){const n=s.trackData.get(this.internalTrack.id);if(r.blockIndex+1<n.blocks.length)return{blockIndex:r.blockIndex+1,correctBlockFound:!0}}else if(s.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 r=this.intoTimescale(e);return this.performClusterLookup(null,s=>{const n=s.trackData.get(this.internalTrack.id);if(!n)return{blockIndex:-1,correctBlockFound:!1};const a=Br(n.presentationTimestamps,u=>n.blocks[u.blockIndex].isKeyFrame&&u.timestamp<=r),o=a!==-1?n.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&r<n.endTimestamp;return{blockIndex:o,correctBlockFound:c}},r,r,t,!0)}async getNextKeyPacket(e,t){const r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,s=>{if(s===r.cluster){const n=s.trackData.get(this.internalTrack.id);for(let a=r.blockIndex+1;a<n.blocks.length;a++)if(n.blocks[a].isKeyFrame)return{blockIndex:a,correctBlockFound:!0}}else{const n=s.trackData.get(this.internalTrack.id);if(n&&n.firstKeyFrameTimestamp!==null){const a=n.blocks.findIndex(o=>o.isKeyFrame);return w(a!==-1),{blockIndex:a,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,r){var h,p;if(t===-1)return null;const n=e.trackData.get(this.internalTrack.id).blocks[t];if(w(n),n.decoded||(n.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,n.data),n.decoded=!0),!n.postProcessed){if(((h=this.internalTrack.info)==null?void 0:h.codec)==="prores"&&!(n.data.length>=8&&n.data[4]===105&&n.data[5]===99&&n.data[6]===112&&n.data[7]===102)){const g=new Uint8Array(n.data.length+8);ie(g).setUint32(0,g.length,!1),g[4]=105,g[5]=99,g[6]=112,g[7]=102,g.set(n.data,8),n.data=g}n.postProcessed=!0}const a=r.metadataOnly?mt:n.data,{codecDelay:o,segment:c}=this.internalTrack,u=(n.timestamp-o)/c.timestampFactor,l=n.duration/c.timestampFactor,d={};n.mainAdditional&&((p=this.internalTrack.info)==null?void 0:p.type)==="video"&&this.internalTrack.info.alphaMode&&(d.alpha=r.metadataOnly?mt:n.mainAdditional,d.alphaByteLength=n.mainAdditional.byteLength);const f=new Ce(a,n.isKeyFrame?"key":"delta",u,l,e.dataStartPos+t,n.data.byteLength,d);return this.packetToClusterLocation.set(f,{cluster:e,blockIndex:t}),f}async performClusterLookup(e,t,r,s,n,a=!1){var g,y;const{demuxer:o,segment:c,cuePoints:u,clusterPositionCache:l}=this.internalTrack;let d=null,f=-1;if(e){const{blockIndex:b,correctBlockFound:S}=t(e);if(S)return this.fetchPacketInCluster(e,b,n);b!==-1&&(d=e,f=b)}let h=de(u,r,b=>b.time),p=de(l,r,b=>b.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 b=Math.max(((g=u[h])==null?void 0:g.clusterPosition)??0,((y=l[p])==null?void 0:y.elementStartPos)??0)||null;let S,A=null;e?b===null||e.elementStartPos>=b?(S=e.elementEndPos,A=e):S=b:S=b??c.clusterSeekStartPos;const x=A?A.elementStartPos:S;for(;(c.elementEndPos===null||S<=c.elementEndPos-Pt)&&S<m;){if(A){const F=A.trackData.get(this.internalTrack.id);if(F&&F.startTimestamp>s)break;A=null}const T=c.clusterSummaries.get(S);if(T&&!T.trackIds.has(this.internalTrack.id)){S=T.elementEndPos;continue}let P=o.reader.requestSliceRange(S,Pt,ui);if(D(P)&&(P=await P),!P)break;const C=S,_=$t(P);if(c.elementEndPos===null&&_&&Nu.includes(_.id)){c.elementEndPos=C;break}if(!_||!bs.includes(_.id)&&_.id!==E.Void){const F=await Ku(o.reader,C+1,bs,Math.min(c.elementEndPos??1/0,C+Qu));if(F){S=F;continue}else break}const I=_.id;let v=_.size;const R=P.filePos;if(I===E.Cluster){A=await o.readCluster(C,c),v=A.elementEndPos-R;const{blockIndex:F,correctBlockFound:H}=t(A);if(H)return this.fetchPacketInCluster(A,F,n);F!==-1&&(d=A,f=F)}v===void 0&&(w(I!==E.Cluster),v=(await Za(o.reader,R,rn,c.elementEndPos)).pos-R),S=R+v}if(b===null||d&&d.elementStartPos>=b)break;m=x,e=null}return d?this.fetchPacketInCluster(d,f,n):null}}class mm extends Gu{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=vr(Ol(e.horizontalScale,e.verticalScale),mo(e.rotation));return Dl(t,e.width,e.height)}async getColorSpace(){var t,r,s,n;const e=await this.getDecoderConfig();return e?{primaries:(t=e.colorSpace)==null?void 0:t.primaries,transfer:(r=e.colorSpace)==null?void 0:r.transfer,matrix:(s=e.colorSpace)==null?void 0:s.matrix,fullRange:(n=e.colorSpace)==null?void 0:n.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 o,c,u,l;const e=this.internalTrack.codecPrivate;let t=this.internalTrack.info.codec==="av1"&&e?ms(e.subarray(4)):null,r=null;(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"&&!t||this.internalTrack.info.codec==="prores"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(r=await this.getFirstPacket({})),this.internalTrack.info.codec==="av1"&&r&&(t=ms(r.data));const n={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"&&r?_s(r.data):null,hevcType:"hev1",hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&r?Is(r.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&r?Po(r.data):null,av1CodecInfo:t,proresCodecInfo:this.internalTrack.info.codec==="prores"&&r?nu(r.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!go(this.internalTrack.info.colorSpace)){const d=Ud(n);(o=this.internalTrack.info.colorSpace).primaries??(o.primaries=d.primaries),(c=this.internalTrack.info.colorSpace).transfer??(c.transfer=d.transfer),(u=this.internalTrack.info.colorSpace).matrix??(u.matrix=d.matrix),(l=this.internalTrack.info.colorSpace).fullRange??(l.fullRange=d.fullRange)}const a={codec:jn(n),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)&&(a.displayAspectWidth=this.internalTrack.info.squarePixelWidth,a.displayAspectHeight=this.internalTrack.info.squarePixelHeight),a})()):null}}class pm extends Gu{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&&mu(e.data)}return{codec:Xo({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 Ei;(function(i){i[i.Unsynchronisation=128]="Unsynchronisation",i[i.ExtendedHeader=64]="ExtendedHeader",i[i.ExperimentalIndicator=32]="ExperimentalIndicator",i[i.Footer=16]="Footer"})(Ei||(Ei={}));var Ze;(function(i){i[i.ISO_8859_1=0]="ISO_8859_1",i[i.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",i[i.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",i[i.UTF_8=3]="UTF_8"})(Ze||(Ze={}));const Oi=128,bi=10,Tr=["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"],gm=(i,e)=>{var d;const t=i.filePos;e.raw??(e.raw={}),(d=e.raw).TAG??(d.TAG=X(i,Oi-3)),i.filePos=t;const r=dr(i,30);r&&(e.title??(e.title=r));const s=dr(i,30);s&&(e.artist??(e.artist=s));const n=dr(i,30);n&&(e.album??(e.album=n));const a=dr(i,4),o=Number.parseInt(a,10);Number.isInteger(o)&&o>0&&(e.date??(e.date=un(o)));const c=X(i,30);let u;if(c[28]===0&&c[29]!==0){const f=c[29];f>0&&(e.trackNumber??(e.trackNumber=f)),i.skip(-30),u=dr(i,28),i.skip(2)}else i.skip(-30),u=dr(i,30);u&&(e.comment??(e.comment=u));const l=Z(i);l<Tr.length&&(e.genre??(e.genre=Tr[l]))},dr=(i,e)=>{const t=X(i,e),r=pr(t.indexOf(0),t.length),s=t.subarray(0,r);let n="";for(let a=0;a<s.length;a++)n+=String.fromCharCode(s[a]);return n.trimEnd()},sr=async(i,e)=>{let t=e;for(;;){let r=i.requestSlice(t,bi);if(D(r)&&(r=await r),!r)return t;const s=Bs(r);if(!s)return t;t=r.filePos+s.size}},Bs=i=>{const e=i.filePos,t=Ie(i,3),r=Z(i),s=Z(i),n=Z(i),a=q(i);if(t!=="ID3"||r===255||s===255||(a&2155905152)!==0)return i.filePos=e,null;let o=fn(a);return r===4&&n&Ei.Footer&&(o+=bi),{majorVersion:r,revision:s,flags:n,size:o}},Vn=(i,e,t)=>{var c,u,l,d,f,h;if(![2,3,4].includes(e.majorVersion)){K._warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}if(e.majorVersion===2&&e.flags&Ei.ExtendedHeader){K._warn("Skipping compressed ID3v2.2 tag");return}const r=e.majorVersion===4&&e.flags&Ei.Footer?e.size-bi:e.size,s=X(i,r),n=new wm(e,s);if(e.flags&Ei.Unsynchronisation&&e.majorVersion<=3&&n.ununsynchronizeAll(),e.flags&Ei.ExtendedHeader){if(n.bytes.length<4)return;const p=n.readU32();e.majorVersion===3?n.pos+=p:n.pos+=fn(p)-4}let a=null,o=null;for(;n.pos<=n.bytes.length-n.frameHeaderSize();){const p=n.readId3V2Frame();if(!p)break;const m=Math.min(n.pos+p.size,n.bytes.length);let g=m,y=!1,b=!1,S=!1,A=!1,x=!1;if(e.majorVersion===3?(y=!!(p.flags&64),b=!!(p.flags&128),A=!!(p.flags&32)):e.majorVersion===4&&(A=!!(p.flags&64),y=!!(p.flags&4),b=!!(p.flags&8),S=!!(p.flags&2)||!!(e.flags&Ei.Unsynchronisation),x=!!(p.flags&1)),y){K._warn(`Skipping encrypted ID3v2 frame ${p.id}`),n.pos=m;continue}if(b){K._warn(`Skipping compressed ID3v2 frame ${p.id}`),n.pos=m;continue}A&&(n.pos+=1),x&&(n.pos+=4),S&&(g=n.ununsynchronizeRegion(n.pos,g));const T=n.pos,P=C=>{if(g-n.pos<C)throw new Error(`Invalid ID3v2 ${p.id} frame: too short.`)};if(t.raw??(t.raw={}),p.id==="TXXX"||p.id==="TXX"){const C=(c=t.raw)[u=p.id]??(c[u]={});P(1);const _=n.readId3V2TextEncoding(),I=n.readId3V2Text(_,g),v=n.readId3V2Text(_,g);C[I]??(C[I]=v)}else if(p.id[0]==="T")(l=t.raw)[d=p.id]??(l[d]=n.readId3V2EncodingAndText(g));else{const C=n.readBytes(g-n.pos),_=t.raw[p.id];_ instanceof Uint8Array?t.raw[p.id]=[_,C]:Array.isArray(_)?_.push(C):(f=t.raw)[h=p.id]??(f[h]=C)}switch(n.pos=T,p.id){case"TIT2":case"TT2":t.title??(t.title=n.readId3V2EncodingAndText(g));break;case"TIT3":case"TT3":t.description??(t.description=n.readId3V2EncodingAndText(g));break;case"TPE1":case"TP1":t.artist??(t.artist=n.readId3V2EncodingAndText(g));break;case"TALB":case"TAL":t.album??(t.album=n.readId3V2EncodingAndText(g));break;case"TPE2":case"TP2":t.albumArtist??(t.albumArtist=n.readId3V2EncodingAndText(g));break;case"TRCK":case"TRK":{const _=n.readId3V2EncodingAndText(g).split("/"),I=Number.parseInt(_[0],10),v=_[1]&&Number.parseInt(_[1],10);Number.isInteger(I)&&I>0&&(t.trackNumber??(t.trackNumber=I)),v&&Number.isInteger(v)&&v>0&&(t.tracksTotal??(t.tracksTotal=v))}break;case"TPOS":case"TPA":{const _=n.readId3V2EncodingAndText(g).split("/"),I=Number.parseInt(_[0],10),v=_[1]&&Number.parseInt(_[1],10);Number.isInteger(I)&&I>0&&(t.discNumber??(t.discNumber=I)),v&&Number.isInteger(v)&&v>0&&(t.discsTotal??(t.discsTotal=v))}break;case"TCON":case"TCO":{const C=n.readId3V2EncodingAndText(g);let _=/^\((\d+)\)/.exec(C);if(_){const I=Number.parseInt(_[1]);if(Tr[I]!==void 0){t.genre??(t.genre=Tr[I]);break}}if(_=/^\d+$/.exec(C),_){const I=Number.parseInt(_[0]);if(Tr[I]!==void 0){t.genre??(t.genre=Tr[I]);break}}t.genre??(t.genre=C)}break;case"TDRC":{const C=Fr(n.readId3V2EncodingAndText(g));C&&(t.date??(t.date=C))}break;case"TYER":case"TYE":{const C=n.readId3V2EncodingAndText(g),_=Number.parseInt(C,10);Number.isInteger(_)&&(a??(a=_))}break;case"TDAT":case"TDA":o??(o=n.readId3V2EncodingAndText(g));break;case"TBPM":case"TBP":{const C=n.readId3V2EncodingAndText(g),_=Number.parseInt(C,10);Number.isInteger(_)&&_>0&&(t.beatsPerMinute??(t.beatsPerMinute=_))}break;case"USLT":case"ULT":{P(4);const C=n.readId3V2TextEncoding();n.pos+=3,n.readId3V2Text(C,g),t.lyrics??(t.lyrics=n.readId3V2Text(C,g))}break;case"COMM":case"COM":{P(4);const C=n.readId3V2TextEncoding();n.pos+=3,n.readId3V2Text(C,g)===""&&(t.comment??(t.comment=n.readId3V2Text(C,g)))}break;case"APIC":case"PIC":{P(1);const C=n.readId3V2TextEncoding();let _;if(e.majorVersion===2){P(3);const F=n.readAscii(3);_=F==="PNG"?"image/png":F==="JPG"?"image/jpeg":"image/*"}else _=n.readId3V2Text(Ze.ISO_8859_1,g);P(1);const I=n.readU8(),v=n.readId3V2Text(C,g).trimEnd(),R=g-n.pos;if(R>=0){const F=n.readBytes(R);t.images||(t.images=[]),t.images.push({data:F,mimeType:_,kind:I===3?"coverFront":I===4?"coverBack":"unknown",description:v})}}break;default:n.pos+=p.size;break}n.pos=m}if(a!==null){let p=un(a);const m=/^(0[1-9]|[12]\d|3[01])(0[1-9]|1[0-2])$/.exec(o??"");if(m){const g=Number(m[1]),y=un(a,Number(m[2])-1,g);y.getUTCDate()===g&&(p=y)}Number.isNaN(p.getTime())||(t.date??(t.date=p))}};class wm{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=new Uint8Array(this.bytes.length);let t=0;for(let r=0;r<this.bytes.length;r++){const s=this.bytes[r];e[t++]=s,s===255&&r!==this.bytes.length-1&&this.bytes[r+1]===0&&r++}this.bytes=e.subarray(0,t),this.view=ie(this.bytes)}ununsynchronizeRegion(e,t){this.ownsBytes||(this.bytes=this.bytes.slice(),this.view=ie(this.bytes),this.ownsBytes=!0);let r=e;for(let s=e;s<t;s++){const n=this.bytes[s];this.bytes[r++]=n,n===255&&s!==t-1&&this.bytes[s+1]===0&&s++}return r}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 r=0;r<e;r++)t+=String.fromCharCode(this.view.getUint8(this.pos+r));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(),r=(t&2155905152)===0;let s=this.header.majorVersion===4&&r?fn(t):t;const n=this.readU16(),a=this.pos,o=c=>{const u=a+c;if(u>this.bytes.length)return!1;if(u<=this.bytes.length-this.frameHeaderSize()){this.pos=u;const l=this.readAscii(4);if(l!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(l))return!1}return!0};if(r&&!o(s)){const c=this.header.majorVersion===4?t:fn(t);o(c)&&(s=c)}return this.pos=a,{id:e,size:s,flags:n}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const r=this.pos,s=this.readBytes(t-this.pos);switch(e){case Ze.ISO_8859_1:{let n="";for(let a=0;a<s.length;a++){const o=s[a];if(o===0){this.pos=r+a+1;break}n+=String.fromCharCode(o)}return n}case Ze.UTF_16_WITH_BOM:if(s[0]===255&&s[1]===254){const n=new Sr("utf-16le"),a=pr(s.findIndex((o,c)=>o===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=r+Math.min(a+2,s.length),n.decode(s.subarray(2,a))}else if(s[0]===254&&s[1]===255){const n=new Sr("utf-16be"),a=pr(s.findIndex((o,c)=>o===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=r+Math.min(a+2,s.length),n.decode(s.subarray(2,a))}else{if(s[0]===0&&s[1]===0)return this.pos=r+2,"";{const n=pr(s.findIndex(a=>a===0),s.length);return this.pos=r+Math.min(n+1,s.length),nt.decode(s.subarray(0,n))}}case Ze.UTF_16_BE_NO_BOM:{const n=new Sr("utf-16be"),a=pr(s.findIndex((o,c)=>o===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=r+Math.min(a+2,s.length),n.decode(s.subarray(0,a))}case Ze.UTF_8:{const n=pr(s.findIndex(a=>a===0),s.length);return this.pos=r+Math.min(n+1,s.length),nt.decode(s.subarray(0,n))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class No{constructor(e){this.helper=new Uint8Array(8),this.helperView=ie(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 r=this.writer.getPos(),s=new Set;for(const{key:o,value:c}of Nr(e))switch(o){case"title":this.writeId3V2TextFrame("TIT2",c),s.add("TIT2");break;case"description":this.writeId3V2TextFrame("TIT3",c),s.add("TIT3");break;case"artist":this.writeId3V2TextFrame("TPE1",c),s.add("TPE1");break;case"album":this.writeId3V2TextFrame("TALB",c),s.add("TALB");break;case"albumArtist":this.writeId3V2TextFrame("TPE2",c),s.add("TPE2");break;case"trackNumber":{const u=e.tracksTotal!==void 0?`${c}/${e.tracksTotal}`:c.toString();this.writeId3V2TextFrame("TRCK",u),s.add("TRCK")}break;case"discNumber":{const u=e.discsTotal!==void 0?`${c}/${e.discsTotal}`:c.toString();this.writeId3V2TextFrame("TPOS",u),s.add("TPOS")}break;case"genre":this.writeId3V2TextFrame("TCON",c),s.add("TCON");break;case"date":this.writeId3V2TextFrame("TDRC",c.toISOString().slice(0,10)),s.add("TDRC");break;case"beatsPerMinute":this.writeId3V2TextFrame("TBPM",`${c}`),s.add("TBPM");break;case"lyrics":this.writeId3V2LyricsFrame(c),s.add("USLT");break;case"comment":this.writeId3V2CommentFrame(c),s.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)}s.add("APIC")}break;case"tracksTotal":case"discsTotal":break;case"raw":break;case"creationTime":break;default:xe(o)}if(e.raw)for(const o in e.raw){const c=e.raw[o];if(c==null||o.length!==4||s.has(o))continue;let u;if(typeof c=="string"){let l;if(ri(c)){l=new Uint8Array(c.length+2),l[0]=Ze.ISO_8859_1;for(let f=0;f<c.length;f++)l[f+1]=c.charCodeAt(f)}else{const f=ge.encode(c);l=new Uint8Array(f.byteLength+2),l[0]=Ze.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"&&$l(c)){for(const l in c){const d=c[l],f=ri(l)&&ri(d),h=f?null:ge.encode(l),p=f?null:ge.encode(d),m=f?l.length:h.byteLength,g=f?d.length:p.byteLength,y=1+m+1+g+1;this.writeAscii("TXXX"),this.writeSynchsafeU32(y),this.writeU16(0),this.writeU8(f?Ze.ISO_8859_1:Ze.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 n=this.writer.getPos(),a=n-r;return this.writer.seek(t+6),this.writeSynchsafeU32(a),this.writer.seek(n),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(Lf(e))}writeIsoString(e){const t=new Uint8Array(e.length+1);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);this.writer.write(t)}writeUtf8String(e){const t=ge.encode(e);this.writer.write(t),this.writeU8(0)}writeId3V2TextFrame(e,t){const r=ri(t),n=1+(r?t.length:ge.encode(t).byteLength)+1;this.writeAscii(e),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(r?Ze.ISO_8859_1:Ze.UTF_8),r?this.writeIsoString(t):this.writeUtf8String(t)}writeId3V2LyricsFrame(e){const t=ri(e),r=t?e.length:ge.encode(e).byteLength,s="",n=4+s.length+1+r+1;this.writeAscii("USLT"),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(t?Ze.ISO_8859_1:Ze.UTF_8),this.writeAscii("und"),t?(this.writeIsoString(s),this.writeIsoString(e)):(this.writeUtf8String(s),this.writeUtf8String(e))}writeId3V2CommentFrame(e){const t=ri(e),r=t?e.length:ge.encode(e).byteLength,s="",n=4+s.length+1+r+1;this.writeAscii("COMM"),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(t?Ze.ISO_8859_1:Ze.UTF_8),this.writeU8(117),this.writeU8(110),this.writeU8(100),t?(this.writeIsoString(s),this.writeIsoString(e)):(this.writeUtf8String(s),this.writeUtf8String(e))}writeId3V2ApicFrame(e,t,r,s){const n=ri(e)&&ri(r),a=n?e.length:ge.encode(e).byteLength,o=n?r.length:ge.encode(r).byteLength,c=1+a+1+1+o+1+s.byteLength;this.writeAscii("APIC"),this.writeSynchsafeU32(c),this.writeU16(0),this.writeU8(n?Ze.ISO_8859_1:Ze.UTF_8),n?this.writeIsoString(e):this.writeUtf8String(e),this.writeU8(t),n?this.writeIsoString(r):this.writeUtf8String(r),this.writer.write(s)}}/*!
|
|
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 Ja=async(i,e,t,r)=>{let s=e;for(;;){const n=await eo(i,s,e+t,r);if(!n)return null;const{header:a}=n,o=Dn(a.mpegVersionId,a.channel);let c=i.requestSlice(n.startPos+o,4);if(D(c)&&(c=await c),c){const d=q(c);if(d===fs||d===Mn)return n}const u=n.startPos+a.totalSize;if(u===i.fileSize)return n;if(u+Oi===i.fileSize){let d=i.requestSlice(u,3);if(D(d)&&(d=await d),d&&Ie(d,3)==="TAG")return n}const l=await eo(i,u,u+Yt);if(l&&l.header.channel===a.channel&&l.header.sampleRate===a.sampleRate)return n;s=n.startPos+1}},eo=async(i,e,t,r=null)=>{let n=e;for(;t===null||n<t;){const a=t!==null?Math.min(65536,t-n):65536;let o=i.requestSliceRange(n,Yt,a);if(D(o)&&(o=await o),!o||o.length<Yt)break;for(;o.remainingLength>=Yt;){const c=o.filePos,u=q(o),l=i.fileSize!==null?i.fileSize-n:null,d=Mr(u,l);if(d.header&&(!r||d.header.sampleRate===r.sampleRate&&d.header.mpegVersionId===r.mpegVersionId&&d.header.layer===r.layer&&hs(d.header.channel)===hs(r.channel)))return{header:d.header,startPos:n};o.filePos=c+d.bytesAdvanced,n=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
|
+
*/const qs=32;class ym extends Ai{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 Jt,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 bm(this)]})())}async advanceReader(){let e;if(this.lastLoadedPos===0){const c=await sr(this.reader,0);e=await Ja(this.reader,c,4096,null)}else if(e=await eo(this.reader,this.lastLoadedPos,this.lastLoadedPos+2,this.firstFrameHeader),!e){if(this.firstFrameHeader){let u=this.reader.requestSlice(this.lastLoadedPos,Yt+1);if(D(u)&&(u=await u),u)for(let l=0;l<2;l++){u.filePos=this.lastLoadedPos+l;const{header:d}=Mr(q(u),null);if(d&&d.sampleRate!==this.firstFrameHeader.sampleRate){K._warn(`The sample rate changes mid-stream (from ${this.firstFrameHeader.sampleRate} Hz to ${d.sampleRate} Hz), which isn't properly supported or handled by Mediabunny.`),this.lastSampleLoaded=!0;return}}}const c=await sr(this.reader,this.lastLoadedPos+1);e=await Ja(this.reader,c,2**16,this.firstFrameHeader)}if(!e){this.lastSampleLoaded=!0;return}const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const r=Dn(t.mpegVersionId,t.channel);let s=this.reader.requestSlice(e.startPos+r,4);if(D(s)&&(s=await s),s){const c=q(s);if(c===fs||c===Mn){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let l=this.reader.requestSlice(e.startPos+r+4,8);if(D(l)&&(l=await l),l){const d=X(l,8),f=ie(d),h=f.getUint32(0,!1);this.xingData={isVbr:c===fs,frameCount:h&Gt.FrameCount?f.getUint32(4,!1):null};const p=e.startPos+r+8+(h&Gt.FrameCount?4:0)+(h&Gt.FileSize?4:0)+(h&Gt.Toc?100:0)+(h&Gt.Quality?4:0);if(!this.firstFrameHeader&&p+24<=e.startPos+t.totalSize){let m=this.reader.requestSlice(p,24);if(D(m)&&(m=await m),m){const g=X(m,24),y=String.fromCharCode(...g.subarray(0,4));(y==="LAME"||y==="Lavf"||y==="Lavc")&&(this.primingDelay=(g[21]<<4|g[22]>>4)+dn,this.nextTimestampInSamples=-this.primingDelay)}}}}return}}let n=t.layer===1?this.reader.requestSlice(e.startPos+Yt+32,18):null;if(D(n)&&(n=await n),n){const c=q(n),u=De(n);if(c===Vf&&u===1){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){n.skip(8);const l=q(n);this.xingData={isVbr:!0,frameCount:l}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);const a=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,o={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:a,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(o),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0,r=!1;for(;;){let s=this.reader.requestSlice(t,bi);if(D(s)&&(s=await s),!s)break;const n=Bs(s);if(!n)break;r=!0;let a=this.reader.requestSlice(s.filePos,n.size);if(D(a)&&(a=await a),!a)break;Vn(a,n,this.metadataTags),t=s.filePos+n.size}if(!r&&this.reader.fileSize!==null&&this.reader.fileSize>=Oi){let s=this.reader.requestSlice(this.reader.fileSize-Oi,Oi);D(s)&&(s=await s),w(s),Ie(s,3)==="TAG"&&gm(s,this.metadataTags)}return this.metadataTags}finally{e()}}}class bm{constructor(e){this.demuxer=e}getType(){return"audio"}getNumber(){return 1}getTimeResolution(){return w(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(w(e.firstFrameHeader!==null),w(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){let r=e.reader.fileSize;if(r-e.firstFrameHeaderPos>=Oi){let a=e.reader.requestSlice(r-Oi,3);D(a)&&(a=await a),w(a),Ie(a,3)==="TAG"&&(r-=Oi)}if(r-e.firstFrameHeaderPos>=qs){let a=e.reader.requestSlice(r-qs,qs);if(D(a)&&(a=await a),w(a),Ie(a,8)==="APETAGEX"){a.skip(4);const o=pi(a);a.skip(4);const u=(pi(a)&1<<31)!==0;if(r-=o+(u?qs:0),r<e.firstFrameHeaderPos)throw new Error("Invalid APE tag size.")}}const s=Wf(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate),n=(r-e.firstFrameHeaderPos)/s;return(Math.round(n)*e.firstFrameHeader.audioSamplesInFrame-e.primingDelay)/e.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return et}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return w(this.demuxer.firstFrameHeader),hs(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return w(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...Si}}async getDecoderConfig(){return w(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:hs(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;const r=this.demuxer.loadedSamples[e];if(!r)return null;let s;if(t.metadataOnly)s=mt;else{let n=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(D(n)&&(n=await n),!n)return null;s=X(n,r.dataSize)}return new Ce(s,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{const s=As(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(s===-1)throw new Error("Packet was not created from this track.");const n=s+1;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{r()}}async getPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{const s=this.getSampleRate(),n=Zt(e*s)/s;for(;;){const a=de(this.demuxer.loadedSamples,n,o=>o.timestamp);if(a===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(a,t);if(a>=0&&a+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(a,t);await this.demuxer.advanceReader()}}finally{r()}}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 Vo=1399285583,km=79764919,Xu=new Uint32Array(256);for(let i=0;i<256;i++){let e=i<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^km:e<<1;Xu[i]=e>>>0&4294967295}const Tm=i=>{const e=ie(i),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let r=0;for(let s=0;s<i.length;s++){const n=i[s];r=(r<<8^Xu[r>>>24^n])>>>0}return e.setUint32(22,t,!0),r},to=(i,e,t)=>{let r=0,s=null;if(i.length>0)if(e.codec==="vorbis"){w(e.vorbisInfo);const n=e.vorbisInfo.modeBlockflags.length,o=(1<<Tf(n-1))-1<<1,c=(i[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(s=e.vorbisInfo.blocksizes[l],l===1){const d=(o|1)+1,f=i[0]&d?1:0;u=e.vorbisInfo.blocksizes[f]}r=u+s>>2}else e.codec==="opus"&&(r=au(i).durationInSamples);return{durationInSamples:r,vorbisBlockSize:s}},Yu=i=>{let e="audio/ogg";if(i.codecStrings.length>0){const t=[...new Set(i.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 Ii=27,Cr=282,Zu=Cr+65025,os=i=>{const e=i.filePos;if(pi(i)!==Vo)return null;i.skip(1);const r=Z(i),s=Fp(i),n=pi(i),a=pi(i),o=pi(i),c=Z(i);if(c===0||i.remainingLength<c)return null;const u=new Uint8Array(c);for(let h=0;h<c;h++)u[h]=Z(i);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:r,granulePosition:s,serialNumber:n,sequenceNumber:a,checksum:o,lacingValues:u}},Sm=(i,e,t)=>{for(;i.filePos<e-3;){const r=pi(i),s=r&255,n=r>>>8&255,a=r>>>16&255,o=r>>>24&255,c=79;if(!(s!==c&&n!==c&&a!==c&&o!==c)){if(i.skip(-4),r===Vo){if(t===void 0||i.filePos+18>i.end)return!0;i.skip(14);const u=pi(i);if(i.skip(-18),u===t)return!0}i.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 vc=64,Am=30,xm=19;class Pm extends Ai{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,Ii,Cr);if(D(t)&&(t=await t),!t)break;const r=os(t);if(!r||!!!(r.headerType&2))break;if(this.bitstreams.length===vc)throw new Error(`Too many (> ${vc}) logical bitstreams.`);this.bitstreams.push({serialNumber:r.serialNumber,bosPage:r,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=r.headerStartPos+r.totalSize}for(const t of this.bitstreams){const r=await this.readPacket(t.bosPage,0);r&&(r.data.byteLength>=Am&&r.data[0]===1&&r.data[1]===118&&r.data[2]===111&&r.data[3]===114&&r.data[4]===98&&r.data[5]===105&&r.data[6]===115?await this.readVorbisMetadata(r,t):r.data.byteLength>=xm&&r.data[0]===79&&r.data[1]===112&&r.data[2]===117&&r.data[3]===115&&r.data[4]===72&&r.data[5]===101&&r.data[6]===97&&r.data[7]===100&&await this.readOpusMetadata(r,t),t.codecInfo.codec!==null&&this.trackBackings.push(new Cm(t,this)))}})())}async readVorbisMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;const s=await this.readPacket(r.startPage,r.startSegmentIndex);if(!s||(r=await this.findNextPacketStart(s),!r))return;const n=await this.readPacket(r.startPage,r.startSegmentIndex);if(!n||s.data[0]!==3||n.data[0]!==5)return;const a=ie(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(s.data.length);const d=new Uint8Array(1+u.length+e.data.length+s.data.length+n.data.length);d[0]=2,d.set(u,1),d.set(e.data,1+u.length),d.set(s.data,1+u.length+e.data.length),d.set(n.data,1+u.length+e.data.length+s.data.length),t.codecInfo.codec="vorbis",t.description=d,t.lastMetadataPacket=n,t.numberOfChannels=o,t.sampleRate=c;const f=a.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(f&15),1<<(f>>4)],modeBlockflags:ou(n.data).modeBlockflags},Oa(s.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const r=await this.findNextPacketStart(e);if(!r)return;const s=await this.readPacket(r.startPage,r.startSegmentIndex);if(!s)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=s;const n=vs(e.data);t.numberOfChannels=n.outputChannelCount,t.sampleRate=Wi,t.codecInfo.opusInfo={preSkip:n.preSkip},Oa(s.data.subarray(8),this.metadataTags)}async readPacket(e,t){w(t<e.lacingValues.length);let r=0;for(let d=0;d<t;d++)r+=e.lacingValues[d];let s=e,n=r,a=t;const o=[];e:for(;;){let d=this.reader.requestSlice(s.dataStartPos,s.dataSize);if(D(d)&&(d=await d),!d)return null;const f=X(d,s.dataSize);for(;;){if(a===s.lacingValues.length){o.push(f.subarray(r,n));break}const p=s.lacingValues[a];if(n+=p,p<255){o.push(f.subarray(r,n));break e}a++}let h=s.headerStartPos+s.totalSize;for(;;){let p=this.reader.requestSliceRange(h,Ii,Cr);if(D(p)&&(p=await p),!p)return null;const m=os(p);if(!m)return null;if(s=m,s.serialNumber===e.serialNumber)break;h=s.headerStartPos+s.totalSize}r=0,n=0,a=0}const c=o.reduce((d,f)=>d+f.length,0);if(c===0)throw new Error("Invalid Ogg stream: empty packets are only allowed at the very end of a stream.");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:s,endSegmentIndex:a}}async findNextPacketStart(e){let t=e.endPage,r=e.endSegmentIndex+1;if(r===t.lacingValues.length){if(!!(t.headerType&4))return null;let a=t.headerStartPos+t.totalSize;for(;;){let o=this.reader.requestSliceRange(a,Ii,Cr);if(D(o)&&(o=await o),!o)return null;const c=os(o);if(!c)return null;if(c.serialNumber===t.serialNumber){t=c,r=0;break}a=c.headerStartPos+c.totalSize}}return!!(t.headerType&4)&&r===t.lacingValues.length-1&&t.lacingValues[r]===0?null:{startPage:t,startSegmentIndex:r}}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.trackBackings.map(t=>t.getDecoderConfig().then(r=>(r==null?void 0:r.codec)??null)));return Yu({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class Cm{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new Jt,this.firstTimestampInSamplesPromise=null;const r=e.codecInfo.codec;w(r),r==="vorbis"?this.internalSampleRate=e.sampleRate:r==="opus"?this.internalSampleRate=Wi:(xe(r),w(!1))}getType(){return"audio"}getNumber(){const e=this.demuxer.trackBackings.findIndex(t=>t.bitstream===this.bitstream);return w(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 w(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 et}getDisposition(){return{...Si,primary:!1}}granulePositionToTimestampInSamples(e){const t=this.bitstream.codecInfo.codec;if(w(t),t==="vorbis")return e;if(t==="opus")return w(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip;xe(t),w(!1)}createEncodedPacketFromOggPacket(e,t,r){if(!e)return null;const{durationInSamples:s,vorbisBlockSize:n}=to(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new Ce(r.metadataOnly?mt:e.data,"key",t.timestampInSamples/this.internalSampleRate,s/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:s,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:n}),a}getFirstTimestampInSamples(){return this.firstTimestampInSamplesPromise??(this.firstTimestampInSamplesPromise=(async()=>{const e=this.granulePositionToTimestampInSamples(0);w(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return e;let r=null,s=0,n=null,a=null;for(;t;){const l=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);if(!l||(r??(r=l.endPage),l.endPage.headerStartPos!==r.headerStartPos))break;const{durationInSamples:d,vorbisBlockSize:f}=to(l.data,this.bitstream.codecInfo,a);s+=d,n??(n=d),a=f,t=await this.demuxer.findNextPacketStart(l)}if(!r)return e;w(n!==null);const o=r.granulePosition-s;if(r.granulePosition!==-1&&!(r.headerType&4))return e+o;const c=this.bitstream.codecInfo.codec;w(c);let u;return c==="vorbis"?u=-n:c==="opus"?u=0:(xe(c),w(!1)),e+Math.max(o,u)})())}async getFirstPacket(e){w(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;const r=await this.getFirstTimestampInSamples(),s=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:r,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){const r=this.encodedPacketToMetadata.get(e);if(!r)throw new Error("Packet was not created from this track.");const s=await this.demuxer.findNextPacketStart(r.packet);if(!s)return null;const n=r.timestampInSamples+r.durationInSamples,a=await this.demuxer.readPacket(s.startPage,s.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:n,vorbisLastBlocksize:r.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);const r=Zt(e*this.internalSampleRate),s=await this.getFirstTimestampInSamples();if(r===s)return this.getFirstPacket(t);if(r<s)return null;w(this.bitstream.lastMetadataPacket);const n=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!n)return null;let a=n.startPage,o=this.demuxer.reader.fileSize;const c=[a];e:for(;a.headerStartPos+a.totalSize<o;){const S=a.headerStartPos,A=Math.floor((S+o)/2);let x=A;for(;;){const T=Math.min(x+Zu,o-Ii);let P=this.demuxer.reader.requestSlice(x,Math.max(T-x,0));if(D(P)&&(P=await P),!P||!Sm(P,T,this.bitstream.serialNumber)){if(o<=A+Ii)break e;o=A+Ii;continue e}const C=P.filePos;let _=this.demuxer.reader.requestSliceRange(C,Ii,Cr);D(_)&&(_=await _);const I=_&&os(_);if(!I||I.serialNumber!==this.bitstream.serialNumber){x=C+4;continue}if(I.granulePosition===-1){x=I.headerStartPos+I.totalSize;continue}this.granulePositionToTimestampInSamples(I.granulePosition)>r||I.headerStartPos+I.totalSize>this.demuxer.reader.fileSize?o=I.headerStartPos:(a=I,c.push(I));continue e}}let u=n.startPage;for(const S of c){if(S.granulePosition===a.granulePosition)break;(!u||S.headerStartPos>u.headerStartPos)&&(u=S)}let l=u;const d=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===a.granulePosition);){const S=l.headerStartPos+l.totalSize;let A=this.demuxer.reader.requestSliceRange(S,Ii,Cr);D(A)&&(A=await A);const x=A&&os(A);if(!x){l=a,d.push(a);break}l=x,l.serialNumber===this.bitstream.serialNumber&&d.push(l)}let f=null,h,p,m=l,g=0;if(l.headerStartPos===n.startPage.headerStartPos)h=s,p=!0,f=0;else{w(l.granulePosition!==-1),h=0,p=!1;for(let x=l.lacingValues.length-1;x>=0;x--)if(l.lacingValues[x]<255){f=x+1;break}if(f===null)throw new Error("Invalid page with granule position: no packets end on this page.");g=f-1;const S={data:mt,endPage:m,endSegmentIndex:g},A=await this.demuxer.findNextPacketStart(S);if(A){const x=Fc(d,l,f);w(x);const T=Bc(d,x.page,x.segmentIndex);T?(l=T.page,f=T.segmentIndex):(l=A.startPage,f=A.startSegmentIndex,h=this.granulePositionToTimestampInSamples(m.granulePosition),p=!0)}else for(;;){const x=Fc(d,l,f);if(!x)break;const T=Bc(d,x.page,x.segmentIndex);if(!T)break;if(l=T.page,f=T.segmentIndex,x.page.headerStartPos!==m.headerStartPos){m=x.page,g=x.segmentIndex;break}}}let y=null,b=null;for(;l!==null;){w(f!==null);const S=await this.demuxer.readPacket(l,f);if(!S)break;if(!(l.headerStartPos===n.startPage.headerStartPos&&f<n.startSegmentIndex)){let T=this.createEncodedPacketFromOggPacket(S,{timestampInSamples:h,vorbisLastBlocksize:(b==null?void 0:b.vorbisBlockSize)??null},t);w(T);let P=this.encodedPacketToMetadata.get(T);if(w(P),!p&&S.endPage.headerStartPos===m.headerStartPos&&S.endSegmentIndex===g?(h=this.granulePositionToTimestampInSamples(m.granulePosition),p=!0,T=this.createEncodedPacketFromOggPacket(S,{timestampInSamples:h-P.durationInSamples,vorbisLastBlocksize:(b==null?void 0:b.vorbisBlockSize)??null},t),w(T),P=this.encodedPacketToMetadata.get(T),w(P)):h+=P.durationInSamples,y=T,b=P,p&&(h>r||P.timestampInSamples===r))break}const x=await this.demuxer.findNextPacketStart(S);if(!x)break;l=x.startPage,f=x.startSegmentIndex}return y}async getPacketSequential(e,t){const r=await this.sequentialScanMutex.acquire();try{const s=Zt(e*this.internalSampleRate);e=s/this.internalSampleRate;const n=de(this.sequentialScanCache,s,c=>c.timestampInSamples);let a;if(n!==-1){const c=this.sequentialScanCache[n];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);w(u),this.sequentialScanCache.length>0&&w(Te(this.sequentialScanCache).timestampInSamples<=u.timestampInSamples),this.sequentialScanCache.push(u)}}return a}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Bc=(i,e,t)=>{let r=e,s=t;e:for(;;){for(s--,s;s>=0;s--)if(r.lacingValues[s]<255){s++;break e}if(w(s===-1),!(r.headerType&1)){s=0;break}const a=Ll(i,o=>o.headerStartPos<r.headerStartPos);if(!a)return null;r=a,s=r.lacingValues.length}if(w(s!==-1),s===r.lacingValues.length){const n=i[i.indexOf(r)+1];w(n),r=n,s=0}return{page:r,segmentIndex:s}},Fc=(i,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};const r=Ll(i,s=>s.headerStartPos<e.headerStartPos);return r?{page:r,segmentIndex:r.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 ze;(function(i){i[i.PCM=1]="PCM",i[i.IEEE_FLOAT=3]="IEEE_FLOAT",i[i.ALAW=6]="ALAW",i[i.MULAW=7]="MULAW",i[i.EXTENSIBLE=65534]="EXTENSIBLE"})(ze||(ze={}));class _m extends Ai{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.dataSizeCapped=!1,this.dataSizeIsPlaceholder=!1,this.audioInfo=null,this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=this.reader.requestSlice(0,12);D(e)&&(e=await e),w(e);const t=Ie(e,4),r=t!=="RIFX",s=t==="RF64",n=Mi(e,r);let a=!s&&n===0,o=s||a||n===4294967295?this.reader.fileSize:Math.min(n+8,this.reader.fileSize??1/0);if(Ie(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let u=0,l=null,d=e.filePos;for(;o===null||d<o;){let h=this.reader.requestSlice(d,8);if(D(h)&&(h=await h),!h)break;const p=Ie(h,4);let m=Mi(h,r);const g=h.filePos;if(s&&u===0&&p!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(p==="fmt ")await this.parseFmtChunk(g,m,r);else if(p==="data"){if(l??(l=m),(a&&l===0||!s&&l===4294967295)&&(l=Number.MAX_SAFE_INTEGER,m=l),this.dataSizeIsPlaceholder=l===Number.MAX_SAFE_INTEGER,s&&(m=l),this.dataStart=h.filePos,this.dataSize=Math.max(Math.min(l,(o??1/0)-this.dataStart),0),this.reader.fileSize===null)break}else if(p==="ds64"){let y=this.reader.requestSlice(g,m);if(D(y)&&(y=await y),!y)break;if(m<16)throw new Error('Invalid RF64 file: "ds64" chunk is too small.');const b=Math.min(dl(y,r),Number.MAX_SAFE_INTEGER);l=Math.min(dl(y,r),Number.MAX_SAFE_INTEGER),a=b===0,o=a?this.reader.fileSize:Math.min(b+8,this.reader.fileSize??1/0)}else p==="LIST"?await this.parseListChunk(g,m,r):(p==="ID3 "||p==="id3 ")&&await this.parseId3Chunk(g,m);d=g+m+(m&1),u++}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 f=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/f)*f,this.maybeCapDataSize(),this.trackBackings.push(new Em(this))})())}async parseFmtChunk(e,t,r){let s=this.reader.requestSlice(e,t);if(D(s)&&(s=await s),!s)return;if(t<14)throw new Error('Invalid WAVE file - "fmt " chunk is too small');let n=Yr(s,r);const a=Yr(s,r),o=Mi(s,r);s.skip(4);const c=Yr(s,r);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=Yr(s,r),t>=18&&n!==357){const l=Yr(s,r),d=t-18;if(Math.min(d,l)>=22&&n===ze.EXTENSIBLE){s.skip(6);const h=X(s,16);n=h[0]|h[1]<<8}}if((n===ze.MULAW||n===ze.ALAW)&&(u=8),n!==ze.PCM&&n!==ze.IEEE_FLOAT&&n!==ze.ALAW&&n!==ze.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${n}). Only integer/float PCM, A-law, and μ-law are supported.`);if(n===ze.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(n===ze.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:n,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(u/8),blockSizeInBytes:c}}async parseListChunk(e,t,r){var o,c,u,l,d,f,h,p,m,g,y;if(t<4)return;let s=this.reader.requestSlice(e,t);if(D(s)&&(s=await s),!s)return;const n=Ie(s,4);if(n!=="INFO"&&n!=="INF0")return;let a=s.filePos;for(;a<=e+t-8;){s.filePos=a;const b=Ie(s,4),S=Mi(s,r);if(S>s.remainingLength)break;const A=X(s,S),x=A.indexOf(0),T=A.subarray(0,x===-1?A.length:x);let P;try{P=ff.decode(T)}catch{P="";for(const C of T)P+=String.fromCharCode(C)}switch((o=this.metadataTags).raw??(o.raw={}),this.metadataTags.raw[b]=P,b){case"INAM":case"TITL":(c=this.metadataTags).title??(c.title=P);break;case"TIT3":(u=this.metadataTags).description??(u.description=P);break;case"IART":(l=this.metadataTags).artist??(l.artist=P);break;case"IPRD":(d=this.metadataTags).album??(d.album=P);break;case"IPRT":case"ITRK":case"TRCK":{const C=P.split("/"),_=Number.parseInt(C[0],10),I=C[1]&&Number.parseInt(C[1],10);Number.isInteger(_)&&_>0&&((f=this.metadataTags).trackNumber??(f.trackNumber=_)),I&&Number.isInteger(I)&&I>0&&((h=this.metadataTags).tracksTotal??(h.tracksTotal=I))}break;case"ICRD":{const C=Fr(P);C&&((p=this.metadataTags).date??(p.date=C))}break;case"YEAR":{const C=Number.parseInt(P,10),_=un(C);C>0&&!Number.isNaN(_.getTime())&&((m=this.metadataTags).date??(m.date=_))}break;case"IGNR":case"GENR":(g=this.metadataTags).genre??(g.genre=P);break;case"ICMT":case"CMNT":case"COMM":(y=this.metadataTags).comment??(y.comment=P);break}a+=8+S+(S&1)}}async parseId3Chunk(e,t){if(t<bi)return;let r=this.reader.requestSlice(e,t);if(D(r)&&(r=await r),!r)return;const s=Bs(r);if(s){const n=t-bi;if(s.size=Math.min(s.size,n),s.size>0){const a=r.slice(e+bi,s.size);Vn(a,s,this.metadataTags)}}}getCodec(){if(w(this.audioInfo),this.audioInfo.format===ze.MULAW)return"ulaw";if(this.audioInfo.format===ze.ALAW)return"alaw";if(this.audioInfo.format===ze.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===ze.IEEE_FLOAT){if(this.audioInfo.sampleSizeInBytes===4)return"pcm-f32";if(this.audioInfo.sampleSizeInBytes===8)return"pcm-f64"}w(!1)}maybeCapDataSize(){if(w(this.audioInfo),this.dataSizeCapped)return;const e=this.reader.fileSize;e!==null&&(this.dataSize=Math.min(this.dataSize,Js(e-this.dataStart,this.audioInfo.blockSizeInBytes)),this.dataSizeCapped=!0)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const fr=2048;class Em{constructor(e){this.demuxer=e}getType(){return"audio"}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(w(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return w(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 w(this.demuxer.dataSize!==-1),this.demuxer.maybeCapDataSize(),this.demuxer.dataSizeIsPlaceholder&&!this.demuxer.dataSizeCapped?null:this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return et}getDisposition(){return{...Si}}async getPacketAtIndex(e,t){w(e>=0),w(this.demuxer.audioInfo);const r=this.demuxer.audioInfo.blockSizeInBytes;this.demuxer.maybeCapDataSize();const s=this.demuxer.reader.fileSize,n=e*fr*r;if(n>=this.demuxer.dataSize)return null;const a=Math.min(fr*r,this.demuxer.dataSize-n);if(s===null){let l=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,a);if(D(l)&&(l=await l),!l)return w(this.demuxer.reader.fileSize!==null),this.getPacketAtIndex(e,t)}let o;if(t.metadataOnly)o=mt;else{let l=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,a);D(l)&&(l=await l),w(l),o=X(l,a)}const c=e*fr/this.demuxer.audioInfo.sampleRate,u=a/r/this.demuxer.audioInfo.sampleRate;return new Ce(o,"key",c,u,e,a)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){w(this.demuxer.audioInfo);const r=Math.floor(Math.min(Zt(e*this.demuxer.audioInfo.sampleRate)/fr,(this.demuxer.dataSize-1)/(fr*this.demuxer.audioInfo.blockSizeInBytes)));if(r<0)return null;const s=await this.getPacketAtIndex(r,t);return s||this.getPacket(e,t)}getNextPacket(e,t){w(this.demuxer.audioInfo);const r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/fr);return this.getPacketAtIndex(r+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 Ut=7,Et=9,io=async(i,e,t,r)=>{const s=(a,o)=>a.objectType===o.objectType&&a.samplingFrequencyIndex===o.samplingFrequencyIndex&&a.channelConfiguration===o.channelConfiguration;let n=i.requestSliceRange(e,Ut,t+Et);if(D(n)&&(n=await n),!n)return null;for(let a=e;a<Math.min(e+t,n.end);a++){if(n.filePos=a,Z(n)!==255)continue;n.filePos=a;const o=Ti(n);if(!o||r&&!s(o,r))continue;const c=a+o.frameLength;if(c===i.fileSize)return o;let u=i.requestSliceRange(c,Ut,Et);D(u)&&(u=await u);const l=u&&Ti(u);if(l&&s(o,l))return o}return null},Ti=i=>{const e=i.filePos;if(i.remainingLength<Ut)return null;const t=X(i,Ut),r=new oe(t);if(r.readBits(12)!==4095||(r.skipBits(1),r.readBits(2)!==0))return null;const a=r.readBits(1),o=r.readBits(2)+1,c=r.readBits(4);if(c>=Ot.length)return null;r.skipBits(1);const u=r.readBits(3);r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const l=r.readBits(13);r.skipBits(11);const d=r.readBits(2)+1;if(d!==1)return null;let f=null;if(a===0){if(i.remainingLength<2)return null;f=De(i)}return l<i.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 ro=1024;class Im extends Ai{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.numberOfChannels=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new Jt,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();const e=this.firstFrameHeader;if(w(e),e.channelConfiguration===0){const t=e.crcCheck===null?Ut:Et;let r=this.reader.requestSlice(e.startPos+t,e.frameLength-t);if(D(r)&&(r=await r),!r)throw new Error("Invalid ADTS file: the first frame is cut off.");const s=Rr(X(r,e.frameLength-t));if(!s)throw new Error("Invalid ADTS file: frames with channel configuration 0 must begin with a program config element.");this.numberOfChannels=Cs(s.programConfigElement)}else this.numberOfChannels=Vr[e.channelConfiguration];this.trackBackings=[new vm(this)]})())}async advanceReader(){let e;if(this.lastLoadedPos===0){const s=await sr(this.reader,0);e=await io(this.reader,s,4096,null)}else{let s=this.reader.requestSliceRange(this.lastLoadedPos,Ut,Et);if(D(s)&&(s=await s),e=s&&Ti(s),!e){w(this.firstFrameHeader);const n=await sr(this.reader,this.lastLoadedPos);e=await io(this.reader,n,2**16,this.firstFrameHeader)}}if(!e){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&e.startPos+e.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader??(this.firstFrameHeader=e);const t=Ot[this.firstFrameHeader.samplingFrequencyIndex];if(w(t!==void 0),e.samplingFrequencyIndex!==this.firstFrameHeader.samplingFrequencyIndex){K._warn(`The sample rate changes mid-stream (from ${t} Hz to ${Ot[e.samplingFrequencyIndex]} Hz), which isn't properly supported or handled by Mediabunny.`),this.lastSampleLoaded=!0;return}const r={timestamp:this.nextTimestampInSamples/t,duration:ro/t,dataStart:e.startPos,dataSize:e.frameLength};this.loadedSamples.push(r),this.nextTimestampInSamples+=ro,this.lastLoadedPos=e.startPos+e.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 r=this.reader.requestSlice(t,bi);if(D(r)&&(r=await r),!r)break;const s=Bs(r);if(!s)break;let n=this.reader.requestSlice(r.filePos,s.size);if(D(n)&&(n=await n),!n)break;Vn(n,s,this.metadataTags),t=r.filePos+s.size}return this.metadataTags}finally{e()}}}class vm{constructor(e){this.demuxer=e}getType(){return"audio"}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return et}getCodec(){return"aac"}getInternalCodecId(){return w(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){return w(this.demuxer.numberOfChannels!==null),this.demuxer.numberOfChannels}getSampleRate(){w(this.demuxer.firstFrameHeader);const e=Ot[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return w(e!==void 0),e}getDisposition(){return{...Si}}async getDecoderConfig(){return w(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 r=this.demuxer.loadedSamples[e];if(!r)return null;let s;if(t.metadataOnly)s=mt;else{let n=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(D(n)&&(n=await n),!n)return null;s=X(n,r.dataSize)}return new Ce(s,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{const s=As(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(s===-1)throw new Error("Packet was not created from this track.");const n=s+1;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{r()}}async getPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{const s=this.getSampleRate(),n=Zt(e*s)/s;for(;;){const a=de(this.demuxer.loadedSamples,n,o=>o.timestamp);if(a===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(a,t);if(a>=0&&a+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(a,t);await this.demuxer.advanceReader()}}finally{r()}}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 Ju=i=>i===0?null:i===1?192:i>=2&&i<=5?144*2**i:i===6?"uncommon-u8":i===7?"uncommon-u16":i>=8&&i<=15?2**i:null,Bm=(i,e)=>{switch(i){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}},ed=i=>{let e=0;const t=new oe(X(i,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);const r=[],s=e-1,n=new oe(X(i,s)),a=8-e-1;for(let c=0;c<a;c++)r.unshift(t.readBits(1));for(let c=0;c<s;c++)for(let u=0;u<8;u++){const l=n.readBits(1);u<2||r.unshift(l)}return r.reduce((c,u,l)=>c+u*2**l,0)},td=(i,e)=>{if(e==="uncommon-u16")return De(i)+1;if(e==="uncommon-u8")return Z(i)+1;if(typeof e=="number")return e;xe(e),w(!1)},Fm=(i,e)=>e==="uncommon-u16"?De(i):e==="uncommon-u16-10"?De(i)*10:e==="uncommon-u8"?1e3*Z(i):typeof e=="number"?e:null,Rm=i=>{let t=0;for(const r of i){t^=r;for(let s=0;s<8;s++)(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 Mm extends Ai{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 Jt,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),w(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{var t;let e=0;for(;;){let r=this.reader.requestSlice(e,bi);if(D(r)&&(r=await r),!r)break;const s=Bs(r);if(!s)break;let n=this.reader.requestSlice(r.filePos,s.size);D(n)&&(n=await n),w(n),Vn(n,s,this.metadataTags),e=r.filePos+s.size}for(e+=4;this.reader.fileSize===null||e<this.reader.fileSize;){let r=this.reader.requestSlice(e,4);if(D(r)&&(r=await r),e+=4,r===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);w(r);const s=Z(r),n=ai(r),a=(s&128)!==0;switch(s&127){case yi.STREAMINFO:{if(n<34)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let c=this.reader.requestSlice(e,n);if(D(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 oe(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 g=l.readBits(3)+1;l.readBits(5);const y=l.readBits(36);l.skipBits(128);const b=new Uint8Array(42);b.set(new Uint8Array([102,76,97,67]),0),b.set(new Uint8Array([128,0,0,34]),4),b.set(u,8),this.audioInfo={numberOfChannels:g,sampleRate:m,totalSamples:y,minimumBlockSize:d,maximumBlockSize:f,minimumFrameSize:h,maximumFrameSize:p,description:b},this.trackBacking=new Dm(this);break}case yi.VORBIS_COMMENT:{let c=this.reader.requestSlice(e,n);if(D(c)&&(c=await c),!c)throw new Error(`Vorbis comment block at position ${e} exceeds the file. Corrupted file.`);Oa(X(c,n),this.metadataTags);break}case yi.PICTURE:{let c=this.reader.requestSlice(e,n);if(D(c)&&(c=await c),!c)throw new Error(`Picture block at position ${e} exceeds the file. Corrupted file.`);try{const u=q(c),l=q(c),d=nt.decode(X(c,l)),f=q(c),h=nt.decode(X(c,f));c.skip(16);const p=q(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+=n,a)break}if(this.lastLoadedPos=e,!this.audioInfo)throw new Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})())}async readNextFlacFrame(e){w(this.audioInfo);const t=6,r=16,s=10,n=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+r+2,a=this.audioInfo.minimumFrameSize||s,c=(this.audioInfo.maximumFrameSize||n)+r,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(Z(u)===255){const f=u.filePos,h=Z(u),p=this.blockingBit===1?249:248;if(h!==p){u.filePos=f;continue}u.skip(-2);const m=u.filePos-e,g=this.readFlacFrameHeader(u);if(!g){u.filePos=f;continue}if(this.blockingBit===0){if(g.num-l.num!==1){u.filePos=f;continue}}else if(g.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,r=X(e,4),s=new oe(r);if(s.readBits(15)!==32764)return null;const a=s.readBits(1);if(this.blockingBit!==null&&a!==this.blockingBit)return null;const o=Ju(s.readBits(4));if(!o)return null;w(this.audioInfo);const c=Bm(s.readBits(4),this.audioInfo.sampleRate);if(!c||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;const l=Z(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=ed(e),p=td(e,o),m=Fm(e,c);if(m===null||m!==this.audioInfo.sampleRate)return null;const g=e.filePos-t,y=Z(e);e.skip(-g),e.skip(-1);const b=Rm(X(e,g));return y!==b?null:(this.blockingBit=a,{num:h,blockSize:p,sampleRate:m})}async advanceReader(){await this.readMetadata(),w(this.lastLoadedPos!==null),w(this.audioInfo);const e=this.lastLoadedPos,t=await this.readNextFlacFrame(e);if(!t){this.lastSampleLoaded=!0;return}const r=this.loadedSamples[this.loadedSamples.length-1],n={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(n),t.isLastFrame){this.lastSampleLoaded=!0;return}}}class Dm{constructor(e){this.demuxer=e}getType(){return"audio"}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return w(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return et}getTimeResolution(){return w(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 w(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...Si}}async getDecoderConfig(){return w(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(w(this.demuxer.audioInfo),e<0)return null;const r=await this.demuxer.readingMutex.acquire();try{const s=Zt(e*this.demuxer.audioInfo.sampleRate);for(;;){const n=de(this.demuxer.loadedSamples,s,o=>o.blockOffset);if(n===-1){if(this.demuxer.lastSampleLoaded)return null;await this.demuxer.advanceReader();continue}const a=this.demuxer.loadedSamples[n];if(a.blockOffset+a.blockSize<=s){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(n,t)}}finally{r()}}async getNextPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{const s=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&s>=this.demuxer.loadedSamples.length)return null;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){const r=this.demuxer.loadedSamples[e];if(!r)return null;let s;if(t.metadataOnly)s=mt;else{let o=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(D(o)&&(o=await o),!o)return null;s=X(o,r.byteSize)}w(this.demuxer.audioInfo);const n=r.blockOffset/this.demuxer.audioInfo.sampleRate,a=r.blockSize/this.demuxer.audioInfo.sampleRate;return new Ce(s,"key",n,a,e,r.byteSize)}async getFirstPacket(e){const t=await this.demuxer.readingMutex.acquire();try{for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}finally{t()}}}/*!
|
|
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 lt=9e4,ks=2**33,ct=188,id=i=>{let e="video/MP2T";const t=[...new Set(i.filter(Boolean))];return t.length>0&&(e+=`; codecs="${t.join(", ")}"`),e},so=i=>Hl(Math.round(lt*i),ks),rd=i=>{const e=60*lt;return{reference:i>=ks-e?i-e-ks:i-e}},sd=(i,e)=>e.reference+Hl(i-e.reference,ks);/*!
|
|
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 nd="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.",Rc=5,zm=1212435798,Om=1212436562,Um=1146376960,Nm=new Set([133,134,162]),Mc=new Set;class Wo extends Ai{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=ct+16+1;let t=this.reader.requestSlice(0,e);D(t)&&(t=await t),w(t);const r=X(t,e);if(r[0]===71&&r[ct]===71)this.packetOffset=0,this.packetStride=ct;else if(r[0]===71&&r[ct+16]===71)this.packetOffset=0,this.packetStride=ct+16;else if(r[4]===71&&r[4+ct+4]===71)this.packetOffset=4,this.packetStride=ct+4;else throw new Error("Unreachable.");const s=256;this.minReferencePointByteDistance=s*this.packetStride;let n=this.packetOffset,a=null,o=!1,c=!1;for(;;){const u=await this.readPacketHeader(n);if(!u)break;if(u.payloadUnitStartIndicator===0){n+=this.packetStride;continue}if(c&&!this.elementaryStreams.some(m=>m.pid===u.pid&&!m.initialized)){n+=this.packetStride;continue}const l=this.elementaryStreams.some(m=>m.pid===u.pid),d=await this.readSection(n,!l,!c);if(!d)break;const f=32;let h=!1;if(!c&&d.pid!==0&&(a===null||d.pid===a)&&!(d.payload[0]===0&&d.payload[1]===0&&d.payload[2]===1)){const g=new oe(d.payload),y=g.readAlignedByte();g.skipBits(8*y),h=g.readBits(8)===2}if(d.pid===0&&!o){const m=new oe(d.payload),g=m.readAlignedByte();m.skipBits(8*g),m.skipBits(14);const y=m.readBits(10),b=m.pos+8*y;for(m.skipBits(40);b-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(h){const m=new oe(d.payload),g=m.readAlignedByte();m.skipBits(8*g),m.skipBits(12);const y=m.readBits(12),b=m.pos+8*y;m.skipBits(43),m.readBits(13),m.skipBits(6);const S=m.readBits(10),A=m.pos+8*S;let x=!1;for(;m.pos<A;){const T=m.readBits(8),P=m.readBits(8),C=m.pos+8*P;if(T===Rc&&P>=4){const _=m.readBits(32);x||(x=_===zm||_===Om)}m.pos=C}for(m.pos=A;b-m.pos>f;){const T=m.readBits(8);m.skipBits(3);const P=m.readBits(13);m.skipBits(6);const C=m.readBits(10),_=m.pos+8*C;let I=!1,v=!1,R=!1;for(;m.pos<_;){const O=m.readBits(8),U=m.readBits(8),L=m.pos+8*U;if(O===106)I=!0;else if(O===122||O===204)v=!0;else if(O===123)R=!0;else if(O===Rc&&U>=4){const Q=m.readBits(32);R||(R=(Q&4294967040)===Um)}m.pos=L}let F=null;const H=x&&Nm.has(T)?130:T;switch(H){case 27:case 36:F={type:"video",codec:T===27?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:case 130:case 138:{let O;H===3||H===4?O="mp3":H===15?O="aac":H===129?O="ac3":H===135?O="eac3":O="dts",F={type:"audio",codec:O,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:v?F={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:I?F={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:R&&(F={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:Mc.has(T)||(K._warn(`Note: MPEG-TS streams with stream_type 0x${T.toString(16)} are not currently supported.`),Mc.add(T))}F&&this.elementaryStreams.push({demuxer:this,pid:P,streamType:T,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:F,referencePesPackets:[]})}c=!0}else{const m=this.elementaryStreams.find(g=>g.pid===d.pid);e:if(m&&!m.initialized){if(!li(this,d,!0))throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${m.pid}`);if(m.firstSection=d,m.canBeTrustedWithKeyPackets=d.randomAccessIndicator===1,this.input._initInput){const b=await this.input._initInput._getDemuxer();if(b.constructor!==Wo)throw new Error("Init input must match the input's format.");await b.readMetadata();const S=b.elementaryStreams.find(A=>A.pid===d.pid&&A.info.codec===m.info.codec&&A.initialized);if(S){m.info=S.info,m.initialized=!0;break e}}const y=new ss(m,d.startPos);if(m.info.type==="video"){for(;;){const b=y;if(b.suppliedPacket=null,await y.markNextPacket(),m.info.codec==="avc"){if(!y.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(m.info.avcCodecInfo=_s(y.suppliedPacket.data),!m.info.avcCodecInfo)continue;const S=m.info.avcCodecInfo.sequenceParameterSets[0];w(S);const A=Zi(S);m.info.width=A.displayWidth,m.info.height=A.displayHeight;const x=A.pixelAspectRatio.num,T=A.pixelAspectRatio.den;m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=m.info.height,x>0&&T>0&&(x>T?m.info.squarePixelWidth=Math.round(m.info.width*x/T):m.info.squarePixelHeight=Math.round(m.info.height*T/x)),m.info.colorSpace={primaries:di[A.colourPrimaries],transfer:fi[A.transferCharacteristics],matrix:hi[A.matrixCoefficients],fullRange:!!A.fullRangeFlag},m.info.reorderSize=A.maxDecFrameBuffering;break}else if(m.info.codec==="hevc"){if(!y.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(m.info.hevcCodecInfo=Is(y.suppliedPacket.data),!m.info.hevcCodecInfo)continue;const A=m.info.hevcCodecInfo.arrays.find(C=>C.nalUnitType===ke.SPS_NUT).nalUnits[0];w(A);const x=Un(A);m.info.width=x.displayWidth,m.info.height=x.displayHeight;const T=x.pixelAspectRatio.num,P=x.pixelAspectRatio.den;m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=m.info.height,T>0&&P>0&&(T>P?m.info.squarePixelWidth=Math.round(m.info.width*T/P):m.info.squarePixelHeight=Math.round(m.info.height*P/T)),m.info.colorSpace={primaries:di[x.colourPrimaries],transfer:fi[x.transferCharacteristics],matrix:hi[x.matrixCoefficients],fullRange:!!x.fullRangeFlag},m.info.reorderSize=x.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}m.info.decoderConfig={codec:jn({width:m.info.width,height:m.info.height,codec:m.info.codec,codecDescription:null,colorSpace:m.info.colorSpace,avcType:1,avcCodecInfo:m.info.avcCodecInfo,hevcType:"hev1",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 y.markNextPacket(),!y.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${m.pid}`);if(m.info.codec==="aac"){const b=at.tempFromBytes(y.suppliedPacket.data),S=Ti(b);if(!S)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");if(m.info.aacCodecInfo={isMpeg2:!1,objectType:S.objectType},S.channelConfiguration===0){const A=S.crcCheck===null?Ut:Et,x=Rr(y.suppliedPacket.data.subarray(A,S.frameLength));if(!x)throw new Error("Invalid AAC audio stream; ADTS frames with channel configuration 0 must begin with a program config element.");m.info.numberOfChannels=Cs(x.programConfigElement)}else m.info.numberOfChannels=Vr[S.channelConfiguration];m.info.sampleRate=Ot[S.samplingFrequencyIndex]}else if(m.info.codec==="mp3"){const b=q(at.tempFromBytes(y.suppliedPacket.data)),S=Mr(b,y.suppliedPacket.data.byteLength);if(!S.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");m.info.numberOfChannels=hs(S.header.channel),m.info.sampleRate=S.header.sampleRate}else if(m.info.codec==="ac3"){const b=cu(y.suppliedPacket.data);if(!b)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(b.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=_o[b.acmod]+b.lfeon,m.info.sampleRate=zn[b.fscod]}else if(m.info.codec==="eac3"){const b=lu(y.suppliedPacket.data);if(!b)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const S=du(b);if(S===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=fu(b),m.info.sampleRate=S}else if(m.info.codec==="dts"){const b=vo(y.suppliedPacket.data);if(!b)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");m.info.numberOfChannels=b.numberOfChannels,m.info.sampleRate=b.sampleRate,b.core&&(m.info.dtsFormat=b.hasExtensions?"dtsh":"dtsc")}else throw new Error("Unhandled.");m.info.decoderConfig={codec:Xo({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;n+=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 Vm(u)):this.trackBackingEntries.push(new Wm(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(r=>(r==null?void 0:r.codec)??null)));return id(e)}async readSection(e,t,r=!1){let s=e,n=e;const a=[];let o=0,c=null,u=!0,l=0;for(;;){const f=await this.readPacket(n);if(n+=this.packetStride,!f)break;if(!c)w(f.payloadUnitStartIndicator===1),c=f;else{if(f.pid!==c.pid)if(r){u=!1;break}else continue;if(f.payloadUnitStartIndicator===1)break}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)),s=n,!t&&o>=64){u=!1;break}if(As(this.sectionEndPositions,s,y=>y)!==-1){u=!1;break}}if(u){const f=de(this.sectionEndPositions,s,h=>h);this.sectionEndPositions.splice(f+1,0,s)}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,pid:c.pid,payload:d,randomAccessIndicator:l}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(D(t)&&(t=await t),!t)return null;if(Z(t)!==71)throw new Error("Invalid TS packet sync byte; the file is likely corrupted.");const s=De(t),n=s>>14&1,a=s&8191,c=Z(t)>>4&3;return{payloadUnitStartIndicator:n,pid:a,adaptationFieldControl:c}}async readPacket(e){let t=this.reader.requestSlice(e,ct);if(D(t)&&(t=await t),!t)return null;const r=X(t,ct);if(r[0]!==71)throw new Error("Invalid TS packet sync byte; the file is likely corrupted.");const n=(r[1]<<8)+r[2],a=n>>14&1,o=n&8191,u=r[3]>>4&3;return{payloadUnitStartIndicator:a,pid:o,adaptationFieldControl:u,body:r.subarray(4)}}normalizeTimestamp(e){return this.timestampWrapInfo??(this.timestampWrapInfo=rd(e)),sd(e,this.timestampWrapInfo)}}const li=(i,e,t)=>{if(e.payload.byteLength<3)return null;const r=new oe(e.payload);if(r.readBits(24)!==1)return null;const n=r.readBits(8);if(r.skipBits(16),n===188||n===190||n===191||n===240||n===241||n===255||n===242||n===248)return null;r.skipBits(8);const a=r.readBits(2);r.skipBits(14);let o=null;if(a===2||a===3)o=0,r.skipBits(4),o+=r.readBits(3)*(1<<30),r.skipBits(1),o+=r.readBits(15)*32768,r.skipBits(1),o+=r.readBits(15),o=i.normalizeTimestamp(o);else if(t)throw new Error(nd);return{sectionStartPos:e.startPos,pts:o,randomAccessIndicator:e.randomAccessIndicator}};class Wn{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getNumber(){const e=this.elementaryStream.demuxer,t=this.elementaryStream.info.type;let r=0;for(const s of e.trackBackingEntries)if(s.getType()===t&&r++,w(s instanceof Wn),s.elementaryStream===this.elementaryStream)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return et}getDisposition(){return{...Si,primary:!1}}getTimeResolution(){return lt}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,r){let s;return this.allPacketsAreKeyPackets()?s="key":s=e.randomAccessIndicator===1?"key":"delta",new Ce(r.metadataOnly?mt:e.data,s,e.pts/lt,Math.max(t/lt,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;w(t);const r=new ss(this.elementaryStream,t.startPos),s=new aa(this,r),n=await s.readNext();if(!n)return null;const a=this.createEncodedPacket(n.packet,n.duration,e);return this.packetBuffers.set(a,s),this.packetSectionStarts.set(a,n.packet.sectionStartPos),a}async getNextPacket(e,t){let r=this.packetBuffers.get(e);if(r){this.packetBuffers.delete(e);const d=await r.readNext();if(!d)return null;const f=this.createEncodedPacket(d.packet,d.duration,t);return this.packetBuffers.set(f,r),this.packetSectionStarts.set(f,d.packet.sectionStartPos),f}const s=this.packetSectionStarts.get(e);if(s===void 0)throw new Error("Packet was not created from this track.");const n=this.elementaryStream.demuxer;let a=s,o=this.getReorderSize(),c=s-n.packetStride;for(;o>0&&c>=n.packetOffset;){const d=await n.readPacketHeader(c);if(w(d),d.pid===this.elementaryStream.pid&&d.payloadUnitStartIndicator===1){const f=await n.readSection(c,!1);w(f);const h=li(n,f,!1);h&&h.pts!==null&&(a=c,o--)}c-=n.packetStride}const u=new ss(this.elementaryStream,a);r=new aa(this,u);const l=e.sequenceNumber;for(;;){const d=await r.readNext();if(!d)return null;if(d.packet.sequenceNumber>l){const f=this.createEncodedPacket(d.packet,d.duration,t);return this.packetBuffers.set(f,r),this.packetSectionStarts.set(f,d.packet.sectionStartPos),f}}}async getNextKeyPacket(e,t){let r=e;for(;;){if(r=await this.getNextPacket(r,t),!r)return null;if(r.type==="key")return r}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,r){var S;const s=Zt(e*lt),n=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=n,c=this.elementaryStream.pid,u=async(A,x)=>{let T=A;for(;T<x;){const P=await n.readPacketHeader(T);if(!P)return null;if(P.pid===c&&P.payloadUnitStartIndicator===1){const C=await n.readSection(T,!1);if(!C)return null;const _=li(n,C,!1);if(_&&_.pts!==null)return _}T+=n.packetStride}return null},l=this.elementaryStream.firstSection;w(l);const d=li(n,l,!0);w(d);let f;const h=this.elementaryStream.referencePesPackets,p=de(h,s,A=>A.pts),m=p!==-1?h[p]:null;if(m&&s-m.pts<lt/2)f=m.sectionStartPos;else{let A=0;if(a.fileSize!==null&&s>=d.pts){const x=Math.ceil(a.fileSize/o);if(x>1){let T=0,P=x-1;for(A=T;T<=P;){const C=Math.floor((T+P)/2),_=Js(C*o,n.packetStride)+d.sectionStartPos,I=_+o,v=await u(_,I);if(!v){P=C-1;continue}v.pts<=s?(A=C,T=C+1):P=C-1}}}f=Js(A*o,n.packetStride)+d.sectionStartPos}let g=await u(f,a.fileSize??1/0);g||(g=d);const y=this.getReorderSize(),b=async(A,x)=>{var R;const T=new ss(this.elementaryStream,A),P=new aa(this,T);for(;!((((R=Te(P.presentationOrderPackets))==null?void 0:R.pts)??-1/0)>=s||!await P.readNextPacket()););const C=Br(P.presentationOrderPackets,x);if(C===-1)return null;const _=P.presentationOrderPackets[C];P.decodeOrderPackets.splice(0,P.decodeOrderPackets.indexOf(_));const I=await P.readNext();w(I);const v=this.createEncodedPacket(I.packet,I.duration,r);return this.packetBuffers.set(v,P),this.packetSectionStarts.set(v,I.packet.sectionStartPos),v};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let A=g.sectionStartPos+n.packetStride;for(;;){const x=await n.readPacketHeader(A);if(!x)break e;if(x.pid===c&&x.payloadUnitStartIndicator===1){const T=await n.readSection(A,!1);if(T){const P=li(n,T,!1);if(P&&P.pts!==null){if(P.pts>s)break e;g=P,no(this.elementaryStream,g);break}}}A+=n.packetStride}}e:for(let A=0;A<y+1;A++){let x=g.sectionStartPos-n.packetStride;for(;x>=d.sectionStartPos;){const T=await n.readPacketHeader(x);if(!T)break e;if(T.pid===c&&T.payloadUnitStartIndicator===1){const P=await n.readSection(x,!1);if(P){const C=li(n,P,!1);if(C&&C.pts!==null){g=C;break}}}x-=n.packetStride}if(x<d.sectionStartPos)break}return b(g.sectionStartPos,A=>A.pts<=s)}else{let A=f,x=null;for(;;){let T=null;const P=A<=d.sectionStartPos;let C;P?C=d:C=await u(A,x??a.fileSize??1/0);let _=!1,I=0,v=null;e:for(;C&&!(x!==null&&C.sectionStartPos>=x);){if(C.pts<=s){let F;if(this.elementaryStream.canBeTrustedWithKeyPackets)F=C.randomAccessIndicator===1;else{for(v??(v=new ss(this.elementaryStream,C.sectionStartPos));(!v.suppliedPacket||v.suppliedPacket.sectionStartPos<C.sectionStartPos)&&(v.suppliedPacket=null,await v.markNextPacket(),!!v.suppliedPacket););F=((S=v.suppliedPacket)==null?void 0:S.sectionStartPos)===C.sectionStartPos&&v.suppliedPacket.randomAccessIndicator===1}F&&(T=C)}if(C.pts>s&&(_=!0),_&&(I++,I>y))break;let R=C.sectionStartPos+n.packetStride;for(;;){const F=await n.readPacketHeader(R);if(!F)break e;if(F.pid===c&&F.payloadUnitStartIndicator===1){const H=await n.readSection(R,!1);if(H){const O=li(n,H,!1);if(O&&O.pts!==null){C=O,no(this.elementaryStream,C);break}}}R+=n.packetStride}}if(T){let R=T;if(I===0)e:for(let H=0;H<y+1;H++){let O=R.sectionStartPos-n.packetStride;for(;O>=d.sectionStartPos;){const U=await n.readPacketHeader(O);if(!U)break e;if(U.pid===c&&U.payloadUnitStartIndicator===1){const L=await n.readSection(O,!1);if(L){const Q=li(n,L,!1);if(Q&&Q.pts!==null){R=Q;break}}}O-=n.packetStride}if(O<d.sectionStartPos)break}const F=await b(R.sectionStartPos,H=>H.pts<=s&&H.randomAccessIndicator===1);if(F)return F}if(P)return null;x=A,A=Math.max(Js(A-d.sectionStartPos-o,n.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}}class Vm extends Wn{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[...cs]}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return w(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Wm extends Wn{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return w(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const no=(i,e)=>{const t=i.referencePesPackets,r=de(t,e.sectionStartPos,n=>n.sectionStartPos),s=i.demuxer.minReferencePointByteDistance;if(r>=0){const n=t[r];if(e.pts<=n.pts||e.sectionStartPos-n.sectionStartPos<s)return!1}if(r<t.length-1){const n=t[r+1];if(n.pts<e.pts||n.sectionStartPos-e.sectionStartPos<s)return!1}return t.splice(r+1,0,{sectionStartPos:e.sectionStartPos,pts:e.pts,randomAccessIndicator:e.randomAccessIndicator}),!0};class ss{constructor(e,t){this.reachedEnd=!1,this.isInPesPacket=!1,this.pesHeaderBytesLeft=0,this.pesDataBytesLeft=0,this.currentPos=0,this.endPos=0,this.scratch=new Uint8Array(2**16),this.scratchStartPos=0,this.pesPackets=[],this.pesPacketDataStartPositions=[],this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.nextTsPacketPos=t}ensureBuffered(e){const t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}async bufferData(e){const t=this.endPos+e;for(;this.endPos<t&&!this.reachedEnd;){const r=this.nextTsPacketPos,s=await this.demuxer.readPacket(r);if(!s){this.reachedEnd=!0;break}if(this.nextTsPacketPos+=this.demuxer.packetStride,s.pid!==this.pid)continue;if(s.payloadUnitStartIndicator===1){this.isInPesPacket=!1;const d=await this.demuxer.readSection(r,!1);w(d);const f=li(this.demuxer,d,!1);if(!f)continue;const h=new oe(d.payload);h.skipBits(32);const p=h.readBits(16),m=6;h.skipBits(16);const g=h.readBits(8);this.pesHeaderBytesLeft=h.pos/8+g,this.pesDataBytesLeft=p>0?Math.max(m+p-this.pesHeaderBytesLeft,0):1/0,this.isInPesPacket=!0,this.pesPackets.push(f),this.pesPacketDataStartPositions.push(this.endPos)}if(!this.isInPesPacket||!(s.adaptationFieldControl&1))continue;const n=s.body;let a=s.adaptationFieldControl&2?1+n[0]:0;const o=Math.min(this.pesHeaderBytesLeft,Math.max(n.byteLength-a,0));this.pesHeaderBytesLeft-=o,a+=o;const c=Math.min(n.byteLength,a+this.pesDataBytesLeft);if(c<=a)continue;const u=c-a;this.pesDataBytesLeft-=u;const l=this.endPos-this.scratchStartPos;if(l+u>this.scratch.byteLength){const d=new Uint8Array(2*this.scratch.byteLength);d.set(this.scratch.subarray(0,l)),this.scratch=d}this.scratch.set(n.subarray(a,c),l),this.endPos+=u}}readBytes(e){const t=this.currentPos-this.scratchStartPos;return this.currentPos+=e,this.scratch.subarray(t,t+e)}readU8(){return this.scratch[this.currentPos++-this.scratchStartPos]}seekTo(e){w(e>=this.scratchStartPos),this.currentPos=e}skip(e){this.seekTo(this.currentPos+e)}async markNextPacket(){var t;w(!this.suppliedPacket);const e=this.elementaryStream;if(e.info.type==="video"){const r=e.info.codec,s=1024;if(r!=="avc"&&r!=="hevc")throw new Error("Unhandled.");const n=r==="avc"?1:2;let a=null,o=!1,c=0;for(;;){let u=this.ensureBuffered(s);if(D(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 g=d[h+1],y=d[h+2],b=d[h+3];let S=0;if(g===0&&y===0&&b===1?S=4:g===0&&y===1&&(S=3),S===0){h++;continue}const A=m;a??(a=A);const x=h+S,T=x+n;if(T+1>f){this.seekTo(m);break}const P=d[x];let C,_,I,v;if(r==="avc")C=rr(P),_=C===Ve.NON_IDR_SLICE||C===Ve.SLICE_DPA||C===Ve.IDR,I=C===Ve.SEI||C===Ve.SPS||C===Ve.PPS||C===Ve.AUD,v=C===Ve.AUD;else{if(C=zi(P),((P&1)<<5|d[x+1]>>3)>0){h+=S;continue}_=C<=ke.RASL_R||C>=ke.BLA_W_LP&&C<=21,I=C>=ke.VPS_NUT&&C<=35||C===ke.PREFIX_SEI_NUT||C>=41&&C<=44||C>=48&&C<=55,v=C===ke.AUD_NUT}let R=!1;if(_){let F;if(r==="avc"){const H=new oe(d.subarray(T));let O;try{O=j(H)}catch{O=null}if(O===null||H.getBitsLeft()<0){this.seekTo(m);break}F=!o||O<=c,c=O}else F=d[T]>>7===1;F&&(o?R=!0:o=!0)}else I&&o?R=!0:v&&(a=A);if(R){const F=A-a;return this.seekTo(a),this.supplyPacket(F,0)}h+=S}if(u<s)break}if(o){w(a!==null);const u=this.endPos-a;return this.seekTo(a),this.supplyPacket(u,0)}}else{const r=e.info.codec,s=128;for(;;){let n=this.ensureBuffered(s);D(n)&&(n=await n);const a=this.currentPos;for(;this.currentPos-a<n;){const o=this.readU8();if(r==="aac"){if(o!==255)continue;this.skip(-1);const c=this.currentPos;let u=this.ensureBuffered(Et);if(D(u)&&(u=await u),u<Et)return;const l=this.readBytes(Et),d=Ti(at.tempFromBytes(l));if(d){this.seekTo(c);let f=this.ensureBuffered(d.frameLength);return D(f)&&(f=await f),this.supplyPacket(f,ro*lt/e.info.sampleRate)}else this.seekTo(c+1)}else if(r==="mp3"){if(o!==255)continue;this.skip(-1);const c=this.currentPos;let u=this.ensureBuffered(Yt);if(D(u)&&(u=await u),u<Yt)return;const l=this.readBytes(Yt),d=ie(l).getUint32(0),f=Mr(d,null);if(f.header){this.seekTo(c);let h=this.ensureBuffered(f.header.totalSize);D(h)&&(h=await h);const p=f.header.audioSamplesInFrame*lt/e.info.sampleRate;return this.supplyPacket(h,p)}else this.seekTo(c+1)}else if(r==="ac3"){if(o!==11)continue;this.skip(-1);const c=this.currentPos;let u=this.ensureBuffered(5);if(D(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=ah[3*f+d];w(h!==void 0),this.seekTo(c),u=this.ensureBuffered(h),D(u)&&(u=await u);const p=oh*lt/e.info.sampleRate;return this.supplyPacket(u,p)}else if(r==="eac3"){if(o!==11)continue;this.skip(-1);const c=this.currentPos;let u=this.ensureBuffered(5);if(D(u)&&(u=await u),u<5)return;const l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(c+1);continue}let f=(((l[2]&7)<<8|l[3])+1)*2;const p=l[4]>>6===3?3:l[4]>>4&3,m=Eo[p];for(;;){this.seekTo(c);const b=f+4;let S=this.ensureBuffered(b);if(D(S)&&(S=await S),S<b)break;this.seekTo(c+f);const A=this.readBytes(4);if(A[0]!==11||A[1]!==119||A[2]>>6!==1)break;f+=2*(((A[2]&7)<<8|A[3])+1)}this.seekTo(c),u=this.ensureBuffered(f),D(u)&&(u=await u);const y=m*256*lt/e.info.sampleRate;return this.supplyPacket(u,y)}else if(r==="dts"){if(o!==127&&o!==100)continue;this.skip(-1);const c=this.currentPos;let u=this.ensureBuffered(en);if(D(u)&&(u=await u),u<en)return;const l=this.readBytes(en),d=pu(l);let f=d?null:tn(l);if(!d&&!f){this.seekTo(c+1);continue}if(f&&!f.asset){this.seekTo(c);const g=Math.min(f.frameSize,uh);let y=this.ensureBuffered(g);D(y)&&(y=await y),f=tn(this.readBytes(y))??f}let h=d?d.frameSize:f.frameSize;if(d){let g=Math.ceil(d.frameSize/4)*4;for(;;){this.seekTo(c);const y=g+Na;let b=this.ensureBuffered(y);if(D(b)&&(b=await b),b<y)break;this.seekTo(c+g);const S=tn(this.readBytes(Na));if(!S)break;g+=S.frameSize,h=g}}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),D(u)&&(u=await u);const m=p*lt/e.info.sampleRate;return this.supplyPacket(u,m)}else throw new Error("Unhandled.")}if(n<s)break}}}supplyPacket(e,t){const r=Br(this.pesPacketDataStartPositions,p=>p<=this.currentPos);w(r!==-1);const s=this.pesPackets[r],n=this.pesPacketDataStartPositions[r];let a;if(this.lastSuppliedPesPacket===s)w(this.nextPts!==null),a=this.nextPts;else{if(s.pts===null)throw new Error(nd);a=s.pts,no(this.elementaryStream,s)}this.lastSuppliedPesPacket=s,this.nextPts=a+t;const o=s.sectionStartPos,c=o+(this.currentPos-n),u=this.readBytes(e).slice();let l=s.randomAccessIndicator;if(l===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")l=1;else if(this.elementaryStream.info.decoderConfig){const p=Nn(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,u)==="key";l=Number(p)}}const d=Math.round(a);this.suppliedPacket={pts:d,intrinsicDuration:Math.round(a+t)-d,data:u,sequenceNumber:c,sectionStartPos:o,randomAccessIndicator:l};const f=this.currentPos-this.scratchStartPos;this.scratch.copyWithin(0,f,this.endPos-this.scratchStartPos),this.scratchStartPos=this.currentPos;const h=Br(this.pesPacketDataStartPositions,p=>p<=this.currentPos);this.pesPackets.splice(0,h),this.pesPacketDataStartPositions.splice(0,h)}}class aa{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(),w(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 r;for(t!==-1&&t<this.presentationOrderPackets.length-1?(r=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=r):e.intrinsicDuration>0?r=e.intrinsicDuration:t>0?r=e.pts-this.presentationOrderPackets[t-1].pts:r=this.lastDuration,this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const s=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(s))break;this.presentationOrderPackets.shift()}return{packet:e,duration:r}}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(w(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 s=1;s<this.reorderBuffer.length;s++)this.reorderBuffer[s].pts<this.reorderBuffer[t].pts&&(t=s);const r=this.reorderBuffer[t];this.presentationOrderPackets.push(r),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 _r="application/vnd.apple.mpegurl",Dc="#EXT-X-STREAM-INF:",zc="#EXT-X-I-FRAME-STREAM-INF:",Oc="#EXT-X-MEDIA:",Sn="#EXT-X-DEFINE:",ao="#EXTINF:",Uc="#EXT-X-MAP:",Nc="#EXT-X-KEY:",Vc="#EXT-X-MEDIA-SEQUENCE:",Wc="#EXT-X-BYTERANGE:",Lc="#EXT-X-PROGRAM-DATE-TIME:",Lm="#EXT-X-DISCONTINUITY",Hc="#EXT-X-DISCONTINUITY-SEQUENCE:",qc="#EXT-X-TARGETDURATION:",Hm="#EXT-X-ENDLIST",jc="#EXT-X-PLAYLIST-TYPE:",qm="#EXT-X-I-FRAMES-ONLY",Qt="com.apple.streaming.transportStreamTimestamp",ad=i=>i.length===0||i.startsWith("#")&&!i.startsWith("#EXT");class Er{constructor(e,t){this._attributes={};let r="",s="",n=!1,a=!1,o=!1;const c=()=>{if(!r)return;const u=r.trim().toLowerCase();Object.prototype.hasOwnProperty.call(this._attributes,u)&&K._warn(`Duplicate AttributeName "${u}"; using last value`);const l=o||s.startsWith("0x")||s.startsWith("0X");this._attributes[u]=l&&t?t.substitute(s):s,r="",s="",n=!1,o=!1};for(let u=0;u<e.length;u++){const l=e[u];l==='"'?(n&&!a&&s.length===0&&(o=!0),a=!a):l==="="&&!n&&!a?n=!0:l===","&&!a?c():n?s+=l:r+=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 r=Number(t);return Number.isFinite(r)?r:null}merge(e){Object.assign(this._attributes,e._attributes)}}const jm=/^[A-Za-z0-9_-]+$/,Km=/\{\$([A-Za-z0-9_-]+)\}/g,$m=2**26;class od{constructor(e,t){this.playlistPath=e,this.importedVariables=t,this.variables=new Map,this.totalSubstitutedLength=0}define(e){var o;const t=new Er(e,this),r=t.get("name"),s=t.get("import"),n=t.get("queryparam");if([r,s,n].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(r!==null){const c=t.get("value");if(c===null)throw new Error("Invalid #EXT-X-DEFINE tag; NAME requires VALUE.");this.set(r,c)}else if(s!==null){const c=(o=this.importedVariables)==null?void 0:o.get(s);if(c===void 0)throw new Error(`Invalid #EXT-X-DEFINE tag; cannot import undefined variable "${s}".`);this.set(s,c)}else if(n!==null){const c=vf(this.playlistPath,n);if(c===null)throw new Error(`Invalid #EXT-X-DEFINE tag; query parameter "${n}" is missing.`);this.set(n,c)}}substitute(e){return e.replaceAll(Km,(t,r)=>{const s=this.variables.get(r);if(s===void 0)throw new Error(`Invalid M3U8 file; variable "${r}" is referenced before being defined.`);if(this.totalSubstitutedLength+=s.length,this.totalSubstitutedLength>$m)throw new Error("Invalid M3U8 file; variable substitution produces an excessive amount of data.");return s})}get(e){return this.variables.get(e)}set(e,t){if(!jm.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 Qm{constructor(e,t,r){this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.hasOnlyKeyPackets=!1,this.learnedSegmentTimestampOffset=null,this.segmentMediaOffsets=new WeakMap,this.input=e,this.path=t,this.trackDeclarations=r}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,{skipLiveWait:!0});if(t??(t=await this.getFirstSegment({})),!t||t.unixEpochTimestamp===null)return null;const r=e-(t.timestamp+await this.getFirstSegmentTimestampOffset());return t.unixEpochTimestamp+r}async getTrackBackings(){return this.trackBackingsPromise??(this.trackBackingsPromise=(async()=>{const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if(t.type==="video"){const r=is(e,s=>s.getType()==="video")+1;e.push(new $c(this,t,r))}else if(t.type==="audio"){const r=is(e,s=>s.getType()==="audio")+1;e.push(new Qc(this,t,r))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];const r=await this.getInputForSegment(this.firstSegment).getTracks();for(const s of r)if(s.type==="video"){const n=is(e,a=>a.getType()==="video")+1;e.push(new $c(this,{type:"video"},n))}else if(s.type==="audio"){const n=is(e,a=>a.getType()==="audio")+1;e.push(new Qc(this,{type:"audio"},n))}}return e})())}getMediaOffset(e,t){let r=this.segmentMediaOffsets.get(e);return r||(r=(async()=>{const s=await this.getRawTimestampOffset(t);if(s===null)return e.timestamp;let n=s+await this.getMediaOffsetForDiscontinuity(e.discontinuityNumber);const a=this.getTimestampWrapPeriod();if(a<1/0){const o=await Lo(t);if(o!==null){const c=o+n;n+=a*Math.round((e.timestamp-c)/a)}}return n})(),this.segmentMediaOffsets.set(e,r),r)}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}const Lo=async i=>{const e=await i.getTracks(),t=[...e.filter(r=>r.type==="video"),...e.filter(r=>r.type!=="video")];for(const r of t){const s=await r.getFirstTimestampOrNull();if(s!==null)return s}return null};class cd{constructor(e,t,r){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=null,this.segmentedInput=e,this.decl=t,this.number=r}hydrate(){return this.hydrationPromise??(this.hydrationPromise=(async()=>{var r;if((r=this.segmentedInput).firstSegment??(r.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})())}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 this.segmentedInput.hasOnlyKeyPackets||(((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(),w(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,r){w(e.sequenceNumber>=0),w(this.segmentedInput.firstSegment);const s=await this.segmentedInput.getMediaOffset(t,r.input),n=t.timestamp-this.segmentedInput.firstSegment.timestamp,a=e.clone({timestamp:tr(e.timestamp+s,await r.getTimeResolution()),sequenceNumber:Math.floor(1e8*n)+e.sequenceNumber});return this.packetInfos.set(a,{segment:t,track:r,sourcePacket:e}),a}async getFirstPacket(e){await this.hydrate(),w(this.firstInputTrack),w(this.firstSegment);let t=this.firstInputTrack,r=this.firstSegment;for(;;){if(t){const a=await t._backing.getFirstPacket(e);if(a)return this.createAdjustedPacket(a,r,t)}if(r=await this.segmentedInput.getNextSegment(r,{skipLiveWait:e.skipLiveWait}),!r)break;t=(await this.segmentedInput.getInputForSegment(r).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,r){const s=this.packetInfos.get(e);if(!s)throw new Error("Packet was not created from this track.");const n=r?await s.track._backing.getNextKeyPacket(s.sourcePacket,t):await s.track._backing.getNextPacket(s.sourcePacket,t);if(n)return this.createAdjustedPacket(n,s.segment,s.track);let a=s.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===s.track.type&&f.number===s.track.number);if(!l){a=o;continue}let d=await l._backing.getFirstPacket(t);if(d&&r&&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,r){let s=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(s??(s=await this.segmentedInput.getFirstSegment({})),!s)return null;for(await this.hydrate();s;){const n=this.segmentedInput.getInputForSegment(s),o=(await n.getTracks()).find(h=>h.type===this.firstInputTrack.type&&h.number===this.firstInputTrack.number);if(!o){s=await this.segmentedInput.getPreviousSegment(s,{skipLiveWait:t.skipLiveWait});continue}const c=await this.segmentedInput.getMediaOffset(s,n),u=this.segmentedInput.learnedSegmentTimestampOffset===null?await o._backing.getFirstPacket({...t,metadataOnly:!0}):null;if(u){const h=u.timestamp+c;this.segmentedInput.learnedSegmentTimestampOffset=h-s.timestamp;const p=e-h;if(p<-s.duration||p>=2*s.duration){const m=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(m!==s){s=m;continue}}}const l=Kc(e,c,await o.getTimeResolution()),d=r?await o._backing.getKeyPacket(l,t):await o._backing.getPacket(l,t);if(!d){s=await this.segmentedInput.getPreviousSegment(s,{skipLiveWait:t.skipLiveWait});continue}const f=r?await o._backing.getPacket(l,{...t,metadataOnly:!0}):d;if(w(f),l>=f.timestamp+f.duration){const h=await this.segmentedInput.getNextSegment(s,{skipLiveWait:t.skipLiveWait});if(h){const p=this.segmentedInput.getInputForSegment(h),g=(await p.getTracks()).find(b=>b.type===this.firstInputTrack.type&&b.number===this.firstInputTrack.number);let y=g?await g._backing.getFirstPacket({...t,metadataOnly:!0}):null;if(y&&r&&y.type!=="key"&&(y=await g._backing.getNextKeyPacket(y,{...t,metadataOnly:!0})),y){const b=await this.segmentedInput.getMediaOffset(h,p),S=Kc(e,b,await g.getTimeResolution());if(y.timestamp<=S){s=h;continue}}}}return this.createAdjustedPacket(d,s,o)}return null}}const Kc=(i,e,t)=>(Math.floor(Zt(t*i))-Math.round(t*e))/t;class $c extends cd{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 Qc extends cd{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
|
+
*/wo();const Gc=typeof an<"u"?an:void 0,ld=0,ud=1/0;class It extends Ps{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 He;return this._sizePromise??(this._sizePromise=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,ld,ud),e=this._getFileSize(),w(e!==void 0)),e})())}async getSize(){if(this._disposed)throw new He;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 ep(this,e,t)}_dispatchRead(e,t){var r;(r=this.onread)==null||r.call(this,e,t),this._emit("read",{start:e,end:t})}ref(){return new Ho(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}}class Ho{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;w(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 ar extends It{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),r=s=>{var a;if(!(s instanceof It||s instanceof Ho))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const n=s instanceof It?s.ref():s;return(a=n.source)._usedForHls||(a._usedForHls=this._usedForHls),n};return D(t)?t.then(r):r(t)}}const Xc=(i,e)=>i.path===e.path;class Gm extends ar{constructor(){super(...arguments),this._root=null,this._rootRequest=null,this._removeRootReadListener=null}_read(e,t,r,s){if(!this._root){if(!this._rootRequest){const a=this._resolveRequest({path:this.rootPath,isRoot:!0}),o=c=>{const u=c instanceof It?c.ref():c;return this._root=u,this._rootRequest=null,this._removeRootReadListener=u.source.on("read",({start:l,end:d})=>{this._dispatchRead(l,d)}),u};D(a)?this._rootRequest=a.then(o):(o(a),w(this._root))}if(this._rootRequest)return this._rootRequest.then(()=>this._read(e,t,r,s))}const n=this._root.source;return t>(n._getFileSize()??1/0)?null:n._read(e,t,r,s)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?(this._removeRootReadListener(),this._root.free()):this._rootRequest&&this._rootRequest.then(e=>{this._removeRootReadListener(),e.free()}).catch(()=>{})}}class w0 extends It{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=me(e),this._view=ie(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 hr=typeof FinalizationRegistry<"u"?new FinalizationRegistry(i=>{i.cancel().catch(()=>{})}):null;class y0 extends It{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&&(!ut(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 jo({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:r=>{const s=this._readers.get(r);s&&(this._readers.delete(r),hr==null||hr.unregister(r),s.cancel().catch(()=>{}))},prefetchProfile:qo.fileSystem,handleUnhandledError:t.handleUnhandledError}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,r,s){return this._orchestrator.read(e,t,r,s)}async _runWorker(e){w(e.strictTarget);let t=this._readers.get(e);for(t===void 0&&("stream"in this._blob&&!wi()&&this._options.useStreamReader!==!1?(t=this._blob.slice(e.currentPos).stream().getReader(),hr==null||hr.register(e,t,e)):t=null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){const{done:r,value:s}=await t.read();if(r)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+s.length),this._orchestrator.supplyWorkerData(e,s)}else{const r=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+r.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(r))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await(t==null?void 0:t.cancel().catch(()=>{}))}_dispose(){this._orchestrator.dispose()}}const Xm=.5*2**20,Ym=((i,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 s=null;try{typeof window<"u"&&typeof window.location<"u"&&(s=new URL(t instanceof Request?t.url:t,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&s!==null&&s!==window.location.origin)return K._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**(i-2),16)}),Yc=new Set;class dd extends ar{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&&(!ut(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 r=e instanceof Request?e.url:e instanceof URL?e.href:e;super(r,o=>new dd(o.path,{...this._options,requestInit:this._requestInit})),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??Ym,this._requestInit={...t.requestInit};let s=null;if((a=t.requestInit)!=null&&a.headers){const o={...Ba(t.requestInit.headers)},c=Object.keys(o).find(u=>u.toLowerCase()==="range");c!==void 0&&(s=o[c],delete o[c],this._requestInit.headers=o)}if(e instanceof Request){let o=e;const c=e.headers.get("Range");c!==null&&(s??(s=c),o=new Request(e),o.headers.delete("Range"),this._url=o),this._requestInit={cache:o.cache,credentials:o.credentials,integrity:o.integrity,keepalive:o.keepalive,mode:o.mode==="navigate"?void 0:o.mode,redirect:o.redirect,referrer:o.referrer,referrerPolicy:o.referrerPolicy,...this._requestInit},this._requestInit.headers=$n({headers:o.headers},this._requestInit).headers}if(s!==null){const o=Jm(s);o&&(this._offset=o.offset,this._length=o.length)}const n=2;this._orchestrator=new jo({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:t.parallelism??n,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:o=>{var c;(c=this._abortControllers.get(o))==null||c.abort(),this._abortControllers.delete(o)},prefetchProfile:qo.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:Be(e-this._offset,0,this._length??1/0)}_read(e,t,r,s){if(this._length!==null&&t>this._length)return null;const n=this._offset,a=this._sequentialBacking?this._sequentialBacking._read(n+e,n+t):this._orchestrator.read(n+e,n+t,Math.max(n+r,n),n+Math.min(s,this._length??1/0)),o=c=>c?(c.offset-=this._offset,c):null;return D(a)?a.then(o):o(a)}async _runWorker(e){var r,s;let t=0;for(;;){if(e.aborted){this._orchestrator.signalWorkerStoppedRunning(e);return}const n=new AbortController;this._abortControllers.set(e,n);const a=await nc(this._options.fetchFn??fetch,this._url,$n(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:n.signal}),this._getRetryDelay,()=>n.signal.aborted),o=a.status===416?/^bytes \*\/(\d+)$/.exec(a.headers.get("Content-Range")??""):null;let c=null;if(o?c=Number(o[1]):a.status===416&&e.currentPos>e.startPos&&(c=e.currentPos),c!==null&&c<=e.currentPos){(r=a.body)==null||r.cancel().catch(()=>{}),this._orchestrator.fileSize===null&&this._orchestrator.supplyFileSize(c),this._fileSizeDetermined=!0,this._orchestrator.onWorkerFinished(e);return}if(!a.ok)throw(s=a.body)==null||s.cancel().catch(()=>{}),new Error(`Error fetching ${this.rootPath}: ${a.status} ${a.statusText}`);a.redirected&&(this.rootPath=a.url);e:if(this._orchestrator.fileSize===null&&!a.headers.has("Content-Encoding")&&(a.status===206||a.type==="basic")){const d=a.headers.get("Content-Range");if(d){const h=/\/(\d+)/.exec(d);if(h){this._orchestrator.supplyFileSize(Number(h[1]));break e}}const f=a.headers.get("Content-Length");if(f){const h=a.status===206?e.currentPos:0;this._orchestrator.supplyFileSize(h+Number(f))}}if(this._fileSizeDetermined=!0,!a.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(a.status!==206){if(this._sequentialBacking){a.body.cancel().catch(()=>{});return}if(!this._usedForHls){const d=new URL(a.url||(this._url instanceof Request?this._url.url:this._url),typeof window<"u"?window.location.href:void 0);d.origin!=="null"&&!(d.pathname.endsWith(".m3u8")||d.pathname.endsWith(".m3u"))&&(Yc.has(d.origin)||(K._warn(`HTTP server (origin ${d.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.`),Yc.add(d.origin)))}this._abortControllers.delete(e),this._transitionToSequentialMode(a.body,n);return}const u=a.body.getReader(),l=e.currentPos;for(;;){if(e.currentPos>=e.targetPos||e.aborted){n.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let d;try{d=await u.read()}catch(p){if(n.signal.aborted)throw p;const m=this._getRetryDelay(++t,p,this._url);if(m!==null){K._error("Error while reading response stream. Attempting to resume.",p),await Ar(1e3*m);break}else throw p}if(e.aborted)continue;const{done:f,value:h}=d;if(f){if(e.currentPos>=e.targetPos){this._orchestrator.onWorkerFinished(e);return}if(!e.strictTarget&&(e.currentPos===l||a.headers.has("Content-Encoding"))){this._orchestrator.onWorkerFinished(e);return}if(e.currentPos>l)break;t++;const p=new Error("Range response ended without delivering any data."),m=this._getRetryDelay(t,p,this._url);if(m===null)throw p;K._error("Retrying range request that ended without delivering any data."),await Ar(1e3*m);break}t=0,this._dispatchResourceRead(e.currentPos,e.currentPos+h.length),this._orchestrator.supplyWorkerData(e,h)}}}_transitionToSequentialMode(e,t){this._sequentialAbortController=t;let r=e.getReader(),s=0,n=0,a=0;const o=new ReadableStream({pull:async l=>{var d;for(;;){let f;try{f=await r.read()}catch(p){if(this._disposed)throw p;const m=this._getRetryDelay(++a,p,this._url);if(m===null)throw p;K._error("Error while reading response stream. Attempting to resume.",p),await Ar(1e3*m),this._sequentialAbortController=new AbortController,this._disposed&&this._sequentialAbortController.abort();const g=await nc(this._options.fetchFn??fetch,this._url,$n(this._requestInit,{headers:{Range:`bytes=${s}-`},signal:this._sequentialAbortController.signal}),this._getRetryDelay,()=>this._disposed);if(!g.ok)throw(d=g.body)==null||d.cancel().catch(()=>{}),new Error(`Error fetching ${this.rootPath}: ${g.status} ${g.statusText}`);if(!g.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");r=g.body.getReader(),n=g.status===206?0:s;continue}if(f.done){l.close();return}let h=f.value;if(n>0){const p=Math.min(n,h.length);if(n-=p,h=h.subarray(p),h.length===0)continue}if(a=0,h.length!==0){s+=h.length,l.enqueue(h);return}}},cancel:()=>r.cancel().catch(()=>{})}),c=new md(o,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});c._endIndex=this._orchestrator.fileSize,c._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.",c.on("read",({start:l,end:d})=>this._dispatchResourceRead(l,d)),this._sequentialBacking=c;const u=new Set;for(const l of this._orchestrator.workers){for(const d of l.pendingSlices)u.add(d);l.aborted=!0,l.pendingSlices.length=0}for(const l of this._orchestrator.queuedReads)for(const d of l.pendingSlices)u.add(d);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const[,l]of this._abortControllers)l.abort();this._abortControllers.clear();for(const l of u){const d=c._read(l.start,l.start+l.bytes.length);D(d)?d.then(f=>{f?(w(f.offset===l.start),l.resolve(f.bytes)):l.resolve(null)},f=>l.reject(f)):(w(d===null),l.resolve(null))}}_dispatchResourceRead(e,t){const r=Math.max(e-this._offset,0),s=Math.min(t-this._offset,this._length??1/0);r<s&&this._dispatchRead(r,s)}_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 Zm=/^bytes=(\d+)-(\d*)$/,Jm=i=>{const e=Zm.exec(i.trim());if(!e)return null;const t=Number(e[1]),r=e[2]===""?null:Number(e[2]);return r!==null&&r<t?null:{offset:t,length:r!==null?r-t+1:null}};let ji=null;typeof FinalizationRegistry<"u"&&(ji=new FinalizationRegistry(i=>{i.close()}));class fd extends ar{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&&(!ut(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(!Gc.fs)throw new Error("FilePathSource is only available in server-side environments (Node.js, Bun, Deno).");super(e,r=>new fd(r.path,t)),this._fileHandle=null,this._customSource=new hd({getSize:async()=>{const r=await Gc.fs.open(e,"r");if(this._disposed)throw r.close(),new He;return this._fileHandle=r,ji==null||ji.register(this,r,this),(await r.stat()).size},read:async(r,s)=>{w(this._fileHandle);const n=new Uint8Array(s-r);let a=0;for(;a<n.length;){const o=await this._fileHandle.read(n,a,n.length-a,r+a);if(o.bytesRead===0)throw new Error(`File ended at byte ${r+a}, before byte ${s} was read; it was likely truncated while being read.`);a+=o.bytesRead}return n},maxCacheSize:t.maxCacheSize,prefetchProfile:"fileSystem",handleUnhandledError:t.handleUnhandledError}),this._customSource.on("read",({start:r,end:s})=>this._dispatchRead(r,s))}_read(e,t,r,s){return this._customSource._read(e,t,r,s)}_getFileSize(){return this._customSource._getFileSize()}_dispose(){this._customSource._disposed=!0,this._customSource._dispose(),this._fileHandle&&(this._fileHandle.close(),this._fileHandle=null,ji==null||ji.unregister(this))}}class hd extends It{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&&(!ut(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._pendingSize=null,this._options=e,this._orchestrator=new jo({maxCacheSize:e.maxCacheSize??8*2**20,maxWorkerCount:2,prefetchProfile:qo[e.prefetchProfile??"none"],runWorker:this._runWorker.bind(this),handleUnhandledError:e.handleUnhandledError})}_getFileSize(){return this._orchestrator.fileSize??void 0}_read(e,t,r,s){if(this._orchestrator.fileSize!==null)return this._orchestrator.read(e,t,r,s);const n=this._pendingSize??this._options.getSize();if(D(n))return this._pendingSize=n,n.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 He;return this._orchestrator.fileSize=a,t>a?null:this._orchestrator.read(e,t,r,s)});if(!Number.isInteger(n)||n<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=n,t>n?null:this._orchestrator.read(e,t,r,s)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){const t=e.currentPos,r=e.targetPos;let s=this._options.read(e.currentPos,r);if(D(s)&&(s=await s),e.aborted){s instanceof ReadableStream&&await s.cancel().catch(()=>{});break}if(s instanceof Uint8Array){if(s=me(s),s.length!==r-e.currentPos)throw new Error(`options.read returned a Uint8Array with unexpected length: Requested ${r-e.currentPos} bytes, but got ${s.length}.`);this._dispatchRead(e.currentPos,e.currentPos+s.length),this._orchestrator.supplyWorkerData(e,s)}else if(s instanceof ReadableStream){const n=s.getReader();this._readers.add(n);try{for(;e.currentPos<r&&!e.aborted;){const{done:a,value:o}=await n.read();if(a){if(e.currentPos<r)throw new Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${r-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=me(o);this._dispatchRead(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}}finally{this._readers.delete(n),n.cancel().catch(()=>{}),n.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 r of this._readers)r.cancel().catch(()=>{});this._readers.clear(),(t=(e=this._options).dispose)==null||t.call(e)}}const b0=hd;class md extends It{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&&(!ut(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 r=de(this._cache,e,l=>l.start),s=r!==-1?this._cache[r]:null;if(s&&s.start<=e&&t<=s.end)return{bytes:s.bytes,view:s.view,offset:s.start};let n=e;const a=[];if(r!==-1)for(let l=r;l<this._cache.length;l++){const d=this._cache[l];if(d.start>=t)break;const f=Math.max(e,d.start);f>n&&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)}),n=h)}if(n===t)return Zc(e,t,a);this._currentIndex>n&&this._throwDueToCacheMiss();const{promise:o,resolve:c,reject:u}=Ae();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 n of this._pendingSlices)n.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}const r=this._currentIndex,s=this._currentIndex+t.byteLength;this._dispatchRead(r,s);for(let n=0;n<this._pendingSlices.length;n++){const a=this._pendingSlices[n],o=Math.max(r,a.start),c=Math.min(s,a.end);o<c&&(a.parts.push({start:o,bytes:t.subarray(o-r,c-r)}),c===a.end&&(a.resolve(Zc(a.start,a.end,a.parts)),this._pendingSlices.splice(n,1),n--))}for(this._cache.push({start:r,end:s,bytes:t,view:ie(t),age:0});this._cache.length>0;){const n=this._cache[0];if(this._maxRequestedIndex-n.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){for(const e of this._pendingSlices)e.reject(new He);this._pendingSlices.length=0,this._cache.length=0,(this._reader??this._stream).cancel().catch(()=>{})}}const Zc=(i,e,t)=>{const r=new Uint8Array(e-i);for(const s of t)r.set(s.bytes,s.start-i);return{bytes:r,view:ie(r),offset:i}},qo={none:(i,e)=>({start:i,end:e}),fileSystem:(i,e)=>(i=Math.floor((i-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:i,end:e}),network:(i,e,t)=>{i=Math.max(0,Math.floor((i-65536)/65536)*65536);for(const s of t){const a=Math.max((s.startPos+s.targetPos)/2,s.targetPos-8388608);if(Fa(i,e,a,s.targetPos)){const o=s.targetPos-s.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,s.startPos+l)}}return e=Math.max(e,i+Xm),{start:i,end:e}}};class jo{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,r,s){w(!this.disposed);const n=this.options.prefetchProfile(e,t,this.workers),a=Math.max(n.start,r),o=Math.min(n.end,this.fileSize??1/0,s);w(a<=e&&t<=o);let c=null;const u=de(this.cache,e,x=>x.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=de(this.cache,a,x=>x.start),f=c?null:new Uint8Array(t-e);let h=0,p=a;const m=[];if(d!==-1){for(let x=d;x<this.cache.length;x++){const T=this.cache[x];if(T.start>=o)break;if(T.end<=a)continue;const P=Math.max(a,T.start),C=Math.min(o,T.end);if(w(P<=C),p<P&&m.push({start:p,end:P}),p=C,f){const _=Math.max(e,T.start),I=Math.min(t,T.end);if(_<I){const v=_-e;f.set(T.bytes.subarray(_-T.start,I-T.start),v),v===h&&(h=I-e)}}T.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:ie(f),offset:e}),m.length===0)return w(c),c;const{promise:g,resolve:y,reject:b}=Ae(),S=[];for(const x of m){const T=Math.max(e,x.start),P=Math.min(t,x.end);T===x.start&&P===x.end?S.push(x):T<P&&S.push({start:T,end:P})}const A=f&&{start:e,bytes:f,holes:S,resolve:y,reject:b};e:for(const x of m){for(const C of this.workers)if(this.checkHoleAgainstWorker(C,x,A?[A]:[])){this.checkQueuedReadsAgainstWorker(C);continue e}const T=x.end<o||this.fileSize!==null,P=this.createWorker(x.start,x.end,T);if(P)A&&(P.pendingSlices=[A]),this.runWorker(P);else{let C=de(this.queuedReads,x.start,I=>I.hole.start),_=C!==-1?this.queuedReads[C]:null;for(_&&x.start<=_.hole.end?(_.hole.end=Math.max(_.hole.end,x.end),_.strictTarget&&(_.strictTarget=T),A&&_.pendingSlices.push(A)):(C++,_={hole:{start:x.start,end:x.end},strictTarget:T,pendingSlices:A?[A]:[],age:this.nextAge++},this.queuedReads.splice(C,0,_));C+1<this.queuedReads.length;){const I=this.queuedReads[C+1];if(I.hole.start>_.hole.end)break;_.hole.end=Math.max(_.hole.end,I.hole.end),_.pendingSlices.push(...I.pendingSlices),_.strictTarget&&(_.strictTarget=I.strictTarget),_.age=Math.min(_.age,I.age),this.queuedReads.splice(C+1,1)}}}return c?g.catch(x=>{if(!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(x);else throw x}):(w(f),c=g.then(x=>x&&{bytes:x,view:ie(x),offset:e})),c}checkHoleAgainstWorker(e,t,r){if(Fa(t.start-131072,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let n=0;n<r.length;n++){const a=r[n];e.pendingSlices.includes(a)||e.pendingSlices.push(a)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let t=!1;for(let r=0;r<this.queuedReads.length;r++){const s=this.queuedReads[r];if(this.checkHoleAgainstWorker(e,s.hole,s.pendingSlices))this.queuedReads.splice(r,1),r--,t=!0;else if(t)break}}createWorker(e,t,r){var n,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)w(c!==null),w(o.pendingSlices.length===0),this.workers.splice(c,1),(a=(n=this.options).onIdleWorkerRemoved)==null||a.call(n,o);else return null}const s={startPos:e,currentPos:e,targetPos:t,strictTarget:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(s),s}runWorker(e){w(!e.running),w(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(r=>r.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 n=1;n<this.queuedReads.length;n++)this.queuedReads[n].age<this.queuedReads[t].age&&(t=n);const r=this.queuedReads[t],s=this.createWorker(r.hole.start,r.hole.end,r.strictTarget);if(!s)return;this.queuedReads.splice(t,1),s.pendingSlices=r.pendingSlices,this.runWorker(s)}})}supplyWorkerData(e,t){var n,a;w(!e.aborted);const r=e.currentPos,s=r+t.length;this.insertIntoCache({start:r,end:s,bytes:t,view:ie(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(r,c.start),l=Math.min(s,c.start+c.bytes.length);u<l&&c.bytes.set(t.subarray(u-r,l-r),u-c.start);for(let d=0;d<c.holes.length;d++){const f=c.holes[d];r<=f.start&&s>f.start&&(f.start=s),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||Fa(r,s,c.currentPos,c.targetPos)&&(this.workers.splice(o,1),(a=(n=this.options).onIdleWorkerRemoved)==null||a.call(n,c),o--)}}supplyFileSize(e){w(this.fileSize===null),this.fileSize=e;for(const t of this.workers){t.targetPos=Math.min(t.targetPos,e),t.strictTarget=!0;for(let r=0;r<t.pendingSlices.length;r++){const s=t.pendingSlices[r];for(const n of s.holes)if(n.end>e){s.resolve(null),t.pendingSlices.splice(r,1),r--;break}}}for(let t=0;t<this.queuedReads.length;t++){const r=this.queuedReads[t];for(let s=0;s<r.pendingSlices.length;s++){const n=r.pendingSlices[s];n.start+n.bytes.length>e&&(n.resolve(null),r.pendingSlices.splice(s,1),s--)}r.hole.start>=e?(this.queuedReads.splice(t,1),t--):(r.hole.end=Math.min(r.hole.end,e),r.strictTarget=!0)}}signalWorkerStoppedRunning(e){e.running=!1,e.aborted||(e.pendingSlices.length=0)}onWorkerFinished(e){var r,s;const t=this.workers.indexOf(e);w(t!==-1),e.running=!1,this.workers.splice(t,1),(s=(r=this.options).onIdleWorkerRemoved)==null||s.call(r,e),this.fileSize===null&&this.supplyFileSize(e.currentPos);for(const n of e.pendingSlices)n.start+n.bytes.length>e.currentPos&&n.resolve(null)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=de(this.cache,e.start,r=>r.start)+1;if(t>0){const r=this.cache[t-1];if(r.end>=e.end)return;if(r.end>e.start){const s=new Uint8Array(e.end-r.start);s.set(r.bytes,0),s.set(e.bytes,e.start-r.start),this.currentCacheSize+=e.end-r.end,r.bytes=s,r.view=ie(s),r.end=e.end,t--,e=r}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 r=t+1;r<this.cache.length;r++){const s=this.cache[r];if(e.end<=s.start)break;if(e.end>=s.end){this.cache.splice(r,1),this.currentCacheSize-=s.bytes.length,r--;continue}const n=new Uint8Array(s.end-e.start);n.set(e.bytes,0),n.set(s.bytes,s.start-e.start),this.currentCacheSize-=e.end-s.start,e.bytes=n,e.view=ie(n),e.end=s.end,this.cache.splice(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let r=0,s=this.cache[0];for(let n=1;n<this.cache.length;n++){const a=this.cache[n];a.age<s.age&&(r=n,s=a)}if(this.currentCacheSize-s.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(r,1),this.currentCacheSize-=s.bytes.length}}dispose(){var e,t;for(const r of this.workers){for(const s of r.pendingSlices)s.reject(new He);r.pendingSlices.length=0,r.aborted=!0,r.running||(t=(e=this.options).onIdleWorkerRemoved)==null||t.call(e,r)}for(const r of this.queuedReads)for(const s of r.pendingSlices)s.reject(new He);this.workers.length=0,this.cache.length=0,this.queuedReads.length=0,this.disposed=!0}}class ep extends It{constructor(e,t,r){if(super(),this._ref=null,this._removeReadListener=null,e._disposed)throw new Error("Cannot create a slice of a disposed source.");this._baseSource=e,this._offset=t,this._length=r??null}_getFileSize(){if(this._length!==null)return this._length;const e=this._baseSource._getFileSize();return e==null?e:Math.max(e-this._offset,0)}_read(e,t,r,s){if(this._length!==null&&t>this._length)return null;const n=this._baseSource._getFileSize(),a=typeof n=="number"&&this._offset+t>n?null:this._baseSource._read(this._offset+e,this._offset+t,this._offset+r,this._offset+s),o=c=>{if(!c){if(this._length!==null){const u=this._offset+this._length;throw new Error(`Underlying data too short, expected a length of at least ${u} bytes.`)}return null}return c.offset-=this._offset,c};return D(a)?a.then(o):o(a)}_dispose(){var e,t;(e=this._ref)==null||e.free(),(t=this._removeReadListener)==null||t.call(this)}ref(){return this._ref||(this._ref=this._baseSource.ref(),this._removeReadListener=this._baseSource.on("read",({start:e,end:t})=>{const r=Math.max(e-this._offset,0),s=Math.min(t-this._offset,this._length??1/0);r<s&&this._dispatchRead(r,s)})),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 Jc=function(i,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,s;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],t&&(s=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");s&&(r=function(){try{s.call(this)}catch(n){return Promise.reject(n)}}),i.stack.push({value:e,dispose:r,async:t})}else t&&i.stack.push({async:!0});return e},el=(function(i){return function(e){function t(a){e.error=e.hasError?new i(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var r,s=0;function n(){for(;r=e.stack.pop();)try{if(!r.async&&s===1)return s=0,e.stack.push(r),Promise.resolve().then(n);if(r.dispose){var a=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(a).then(n,function(o){return t(o),n()})}else s|=1}catch(o){t(o)}if(s===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return n()}})(typeof SuppressedError=="function"?SuppressedError:function(i,e,t){var r=new Error(t);return r.name="SuppressedError",r.error=i,r.suppressed=e,r});const tp=/^0[xX][0-9a-fA-F]+$/,ip=/^data:.*;base64,/i,tl=1e9;class il extends Qm{constructor(e,t,r,s){super(e.input,t,r),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=s}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 S;let e=this.nextLines;if(this.nextLines=null,!e){const A={stack:[],error:void 0,hasError:!1};try{const x=Jc(A,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),T=new sn(x.source);let P=T.requestSliceRange(0,0,64);if(D(P)&&(P=await P),P&&!nt.decode(X(P,P.length)).trimStart().startsWith("#EXTM3U"))throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");const C=await T.requestEntireFile();w(C),e=Bd(C,C.length,{ignore:ad}),x.source instanceof ar&&(this.rootPath=x.source.rootPath)}catch(x){A.error=x,A.hasError=!0}finally{el(A)}}const t=((S=this.input._formatOptions.hls)==null?void 0:S.offsetTimestampsByDateTime)!==!1&&(this.segments.length===0||this.segments[0].unixEpochTimestamp===this.segments[0].timestamp),r=new od(this.rootPath,this.demuxer.hasMasterPlaylist?this.demuxer.masterPlaylistVariables:null);let s=!1,n=0,a=null,o=null,c=null,u=0,l=0,d=null,f=null,h=null,p=null,m=null,g=Te(this.segments)??null;const y=A=>{const x=A.indexOf("@"),T=Number(x===-1?A:A.slice(0,x));if(!Number.isInteger(T)||T<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${A}'.`);let P=null;if(x!==-1&&(P=Number(A.slice(x+1)),!Number.isInteger(P)||P<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${A}'.`);return{length:T,offset:P}},b=A=>{if(u=A,g&&(w(g.sequenceNumber!==null),g.sequenceNumber<A)){const x=(A-g.sequenceNumber)*g.duration;n=g.timestamp+x,d=g.firstSegment??g,f=g.initSegment,m=g.lastProgramDateTimeSeconds,a=g.unixEpochTimestamp!==null?g.unixEpochTimestamp+x:null,g=null}};for(let A=0;A<e.length;A++){const x=e[A];if(!s){if(x!=="#EXTM3U")throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");s=!0;continue}if(!x.startsWith("#")){if(!g){if(o===null)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let T=c;if(T&&T.method==="AES-128"&&!T.iv){const I=new Uint8Array(Kt),v=ie(I);v.setUint32(8,Math.floor(u/2**32)),v.setUint32(12,u),T={...T,iv:I}}const C={path:st(this.rootPath,r.substitute(x)),offset:(p==null?void 0:p.offset)??0,length:(p==null?void 0:p.length)??null};d&&d.discontinuityNumber!==l&&(d=null);const _={index:this.segments.length,timestamp:n,unixEpochTimestamp:a,discontinuityNumber:l,firstSegment:d,sequenceNumber:u,location:C,duration:o,encryption:T,initSegment:f,lastProgramDateTimeSeconds:m};d??(d=_),n+=o,a!==null&&(a+=o),this.segments.push(_)}o=null,p===null?h=null:p=null,b(u+1)}if(x.startsWith(ao)){if(g)continue;const T=x.slice(ao.length),P=T.indexOf(","),C=P===-1?T:T.slice(0,P),_=Number(C);if(!Number.isFinite(_)||_<0||_>tl)throw new Error(`Invalid #EXTINF tag duration '${C}'.`);o=_}else if(x.startsWith(Sn))r.define(x.slice(Sn.length));else if(x.startsWith(Uc)){const T=new Er(x.slice(Uc.length),r),P=T.get("uri");if(!P)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const C=T.get("byterange");let _=null;if(C!==null&&(_=y(C)),_&&_.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!g){const v={path:st(this.rootPath,P),offset:(_==null?void 0:_.offset)??0,length:(_==null?void 0:_.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:n,unixEpochTimestamp:a,discontinuityNumber:l,firstSegment:null,sequenceNumber:null,location:v,duration:0,encryption:c,initSegment:null,lastProgramDateTimeSeconds:m}}}else if(x.startsWith(Nc)){const T=new Er(x.slice(Nc.length),r),P=T.get("method");if(P==="NONE")c=null;else if(P==="AES-128"){const C=T.get("uri");if(!C)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let _=null;const I=T.get("iv");if(I){if(!tp.test(I))throw new Error(`Unsupported IV format '${I}'.`);let R=I.slice(2);R=R.padStart(2*Kt,"0"),R=R.slice(-2*Kt),_=new Uint8Array(Kt);for(let F=0;F<Kt;F++){const H=2*F;_[F]=parseInt(R.slice(H,H+2),16)}}const v=T.get("keyformat")??"identity";if(v!=="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:st(this.rootPath,C),iv:_,keyFormat:v}}else if(P==="SAMPLE-AES"||P==="SAMPLE-AES-CTR"){const C=T.get("uri");if(!C)throw new Error(`Invalid #EXT-X-KEY: ${P} requires a URI attribute.`);if((T.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 I=null;if(ip.test(C)){const v=C.indexOf(","),R=ln(C.slice(v+1));if(R.length>=8&&R[4]===112&&R[5]===115&&R[6]===115&&R[7]===104){const F=ie(R).getUint32(0);I=Iu(R.subarray(8,Math.min(F,R.length)))}}c={method:P,psshBox:I}}else throw new Error(`Unsupported encryption method '${P}'. If you think this method should be supported, please raise an issue.`)}else if(x.startsWith(Vc)){const T=x.slice(Vc.length),P=Number(T);if(!Number.isSafeInteger(P)||P<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${T}'.`);b(P)}else if(x.startsWith(Wc)){const T=y(x.slice(Wc.length));if(T.offset===null){if(h===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");T.offset=h}p=T,h=T.offset+T.length}else if(x.startsWith(Lc)){if(g)continue;const T=x.slice(Lc.length),P=Date.parse(T);if(!Number.isFinite(P))continue;const C=P/1e3;if(m===C)continue;if(m===null&&this.segments.length>0){const _=C-n;for(const I of this.segments)I.unixEpochTimestamp=I.timestamp+_,t&&(I.timestamp=I.unixEpochTimestamp)}m=C,a=C,t&&(n=C)}else if(x===Lm)d=null,l++;else if(x.startsWith(Hc)){const T=x.slice(Hc.length),P=Number(T);if(!Number.isSafeInteger(P)||P<0)throw new Error(`Invalid EXT-X-DISCONTINUITY-SEQUENCE value '${T}'.`);l=P}else if(x.startsWith(qc)){const T=x.slice(qc.length),P=Number(T);if(!Number.isFinite(P)||P<0||P>tl)throw new Error(`Invalid EXT-X-TARGETDURATION value '${T}'.`);this.refreshInterval=Be(P,.5,3600)}else if(x===qm)this.hasOnlyKeyPackets=!0;else if(x===Hm){this.streamHasEnded=!0;break}else if(x.startsWith(jc)){const T=x.slice(jc.length).toLowerCase();T==="vod"&&(this.streamHasEnded=!0),(T==="vod"||T==="event")&&(this.neverRemovesSegments=!0)}}if(!s)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&!this.streamHasEnded&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){this.segments.length===0&&!this.streamHasEnded&&!(t.skipLiveWait&&this.getRemainingWaitTimeMs()>0)&&await this.runUpdateSegments();const r=e-(this.learnedSegmentTimestampOffset??0);let s=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const n=de(this.segments,r,o=>o.timestamp);if(n===-1)return null;if(n<this.segments.length-1||this.streamHasEnded||s)return this.segments[n];const a=this.segments[n];if(r<a.timestamp+a.duration)return a;await this.runUpdateSegments(),t.skipLiveWait&&(s=!0)}}async getNextSegment(e,t){const r=e.index;w(r!==-1);const s=r+1;let n=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(s<this.segments.length)return this.segments[s];if(this.streamHasEnded||n)return null;await this.runUpdateSegments(),t.skipLiveWait&&(n=!0)}}async getPreviousSegment(e){const t=e.index;return w(t!==-1),this.segments[t-1]??null}getInputForSegment(e){var c;const t=e,r=this.inputCache.find(u=>u.segment===t);if(r)return r.age=this.nextInputCacheAge++,r.input;let s=null;(t.initSegment||t.firstSegment)&&(s=this.getInputForSegment(t.initSegment??t.firstSegment));const n={...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=>vu(f,d))&&(l=[...l,d]),this.input._formatOptions.isobmff.resolveKeyId({...u,psshBoxes:l})})}},a=new qn({source:new Gm(t.location.path,async u=>{w(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;w(h.iv);let p=await this.input._getSourceCached(l);if(f){const b=p.source.slice(t.location.offset,t.location.length??void 0).ref();p.free(),p=b}const m=new sn(p.source),g=im(m,async()=>{const y={stack:[],error:void 0,hasError:!1};try{const b=Jc(y,await this.input._getSourceCached({path:h.keyUri,isRoot:!1},Ip),!1),A=await new sn(b.source).requestSlice(0,Kt);if(!A)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:X(A,Kt),iv:h.iv}}catch(b){y.error=b,y.hasError=!0}finally{el(y)}},()=>{p.free()});d=new md(g).ref()}else w(!1);return d}),formats:this.input._formats.filter(u=>!(u instanceof kd)),initInput:s??void 0,formatOptions:n});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=Fn(this.inputCache,l=>l.age);w(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();w(e);const t=this.demuxer.getReferenceSegmentedInput();if(this===t)return 0;const r=await t.getFirstSegment();if(r&&(this.listsAllSegments()&&t.listsAllSegments()||e.unixEpochTimestamp===e.timestamp&&r.unixEpochTimestamp===r.timestamp))return 0;const s=this.getInputForSegment(e);if(await this.getRawTimestampOffset(s)===null)return 0;const n=await Lo(s);if(n===null)throw new Error("The playlist's first segment contains no media.");const a=await this.getMediaOffset(e,s),o=n+a-e.timestamp;return this.learnedSegmentTimestampOffset??(this.learnedSegmentTimestampOffset=o),o})())}listsAllSegments(){return this.segments[0].sequenceNumber===0||this.neverRemovesSegments}async getRawTimestampOffset(e){var n;if((await e.getFormat()).supportsTimestampedMediaData)return 0;const s=(n=(await e.getMetadataTags()).raw)==null?void 0:n.PRIV;for(const a of Fi(s)){if(!(a instanceof Uint8Array)||a.length!==Qt.length+1+8||nt.decode(a.subarray(0,Qt.length))!==Qt||a[Qt.length]!==0)continue;const o=ie(a),c=o.getUint32(Qt.length+1),u=o.getUint32(Qt.length+5);if(c>1)continue;const l=2**32*c+u;return sd(l,rd(l))/lt-await e.getFirstTimestamp()}return null}getTimestampWrapPeriod(){return ks/lt}}/*!
|
|
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 rp=256,sp=256;class np extends Ai{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()=>{w(this.input._rootSource instanceof ar);const e=await this.input._reader.requestEntireFile();w(e);const t=Bd(e,e.length,{ignore:ad}),{rootPath:r}=this.input._rootSource,s=new od(r,null),n=[],a=[];for(let l=1;l<t.length;l++){const d=t[l];if(d.startsWith(Sn))s.define(d.slice(Sn.length));else if(d.startsWith(Dc)){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=s.substitute(h);const p=st(r,h),m=new Er(d.slice(Dc.length),s);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.");n.push({fullPath:p,attributes:m,lineNumber:f,hasOnlyKeyPackets:!1})}else if(d.startsWith(zc)){const f=new Er(d.slice(zc.length),s),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=st(r,h);n.push({fullPath:m,attributes:f,lineNumber:l,hasOnlyKeyPackets:!0})}else if(d.startsWith(Oc)){const f=new Er(d.slice(Oc.length),s);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 g=f.get("uri");g!==null&&(m=st(r,g)),a.push({fullPath:m,attributes:f,lineNumber:l})}else if(d.startsWith(ao)){const f=new il(this,r,null,t);this.segmentedInputs=[f],this.hasMasterPlaylist=!1,this.trackBackings=await f.getTrackBackings();return}}if(n.length>rp||a.length>sp)throw new Error("Unsupported M3U8 file; too many variant streams or media tags.");this.masterPlaylistVariables=s;const o=await Promise.all(n.map(async(l,d)=>{const f=[],h=l.attributes.get("codecs");let p;if(h)p=h.split(",").map(_=>_.trim());else{const I=await this.getSegmentedInputForPath(l.fullPath).getTrackBackings(),v=await Promise.all(I.map(async R=>({track:R,codec:await R.getCodec()})));p=await Promise.all(v.filter(R=>R.codec!==null).map(R=>R.track.getDecoderConfig().then(F=>F.codec)))}const m=l.attributes.get("video"),g=l.attributes.get("audio"),y=p.some(_=>Oe.includes(Dt(_))),b=p.some(_=>Ke.includes(Dt(_)));if(m!==null&&!y){const _=a.find(I=>{const v=I.attributes.get("group-id"),R=I.attributes.get("type");return v===m&&R.toLowerCase()==="video"});e:if(_){const I=_.attributes.get("uri");if(I===null)break e;const v=st(r,I),H=(await this.getSegmentedInputForPath(v).getTrackBackings()).find(U=>U.getType()==="video");if(!H||await H.getCodec()===null)break e;const O=await H.getDecoderConfig().then(U=>(U==null?void 0:U.codec)??null);w(O!==null),p.push(O)}}if(g!==null&&!b){const _=a.find(I=>{const v=I.attributes.get("group-id"),R=I.attributes.get("type");return v===g&&R.toLowerCase()==="audio"});e:if(_){const I=_.attributes.get("uri");if(I===null)break e;const v=st(r,I),H=(await this.getSegmentedInputForPath(v).getTrackBackings()).find(U=>U.getType()==="audio");if(!H||await H.getCodec()===null)break e;const O=await H.getDecoderConfig().then(U=>(U==null?void 0:U.codec)??null);w(O!==null),p.push(O)}}p=[...new Set(p)];const S=l.attributes.getAsNumber("bandwidth");w(S!==null);const A=l.attributes.getAsNumber("average-bandwidth"),x=l.attributes.get("name"),T=async(_,I,v)=>{const R=new Set(_.map(L=>Dt(L)));if(R.size===1){const[L]=R;return w(L),{codec:L,fullCodecString:_.length===1?_[0]:null}}const H=(await this.getSegmentedInputForPath(I).getTrackBackings()).filter(L=>L.getType()===v);if(H.length!==1)throw new Error(`Unsupported M3U8 file; a variant stream lists several ${v} codecs, but its media doesn't contain exactly one ${v} track.`);const O=await H[0].getCodec();if(O===null)return null;const U=await H[0].getDecoderConfig();return w(U),{codec:O,fullCodecString:U.codec}},P=p.filter(_=>Oe.includes(Dt(_))),C=p.filter(_=>Ke.includes(Dt(_)));for(const _ of p)if(_===P[0]){const I=a.filter(v=>v.attributes.get("group-id")===m&&v.attributes.get("type").toLowerCase()==="video");if(I.length===0){const v=l.attributes.get("resolution");let R=null,F=null;if(v){const O=v.match(/^(\d+)x(\d+)$/);O&&(R=Number(O[1]),F=Number(O[2]))}const H=await T(P,l.fullPath,"video");H&&f.push({demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:et,lineNumber:l.lineNumber,fullPath:l.fullPath,codec:H.codec,fullCodecString:H.fullCodecString,pairingMask:1n<<BigInt(d),peakBitrate:S,averageBitrate:A,name:x,hasOnlyKeyPackets:l.hasOnlyKeyPackets,info:{type:"video",width:R,height:F}})}else{const v=await Promise.all(I.map(R=>T(P,R.fullPath??l.fullPath,"video")));for(let R=0;R<I.length;R++){const F=I[R],H=v[R];if(!H)continue;const O=F.attributes.get("resolution")??l.attributes.get("resolution");let U=null,L=null;if(O){const Q=O.match(/^(\d+)x(\d+)$/);Q&&(U=Number(Q[1]),L=Number(Q[2]))}f.push({demuxer:this,backingTrack:null,default:js(F.attributes),autoselect:js(F.attributes)||rl(F.attributes),languageCode:sl(F.attributes.get("language")),lineNumber:F.lineNumber,fullPath:F.fullPath??l.fullPath,codec:H.codec,fullCodecString:H.fullCodecString,pairingMask:1n<<BigInt(d),peakBitrate:F.fullPath===null?S:null,averageBitrate:F.fullPath===null?A:null,name:F.attributes.get("name"),hasOnlyKeyPackets:l.hasOnlyKeyPackets,info:{type:"video",width:U,height:L}})}}}else if(_===C[0]){const I=a.filter(v=>v.attributes.get("group-id")===g&&v.attributes.get("type").toLowerCase()==="audio");if(I.length===0){const v=await T(C,l.fullPath,"audio");if(v){const R=l.attributes.get("channels");f.push({demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:et,lineNumber:l.lineNumber,fullPath:l.fullPath,codec:v.codec,fullCodecString:v.fullCodecString,pairingMask:1n<<BigInt(d),peakBitrate:S,averageBitrate:A,name:x,hasOnlyKeyPackets:l.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:nl(R)}})}}else{const v=await Promise.all(I.map(R=>T(C,R.fullPath??l.fullPath,"audio")));for(let R=0;R<I.length;R++){const F=I[R],H=v[R];if(!H)continue;const O=F.attributes.get("channels")??l.attributes.get("channels");f.push({demuxer:this,backingTrack:null,default:js(F.attributes),autoselect:js(F.attributes)||rl(F.attributes),languageCode:sl(F.attributes.get("language")),lineNumber:F.lineNumber,fullPath:F.fullPath??l.fullPath,codec:H.codec,fullCodecString:H.fullCodecString,pairingMask:1n<<BigInt(d),peakBitrate:F.fullPath===null?S:null,averageBitrate:F.fullPath===null?A:null,name:F.attributes.get("name"),hasOnlyKeyPackets:l.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:nl(O)}})}}}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===et&&(d.languageCode=l.languageCode)):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 gd(l)):this.trackBackings.push(new wd(l));this.internalTracks=c})())}async getTrackBackings(){return await this.readMetadata(),w(this.trackBackings),this.trackBackings}getMediaOffsetForDiscontinuity(e){let t=this.mediaOffsets.get(e);return t||(t=(async()=>{const r=this.getReferenceSegmentedInput();let s=await r.getFirstSegment();for(;s&&s.discontinuityNumber<e;)s=await r.getNextSegment(s,{});if(!s||s.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 n=r.getInputForSegment(s),a=await r.getRawTimestampOffset(n)??0,o=await Lo(n);if(o===null)throw new Error("The reference playlist's segment contains no media.");return s.timestamp-(a+o)})(),this.mediaOffsets.set(e,t),t)}getReferenceSegmentedInput(){if(!this.hasMasterPlaylist)return this.segmentedInputs[0];w(this.internalTracks);const e=this.internalTracks.filter(a=>!a.hasOnlyKeyPackets),t=e.length>0?e:this.internalTracks,r=t.filter(a=>a.info.type==="video"),s=r.length>0?r:t,n=Fn(s,a=>a.peakBitrate??1/0);return w(n!==-1),this.getSegmentedInputForPath(s[n].fullPath)}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(s=>s.path===e);if(t)return t;let r=null;return this.internalTracks&&(r=this.internalTracks.filter(n=>n.fullPath===e).map(n=>({type:n.info.type}))),t=new il(this,e,r,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return _r}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class pd{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 s=(await e.getTrackBackings()).filter(n=>n.getType()===this.getType());if(s.length===1)t=s[0];else if(this instanceof gd){for(const n of s)if(await n.getCodec()===this.getCodec()){t=n;break}}else{w(this instanceof wd);for(const n of s)if(await n.getCodec()===this.getCodec()){t=n;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{...Si,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){w(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const r of this.internalTrack.demuxer.internalTracks)if(r.info.type===e&&t++,r===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 gd extends pd{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return this.internalTrack.codec}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getTransformationMatrix(){return this.delegate(()=>this.backingVideoTrack.getTransformationMatrix())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){if(await this.hydrate(),await this.backingVideoTrack.getCodec()!==this.getCodec())throw new Error("The codec in the playlist doesn't match the codec of the media data.");return this.backingVideoTrack.getDecoderConfig()}}class wd extends pd{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return this.internalTrack.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels!==null?this.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 js=i=>{const e=i.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}".`)},rl=i=>{const e=i.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}".`)},sl=i=>{if(i===null)return et;const e=i.split("-")[0];return e||et},nl=i=>{if(i===null)return null;const[e,t]=i.split("/");if(t!==void 0&&t!=="-")return null;const r=Number(e);return Number.isInteger(r)&&r>0?r:null};/*!
|
|
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 ei{constructor(){this._isIsobmff=!1}}class yd extends ei{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(D(t)&&(t=await t),!t)return null;const r=q(t),s=Ie(t,4);if(s!=="ftyp"&&s!=="styp")return null;if(r===1){let n=e._reader.requestSlice(16,4);return D(n)&&(n=await n),n?Ie(n,4):null}return Ie(t,4)}_createDemuxer(e){return new zo(e)}get supportsTimestampedMediaData(){return!0}}class ap extends yd{async _getMatchPosition(e){const t=await this._getMajorBrand(e);if(t!==null)return t!=="qt "?0:null;let r=0;for(let s=0;s<10;s++){let n=e._reader.requestSlice(r,8);if(D(n)&&(n=await n),!n)return null;let a=q(n),o=8;if(a===1){let u=e._reader.requestSlice(r+8,8);if(D(u)&&(u=await u),!u)return null;a=ft(u),o=16}if(a<o)return null;const c=Ie(n,4);if(c==="moof"||c==="sidx"||c==="moov"||c==="mdat")return 0;if(c==="emsg"||c==="prft"||c==="free"||c==="skip"||c==="wide")r+=a;else return null}return null}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class op extends yd{async _getMatchPosition(e){return await this._getMajorBrand(e)==="qt "?0:null}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class bd extends ei{async isSupportedEBMLOfDocType(e,t){let r=e._reader.requestSlice(0,ui);if(D(r)&&(r=await r),!r)return!1;const s=Lu(r);if(s===null||s<1||s>8||le(r,s)!==E.EBML)return!1;const a=ju(r);if(typeof a!="number")return!1;let o=e._reader.requestSlice(r.filePos,a);if(D(o)&&(o=await o),!o)return!1;const c=r.filePos;for(;o.filePos<=c+a-Pt;){const u=$t(o);if(!u)break;const{id:l,size:d}=u,f=o.filePos;if(d===void 0||f+d>c+a||d>8&&l!==E.DocType)return!1;switch(l){case E.EBMLReadVersion:if(le(o,d)!==1)return!1;break;case E.DocType:if(kr(o,d)!==t)return!1;break;case E.DocTypeReadVersion:if(le(o,d)>4)return!1;break}o.filePos=f+d}return!0}async _getMatchPosition(e){return await this.isSupportedEBMLOfDocType(e,"matroska")?0:null}_createDemuxer(e){return new hm(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}get supportsTimestampedMediaData(){return!0}}class cp extends bd{async _getMatchPosition(e){return await this.isSupportedEBMLOfDocType(e,"webm")?0:null}get name(){return"WebM"}get mimeType(){return"video/webm"}}class lp extends ei{async _getMatchPosition(e){const t=await sr(e._reader,0),r=await Ja(e._reader,t,4096,null);return r?r.startPos===t?0:r.startPos:null}_createDemuxer(e){return new ym(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}get supportsTimestampedMediaData(){return!1}}class up extends ei{async _getMatchPosition(e){let t=e._reader.requestSlice(0,12);if(D(t)&&(t=await t),!t)return null;const r=Ie(t,4);return r!=="RIFF"&&r!=="RIFX"&&r!=="RF64"?null:(t.skip(4),Ie(t,4)==="WAVE"?0:null)}_createDemuxer(e){return new _m(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}get supportsTimestampedMediaData(){return!1}}class dp extends ei{async _getMatchPosition(e){let t=e._reader.requestSlice(0,4);return D(t)&&(t=await t),t&&Ie(t,4)==="OggS"?0:null}_createDemuxer(e){return new Pm(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}get supportsTimestampedMediaData(){return!0}}class fp extends ei{async _getMatchPosition(e){const t=await sr(e._reader,0);let r=e._reader.requestSlice(t,4);return D(r)&&(r=await r),r&&Ie(r,4)==="fLaC"?0:null}get name(){return"FLAC"}get mimeType(){return"audio/flac"}get supportsTimestampedMediaData(){return!1}_createDemuxer(e){return new Mm(e)}}class hp extends ei{async _getMatchPosition(e){const t=await sr(e._reader,0),r=await io(e._reader,t,4096,null);return r?r.startPos===t?0:r.startPos:null}_createDemuxer(e){return new Im(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}get supportsTimestampedMediaData(){return!1}}class mp extends ei{async _getMatchPosition(e){const t=ct+16+1;let r=e._reader.requestSlice(0,t);if(D(r)&&(r=await r),!r)return null;const s=X(r,t);return s[0]===71&&s[ct]===71||s[0]===71&&s[ct+16]===71||s[4]===71&&s[4+ct+4]===71?0:null}_createDemuxer(e){return new Wo(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}get supportsTimestampedMediaData(){return!0}}class kd extends ei{async _getMatchPosition(e){let t=e._reader.requestSlice(0,7);if(D(t)&&(t=await t),!t||!(Ie(t,7)==="#EXTM3U"))return null;if(!(e._rootSource instanceof ar))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 np(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return _r}get supportsTimestampedMediaData(){return!0}}const Td=new ap,Sd=new op,pp=new bd,gp=new cp,Ad=new lp,wp=new up,yp=new dp,xd=new hp,bp=new fp,Pd=new mp,Cd=new kd,k0=[Cd,Td,Sd,pp,gp,wp,yp,bp,Ad,xd,Pd],T0=[Cd,Td,Sd,Ad,xd,Pd],kp=(i,e)=>{if(!i||typeof i!="object")throw new TypeError(`${e}, when provided, must be an object.`);if(i.isobmff!==void 0){if(!i.isobmff||typeof i.isobmff!="object")throw new TypeError(`${e}.isobmff, when provided, must be an object.`);if(i.isobmff.resolveKeyId!==void 0&&typeof i.isobmff.resolveKeyId!="function")throw new TypeError(`${e}.isobmff.resolveKeyId, when provided, must be a function.`)}if(i.hls!==void 0){if(!i.hls||typeof i.hls!="object")throw new TypeError(`${e}.hls, when provided, must be an object.`);if(i.hls.offsetTimestampsByDateTime!==void 0&&typeof i.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 qi=i=>{if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.metadataOnly!==void 0&&typeof i.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(i.verifyKeyPackets!==void 0&&typeof i.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(i.verifyKeyPackets&&i.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(i.skipLiveWait!==void 0&&typeof i.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},ki=i=>{if(!ut(i))throw new TypeError("timestamp must be a number.")},oa=(i,e,t)=>t.verifyKeyPackets?e.then(async r=>{if(!r||r.type==="delta")return r;const s=await i.determinePacketType(r);return s&&(r.type=s),r}):e;class Ri{constructor(e){if(!(e instanceof Fs))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(qi(e),this._track.input._disposed)throw new He;return oa(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){qi(e);const t=await this.getFirstPacket(e);return t?t.type==="key"?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(ki(e),qi(t),this._track.input._disposed)throw new He;return oa(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(qi(t),this._track.input._disposed)throw new He;return oa(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(ki(e),qi(t),this._track.input._disposed)throw new He;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let r=await this._track._backing.getKeyPacket(e,t);for(;r;){if(w(r.type==="key"),await this._track.determinePacketType(r)!=="delta")return r;let n=1/await this._track.getTimeResolution(),a;for(;a=await this._track._backing.getKeyPacket(r.timestamp-n,t),!(!a||a.timestamp<r.timestamp);)n*=2;r=a}return null}async getNextKeyPacket(e,t={}){if(!(e instanceof Ce))throw new TypeError("packet must be an EncodedPacket.");if(qi(t),this._track.input._disposed)throw new He;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let r=await this._track._backing.getNextKeyPacket(e,t);for(;r;){if(w(r.type==="key"),await this._track.determinePacketType(r)!=="delta")return r;r=await this._track._backing.getNextKeyPacket(r,t)}return null}packets(e,t,r={}){if(e!==void 0&&!(e instanceof Ce))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!(r!=null&&r.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(qi(r),this._track.input._disposed)throw new He;const s=[];let{promise:n,resolve:a}=Ae(),{promise:o,resolve:c}=Ae(),u=!1,l=!1,d=null,f=!1;const h=[],p=()=>Math.max(2,h.length);(async()=>{let g=e??await this.getFirstPacket(r);for(;g&&!l&&!this._track.input._disposed&&!(t&&g.sequenceNumber>=(t==null?void 0:t.sequenceNumber));){if(s.length>p()){({promise:o,resolve:c}=Ae()),await o;continue}s.push(g),a(),{promise:n,resolve:a}=Ae(),g=await this.getNextPacket(g,r)}u=!0,a()})().catch(g=>{f||(d=g,f=!0,a())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new He;if(l)return{value:void 0,done:!0};if(f)throw d;if(s.length>0){const g=s.shift(),y=performance.now();for(h.push(y);h.length>0&&y-h[0]>=1e3;)h.shift();return c(),{value:g,done:!1}}else{if(u)return{value:void 0,done:!0};await n}}},async return(){return l=!0,c(),a(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}}const al=4;class Ko{constructor(e,t){this.onSample=e,this.onError=t,this.onDequeue=null}}class _d{mediaSamplesInRange(e=-1/0,t=1/0,r){ki(e),ki(t);const s=[];let n=!1,a=null,{promise:o,resolve:c}=Ae(),{promise:u,resolve:l}=Ae(),d=!1,f=!1,h=!1,p=null,m=null,g=!1;const y={...r,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{p=await this._createDecoder(v=>{if(l(),v.timestamp>=t&&(f=!0),f){v.close();return}a&&(v.timestamp>e?(s.push(a),n=!0):a.close()),v.timestamp>=e&&(s.push(v),n=!0),a=n?null:v,s.length>0&&(c(),{promise:o,resolve:c}=Ae())},v=>{g||(m=v,g=!0,c())}),p.onDequeue=()=>l();const A=this._createPacketSink(),x=await this._getPreRollDuration(),T=await A.getPacket(e,y),P=await A.getKeyPacket(((T==null?void 0:T.timestamp)??e)-x,y)??await A.getFirstKeyPacket(y);let C=P;const I=A.packets(P??void 0,void 0,y);for(await I.next();C&&!f&&!this._track.input._disposed;){if(s.length+p.getDecodeQueueSize()>=al){({promise:u,resolve:l}=Ae()),await u;continue}p.decode(C);const v=await I.next();if(v.done)break;C=v.value}await I.return(),!h&&!this._track.input._disposed&&await p.flush(),!n&&a&&(s.push(a),a=null),d=!0,c()})().catch(A=>{g||(m=A,g=!0,c())}).finally(()=>{p==null||p.close()});const b=this._track,S=()=>{a==null||a.close();for(const A of s)A.close()};return{async next(){for(;;){if(b.input._disposed)throw h=!0,f=!0,l(),S(),new He;if(h)return{value:void 0,done:!0};if(g)throw h=!0,f=!0,l(),S(),m;if(s.length>0){const A=s.shift();return l(),{value:A,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return h=!0,f=!0,l(),c(),S(),{value:void 0,done:!0}},async throw(A){throw await this.return(),A},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){gf(e);const r=pf(e),s=[],n=[];let{promise:a,resolve:o}=Ae(),{promise:c,resolve:u}=Ae(),l=!1,d=!1;const{promise:f,resolve:h}=Ae();let p=null,m=null,g=!1;const y=P=>{n.push(P),o(),{promise:a,resolve:o}=Ae()};let b=null;const S=P=>{for(let C=0;C<P;C++)y(b&&(C<P-1?b.clone():b));P===0&&(b==null||b.close()),b=null},A={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{p=await this._createDecoder(U=>{if(u(),d){U.close();return}let L=0;for(;s.length>0&&U.timestamp-s[0]>1e-10;)L++,s.shift();S(L),b=U},U=>{g||(m=U,g=!0,o())}),p.onDequeue=()=>u();const P=this._createPacketSink(),C=await this._getPreRollDuration();let _=null,I=-1/0,v=null,R=null,F=-1;const H=async()=>{w(v),w(p);let U=R;for(U||(U=v,p.decode(U));U.sequenceNumber<F;){for(;n.length+p.getDecodeQueueSize()>=al&&!d;)({promise:c,resolve:u}=Ae()),await c;if(d)break;const L=await P.getNextPacket(U,A);if(!L)throw new Error("Internal error: couldn't get next packet when one was expected.");p.decode(L),U=L}R=U},O=async()=>{w(p),await p.flush(),S(s.length),s.length=0};try{for(;;){const U=r.next();U.catch(()=>{});const L=await Promise.race([U,f]);if(!L||L.done)break;const Q=L.value;if(ki(Q),d||this._track.input._disposed)break;const re=await P.getPacket(Q,A);let Y=re&&await P.getKeyPacket(re.timestamp-C,A);if(re&&!Y){const se=await P.getFirstKeyPacket(A);se&&se.timestamp<=re.timestamp&&(Y=se)}if(!re||!Y){_&&await O(),y(null),_=null;continue}(!_||Y.sequenceNumber>F+1||Q<I)&&(_&&await O(),v=Y,R=null,F=-1),s.push(Q),F=Math.max(re.sequenceNumber,F),_=re,I=Q,await H()}}finally{r.return().catch(()=>{})}!d&&!this._track.input._disposed&&await O(),l=!0,o()})().catch(P=>{g||(m=P,g=!0,o())}).finally(()=>{p==null||p.close()});const x=this._track,T=()=>{b==null||b.close(),b=null;for(const P of n)P==null||P.close()};return{async next(){for(;;){if(x.input._disposed)throw d=!0,h(),u(),T(),new He;if(d)return{value:void 0,done:!0};if(g)throw d=!0,h(),u(),T(),m;if(n.length>0){const P=n.shift();return w(P!==void 0),u(),{value:P,done:!1}}else if(!l)await a;else return{value:void 0,done:!0}}},async return(){return d=!0,h(),u(),o(),T(),{value:void 0,done:!0}},async throw(P){throw await this.return(),P},[Symbol.asyncIterator](){return this}}}}class Tp extends Ko{constructor(e,t,r,s,n,a,o){var u,l,d,f;super(e,t),this.codec=r,this.decoderConfig=s,this.rotation=n,this.flip=a,this.timeResolution=o,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new vn,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=ws.find(h=>h.supports(r,s));if(c)this.customDecoder=new c,this.customDecoder.codec=r,this.customDecoder.config=s,this.customDecoder.onSample=h=>{if(!(h instanceof Je))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 g=this.alphaQueue.shift();w(g!==void 0),this.mergeAlpha(m,g)}else this.colorQueue.push(m)};if(ts()){if(r==="avc"&&this.decoderConfig.description){const m=Es(me(this.decoderConfig.description));if(m&&m.sequenceParameterSets.length>0){const g=Zi(m.sequenceParameterSets[0]);g&&g.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"});let y=!1;for(let b=0;b<m.sequenceParameterSets.length;b++){const S=Zi(m.sequenceParameterSets[b]);S&&S.maxDecFrameBuffering!==0&&S.bitstreamRestrictionFlag!==1&&(m.sequenceParameterSets[b]=uc(S),y=!0)}y&&(this.decoderConfig={...this.decoderConfig,description:So(m)})}}go(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(g){this.onError(g)}},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:(w(this.decoder),Math.max(this.decoder.decodeQueueSize,((e=this.alphaDecoder)==null?void 0:e.decodeQueueSize)??0)+this.finalSamples.length)}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(t=>this.onError(t)).finally(()=>{var t;this.customDecoderQueueSize--,(t=this.onDequeue)==null||t.call(this)});else{if(w(this.decoder),!wi()){const t=nh(this.codec,e.data);for(let r=0;r<t;r++)rc(this.inputTimestamps,e.timestamp,s=>s)}if(ts()&&this.currentPacketIndex===0){const t=this.fixFirstPacketDataForChromium(e.data);t&&(e=e.clone({data:t}))}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||(this.merger=new Sp),!this.alphaDecoder){const r=n=>{if(this.colorQueue.length>0){const a=this.colorQueue.shift();w(a!==void 0),this.mergeAlpha(a,n)}else this.alphaQueue.push(n);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();w(a!==void 0),this.mergeAlpha(a,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},s=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:n=>{try{r(this.copyFrameIfNeeded(n))}catch(a){this.onError(a)}},error:n=>{n.stack=s,this.onError(n)}}),this.alphaDecoder.addEventListener("dequeue",()=>{var n;(n=this.onDequeue)==null||n.call(this)}),this.alphaDecoder.configure({...this.decoderConfig,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"}})}const t=Nn(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}if(ts()&&this.currentAlphaPacketIndex===0){const r=this.fixFirstPacketDataForChromium(e.sideData.alpha);r&&(e=e.clone({sideData:{...e.sideData,alpha:r}}))}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}fixFirstPacketDataForChromium(e){if(this.codec==="avc"){const t=[];let r=!1;for(const s of tu(e,this.decoderConfig)){const n=rr(e[s.offset]);if(r||(r=n>=1&&n<=5),n===Ve.AUD){if(r)break;t.length=0}n>=20&&n<=31||t.push(e.subarray(s.offset,s.offset+s.length))}if(!this.decoderConfig.description)for(let s=0;s<t.length;s++){const n=t[s];if(rr(n[0])!==Ve.SPS)continue;const a=Zi(n);a&&a.maxDecFrameBuffering!==0&&a.bitstreamRestrictionFlag!==1&&(t[s]=uc(a))}return Kf(t,this.decoderConfig)}else return this.codec==="hevc"?th(e,this.decoderConfig):null}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(const t of mn(e,this.decoderConfig)){const r=zi(e[t.offset]);if(r===ke.RASL_N||r===ke.RASL_R)return!0}return!1}sampleHandler(e){if(wi()){if(this.sampleQueue.length>0&&e.timestamp>=Te(this.sampleQueue).timestamp){for(const t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}rc(this.sampleQueue,e,t=>t.timestamp)}else{const t=this.inputTimestamps.shift();w(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 r=Ae();this.mergeAlphaPromises.push(r.promise);const s={sample:null};this.finalSamples.push(s);try{if(!t)s.sample=new Je(e);else{w(this.merger);const n=await this.merger.merge(e,t);s.sample=new Je(n)}for(;this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){const n=this.finalSamples.shift();this.sampleHandler(n.sample)}}catch(n){for(on(this.finalSamples,s);this.finalSamples.length>0&&this.finalSamples[0].sample!==null;)this.finalSamples.shift().sample.close();this.onError(n)}finally{on(this.mergeAlphaPromises,r.promise),r.resolve()}}copyFrameIfNeeded(e){if(!ts()||!Pf())return e;const t=e.visibleRect,r=t.width,s=t.height;if(!this.frameCopyContext){let o;if(typeof OffscreenCanvas<"u"?o=new OffscreenCanvas(r,s).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 n=this.frameCopyContext.canvas;(n.width!==r||n.height!==s)&&(n.width=r,n.height=s),this.frameCopyContext.drawImage(e,0,0,r,s),this.flushing&&this.frameCopyContext.getImageData(0,0,1,1);const a=new VideoFrame(n,{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()):(w(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.inputTimestamps.length=0,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),wi()){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()).catch(t=>this.onError(t)):(w(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 ca=null;class Sp{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(this.workers.length===0){if(!ca){const o=new Blob([`(${Ap.toString()})()`],{type:"application/javascript"});ca=URL.createObjectURL(o)}const a=Be(navigator.hardwareConcurrency,1,4);for(let o=0;o<a;o++){const c=new Worker(ca);c.addEventListener("message",u=>{const l=u.data,d=this.pendingRequests.get(l.id);if(!d){"frame"in l&&l.frame.close();return}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 r=this.nextRequestId++,s=Ae();this.pendingRequests.set(r,s);const n=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,n.postMessage({id:r,color:e,alpha:t},{transfer:[e,t]}),s.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 Ap=()=>{let i=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 r(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 r=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 s(c,u,l);if(l==="I420"||l==="I420P10"||l==="I420P12"||l==="I422"||l==="I422P10"||l==="I422P12"||l==="I444"||l==="I444P10"||l==="I444P12")return await n(c,u,l);if(l==="NV12")return await a(c,u);throw new Error(`CPU color/alpha merging does not support format '${l}'.`)},s=async(c,u,l)=>{var b,S;const d=((b=c.visibleRect)==null?void 0:b.width)??c.codedWidth,f=((S=c.visibleRect)==null?void 0:S.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 A=0,x=3;A<h;A++,x+=4)p[x]=m[A];const y={format:l==="RGBX"||l==="RGBA"?"RGBA":"BGRA",codedWidth:d,codedHeight:f,displayWidth:c.displayWidth,displayHeight:c.displayHeight,colorSpace:c.colorSpace.toJSON(),timestamp:c.timestamp,duration:c.duration??void 0,transfer:[p.buffer]};return new VideoFrame(p,y)},n=async(c,u,l)=>{var F,H;const d=((F=c.visibleRect)==null?void 0:F.width)??c.codedWidth,f=((H=c.visibleRect)==null?void 0:H.height)??c.codedHeight,h=l.includes("P10"),p=l.includes("P12"),m=h||p?2:1;let g,y;l.startsWith("I420")?(g=Math.ceil(d/2),y=Math.ceil(f/2)):l.startsWith("I422")?(g=Math.ceil(d/2),y=f):(g=d,y=f);const b=d*f,S=g*y,A=b*m,x=S*m,T=b*m,P=A+2*x+T,C=new Uint8Array(P);await c.copyTo(C);const _=await o(u,d,f,m),I=A+2*x;C.set(_,I);const R={format:l.slice(0,4)+"A"+l.slice(4),codedWidth:d,codedHeight:f,displayWidth:c.displayWidth,displayHeight:c.displayHeight,colorSpace:c.colorSpace.toJSON(),timestamp:c.timestamp,duration:c.duration??void 0,transfer:[C.buffer]};return new VideoFrame(C,R)},a=async(c,u)=>{var P,C;const l=((P=c.visibleRect)==null?void 0:P.width)??c.codedWidth,d=((C=c.visibleRect)==null?void 0:C.height)??c.codedHeight,f=l*d,h=Math.ceil(l/2),p=Math.ceil(d/2),m=h*p,g=c.allocationSize();(!e||e.byteLength!==g)&&(e=new Uint8Array(g)),await c.copyTo(e);const y=new Uint8Array(f+2*m+f);y.set(e.subarray(0,f),0);const b=f,S=f+m,A=f;for(let _=0;_<m;_++)y[b+_]=e[A+_*2],y[S+_]=e[A+_*2+1];const x=await o(u,l,d,1);y.set(x,f+2*m);const T={format:"I420A",codedWidth:l,codedHeight:d,displayWidth:c.displayWidth,displayHeight:c.displayHeight,colorSpace:c.colorSpace.toJSON(),timestamp:c.timestamp,duration:c.duration??void 0,transfer:[y.buffer]};return new VideoFrame(y,T)},o=async(c,u,l,d)=>{const f=c.allocationSize();(!i||i.byteLength!==f)&&(i=new Uint8Array(f)),await c.copyTo(i);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 g=0;g<m;g++)i[g]=i[g*4+p];return i.subarray(0,m)}else{const p=i.subarray(0,u*l*d);if(c.colorSpace.fullRange===!1){const m=h.includes("P12")?12:h.includes("P10")?10:8,g=16<<m-8,y=235<<m-8,b=(1<<m)-1,S=d===2?new Uint16Array(p.buffer,0,u*l):p;for(let A=0;A<S.length;A++){const x=Math.round((S[A]-g)*b/(y-g));S[A]=Math.min(Math.max(x,0),b)}}return p}}},Ed=i=>{if(!i||typeof i!="object")throw new TypeError("decoderOptions must be an object.");if(i.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(i.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(i.optimizeForLatency!==void 0&&typeof i.optimizeForLatency!="boolean")throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};class oo extends _d{constructor(e,t={}){if(!(e instanceof Ln))throw new TypeError("videoTrack must be an InputVideoTrack.");Ed(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!await this._track.canDecode())throw typeof VideoDecoder>"u"?new Error(Bn("VideoDecoder")):new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.");const r=await this._track.getCodec(),s=await this._track.getRotation(),n=await this._track.getFlip();let a=await this._track.getDecoderConfig();const o=await this._track.getTimeResolution();return w(r&&a),a={...a,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new Tp(e,t,r,a,s,n,o)}_createPacketSink(){return new Ri(this._track)}async _getPreRollDuration(){return 0}async getSample(e,t={}){ki(e);for await(const r of this.mediaSamplesAtTimestamps([e],t))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,r={}){return this.mediaSamplesInRange(e,t,r)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class S0{constructor(e,t={}){if(this._rotation=0,this._flip=!1,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof Ln))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&&ps(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&&Ed(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new oo(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,r=e.rotation??await t.getRotation(),s=e.flip??await t.getFlip(),n=await t.getSquarePixelWidth(),a=await t.getSquarePixelHeight(),[o,c]=r%180===0?[n,a]:[a,n];let u=e.crop;u&&(u=wn(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=r,this._flip=s,this._crop=u})())}_videoSampleToWrappedCanvas(e){const t=this._width,r=this._height;let s=this._canvasPool[this._nextCanvasIndex],n=!1;s||(typeof document<"u"?(s=document.createElement("canvas"),s.width=t,s.height=r):s=new OffscreenCanvas(t,r),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=s),n=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const a=s.getContext("2d",{alpha:this._alpha||ir()});w(a);try{return e._drawWithFitAndMipmapping(s,a,{fit:this._fit,rotation:this._rotation,flip:this._flip,crop:this._crop,targetIsFresh:n,fillBlack:!this._alpha&&ir()}),{canvas:s,timestamp:e.timestamp,duration:e.duration}}finally{e.close()}}async getCanvas(e,t){ki(e),await this._ensureInit();const r=await this._videoSampleSink.getSample(e,t);return r&&this._videoSampleToWrappedCanvas(r)}async*canvases(e,t,r){await this._ensureInit(),yield*cn(this._videoSampleSink.samples(e,t,r),s=>this._videoSampleToWrappedCanvas(s))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*cn(this._videoSampleSink.samplesAtTimestamps(e,t),r=>r&&this._videoSampleToWrappedCanvas(r))}}class xp extends Ko{constructor(e,t,r,s){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new vn,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const n=r==="opus"&&s.description?vs(me(s.description)).preSkip/Wi:0,a=c=>{let u=c.timestamp;this.expectedFirstTimestamp!==null&&this.currentTimestamp===null&&(this.timestampOffset=this.expectedFirstTimestamp+n-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=s.sampleRate;c.setTimestamp(Math.round(l*d)/d),e(c)},o=ys.find(c=>c.supports(r,s));if(o)this.customDecoder=new o,this.customDecoder.codec=r,this.customDecoder.config=s,this.customDecoder.onSample=c=>{if(!(c instanceof qe))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 qe(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(s)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(w(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)})):(w(this.decoder),this.expectedFirstTimestamp??(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(w(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()).catch(e=>this.onError(e)):(w(this.decoder),this.decoder.state!=="closed"&&this.decoder.close())}}class Pp extends Ko{constructor(e,t,r){super(e,t),this.decoderConfig=r,this.currentTimestamp=null,w(je.includes(r.codec)),this.codec=r.codec;const{dataType:s,sampleSize:n,littleEndian:a}=Bt(this.codec);switch(this.inputSampleSize=n,n){case 1:s==="unsigned"?this.readInputValue=(o,c)=>o.getUint8(c)-2**7:s==="signed"?this.readInputValue=(o,c)=>o.getInt8(c):s==="ulaw"?this.readInputValue=(o,c)=>Eh(o.getUint8(c)):s==="alaw"?this.readInputValue=(o,c)=>vh(o.getUint8(c)):w(!1);break;case 2:s==="unsigned"?this.readInputValue=(o,c)=>o.getUint16(c,a)-2**15:s==="signed"?this.readInputValue=(o,c)=>o.getInt16(c,a):w(!1);break;case 3:s==="unsigned"?this.readInputValue=(o,c)=>En(o,c,a)-2**23:s==="signed"?this.readInputValue=(o,c)=>wf(o,c,a):w(!1);break;case 4:s==="unsigned"?this.readInputValue=(o,c)=>o.getUint32(c,a)-2**31:s==="signed"?this.readInputValue=(o,c)=>o.getInt32(c,a):s==="float"?this.readInputValue=(o,c)=>o.getFloat32(c,a):w(!1);break;case 8:s==="float"?this.readInputValue=(o,c)=>o.getFloat64(c,a):w(!1);break;default:xe(n),w(!1)}switch(n){case 1:s==="ulaw"||s==="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,s==="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:xe(n),w(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=ie(e.data),r=Math.floor(e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize);if(r===0)return;const s=r*this.decoderConfig.numberOfChannels*this.outputSampleSize,n=new ArrayBuffer(s),a=new DataView(n);for(let d=0;d<r*this.decoderConfig.numberOfChannels;d++){const f=d*this.inputSampleSize,h=d*this.outputSampleSize,p=this.readInputValue(t,f);this.writeOutputValue(a,h,p)}const o=r/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=this.decoderConfig.sampleRate,l=new qe({format:this.outputFormat,data:n,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:u,numberOfFrames:r,timestamp:tr(c,u),_doNotCopy:!0});this.onSample(l)}async flush(){this.currentTimestamp=null}close(){}}class Id extends _d{constructor(e){if(!(e instanceof Hn))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(Bn("AudioDecoder")):new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.");const r=await this._track.getCodec(),s=await this._track.getDecoderConfig();return w(r&&s),je.includes(s.codec)?new Pp(e,t,s):new xp(e,t,r,s)}_createPacketSink(){return new Ri(this._track)}async _getPreRollDuration(){const e=await this._track.getPreRollDuration();return w(e!==null),e}async getSample(e,t={}){ki(e);for await(const r of this.mediaSamplesAtTimestamps([e],t))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,r={}){return this.mediaSamplesInRange(e,t,r)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class A0{constructor(e){if(!(e instanceof Hn))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Id(e)}_audioSampleToWrappedArrayBuffer(e){try{return{buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration}}finally{e.close()}}async getBuffer(e,t){ki(e);const r=await this._audioSampleSink.getSample(e,t);return r&&this._audioSampleToWrappedArrayBuffer(r)}buffers(e,t,r){return cn(this._audioSampleSink.samples(e,t,r),s=>this._audioSampleToWrappedArrayBuffer(s))}buffersAtTimestamps(e,t){return cn(this._audioSampleSink.samplesAtTimestamps(e,t),r=>r&&this._audioSampleToWrappedArrayBuffer(r))}}/*!
|
|
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 Fs{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Ln}isAudioTrack(){return this instanceof Hn}get id(){const e=this.input._trackBackingsCache;w(e);const t=e.indexOf(this._backing);return w(t!==-1),t+1}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Fe(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Fe(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return Fe(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Fe(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 Fe(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return await this.getFirstTimestampOrNull()??0}async getFirstTimestampOrNull(){const e=await this._backing.getFirstPacket({metadataOnly:!0});return(e==null?void 0:e.timestamp)??null}async computeDuration(e){return await this.computeDurationOrNull(e)??0}async computeDurationOrNull(e){const t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e});return t?tr(t.timestamp+t.duration,await this.getTimeResolution()):null}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){const r=new Ri(this);let s=1/0,n=-1/0,a=0,o=0;for await(const u of r.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&u.timestamp>=n&&n>s)break;s=Math.min(s,u.timestamp),n=Math.max(n,u.timestamp+u.duration),a++,o+=u.byteLength}const c=n-s;return{packetCount:a,averagePacketRate:a>0?Number((a/c).toPrecision(16)):0,averageBitrate:o>0?Number((8*o/c).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof Fs))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(Xi({filter:t=>t.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(Xi({filter:t=>t.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(Xi({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(Xi({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(Xi({filter:t=>t.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&(e=la(e));const t=await this.input.getTracks();for(const r of t)if(this.canBePairedWith(r)&&(!e||await e(r)))return!0;return!1}hasPairableVideoTrack(e){return e&&(e=la(e)),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&(e=la(e)),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const Fe=(i,e,t)=>{if(D(i))throw new Error(`'${e}' is deprecated and not available synchronously for this track. Use the preferred '${t}()' instead.`);return i},la=i=>{if(i!==void 0&&typeof i!="function")throw new TypeError("predicate, when provided, must be a function.");return i?e=>{const t=s=>{if(typeof s!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return s},r=i(e);return D(r)?r.then(t):t(r)}:void 0};class Ln extends Fs{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return Fe(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 Fe(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Fe(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getTransformationMatrix(){return this._backing.getTransformationMatrix()}async getRotation(){return es(await this._backing.getTransformationMatrix())}get rotation(){return es(Fe(this._backing.getTransformationMatrix(),"rotation","getRotation"))}async getFlip(){return zl(await this._backing.getTransformationMatrix())}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Fe(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Fe(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=ol(await this.getSquarePixelWidth()*await this.getCodedHeight(),await this.getSquarePixelHeight()*await this.getCodedWidth()))}get pixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=ol(Fe(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*Fe(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),Fe(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*Fe(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")))}async getDisplayWidth(){var r,s;const e=await((s=(r=this._backing).getMetadataDisplayWidth)==null?void 0:s.call(r));return e??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){var s,n;const e=(n=(s=this._backing).getMetadataDisplayWidth)==null?void 0:n.call(s);if(e!==void 0){const a=Fe(e,"displayWidth","getDisplayWidth");if(a!==null)return a}const r=es(Fe(this._backing.getTransformationMatrix(),"displayWidth","getDisplayWidth"))%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return Fe(r,"displayWidth","getDisplayWidth")}async getDisplayHeight(){var r,s;const e=await((s=(r=this._backing).getMetadataDisplayHeight)==null?void 0:s.call(r));return e??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){var s,n;const e=(n=(s=this._backing).getMetadataDisplayHeight)==null?void 0:n.call(s);if(e!==void 0){const a=Fe(e,"displayHeight","getDisplayHeight");if(a!==null)return a}const r=es(Fe(this._backing.getTransformationMatrix(),"displayHeight","getDisplayHeight"))%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return Fe(r,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return e.transfer==="pq"||e.transfer==="hlg"}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){var r,s;const e=await((s=(r=this._backing).getMetadataCodecParameterString)==null?void 0:s.call(r));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 w(t!==null),ws.some(s=>s.supports(t,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return K._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 r=await this.getDecoderConfig();return w(r),Nn(t,r,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.targetPacketCount!==void 0&&(!ut(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");const t=await this.getTimeResolution(),r=e.targetPacketCount??256,s=new Ri(this),n=[];let a=-1/0,o=0;for await(const I of s.packets(void 0,void 0,{metadataOnly:!0})){if(n.length>=r&&I.timestamp>=a)break;n.push(I.timestamp),a=Math.max(a,I.timestamp),o++}const c=new Float64Array(n.length);for(let I=0;I<n.length;I++)c[I]=Math.round(n[I]*t);c.sort();let u=1;for(let I=1;I<c.length;I++)c[I]!==c[u-1]&&(c[u++]=c[I]);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=Cp(l,t),f=d??t,h=d!==null?t/d:null,p=new Map;let m=1/0,g=-1/0,y=0;for(let I=1;I<u;I++){const v=l[I]-l[I-1],R=h!==null?Math.max(1,Math.round(v/h)):v;p.set(R,(p.get(R)??0)+1),m=Math.min(m,R),g=Math.max(g,R),y+=R}const b=u-1,S=[...p.keys()].sort((I,v)=>I-v),A=b-1>>1,x=b>>1;let T=0,P=0,C=0;for(const I of S)if(C+=p.get(I),T===0&&C>A&&(T=I),C>x){P=I;break}const _=(f/T+f/P)/2;return{underlyingFrameRate:d,bestGuessFrameRate:d!==null?d:_p(_),minFrameRate:f/g,maxFrameRate:f/m,averageFrameRate:f*b/y,medianFrameRate:_,frameRateIsConstant:d!==null&&m===1&&g===1,probedPacketCount:o}}}const ol=(i,e)=>i===0||e===0?{num:1,den:1}:xs({num:i,den:e});class Hn extends Fs{constructor(e,t){super(e,t)}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return Fe(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){var t,r;const e=await this._backing.getCodec();return await((r=(t=this._backing).getHasOnlyKeyPackets)==null?void 0:r.call(t))??(e===null||!An.includes(e))}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Fe(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Fe(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){var r,s;const e=await((s=(r=this._backing).getMetadataCodecParameterString)==null?void 0:s.call(r));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 w(t),Vd(e,t)}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();return w(t!==null),ys.some(r=>r.supports(t,e))||je.includes(e.codec)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return K._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:Co(t,e.data)}}const x0=i=>i??1/0,cl=i=>-(i??-1/0),Gr=i=>-i,Xr=i=>{if(typeof i!="object"||!i)throw new TypeError("query must be an object.");if(i.filter!==void 0&&typeof i.filter!="function")throw new TypeError("query.filter, when provided, must be a function.");if(i.sortBy!==void 0&&typeof i.sortBy!="function")throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:i.filter?e=>{const t=s=>{if(typeof s!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return s},r=i.filter(e);return D(r)?r.then(t):t(r)}:void 0,sortBy:i.sortBy?e=>{const t=s=>{if(typeof s!="number"&&(!Array.isArray(s)||!s.every(n=>typeof n=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return s},r=i.sortBy(e);return D(r)?r.then(t):t(r)}:void 0}},Xi=(i,e)=>({filter:i!=null&&i.filter||e!=null&&e.filter?t=>{var n;const r=((n=i==null?void 0:i.filter)==null?void 0:n.call(i,t))??!0,s=a=>{var o;return a===!1?!1:((o=e==null?void 0:e.filter)==null?void 0:o.call(e,t))??!0};return D(r)?r.then(s):s(r)}:void 0,sortBy:i!=null&&i.sortBy||e!=null&&e.sortBy?t=>{var a,o;const r=((a=i==null?void 0:i.sortBy)==null?void 0:a.call(i,t))??[],s=((o=e==null?void 0:e.sortBy)==null?void 0:o.call(e,t))??[],n=(c,u)=>[...Array.isArray(c)?c:[c],...Array.isArray(u)?u:[u]];return D(r)||D(s)?Promise.all([r,s]).then(([c,u])=>n(c,u)):n(r,s)}:void 0}),ua=async(i,e)=>{let t=i;if(e!=null&&e.filter){const a=i.map(c=>e.filter(c));if(a.some(c=>D(c))){const c=await Promise.all(a);t=i.filter((u,l)=>c[l])}else t=i.filter((c,u)=>a[u])}if(!(e!=null&&e.sortBy))return t;const r=t.map(a=>e.sortBy(a)),n=r.some(a=>D(a))?await Promise.all(r):r;return t.map((a,o)=>({track:a,sortValue:n[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)},Cp=(i,e)=>{const s=1.000000001,n=1e3,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(i.length<2)return null;const o=new Float64Array(i.length-1);for(let C=1;C<i.length;C++){const _=i[C]-i[C-1];if(!(_>0))return null;o[C-1]=_}const c=o.slice();c.sort();let u=c[Math.floor(c.length*.05)],l=1;for(let C=0;C<6;C++){let _=0,I=0;for(const R of o){const F=Math.max(1,Math.round(R/u));Math.abs(R-F*u)>=s+F*l||(_+=R,I+=F)}if(I===0)return null;const v=_/I;if(l=1/Math.min(I,n),Math.abs(v-u)<=1e-12*Math.max(1,u)){u=v;break}u=v}let d=0,f=0,h=0;for(const C of o){const _=Math.max(1,Math.round(C/u));Math.abs(C-_*u)>=s+_*l||(d++,f+=C,h+=_)}if(d/o.length<.98)return null;u=f/h;const p=1/Math.min(h,n),m=Math.max(Number.EPSILON,u-p),g=u+p,y=e/g,b=e/m,S=e/u;let A=null,x=1/0;for(const C of a){if(C<y||C>b)continue;const _=Math.abs(C/S-1);_<x&&(A=C,x=_)}if(A===null){const C=ll(m,g,1e6),_=ll(y,b,1e6);if(_&&(!C||_.den<C.den||_.den===C.den&&_.num<=C.num))A=_.num/_.den;else if(C)A=e*C.den/C.num;else return null}const T=e/A;let P=0;for(const C of o){const _=Math.max(1,Math.round(C/T));Math.abs(C-_*T)<s&&P++}return P/o.length<.98?null:A},ll=(i,e,t)=>{for(let r=1;r<=t;r++){const s=Math.floor(i*r)+1;if(s/r<e)return xs({num:s,den:r})}return null},_p=i=>{const e=[23.976023976023978,29.970029970029973,59.940059940059946,119.88011988011989],t=[12,15,20,24,25,30,48,50,60,100,120,144,240],r=5e-4,s=.025;for(const o of e)if(Math.abs(o/i-1)<=r)return o;let n=i,a=1/0;for(const o of t){const c=Math.abs(o/i-1);c<=s&&c<a&&(n=o,a=c)}return n};/*!
|
|
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
|
+
*/wo();const Ep=1,Ip=2;class qn extends Ps{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 ei)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof It||e.source instanceof Ho))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof It&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof qn))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&kp(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof It?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){if(this._disposed)throw new He;return this._rootRef.source}async _getSourceUncached(e){w(this._rootSource instanceof ar);const t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=Ep){const r=this._sourceCache.find(a=>a.cacheGroup===t&&Xc(a.request,e));if(r)return r.age=this._nextSourceCacheAge++,Promise.resolve(r.sourceRef.source.ref());const s=this._sourceCachePromises.find(a=>a.cacheGroup===t&&Xc(a.request,e));if(s)return s.promise.then(a=>a.sourceRef.source.ref());const n=(async()=>{let a;try{a=await this._getSourceUncached(e)}finally{const l=this._sourceCachePromises.findIndex(d=>d.request===e);w(l!==-1),this._sourceCachePromises.splice(l,1)}if(this._disposed)throw a.free(),new He;if(is(this._sourceCache,l=>l.cacheGroup===t&&l.sourceRef.source._refCount===1)>=4){const l=Fn(this._sourceCache,f=>f.cacheGroup===t&&f.sourceRef.source._refCount===1?f.age:1/0);w(l!==-1);const d=this._sourceCache[l];this._sourceCache.splice(l,1),d.sourceRef.free(),on(this._sourceRefs,d.sourceRef)}return this._sourceRefs.push(a),{request:e,sourceRef:a,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:n}),n.then(a=>{const o=a.sourceRef.source.ref();return this._sourceCache.push(a),o})}_getDemuxer(){return this._demuxerPromise??(this._demuxerPromise=(async()=>{var r;this._reader=new sn(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});let e=null,t=1/0;for(const s of this._formats){const n=await s._getMatchPosition(this);if(n!==null&&n<t&&(e=s,t=n,n===0))break}if(!e)throw new ul;return this._format=e,(r=this._onFormatDetermined)==null||r.call(this,e),e._createDemuxer(this)})())}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),w(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof ul)return!1;throw e}}async getFirstTimestamp(e){e??(e=await this.getTracks());const t=e.filter(n=>n!==null);if(t.length===0)return 0;const r=await Promise.all(t.map(n=>n.getFirstTimestampOrNull())),s=Math.min(...r.map(n=>n??1/0));return s===1/0?0:s}async computeDuration(e,t){e??(e=await this.getTracks());const r=e.filter(a=>a!==null);if(r.length===0)return 0;const s=await Promise.all(r.map(a=>a.computeDurationOrNull(t))),n=Math.max(...s.map(a=>a??-1/0));return n===-1/0?0:n}async getDurationFromMetadata(e,t){e??(e=await this.getTracks());const r=e.filter(a=>a!==null),n=(await Promise.all(r.map(a=>a.getDurationFromMetadata(t)))).filter(a=>a!==null);return n.length===0?null:Math.max(...n)}async getTracks(e){e&&(e=Xr(e));const r=(await this._getTrackBackings()).map(s=>this._wrapBackingAsTrack(s));return ua(r,e)}async getVideoTracks(e){e&&(e=Xr(e));const r=(await this.getTracks()).filter(s=>s.isVideoTrack());return ua(r,e)}async getAudioTracks(e){e&&(e=Xr(e));const r=(await this.getTracks()).filter(s=>s.isAudioTrack());return ua(r,e)}async getPrimaryVideoTrack(e){e&&(e=Xr(e));const t=Xi(e,{sortBy:async s=>[Gr((await s.getDisposition()).default),Gr(await s.hasPairableAudioTrack()),Gr(!await s.hasOnlyKeyPackets()),cl(await s.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&(e=Xr(e));const t=await this.getPrimaryVideoTrack(),r=Xi(e,{sortBy:async n=>[Gr(!t||n.canBePairedWith(t)),Gr((await n.getDisposition()).default),cl(await n.getBitrate())]});return(await this.getAudioTracks(r))[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 s=e.getType()==="video"?new Ln(this,e):new Hn(this,e);return this._backingToTrack.set(e,s),s}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._sourceCache.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}}class ul extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class He 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 sn{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 He;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){const n=new Uint8Array(0);return new at(n,ie(n),0,e,e)}const r=e+t,s=this.source._read(e,r,ld,ud);return D(s)?s.then(n=>n?new at(n.bytes,n.view,n.offset,e,r):null):s?new at(s.bytes,s.view,s.offset,e,r):null}requestSliceRange(e,t,r){if(this.source._disposed)throw new He;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,Be(this.fileSizeNonStrict-e,t,r));{const s=this.requestSlice(e,r),n=a=>a||(w(this.fileSizeNonStrict!==null),this.requestSlice(e,Be(this.fileSizeNonStrict-e,t,r)));return D(s)?s.then(n):n(s)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);const e=1024;return(async()=>{const t=[];let r=0;for(;;){if(t.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let a=this.requestSliceRange(r,0,e);if(D(a)&&(a=await a),!a||a.length===0)break;const o=X(a,a.length);t.push(o),r+=a.length}const s=new Uint8Array(r);let n=0;for(const a of t)s.set(a,n),n+=a.length;return new at(s,ie(s),0,0,r)})()}}class at{constructor(e,t,r,s,n){this.bytes=e,this.view=t,this.offset=r,this.start=s,this.end=n,this.bufferPos=s-r}static tempFromBytes(e){return new at(e,ie(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 at(this.bytes,this.view,this.offset,e,e+t)}}const pt=(i,e)=>{if(e<0||i.filePos<i.start||i.filePos+e>i.end)throw new RangeError(`Tried reading [${i.filePos}, ${i.filePos+e}), but slice is [${i.start}, ${i.end}). This is likely an internal error, please report it alongside the file that caused it.`)},X=(i,e)=>{pt(i,e);const t=i.bytes.subarray(i.bufferPos,i.bufferPos+e);return i.bufferPos+=e,t},Z=i=>(pt(i,1),i.view.getUint8(i.bufferPos++)),Yr=(i,e)=>{pt(i,2);const t=i.view.getUint16(i.bufferPos,e);return i.bufferPos+=2,t},De=i=>{pt(i,2);const e=i.view.getUint16(i.bufferPos,!1);return i.bufferPos+=2,e},ai=i=>{pt(i,3);const e=En(i.view,i.bufferPos,!1);return i.bufferPos+=3,e},co=i=>{pt(i,2);const e=i.view.getInt16(i.bufferPos,!1);return i.bufferPos+=2,e},Mi=(i,e)=>{pt(i,4);const t=i.view.getUint32(i.bufferPos,e);return i.bufferPos+=4,t},q=i=>{pt(i,4);const e=i.view.getUint32(i.bufferPos,!1);return i.bufferPos+=4,e},pi=i=>{pt(i,4);const e=i.view.getUint32(i.bufferPos,!0);return i.bufferPos+=4,e},Yi=i=>{pt(i,4);const e=i.view.getInt32(i.bufferPos,!1);return i.bufferPos+=4,e},vp=i=>{pt(i,4);const e=i.view.getInt32(i.bufferPos,!0);return i.bufferPos+=4,e},dl=(i,e)=>{let t,r;return e?(t=Mi(i,!0),r=Mi(i,!0)):(r=Mi(i,!1),t=Mi(i,!1)),r*4294967296+t},ft=i=>{const e=q(i),t=q(i);return e*4294967296+t},Bp=i=>{const e=Yi(i),t=q(i);return e*4294967296+t},Fp=i=>{const e=pi(i);return vp(i)*4294967296+e},Rp=i=>{pt(i,4);const e=i.view.getFloat32(i.bufferPos,!1);return i.bufferPos+=4,e},vd=i=>{pt(i,8);const e=i.view.getFloat64(i.bufferPos,!1);return i.bufferPos+=8,e},Ie=(i,e)=>{pt(i,e);let t="";for(let r=0;r<e;r++)t+=String.fromCharCode(i.bytes[i.bufferPos++]);return t},Bd=(i,e,t)=>nt.decode(X(i,e)).split(`
|
|
296
|
+
`).map(n=>n.trim()).filter(n=>{var a;return n.length>0&&!((a=t==null?void 0:t.ignore)!=null&&a.call(t,n))});/*!
|
|
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 Xt=8,Di=16,_i=i=>{let e=q(i);const t=Ie(i,4);let r=8;e===1&&(e=ft(i),r=16);const n=e-r;return n<0?null:{name:t,totalSize:e,headerSize:r,contentSize:n}},Ki=i=>Yi(i)/65536,da=i=>Yi(i)/1073741824,fa=i=>{let e=0;for(let t=0;t<4;t++){e<<=7;const r=Z(i);if(e|=r&127,(r&128)===0)break}return e},Fd=i=>{if(Z(i)!==3)throw new Error("Invalid esds: expected ES_Descriptor.");fa(i),i.skip(2);const t=Z(i),r=(t&128)!==0,s=(t&64)!==0,n=(t&32)!==0;if(r&&i.skip(2),s){const d=Z(i);i.skip(d)}if(n&&i.skip(2),Z(i)!==4)throw new Error("Invalid esds: expected DecoderConfigDescriptor.");const o=fa(i),c=i.filePos,u=Z(i);i.skip(12);let l=null;if(o>i.filePos-c){if(Z(i)!==5)throw new Error("Invalid esds: expected DecoderSpecificInfo.");const f=fa(i);l=X(i,f)}return{objectTypeIndication:u,decoderSpecificInfo:l}},xt=i=>{let e=De(i);return i.skip(2),e=Math.min(e,i.remainingLength),nt.decode(X(i,e))},Mp=i=>{const e=_i(i);if(!e||e.name!=="data"||e.contentSize<8||i.remainingLength<8)return null;const t=q(i);i.skip(4);const r=X(i,e.contentSize-8);switch(t){case 1:return nt.decode(r);case 2:return new Sr("utf-16be").decode(r);case 13:return new xr(r,"image/jpeg");case 14:return new xr(r,"image/png");case 27:return new xr(r,"image/bmp");default:return r}};/*!
|
|
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 Dp=function(i,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,s;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],t&&(s=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");s&&(r=function(){try{s.call(this)}catch(n){return Promise.reject(n)}}),i.stack.push({value:e,dispose:r,async:t})}else t&&i.stack.push({async:!0});return e},zp=(function(i){return function(e){function t(a){e.error=e.hasError?new i(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var r,s=0;function n(){for(;r=e.stack.pop();)try{if(!r.async&&s===1)return s=0,e.stack.push(r),Promise.resolve().then(n);if(r.dispose){var a=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(a).then(n,function(o){return t(o),n()})}else s|=1}catch(o){t(o)}if(s===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return n()}})(typeof SuppressedError=="function"?SuppressedError:function(i,e,t){var r=new Error(t);return r.name="SuppressedError",r.error=i,r.suppressed=e,r});class $o{constructor(){this._connectedTrack=null,this._closingPromise=null,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._closingPromise)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),!(e.output.state==="finalizing"||e.output.state==="finalized")&&await e.output._muxer.onTrackClose(e)})(),this._closingPromise.catch(()=>{})}async _flushOrWaitForOngoingClose(e){return this._closingPromise??(this._closingPromise=this._flushAndClose(e))}}class Rs extends $o{constructor(e){if(super(),!Oe.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${Oe.join(", ")}.`);this._codec=e}}const lo=(i,e)=>{if(i.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")};class uo extends Rs{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(),lo(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}}class Qo{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=null,this.emittedEncoderPackets=0,this.chunkTimestampsAreShiftedByDuration=!1,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.addMutex=new Jt,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new vn,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,r){var a,o,c,u,l,d,f,h,p,m,g,y,b,S,A,x;const s=e;let n=null;try{if(this.checkForEncoderError(),n=await this.addMutex.acquire(),this.closed)return;const T=this.encodingConfig,P=T.sizeChangeBehavior??"deny";let C=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(C=!0,P==="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(((a=T.transform)==null?void 0:a.width)!==void 0||((o=T.transform)==null?void 0:o.height)!==void 0||((c=T.transform)==null?void 0:c.rotate)!==void 0||((u=T.transform)==null?void 0:u.flip)!==void 0||((l=T.transform)==null?void 0:l.crop)!==void 0||((d=T.transform)==null?void 0:d.alpha)==="discard"||((f=T.transform)==null?void 0:f.force)===!0||C&&P!=="passThrough"){let R=(h=T.transform)==null?void 0:h.width,F=(p=T.transform)==null?void 0:p.height,H=((m=T.transform)==null?void 0:m.fit)??"fill";P!=="deny"&&P!=="passThrough"&&(H=P),C&&P!=="passThrough"&&(w(this.outputWidth),w(this.outputHeight),R=this.outputWidth,F=this.outputHeight);const O=await e.transform({width:R,height:F,roundDimensionsTo:2,crop:(g=T.transform)==null?void 0:g.crop,rotate:(y=T.transform)==null?void 0:y.rotate,flip:(b=T.transform)==null?void 0:b.flip,fit:H,alpha:(S=T.transform)==null?void 0:S.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=O.displayWidth,this.outputHeight=O.displayHeight),t&&e.close(),e=O,t=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);const v=(A=T.transform)==null?void 0:A.frameRate;if(v!==void 0){const R=e.timestamp+e.duration,F=sc(e.timestamp,v);if(this.frameRateLastSample!==null)if(F<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=R;return}else await this.padFrameRate(F,r);if(e===s){const H=e.clone();t&&e.close(),e=H,t=!0}e.setTimestamp(F),e.setDuration(1/v),(x=this.frameRateLastSample)==null||x.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=F,this.frameRateLastEndTimestamp=R}await this.processAndEncode(e,r)}finally{n==null||n(),t&&e.close()}}async processAndEncode(e,t){var n,a,o;const r=this.encodingConfig;let s;if((n=r.transform)!=null&&n.process){let c=r.transform.process(e);if(D(c)&&(c=await c),c===null)return;Array.isArray(c)||(c=[c]);const u=[];try{for(const l of c)l instanceof Je?u.push(l):typeof VideoFrame<"u"&&l instanceof VideoFrame?u.push(new Je(l)):u.push(new Je(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 Je&&d!==e||typeof VideoFrame<"u"&&d instanceof VideoFrame)&&d.close();throw l}s=u}else s=[e];try{for(const c of s){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(c),this.encoderInitialized||await this.ensureEncoderPromise),w(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{w(this.encoder);const h=c.toVideoFrame(),p=de(this.preciseTimings,h.timestamp,g=>g.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 Np);const{colorFrame:y,alphaFrame:b}=await this.splitter.split(h);this.alphaFrameQueue.push(b);try{this.encoder.encode(y,f)}finally{y.close()}}else try{this.encoder.encode(h,f)}finally{h.close()}this.encoder.encodeQueueSize>=4&&await new Promise(g=>this.encoder.addEventListener("dequeue",g,{once:!0}))}await this.lastMuxerPromise}}finally{for(const c of s)c!==e&&c.close()}}async padFrameRate(e,t){const r=this.encodingConfig.transform.frameRate;w(this.frameRateLastSample);const s=Math.round((e-this.frameRateLastTimestamp)*r);for(let n=1;n<s;n++){const a={stack:[],error:void 0,hasError:!1};try{const o=Dp(a,this.frameRateLastSample.clone(),!1);o.setTimestamp(this.frameRateLastTimestamp+n/r),o.setDuration(1/r),await this.processAndEncode(o,t)}catch(o){a.error=o,a.hasError=!0}finally{zp(a)}}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{var o,c,u;const t=Dr(this.encodingConfig.quality,this.encodingConfig.bitrate);w(t!==void 0);const r=Au({...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 s=null,n;for(const l of r){const d=l.config;if((u=(c=this.encodingConfig).onEncoderConfig)==null||u.call(c,d),n=yn.find(h=>h.supports(this.encodingConfig.codec,d)),n){s=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){s=l;break}}catch{}}if(!s){if(typeof VideoEncoder>"u")throw new Error(Bn("VideoEncoder"));const l=r[0].config,d=r.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=s.config;s.quantizer!==null?this.defaultEncodeOptions=Cu(this.encodingConfig.codec,s.quantizer):this.source._nominalBitrate=a.bitrate??null,n?(this.customEncoder=new n,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.");lo(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"&&ir()&&(this.chunkTimestampsAreShiftedByDuration=await Up()),this.createWebCodecsEncoders()),w(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})(),this.ensureEncoderPromise.catch(t=>this.setError(t))}createWebCodecsEncoders(){const e=this.encoderConfig;w(e);const t=[],r=[];let s=0,n=0;const a=(c,u)=>{if(Cf(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)=>{try{if(!this.alphaEncoder){this.addPacket(c,null,u);return}const l=this.alphaFrameQueue.shift();w(l!==void 0),l?(this.alphaEncoder.encode(l,{...this.defaultEncodeOptions,keyFrame:c.type==="key"}),n++,l.close(),t.push({chunk:c,meta:u})):n===0?this.addPacket(c,null,u):(r.push(s+n),t.push({chunk:c,meta:u}))}catch(l){this.setError(l)}},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)=>{try{n--;const d=t.shift();for(w(d!==void 0),this.addPacket(d.chunk,u,d.meta),s++;r.length>0&&r[0]===s;){r.shift();const f=t.shift();w(f!==void 0),this.addPacket(f.chunk,null,f.meta)}}catch(d){this.setError(d)}},error:u=>a(u,c)}),this.alphaEncoder.configure(e)}}addPacket(e,t,r){var d,f;const s={};if(t){const h=new Uint8Array(t.byteLength);t.copyTo(h),s.alpha=h}let n=Ce.fromEncodedChunk(e,s);const a=this.encoderConfig;if(w(a),r!=null&&r.decoderConfig&&(r.decoderConfig.codec=jn({width:a.width,height:a.height,codec:this.encodingConfig.codec,codecDescription:r.decoderConfig.description?me(r.decoderConfig.description):null,colorSpace:r.decoderConfig.colorSpace??null,avcType:a.codec.includes("avc1.")?1:a.codec.includes("avc3.")?3:null,avcCodecInfo:this.encodingConfig.codec==="avc"&&!r.decoderConfig.description?_s(n.data):null,hevcType:a.codec.includes("hev1.")?"hev1":a.codec.includes("hvc1.")?"hvc1":null,hevcCodecInfo:this.encodingConfig.codec==="hevc"&&!r.decoderConfig.description?Is(n.data):null,vp9CodecInfo:this.encodingConfig.codec==="vp9"?Po(n.data):null,av1CodecInfo:this.encodingConfig.codec==="av1"?ms(n.data):null,proresFormat:null}),this.encodingConfig.codec==="avc"&&r.decoderConfig.description&&ir())){const h=Es(me(r.decoderConfig.description));let p=h==null?void 0:h.sequenceParameterSets[0];if(p&&p[0]===p[1]){w(h),p=p.subarray(1);let m=h.pictureParameterSets[0];m&&(m=m.subarray(1));const g=So({...h,sequenceParameterSets:[p],pictureParameterSets:m?[m]:[]});r.decoderConfig.description=g}}let o=e.timestamp;this.chunkTimestampsAreShiftedByDuration&&(o-=e.duration??0,n=n.clone({timestamp:o/1e6}));const c=de(this.preciseTimings,o,h=>h.microsecondTimestamp),u=c!==-1?this.preciseTimings[c]:null;let l=null;this.emittedEncoderPackets===0&&n.type==="delta"&&(r!=null&&r.decoderConfig)&&(l=Nn(this.encodingConfig.codec,r.decoderConfig,n.data)),(u&&u.microsecondTimestamp===o||l!==null)&&(n=n.clone({timestamp:u!=null&&u.timestampIsValid?u.timestamp:void 0,duration:u!=null&&u.durationIsValid?u.duration:void 0,type:l??void 0})),lo(this.source._connectedTrack,n),(f=(d=this.encodingConfig).onEncodedPacket)==null||f.call(d,n,r),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,n,r).catch(h=>{this.setError(h)}),this.emittedEncoderPackets++}recreateWebCodecsEncoders(){w(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=null,this.createWebCodecsEncoders()}async flushAndClose(e){var t,r,s,n;await((t=this.ensureEncoderPromise)==null?void 0:t.catch(()=>{}));try{if(!e){this.checkForEncoderError();const a=await this.addMutex.acquire();try{if(this.frameRateLastSample){const o=this.encodingConfig.transform.frameRate,c=sc(this.frameRateLastEndTimestamp,o);await this.padFrameRate(c)}}finally{a()}}this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()).catch(a=>this.setError(a)):this.encoder&&!this.encodersReclaimed&&(await this.encoder.flush(),await((r=this.alphaEncoder)==null?void 0:r.flush()),await Ar(25)))}finally{this.closed=!0,(s=this.frameRateLastSample)==null||s.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(a=>this.setError(a)):this.encoder&&(this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(a=>a==null?void 0:a.close()),this.alphaFrameQueue.length=0,(n=this.splitter)==null||n.close())}e||(await this.lastMuxerPromise,this.checkForEncoderError())}getQueueSize(){var e;return this.customEncoder?this.addMutex.pending+this.customEncoderQueueSize:this.addMutex.pending+(((e=this.encoder)==null?void 0:e.encodeQueueSize)??0)}checkForEncoderError(){if(this.errorSet)throw this.error}}let Op=null;const Up=()=>Op??(Op=(async()=>{let i=null;const e=new VideoEncoder({output:t=>{i??(i=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 i===500})());let ha=null;class Np{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!ha){const s=new Blob([`(${Vp.toString()})()`],{type:"application/javascript"});ha=URL.createObjectURL(s)}this.worker=new Worker(ha),this.worker.addEventListener("message",s=>{const n=s.data,a=this.pendingRequests.get(n.id);a&&(this.pendingRequests.delete(n.id),"error"in n?a.reject(new Error(n.error)):a.resolve({colorFrame:n.colorFrame,alphaFrame:n.alphaFrame}))}),this.worker.addEventListener("error",s=>{const n=new Error(s.message||"Color/alpha splitter worker error.");for(const a of this.pendingRequests.values())a.reject(n);this.pendingRequests.clear()})}const t=this.nextRequestId++,r=Ae();return this.pendingRequests.set(t,r),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),r.promise}close(){var t;(t=this.worker)==null||t.terminate(),this.worker=null;const e=new Error("Color/alpha splitter closed.");for(const r of this.pendingRequests.values())r.reject(e);this.pendingRequests.clear()}}const Vp=()=>{let i=null,e=Promise.resolve();self.addEventListener("message",n=>{const{id:a,sourceFrame:o}=n.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 n=>{const a=n.format;if(!a)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");const o=n.allocationSize();if((!i||i.byteLength!==o)&&(i=new Uint8Array(o)),await n.copyTo(i),a==="RGBA"||a==="BGRA")return r(i,a,n);if(a==="I420A"||a==="I420AP10"||a==="I420AP12"||a==="I422A"||a==="I422AP10"||a==="I422AP12"||a==="I444A"||a==="I444AP10"||a==="I444AP12")return s(i,a,n);throw new Error(`CPU color/alpha splitting does not support format '${a}'.`)},r=(n,a,o)=>{var b,S;const c=((b=o.visibleRect)==null?void 0:b.width)??o.codedWidth,u=((S=o.visibleRect)==null?void 0:S.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 A=0,x=3;A<l;A++,x+=4)p[A]=n[x];p.fill(128,l);const m=new VideoFrame(n,{format:a==="RGBA"?"RGBX":"BGRX",codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0}),g={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]},y=new VideoFrame(p,g);return{colorFrame:m,alphaFrame:y}},s=(n,a,o)=>{var re,Y;const c=((re=o.visibleRect)==null?void 0:re.width)??o.codedWidth,u=((Y=o.visibleRect)==null?void 0:Y.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,g=h*p,y=m*f,b=g*f,S=m*f,A=y+b*2,x=a.replace("A",""),T=Math.ceil(c/2),P=Math.ceil(u/2),C=T*P,_=C*f,I=S+2*_,v=new Uint8Array(I),R=A;v.set(n.subarray(R,R+S),0);const F=S,H=l?512:d?2048:128;f===1?v.fill(H,F):new Uint16Array(v.buffer,F,2*C).fill(H);const O=l?"I420P10":d?"I420P12":"I420",U=new VideoFrame(n.subarray(0,A),{format:x,codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0,colorSpace:o.colorSpace}),L={format:O,codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[v.buffer]},Q=new VideoFrame(v,L);return{colorFrame:U,alphaFrame:Q}}};class fl extends Rs{constructor(e){Bo(e),super(e.codec),this._encoder=new Qo(this,e)}add(e,t){if(!(e instanceof Je))throw new TypeError("videoSample must be a VideoSample.");return this._ensureValidAdd(),this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class P0 extends Rs{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.");Bo(t),super(t.codec),this._encoder=new Qo(this,t),this._canvas=e}add(e,t=0,r){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.");this._ensureValidAdd();const s=new Je(this._canvas,{timestamp:e,duration:t});return this._encoder.add(s,!0,r)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class C0 extends Rs{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,r={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");if(Bo(t),typeof r!="object"||!r)throw new TypeError("options must be an object.");if(r.frameRate!=null&&(!Number.isFinite(r.frameRate)||r.frameRate<=0))throw new TypeError("options.frameRate, when provided, must be either a finite positive number or null.");if(r.timestampBase!==void 0&&r.timestampBase!=="synced-zero"&&r.timestampBase!=="zero"&&r.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=Ae(),this._errorPromiseAccessed=!1,this._paused=!1,this._lastVideoFrame=null,this._timerHandle=null,this._videoElement=null,this._options=r,this._encoder=new Qo(this,t),this._track=e}async _start(){this._errorPromiseAccessed||K._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,r=null,s=null,n=0,a=!1,o=null,c=0;const u=()=>{if(w(e!==null),!this._lastVideoFrame)return;w(s!==null),w(r!==null);const f=performance.now();for(;f-s>1e3/e;){s+=1e3/e;const h=r+n/e,p=new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*h,duration:1e6/e});d(p,f)}};e!==null&&(this._timerHandle=Df(u,4));const l=f=>{var h;if(this._closingPromise){f.close();return}if(e===null)d(f);else{const p=performance.now();this._lastVideoFrame?(u(),(h=this._lastVideoFrame)==null||h.close(),this._lastVideoFrame=f):(r=f.timestamp/1e6,d(f.clone(),p),s=p,this._lastVideoFrame=f)}},d=(f,h=performance.now())=>{if(a||this._closingPromise||this._connectedTrack.output.state!=="started"){f.close();return}n++;const p=f.timestamp/1e6;if(this._paused){if(t!==null){if(o!==null&&this._options.timestampBase!=="unix"){const y=p-o;c-=y}o=p}f.close();return}if(t===null){t=p;let g;const y=this._options.timestampBase??"synced-zero";if(y==="unix")g=Date.now()/1e3;else if(y==="zero")g=0;else{const b=this._connectedTrack.output;b._firstMediaStreamTimestamp===null?(b._firstMediaStreamTimestamp=h/1e3,g=0):g=h/1e3-b._firstMediaStreamTimestamp}c=g-t}if(o=p,this._encoder.getQueueSize()>=8){f.close();return}const m=new Je(f,{timestamp:p+c});this._encoder.add(m,!0).catch(g=>{var y;a=!0,(y=this._abortController)==null||y.abort(),this._promiseWithResolvers.reject(g),this._workerTrackId!==null&&ga({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){const f=new MediaStreamTrackProcessor({track:this._track}),h=new WritableStream({write:l});f.readable.pipeTo(h,{signal:this._abortController.signal}).catch(p=>{p instanceof DOMException&&p.name==="AbortError"||this._promiseWithResolvers.reject(p)})}else if(await Kp()){this._workerTrackId=qp++;const h=this._track.clone();ga({type:"videoTrack",trackId:this._workerTrackId,track:h},[h]),this._workerListener=p=>{const m=p.data;m.type==="videoFrame"&&m.trackId===this._workerTrackId?l(m.videoFrame):m.type==="error"&&m.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(m.error)},_t.addEventListener("message",this._workerListener)}else if(e!==null){const h=document.createElement("video");h.style.position="fixed",h.style.left="-10000px",h.style.top="-10000px",h.style.width="1px",h.style.height="1px",h.style.opacity="0",h.style.pointerEvents="none",h.muted=!0,h.srcObject=new MediaStream([this._track]),document.body.appendChild(h),this._videoElement=h,h.addEventListener("loadeddata",()=>{if(a||!this._videoElement)return;const p=new VideoFrame(h,{timestamp:1e3*performance.now()});l(p),p.close()},{once:!0}),h.play().catch(p=>{a=!0,this._promiseWithResolvers.reject(p)})}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&&zf(this._timerHandle),(t=this._lastVideoFrame)==null||t.close(),this._videoElement&&(this._videoElement.srcObject=null,this._videoElement.remove(),this._videoElement=null),this._workerTrackId!==null&&(w(this._workerListener),ga({type:"stopTrack",trackId:this._workerTrackId}),await new Promise(r=>{const s=n=>{const a=n.data;a.type==="trackStopped"&&a.trackId===this._workerTrackId&&(w(this._workerListener),_t.removeEventListener("message",this._workerListener),_t.removeEventListener("message",s),r())};_t.addEventListener("message",s)}))}finally{await this._encoder.flushAndClose(e)}}}class Ms extends $o{constructor(e){if(super(),!Ke.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${Ke.join(", ")}.`);this._codec=e}}class fo extends Ms{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 nn=2048;class Go{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.addMutex=new Jt,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 vn,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 s,n;let r=null;try{if(this.checkForEncoderError(),r=await this.addMutex.acquire(),this.closed)return;if(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 a=this.encodingConfig;((s=a.transform)==null?void 0:s.numberOfChannels)!==void 0||((n=a.transform)==null?void 0:n.sampleRate)!==void 0?(this.resampler||(this.resampler=new em({targetNumberOfChannels:a.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:a.transform.sampleRate??e.sampleRate,onSample:async c=>{await this.processAndEncode(c,!0)}})),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{r==null||r(),t&&e.close()}}async processAndEncode(e,t){var s,n;const r=this.encodingConfig;if(((s=r.transform)==null?void 0:s.sampleFormat)!==void 0&&Hh(e.format)!==r.transform.sampleFormat){const a=jh(e,r.transform.sampleFormat);t&&e.close(),e=a,t=!0}if((n=r.transform)!=null&&n.process)try{let a=r.transform.process(e);if(D(a)&&(a=await a),a===null)return;Array.isArray(a)||(a=[a]);try{for(const o of a)if(!(o instanceof qe))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,o!==e)}finally{for(const o of a)o instanceof qe&&o!==e&&o.close()}}finally{t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){var r,s;try{if(e.numberOfFrames===0||(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),w(this.encoderInitialized),this.closed))return;{const n=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=n-this.lastEndSampleIndex;if(o>=64){const c=Mt(e.format)*e.numberOfChannels,u=new Uint8Array(c*Math.min(o,e.sampleRate));(e.format==="u8"||e.format==="u8-planar")&&u.fill(2**7);let l=o;for(;l>0;){const d=Math.min(l,e.sampleRate),f=new qe({data:u.subarray(0,c*d),_doNotCopy:!0,format:e.format,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:d,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(f,!0),l-=d}}this.lastEndSampleIndex+=e.numberOfFrames}}if((s=(r=this.encodingConfig).onEncodedSample)==null||s.call(r,e),this.customEncoder){this.customEncoderQueueSize++;const n=e.clone(),a=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(n)).catch(o=>this.setError(o)).finally(()=>{this.customEncoderQueueSize--,n.close()});this.customEncoderQueueSize>=4&&await a,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{w(this.encoder),this.checkForEncoderError();const n=e.toAudioData();try{this.encoder.encode(n)}finally{n.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){w(this.outputSampleSize),w(this.writeOutputValue);const{numberOfChannels:r,numberOfFrames:s,sampleRate:n,timestamp:a}=e;this.pcmMeta||(this.pcmMeta={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:r,sampleRate:n}},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<s;){this.pcmScratchView??(this.pcmScratchView=new DataView(new ArrayBuffer(nn*r*this.outputSampleSize)));const h=Math.min(nn-this.pcmScratchFrames,s-f),p=this.pcmScratchFrames*r,m=f*r;for(let g=0;g<h*r;g++)this.writeOutputValue(this.pcmScratchView,(p+g)*this.outputSampleSize,d[m+g]*u);this.pcmScratchFrames+=h,f+=h,this.pcmScratchFrames===nn&&await this.emitPcmScratchPacket()}}async emitPcmScratchPacket(){var n,a,o;w(this.outputSampleSize),w(this.pcmScratchView),w((n=this.pcmMeta)==null?void 0:n.decoderConfig);const{numberOfChannels:e,sampleRate:t}=this.pcmMeta.decoderConfig,r=this.pcmScratchFrames*e*this.outputSampleSize,s=new Ce(new Uint8Array(this.pcmScratchView.buffer,0,r),"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,s,this.pcmMeta),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,s,this.pcmMeta)}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{var u,l;const{format:t,numberOfChannels:r,sampleRate:s,timestamp:n}=e,a=Dr(this.encodingConfig.quality,this.encodingConfig.bitrate),o=Pu({numberOfChannels:r,sampleRate:s,...this.encodingConfig,quality:a});(l=(u=this.encodingConfig).onEncoderConfig)==null||l.call(u,o),this.source._nominalBitrate=o.bitrate??null;const c=bn.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(je.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error(Bn("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 Wp(this.encodingConfig.codec,o.codec)/o.sampleRate;let p=0;const m=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(g,y)=>{var b,S;try{if(y!=null&&y.decoderConfig&&(Md(this.encodingConfig.codec,o,y.decoderConfig),this.encodingConfig.codec==="opus"&&y.decoderConfig.description)){const x=me(y.decoderConfig.description);p=vs(x).preSkip/Wi}let A=Ce.fromEncodedChunk(g);A=A.clone({timestamp:tr(A.timestamp-h-p,o.sampleRate),duration:g.duration!=null?tr(A.duration,o.sampleRate):void 0}),ir()&&(p=0),(S=(b=this.encodingConfig).onEncodedPacket)==null||S.call(b,A,y),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,A,y).catch(x=>{this.setError(x)})}catch(A){this.setError(A)}},error:g=>{g.stack=m,this.setError(g)}}),this.encoder.configure(o),this.encodingConfig.codec==="aac"&&wi()&&Rd(this.encoder,t,r,s,n)}w(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})(),this.ensureEncoderPromise.catch(t=>this.setError(t))}initPcmEncoder(){this.isPcmEncoder=!0;const e=this.encodingConfig.codec,{dataType:t,sampleSize:r,littleEndian:s}=Bt(e);switch(this.outputSampleSize=r,r){case 1:t==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint8(a,Be(Math.round(o*128)+128,0,255)):t==="signed"?this.writeOutputValue=(n,a,o)=>{n.setInt8(a,Be(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(n,a,o)=>{const c=Be(Math.round(o*32768),-32768,32767);n.setUint8(a,_h(c))}:t==="alaw"?this.writeOutputValue=(n,a,o)=>{const c=Be(Math.round(o*32768),-32768,32767);n.setUint8(a,Ih(c))}:w(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint16(a,Be(Math.round(o*32768)+32768,0,65535),s):t==="signed"?this.writeOutputValue=(n,a,o)=>n.setInt16(a,Be(Math.round(o*32768),-32768,32767),s):w(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(n,a,o)=>In(n,a,Be(Math.round(o*8388608)+8388608,0,16777215),s):t==="signed"?this.writeOutputValue=(n,a,o)=>yf(n,a,Be(Math.round(o*8388608),-8388608,8388607),s):w(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint32(a,Be(Math.round(o*2147483648)+2147483648,0,4294967295),s):t==="signed"?this.writeOutputValue=(n,a,o)=>n.setInt32(a,Be(Math.round(o*2147483648),-2147483648,2147483647),s):t==="float"?this.writeOutputValue=(n,a,o)=>n.setFloat32(a,o,s):w(!1);break;case 8:t==="float"?this.writeOutputValue=(n,a,o)=>n.setFloat64(a,o,s):w(!1);break;default:xe(r),w(!1)}}async flushAndClose(e){var t;await((t=this.ensureEncoderPromise)==null?void 0:t.catch(()=>{}));try{if(!e){this.checkForEncoderError();const r=await this.addMutex.acquire();try{this.resampler&&await this.resampler.finalize(),this.pcmScratchFrames>0&&await this.emitPcmScratchPacket()}finally{r()}}this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()).catch(r=>this.setError(r)):this.encoder&&await this.encoder.flush())}finally{this.closed=!0,this.resampler=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(r=>this.setError(r)):this.encoder&&this.encoder.state!=="closed"&&this.encoder.close()}e||(await this.lastMuxerPromise,this.checkForEncoderError())}getQueueSize(){var e;return this.customEncoder?this.addMutex.pending+this.customEncoderQueueSize:this.isPcmEncoder?this.addMutex.pending:this.addMutex.pending+(((e=this.encoder)==null?void 0:e.encodeQueueSize)??0)}checkForEncoderError(){if(this.errorSet)throw this.error}}const ma=new Map,Wp=(i,e)=>{let t=ma.get(e);return t||(t=(async()=>{const n={codec:e,numberOfChannels:1,sampleRate:48e3,...Hd(i)},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:(b,S)=>{S!=null&&S.decoderConfig&&(l??(l=S.decoderConfig)),u.push(b)},error:b=>{p??(p=b)}}),g=new AudioDecoder({output:b=>{const S=new Float32Array(b.numberOfFrames);b.copyTo(S,{planeIndex:0,format:c}),b.close();for(let A=0;A<S.length;A++)S[A]>f&&(f=S[A],d=h+A);h+=S.length},error:b=>{p??(p=b)}});try{m.configure(n),i==="aac"&&wi()&&Rd(m,c,1,48e3,0);const b=new Float32Array(1*o);b[a]=1;const S=new AudioData({data:b,format:c,numberOfChannels:1,numberOfFrames:o,sampleRate:48e3,timestamp:0});m.encode(S),S.close(),await m.flush(),w(l),Md(i,n,l),g.configure(l);for(const A of u)g.decode(A);await g.flush()}catch(b){throw p??b}finally{m.state!=="closed"&&m.close(),g.state!=="closed"&&g.close()}w(d!==null);const y=Math.round(u[0].timestamp/1e6*48e3);return d-a+y})(),ma.set(e,t),t.catch(()=>ma.delete(e)),t)},Rd=(i,e,t,r,s)=>{const a=Mt(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:r,timestamp:Math.round(1e6*(s-1024/r))});i.encode(c),c.close()},Md=(i,e,t)=>{if(i==="aac"){if(t.description&&t.description.byteLength>0&&me(t.description)[0]===3){const{decoderSpecificInfo:s}=Fd(at.tempFromBytes(me(t.description)));t.description=s??void 0}let r=!1;if(!t.description||t.description.byteLength<2?r=!0:r=nr(me(t.description)).objectType===0,r){const s=Number(Te(e.codec.split(".")));t.description=Rn({objectType:s,outputNumberOfChannels:t.numberOfChannels,outputSampleRate:t.sampleRate,programConfigElement:null})}}};class Lp extends Ms{constructor(e){Fo(e),super(e.codec),this._encoder=new Go(this,e)}add(e){if(!(e instanceof qe))throw new TypeError("audioSample must be an AudioSample.");return this._ensureValidAdd(),this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class _0 extends Ms{constructor(e,t={}){if(Fo(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._addMutex=new Jt,this._encoder=new Go(this,e),this._accumulatedTime=t.startTimestamp??0}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");this._ensureValidAdd();const t=qe._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;const r=await this._addMutex.acquire();try{for(const s of t)await this._encoder.add(s,!0)}finally{r()}}async _flushAndClose(e){return e||(await this._addMutex.acquire())(),this._encoder.flushAndClose(e)}}class E0 extends Ms{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,r={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");if(Fo(t),typeof r!="object"||!r)throw new TypeError("options must be an object.");if(r.timestampBase!==void 0&&r.timestampBase!=="synced-zero"&&r.timestampBase!=="zero"&&r.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=Ae(),this._errorPromiseAccessed=!1,this._paused=!1,this._options=r,this._encoder=new Go(this,t),this._track=e}async _start(){this._errorPromiseAccessed||K._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,r=null,s=0;const n=a=>{if(t||this._closingPromise||this._connectedTrack.output.state!=="started"){a.close();return}const o=a.timestamp;if(this._paused){if(e!==null){if(r!==null&&this._options.timestampBase!=="unix"){const u=o-r;s-=u}r=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}s=c-e}if(r=o,this._encoder.getQueueSize()>=8){a.close();return}a.setTimestamp(o+s),this._encoder.add(a,!0).catch(c=>{var u;t=!0,(u=this._abortController)==null||u.abort(),this._promiseWithResolvers.reject(c),this._audioContext&&this._audioContext.state!=="closed"&&this._audioContext.suspend()})};if(typeof MediaStreamTrackProcessor<"u"){const a=new MediaStreamTrackProcessor({track:this._track}),o=new WritableStream({write:c=>n(new qe(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=qe._fromAudioBuffer(u.inputBuffer,c);c+=u.inputBuffer.duration;for(const d of l)n(d)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){try{this._abortController&&(this._abortController.abort(),this._abortController=null),this._audioContext&&(w(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.close())}finally{await this._encoder.flushAndClose(e)}}}const Hp=()=>{const i=(r,s)=>{s?self.postMessage(r,{transfer:s}):self.postMessage(r)};i({type:"support",supported:typeof MediaStreamTrackProcessor<"u"});const e=new Map,t=new Map;self.addEventListener("message",r=>{const s=r.data;switch(s.type){case"videoTrack":{t.set(s.trackId,s.track);const n=new MediaStreamTrackProcessor({track:s.track}),a=new WritableStream({write:c=>{if(!t.has(s.trackId)){c.close();return}i({type:"videoFrame",trackId:s.trackId,videoFrame:c},[c])}}),o=new AbortController;e.set(s.trackId,o),n.readable.pipeTo(a,{signal:o.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||i({type:"error",trackId:s.trackId,error:c})})}break;case"stopTrack":{const n=e.get(s.trackId);n&&(n.abort(),e.delete(s.trackId));const a=t.get(s.trackId);a==null||a.stop(),t.delete(s.trackId),i({type:"trackStopped",trackId:s.trackId})}break;default:xe(s)}})};let qp=0,_t=null;const jp=()=>{const i=new Blob([`(${Hp.toString()})()`],{type:"application/javascript"}),e=URL.createObjectURL(i);_t=new Worker(e)};let pa=null;const Kp=async()=>pa!==null?pa:(_t||jp(),new Promise(i=>{w(_t);const e=t=>{const r=t.data;r.type==="support"&&(pa=r.supported,_t.removeEventListener("message",e),i(r.supported))};_t.addEventListener("message",e)})),ga=(i,e)=>{w(_t),e?_t.postMessage(i,e):_t.postMessage(i)};class Dd extends $o{constructor(e){if(super(),!vt.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${vt.join(", ")}.`);this._codec=e}}class I0 extends Dd{constructor(e){super(e),this._error=null,this._errorSet=!1,this._lastMuxerPromise=Promise.resolve(),this._parser=new Ph({codec:e,output:(t,r)=>{this._lastMuxerPromise=this._connectedTrack.output._muxer.addSubtitleCue(this._connectedTrack,t,r).catch(s=>{this._setError(s)})}})}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 Oe=["avc","hevc","vp9","av1","vp8","prores"],je=["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"],Ji=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts","truehd"],Ke=[...Ji,...je],vt=["webvtt"],An=["truehd"],xn=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],hl=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],zr=[{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}],Pn=[{maxPictureSize:147456,maxHSize:2048,maxVSize:1152,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxHSize:2816,maxVSize:1584,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxHSize:4352,maxVSize:2448,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxHSize:5504,maxVSize:3096,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxHSize:6144,maxVSize:3456,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxHSize:6144,maxVSize:3456,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxHSize:6144,maxVSize:3456,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxHSize:6144,maxVSize:3456,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:8e8,tier:"H",level:19}],ml=".01.01.01.01.00",pl=".0.110.01.01.01.0",er=["ap4x","ap4h","apch","apcn","apcs","apco"],Cn=["dtsc","dtsh","dtsl","dtse"],$p=[{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}],zd=(i,e,t,r,s)=>{if(i==="avc"){const n=wi(),a=n?66:100,o=Math.ceil(e/16)*Math.ceil(t/16),c=xn.find(h=>o<=h.maxMacroblocks&&r<=h.maxBitrate)??Te(xn),u=c?c.level:0,l=a.toString(16).padStart(2,"0"),d=n?"40":"00",f=u.toString(16).padStart(2,"0");return`avc1.${l}${d}${f}`}else if(i==="hevc"){const c=e*t,u=hl.find(d=>c<=d.maxPictureSize&&r<=d.maxBitrate)??Te(hl);return`hvc1.1.6.${u.tier}${u.level}.B0`}else{if(i==="vp8")return"vp8";if(i==="vp9"){const a=e*t;return`vp09.00.${(zr.find(u=>a<=u.maxPictureSize&&r<=u.maxBitrate)??Te(zr)).level.toString().padStart(2,"0")}.08`}else if(i==="av1"){const a=e*t,o=Pn.find(l=>a<=l.maxPictureSize&&e<=l.maxHSize&&t<=l.maxVSize&&r<=l.maxBitrate)??Te(Pn);return`av01.0.${o.level.toString().padStart(2,"0")}${o.tier}.08`}else if(i==="prores"){const a=Math.pow(e*t/2073600,.95),o=$p.filter(l=>l.alpha===s);let c=o[0].fourCc,u=1/0;for(const{fourCc:l,bitrate:d}of o){const f=Math.abs(d*a-r);f<u&&(u=f,c=l)}return c}else xe(i)}throw new TypeError(`Unhandled codec '${String(i)}'.`)},Qp=i=>{const e=i.split("."),t=Number(e[1]),r=Number(e[2]),s=Number(e[3]),n=e[4]?Number(e[4]):1;return[1,1,t,2,1,r,3,1,s,4,1,n]},Od=i=>{const e=i.split("."),s=(1<<7)+1,n=Number(e[1]),a=e[2],o=Number(a.slice(0,-1)),c=(n<<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,g=e[5]?Number(e[5][2]):0,y=(u<<7)+(d<<6)+(f<<5)+(h<<4)+(p<<3)+(m<<2)+g;return[s,c,y,0]},jn=i=>{const{codec:e,codecDescription:t,colorSpace:r,avcCodecInfo:s,hevcCodecInfo:n,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:c}=i;if(e==="avc"){if(w(i.avcType!==null),s){const u=new Uint8Array([s.avcProfileIndication,s.profileCompatibility,s.avcLevelIndication]);return`avc${i.avcType}.${ls(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${i.avcType}.${ls(t.subarray(1,4))}`}else if(e==="hevc"){w(i.hevcType!==null);let u,l,d,f,h,p;if(n)u=n.generalProfileSpace,l=n.generalProfileIdc,d=ic(n.generalProfileCompatibilityFlags),f=n.generalTierFlag,h=n.generalLevelIdc,p=[...n.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 g=ie(t),y=g.getUint8(1);u=y>>6&3,l=y&31,d=ic(g.getUint32(2)),f=y>>5&1,h=g.getUint8(12),p=[];for(let b=0;b<6;b++)p.push(g.getUint8(6+b))}let m=`${i.hevcType}.`;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(g=>g.toString(16).toUpperCase()).join(".")),m}else{if(e==="vp8")return"vp8";if(e==="vp9"){const u=i.width*i.height;let l=Te(zr).level;for(const A of zr)if(u<=A.maxPictureSize){l=A.level;break}if(!a)return`vp09.00.${l.toString().padStart(2,"0")}.08`;const d=a.profile.toString().padStart(2,"0"),f=(a.level===0?l:a.level).toString().padStart(2,"0"),h=a.bitDepth.toString().padStart(2,"0"),p=a.chromaSubsampling.toString().padStart(2,"0"),m=a.colourPrimaries.toString().padStart(2,"0"),g=a.transferCharacteristics.toString().padStart(2,"0"),y=a.matrixCoefficients.toString().padStart(2,"0"),b=a.videoFullRangeFlag.toString().padStart(2,"0");let S=`vp09.${d}.${f}.${h}.${p}`;return S+=`.${m}.${g}.${y}.${b}`,S.endsWith(ml)&&(S=S.slice(0,-ml.length)),S}else if(e==="av1"){if(!o){const A=i.width*i.height;let x=Te(Pn).level;for(const T of Pn)if(A<=T.maxPictureSize&&i.width<=T.maxHSize&&i.height<=T.maxVSize){x=T.level;break}return`av01.0.${x.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,g,y,b;su(o)?(m=o.colourPrimaries,g=o.transferCharacteristics,y=o.matrixCoefficients,b=o.videoFullRangeFlag):(m=r!=null&&r.primaries?Ui[r.primaries]:1,g=r!=null&&r.transfer?Ni[r.transfer]:1,y=r!=null&&r.matrix?Vi[r.matrix]:1,b=r!=null&&r.fullRange?1:0);let S=`av01.${u}.${l}${d}.${f}`;return S+=`.${h}.${p.toString().padStart(3,"0")}`,S+=`.${m.toString().padStart(2,"0")}`,S+=`.${g.toString().padStart(2,"0")}`,S+=`.${y.toString().padStart(2,"0")}`,S+=`.${b}`,S.endsWith(pl)&&(S=S.slice(0,-pl.length)),S}else{if(e==="prores")return c??"apch";e!==null&&xe(e)}}throw new TypeError(`Unhandled codec '${e}'.`)},Ud=i=>{var e,t,r,s,n,a;switch(i.codec){case"avc":{let o=(e=i.avcCodecInfo)==null?void 0:e.sequenceParameterSets[0];if(!o&&i.codecDescription&&(o=(t=Es(i.codecDescription))==null?void 0:t.sequenceParameterSets[0]),o){const c=Zi(o);if(c)return{primaries:di[c.colourPrimaries],transfer:fi[c.transferCharacteristics],matrix:hi[c.matrixCoefficients],fullRange:!!c.fullRangeFlag}}}break;case"hevc":{let o=(s=(r=i.hevcCodecInfo)==null?void 0:r.arrays.find(c=>c.nalUnitType===ke.SPS_NUT))==null?void 0:s.nalUnits[0];if(!o&&i.codecDescription&&(o=(a=(n=xo(i.codecDescription))==null?void 0:n.arrays.find(c=>c.nalUnitType===ke.SPS_NUT))==null?void 0:a.nalUnits[0]),o){const c=Un(o);if(c)return{primaries:di[c.colourPrimaries],transfer:fi[c.transferCharacteristics],matrix:hi[c.matrixCoefficients],fullRange:!!c.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(i.vp9CodecInfo)return{primaries:di[i.vp9CodecInfo.colourPrimaries],transfer:fi[i.vp9CodecInfo.transferCharacteristics],matrix:hi[i.vp9CodecInfo.matrixCoefficients],fullRange:!!i.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(i.av1CodecInfo)return{primaries:di[i.av1CodecInfo.colourPrimaries],transfer:fi[i.av1CodecInfo.transferCharacteristics],matrix:hi[i.av1CodecInfo.matrixCoefficients],fullRange:!!i.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(i.proresCodecInfo)return{primaries:di[i.proresCodecInfo.colourPrimaries],transfer:fi[i.proresCodecInfo.transferCharacteristics],matrix:i.proresCodecInfo.matrixCoefficients===0?void 0:hi[i.proresCodecInfo.matrixCoefficients],fullRange:i.proresCodecInfo.fullRange};break}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},Nd=i=>{if(i==="aac")return"mp4a.40.2";if(i==="mp3")return"mp3";if(i==="opus")return"opus";if(i==="vorbis")return"vorbis";if(i==="flac")return"flac";if(i==="ac3")return"ac-3";if(i==="eac3")return"ec-3";if(i==="dts")return"dtsc";if(i==="truehd")return"mlpa";if(je.includes(i))return i;throw new TypeError(`Unhandled codec '${i}'.`)},Xo=i=>{const{codec:e,codecDescription:t,aacCodecInfo:r,dtsFormat:s}=i;if(e==="aac"){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let n;return r.objectType!==null?n=r.objectType:n=nr(t).objectType,`mp4a.40.${n}`}}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e==="ac3")return"ac-3";if(e==="eac3")return"ec-3";if(e==="dts")return s??"dtsc";if(e==="truehd")return"mlpa";if(e&&je.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},Gp=i=>{},Xp=i=>{switch(i.codec){case"flac":{const e=ln("ZkxhQ4AAACIQABAAAAYtACWtCsRC8AANRBhVFucAcYu5ASE2m1Dxv8tw");return i.sampleRate>=1<<20||i.numberOfChannels>8?!1:(e[18]=i.sampleRate>>>12,e[19]=i.sampleRate>>>4,e[20]=(i.sampleRate&15)<<4|i.numberOfChannels-1<<1,e)}case"vorbis":{const e=ln("Ah7/AgF2b3JiaXMAAAAAAoC7AAAAAAAAgLUBAAAAAAC4AQN2b3JiaXMNAAAATGF2ZjU4Ljc2LjEwMAgAAAAMAAAAbGFuZ3VhZ2U9dW5kGQAAAGhhbmRsZXJfbmFtZT1Tb3VuZEhhbmRsZXIWAAAAdmVuZG9yX2lkPVswXVswXVswXVswXSAAAABlbmNvZGVyPUxhdmM1OC4xMzQuMTAwIGxpYnZvcmJpcxAAAABtYWpvcl9icmFuZD1pc29tEQAAAG1pbm9yX3ZlcnNpb249NTEyIgAAAGNvbXBhdGlibGVfYnJhbmRzPWlzb21pc28yYXZjMW1wNDEmAAAAREVTQ1JJUFRJT049TWFkZSB3aXRoIFJlbW90aW9uIDQuMC4yNzgBBXZvcmJpcyVCQ1YBAEAAACRzGCpGpXMWhBAaQlAZ4xxCzmvsGUJMEYIcMkxbyyVzkCGkoEKIWyiB0JBVAABAAACHQXgUhIpBCCGEJT1YkoMnPQghhIg5eBSEaUEIIYQQQgghhBBCCCGERTlokoMnQQgdhOMwOAyD5Tj4HIRFOVgQgydB6CCED0K4moOsOQghhCQ1SFCDBjnoHITCLCiKgsQwuBaEBDUojILkMMjUgwtCiJqDSTX4GoRnQXgWhGlBCCGEJEFIkIMGQcgYhEZBWJKDBjm4FITLQagahCo5CB+EIDRkFQCQAACgoiiKoigKEBqyCgDIAAAQQFEUx3EcyZEcybEcCwgNWQUAAAEACAAAoEiKpEiO5EiSJFmSJVmSJVmS5omqLMuyLMuyLMsyEBqyCgBIAABQUQxFcRQHCA1ZBQBkAAAIoDiKpViKpWiK54iOCISGrAIAgAAABAAAEDRDUzxHlETPVFXXtm3btm3btm3btm3btm1blmUZCA1ZBQBAAAAQ0mlmqQaIMAMZBkJDVgEACAAAgBGKMMSA0JBVAABAAACAGEoOogmtOd+c46BZDppKsTkdnEi1eZKbirk555xzzsnmnDHOOeecopxZDJoJrTnnnMSgWQqaCa0555wnsXnQmiqtOeeccc7pYJwRxjnnnCateZCajbU555wFrWmOmkuxOeecSLl5UptLtTnnnHPOOeecc84555zqxekcnBPOOeecqL25lpvQxTnnnE/G6d6cEM4555xzzjnnnHPOOeecIDRkFQAABABAEIaNYdwpCNLnaCBGEWIaMulB9+gwCRqDnELq0ehopJQ6CCWVcVJKJwgNWQUAAAIAQAghhRRSSCGFFFJIIYUUYoghhhhyyimnoIJKKqmooowyyyyzzDLLLLPMOuyssw47DDHEEEMrrcRSU2011lhr7jnnmoO0VlprrbVSSimllFIKQkNWAQAgAAAEQgYZZJBRSCGFFGKIKaeccgoqqIDQkFUAACAAgAAAAABP8hzRER3RER3RER3RER3R8RzPESVREiVREi3TMjXTU0VVdWXXlnVZt31b2IVd933d933d+HVhWJZlWZZlWZZlWZZlWZZlWZYgNGQVAAACAAAghBBCSCGFFFJIKcYYc8w56CSUEAgNWQUAAAIACAAAAHAUR3EcyZEcSbIkS9IkzdIsT/M0TxM9URRF0zRV0RVdUTdtUTZl0zVdUzZdVVZtV5ZtW7Z125dl2/d93/d93/d93/d93/d9XQdCQ1YBABIAADqSIymSIimS4ziOJElAaMgqAEAGAEAAAIriKI7jOJIkSZIlaZJneZaomZrpmZ4qqkBoyCoAABAAQAAAAAAAAIqmeIqpeIqoeI7oiJJomZaoqZoryqbsuq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq4LhIasAgAkAAB0JEdyJEdSJEVSJEdygNCQVQCADACAAAAcwzEkRXIsy9I0T/M0TxM90RM901NFV3SB0JBVAAAgAIAAAAAAAAAMybAUy9EcTRIl1VItVVMt1VJF1VNVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVN0zRNEwgNWQkAkAEAkBBTLS3GmgmLJGLSaqugYwxS7KWxSCpntbfKMYUYtV4ah5RREHupJGOKQcwtpNApJq3WVEKFFKSYYyoVUg5SIDRkhQAQmgHgcBxAsixAsiwAAAAAAAAAkDQN0DwPsDQPAAAAAAAAACRNAyxPAzTPAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAA0DwP8DwR8EQRAAAAAAAAACzPAzTRAzxRBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAAsDwP8EQR0DwRAAAAAAAAACzPAzxRBDzRAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEOAAABBgIRQasiIAiBMAcEgSJAmSBM0DSJYFTYOmwTQBkmVB06BpME0AAAAAAAAAAAAAJE2DpkHTIIoASdOgadA0iCIAAAAAAAAAAAAAkqZB06BpEEWApGnQNGgaRBEAAAAAAAAAAAAAzzQhihBFmCbAM02IIkQRpgkAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAGHAAAAgwoQwUGrIiAIgTAHA4imUBAIDjOJYFAACO41gWAABYliWKAABgWZooAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAYcAAACDChDBQashIAiAIAcCiKZQHHsSzgOJYFJMmyAJYF0DyApgFEEQAIAAAocAAACLBBU2JxgEJDVgIAUQAABsWxLE0TRZKkaZoniiRJ0zxPFGma53meacLzPM80IYqiaJoQRVE0TZimaaoqME1VFQAAUOAAABBgg6bE4gCFhqwEAEICAByKYlma5nmeJ4qmqZokSdM8TxRF0TRNU1VJkqZ5niiKommapqqyLE3zPFEURdNUVVWFpnmeKIqiaaqq6sLzPE8URdE0VdV14XmeJ4qiaJqq6roQRVE0TdNUTVV1XSCKpmmaqqqqrgtETxRNU1Vd13WB54miaaqqq7ouEE3TVFVVdV1ZBpimaaqq68oyQFVV1XVdV5YBqqqqruu6sgxQVdd1XVmWZQCu67qyLMsCAAAOHAAAAoygk4wqi7DRhAsPQKEhKwKAKAAAwBimFFPKMCYhpBAaxiSEFEImJaXSUqogpFJSKRWEVEoqJaOUUmopVRBSKamUCkIqJZVSAADYgQMA2IGFUGjISgAgDwCAMEYpxhhzTiKkFGPOOScRUoox55yTSjHmnHPOSSkZc8w556SUzjnnnHNSSuacc845KaVzzjnnnJRSSuecc05KKSWEzkEnpZTSOeecEwAAVOAAABBgo8jmBCNBhYasBABSAQAMjmNZmuZ5omialiRpmud5niiapiZJmuZ5nieKqsnzPE8URdE0VZXneZ4oiqJpqirXFUXTNE1VVV2yLIqmaZqq6rowTdNUVdd1XZimaaqq67oubFtVVdV1ZRm2raqq6rqyDFzXdWXZloEsu67s2rIAAPAEBwCgAhtWRzgpGgssNGQlAJABAEAYg5BCCCFlEEIKIYSUUggJAAAYcAAACDChDBQashIASAUAAIyx1lprrbXWQGettdZaa62AzFprrbXWWmuttdZaa6211lJrrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmstpZRSSimllFJKKaWUUkoppZRSSgUA+lU4APg/2LA6wknRWGChISsBgHAAAMAYpRhzDEIppVQIMeacdFRai7FCiDHnJKTUWmzFc85BKCGV1mIsnnMOQikpxVZjUSmEUlJKLbZYi0qho5JSSq3VWIwxqaTWWoutxmKMSSm01FqLMRYjbE2ptdhqq7EYY2sqLbQYY4zFCF9kbC2m2moNxggjWywt1VprMMYY3VuLpbaaizE++NpSLDHWXAAAd4MDAESCjTOsJJ0VjgYXGrISAAgJACAQUooxxhhzzjnnpFKMOeaccw5CCKFUijHGnHMOQgghlIwx5pxzEEIIIYRSSsaccxBCCCGEkFLqnHMQQgghhBBKKZ1zDkIIIYQQQimlgxBCCCGEEEoopaQUQgghhBBCCKmklEIIIYRSQighlZRSCCGEEEIpJaSUUgohhFJCCKGElFJKKYUQQgillJJSSimlEkoJJYQSUikppRRKCCGUUkpKKaVUSgmhhBJKKSWllFJKIYQQSikFAAAcOAAABBhBJxlVFmGjCRcegEJDVgIAZAAAkKKUUiktRYIipRikGEtGFXNQWoqocgxSzalSziDmJJaIMYSUk1Qy5hRCDELqHHVMKQYtlRhCxhik2HJLoXMOAAAAQQCAgJAAAAMEBTMAwOAA4XMQdAIERxsAgCBEZohEw0JweFAJEBFTAUBigkIuAFRYXKRdXECXAS7o4q4DIQQhCEEsDqCABByccMMTb3jCDU7QKSp1IAAAAAAADADwAACQXAAREdHMYWRobHB0eHyAhIiMkAgAAAAAABcAfAAAJCVAREQ0cxgZGhscHR4fICEiIyQBAIAAAgAAAAAggAAEBAQAAAAAAAIAAAAEBA=="),t=ie(e);return t.setUint8(15,i.numberOfChannels),t.setUint32(16,i.sampleRate,!0),e}default:return}},Vd=(i,e)=>{switch(i){case"aac":{if(!e.description)return 1024/e.sampleRate;const t=nr(me(e.description));if(t.coreSampleRate===null)throw new Error("Invalid AAC sampling frequency index.");return t.frameLength/t.coreSampleRate}case"opus":return Wd;case"mp3":{const{sampleRate:t,numberOfChannels:r}=e,s=t>=32e3,n=s?1152:576,a=s?32e3:8e3,o=s?511:255,c=s?r===1?17:32:r===1?9:17,l=Math.floor(n/8*a/t)-Yt-c;return(1+Math.ceil(o/l))*n/t}case"vorbis":{w(e.description);const t=me(e.description);let r=1,s=2;for(;s>0;)t[r++]<255&&s--;return(1<<(t[r+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:xe(i),w(!1)}},Yp=(i,e)=>{switch(i){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 nn;default:xe(i),w(!1)}},Wi=48e3,Wd=.4,Ld=/^pcm-([usf])(\d+)(be)?$/,Bt=i=>{if(w(je.includes(i)),i==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(i==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=Ld.exec(i);w(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";const r=Number(e[2])/8,s=e[3]!=="be",n=i==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:r,littleEndian:s,silentValue:n}},Dt=i=>i.startsWith("avc1")||i.startsWith("avc3")?"avc":i.startsWith("hev1")||i.startsWith("hvc1")?"hevc":i==="vp8"?"vp8":i.startsWith("vp09")?"vp9":i.startsWith("av01")?"av1":er.includes(i)?"prores":i==="mp3"||i==="mp4a.69"||i==="mp4a.6B"||i==="mp4a.6b"||i==="mp4a.40.34"?"mp3":i.startsWith("mp4a.40.")||i==="mp4a.67"?"aac":i==="opus"||i==="Opus"?"opus":i==="vorbis"?"vorbis":i==="flac"||i==="fLaC"?"flac":i==="ac-3"||i==="ac3"?"ac3":i==="ec-3"||i==="eac3"?"eac3":Cn.includes(i)?"dts":i==="mlpa"?"truehd":i==="ulaw"?"ulaw":i==="alaw"?"alaw":Ld.test(i)?i:i==="webvtt"?"webvtt":null,Zp=i=>i==="avc"?{avc:{format:"avc"}}:i==="hevc"?{hevc:{format:"hevc"}}:{},Hd=i=>i==="aac"?{aac:{format:"aac"}}:i==="opus"?{opus:{format:"opus"}}:{},Jp=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...er],eg=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,tg=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,ig=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,rg=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Ds=(i,e)=>{if(!i)throw new TypeError("Video chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Video chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!Jp.some(t=>i.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(i.decoderConfig.codedWidth)||i.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(i.decoderConfig.codedHeight)||i.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(i.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(i.decoderConfig.displayAspectWidth)||i.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(i.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(i.decoderConfig.displayAspectHeight)||i.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(i.decoderConfig.displayAspectWidth!==void 0!=(i.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(i.decoderConfig.description!==void 0&&!Ur(i.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.colorSpace!==void 0){const{colorSpace:t}=i.decoderConfig;if(typeof t!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const r=Object.keys(Ui);if(t.primaries!=null&&!r.includes(t.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);const s=Object.keys(Ni);if(t.transfer!=null&&!s.includes(t.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${s.join(", ")}.`);const n=Object.keys(Vi);if(t.matrix!=null&&!n.includes(t.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${n.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(i.decoderConfig.codec.startsWith("avc1")||i.decoderConfig.codec.startsWith("avc3")){if(!eg.test(i.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(i.decoderConfig.codec.startsWith("hev1")||i.decoderConfig.codec.startsWith("hvc1")){if(!tg.test(i.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(i.decoderConfig.codec.startsWith("vp8")){if(i.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(i.decoderConfig.codec.startsWith("vp09")){if(!ig.test(i.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(i.decoderConfig.codec.startsWith("av01")){if(!rg.test(i.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(er.some(t=>i.decoderConfig.codec.startsWith(t))&&!er.some(t=>i.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: ${er.join(", ")}.`);if(e!==null&&Dt(i.decoderConfig.codec)!==e)throw new TypeError(`Video chunk metadata decoder configuration codec string '${i.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},sg=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts","mlpa"],Nt=(i,e)=>{if(!i)throw new TypeError("Audio chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!sg.some(t=>i.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(i.decoderConfig.sampleRate)||i.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(i.decoderConfig.numberOfChannels)||i.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(i.decoderConfig.description!==void 0&&!Ur(i.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.codec.startsWith("mp4a")&&i.decoderConfig.codec!=="mp4a.69"&&i.decoderConfig.codec!=="mp4a.6B"&&i.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.40.42","mp4a.67"].includes(i.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(i.decoderConfig.codec.startsWith("mp3")||i.decoderConfig.codec.startsWith("mp4a")){if(i.decoderConfig.codec!=="mp3"&&i.decoderConfig.codec!=="mp4a.69"&&i.decoderConfig.codec!=="mp4a.6B"&&i.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(i.decoderConfig.codec.startsWith("opus")){if(i.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(i.decoderConfig.description&&i.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(i.decoderConfig.codec.startsWith("vorbis")){if(i.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!i.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(i.decoderConfig.codec.startsWith("flac")){if(i.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!i.decoderConfig.description||i.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(i.decoderConfig.codec.startsWith("ac-3")||i.decoderConfig.codec.startsWith("ac3")){if(i.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(i.decoderConfig.codec.startsWith("ec-3")||i.decoderConfig.codec.startsWith("eac3")){if(i.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if(i.decoderConfig.codec.startsWith("dts")){if(!Cn.includes(i.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${Cn.join(", ")}.`)}else if(i.decoderConfig.codec.startsWith("mlpa")){if(i.decoderConfig.codec!=="mlpa")throw new TypeError('Audio chunk metadata decoder configuration codec string for TrueHD must be "mlpa".')}else if((i.decoderConfig.codec.startsWith("pcm")||i.decoderConfig.codec.startsWith("ulaw")||i.decoderConfig.codec.startsWith("alaw"))&&!je.includes(i.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${je.join(", ")}).`);if(e!==null&&Dt(i.decoderConfig.codec)!==e)throw new TypeError(`Audio chunk metadata decoder configuration codec string '${i.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},qd=i=>{if(!i)throw new TypeError("Subtitle metadata must be provided.");if(typeof i!="object")throw new TypeError("Subtitle metadata must be an object.");if(!i.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof i.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof i.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};/*!
|
|
315
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
316
|
+
*
|
|
317
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
318
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
319
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
320
|
+
*/class ti{constructor(e){this.mutex=new Jt,this.trackPacketOrderValidators=new WeakMap,this.output=e}async onTrackClose(e){}validateTimestamp(e,t,r){let s=this.trackPacketOrderValidators.get(e);s||(s=new ho,this.trackPacketOrderValidators.set(e,s));const n=r?"key":"delta";if(s.digest(t,n))return;if(s.maxTimestamp===null)throw new Error("First packet must be a key packet.");const a=n==="key"?s.maxTimestamp:s.maxTimestampBeforeLastKeyPacket;throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${a}s.`)}}class ho{constructor(){this.maxTimestamp=null,this.maxTimestampBeforeLastKeyPacket=null}check(e,t){if(this.maxTimestamp===null)return t==="key";const r=t==="key"?this.maxTimestamp:this.maxTimestampBeforeLastKeyPacket;return r===null||e>=r}digest(e,t){return this.check(e,t)?(t==="key"&&(this.maxTimestampBeforeLastKeyPacket=this.maxTimestamp),this.maxTimestamp=Math.max(this.maxTimestamp??-1/0,e),!0):!1}}class ng extends ti{async start(){}async getMimeType(){return"application/x-black-hole"}async addEncodedVideoPacket(){}async addEncodedAudioPacket(){}async addSubtitleCue(){}async finalize(){}}/*!
|
|
321
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
322
|
+
*
|
|
323
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
324
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
325
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
326
|
+
*/class ag extends ti{constructor(e,t){super(e),this.header=null,this.headerBitstream=null,this.inputIsAdts=null,this.format=t}async start(){const e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!0),ds(this.output._metadataTags)||new No(this.writer).writeId3V2Tag(this.output._metadataTags)}finally{e()}}async getMimeType(){return"audio/aac"}async addEncodedVideoPacket(){throw new Error("ADTS does not support video.")}async addEncodedAudioPacket(e,t,r){var n;const s=await this.mutex.acquire();try{if(this.validateTimestamp(e,t.timestamp,t.type==="key"),this.inputIsAdts===null){Nt(r,e.source._codec);const a=(n=r==null?void 0:r.decoderConfig)==null?void 0:n.description;if(a){const o=nr(me(a)),c=Ql(o);this.header=c.header,this.headerBitstream=c.bitstream}this.inputIsAdts=!a}if(this.inputIsAdts){const a=this.writer.getPos();this.writer.write(t.data),this.format._options.onFrame&&this.format._options.onFrame(t.data,a)}else{w(this.header);const a=t.data.byteLength+this.header.byteLength;Yl(this.headerBitstream,a);const o=this.writer.getPos();if(this.writer.write(this.header),this.writer.write(t.data),this.format._options.onFrame){const c=new Uint8Array(a);c.set(this.header,0),c.set(t.data,this.header.byteLength),this.format._options.onFrame(c,o)}}await this.writer.flush()}finally{s()}}async addSubtitleCue(){throw new Error("ADTS does not support subtitles.")}async finalize(){const e=await this.mutex.acquire();if(this.inputIsAdts===null)throw new Error("Cannot finalize an empty ADTS file: not a single packet was added.");e()}}/*!
|
|
327
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
328
|
+
*
|
|
329
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
330
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
331
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
332
|
+
*/const gl=new Uint8Array([102,76,97,67]),og=38,cg=34,Ks=2**24-1;class lg extends ti{constructor(e,t){super(e),this.metadataWritten=!1,this.blockSizes=[],this.frameSizes=[],this.sampleRate=null,this.channels=null,this.bitsPerSample=null,this.format=t}async start(){const e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.writer.write(gl);const t=this.output.tracks[0];w(t==null?void 0:t.isAudioTrack()),t.metadata.decoderConfig&&(Nt({decoderConfig:t.metadata.decoderConfig},t.source._codec),this.applyDecoderConfig(t.metadata.decoderConfig))}finally{e()}}applyDecoderConfig(e){w(e.description),this.sampleRate=e.sampleRate,this.channels=e.numberOfChannels;const t=new oe(me(e.description));t.skipBits(167),this.bitsPerSample=t.readBits(5)+1,this.format._options.appendOnly&&this.writeHeader({minimumBlockSize:16,maximumBlockSize:65535,minimumFrameSize:0,maximumFrameSize:0,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:0})}writeHeader({bitsPerSample:e,minimumBlockSize:t,maximumBlockSize:r,minimumFrameSize:s,maximumFrameSize:n,sampleRate:a,channels:o,totalSamples:c}){w(this.writer.getPos()===4);const u=!ds(this.output._metadataTags),l=new oe(new Uint8Array(4));l.writeBits(1,+!u),l.writeBits(7,yi.STREAMINFO),l.writeBits(24,cg),this.writer.write(l.bytes);const d=new oe(new Uint8Array(18));d.writeBits(16,t),d.writeBits(16,r),d.writeBits(24,s),d.writeBits(24,n),d.writeBits(20,a),d.writeBits(3,o-1),d.writeBits(5,e-1),d.writeBits(36,c<2**36?c:0),this.writer.write(d.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock(e){const t=ge.encode(e.mimeType),r=ge.encode(e.description??""),s=32+t.length+r.length+e.data.length;if(s>Ks)throw new Error(`Picture is too big for FLAC: its metadata block would take ${s} bytes, but FLAC metadata blocks can take at most ${Ks} bytes.`);const n=new Uint8Array(s);let a=0;const o=ie(n);o.setUint32(a,e.kind==="coverFront"?3:e.kind==="coverBack"?4:0),a+=4,o.setUint32(a,t.length),a+=4,n.set(t,a),a+=t.length,o.setUint32(a,r.length),a+=4,n.set(r,a),a+=r.length,a+=16,o.setUint32(a,e.data.length),a+=4,n.set(e.data,a),a+=e.data.length,w(a===s);const c=new oe(new Uint8Array(4));c.writeBits(1,0),c.writeBits(7,yi.PICTURE),c.writeBits(24,s),this.writer.write(c.bytes),this.writer.write(n)}writeVorbisCommentAndPictureBlock(){if(this.format._options.appendOnly||this.writer.seek(og+gl.byteLength),ds(this.output._metadataTags)){this.metadataWritten=!0;return}const e=this.output._metadataTags.images??[];for(const s of e)this.writePictureBlock(s);const t=Ua(new Uint8Array(0),this.output._metadataTags,!1);if(t.length>Ks)throw new Error(`Metadata tags are too big for FLAC: their Vorbis comment block would take ${t.length} bytes, but FLAC metadata blocks can take at most ${Ks} bytes.`);const r=new oe(new Uint8Array(4));r.writeBits(1,1),r.writeBits(7,yi.VORBIS_COMMENT),r.writeBits(24,t.length),this.writer.write(r.bytes),this.writer.write(t),this.metadataWritten=!0}async getMimeType(){return"audio/flac"}async addEncodedVideoPacket(){throw new Error("FLAC does not support video.")}async addEncodedAudioPacket(e,t,r){const s=await this.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type==="key"),this.sampleRate===null&&(Nt(r,e.source._codec),w(r),w(r.decoderConfig),this.applyDecoderConfig(r.decoderConfig)),this.metadataWritten||this.writeVorbisCommentAndPictureBlock();const n=at.tempFromBytes(t.data);n.skip(2);const a=X(n,2),o=new oe(a),c=Ju(o.readBits(4));if(c===null)throw new Error("Invalid FLAC frame: Invalid block size.");ed(n);const u=td(n,c);this.format._options.appendOnly||(this.blockSizes.push(u),this.frameSizes.push(t.data.length));const l=this.writer.getPos();this.writer.write(t.data),this.format._options.onFrame&&this.format._options.onFrame(t.data,l),await this.writer.flush()}finally{s()}}addSubtitleCue(){throw new Error("FLAC does not support subtitles.")}async finalize(){const e=await this.mutex.acquire();if(this.sampleRate===null)throw new Error("Cannot finalize an empty FLAC file: no packets were added and the track specified no decoderConfig in its metadata, so there's no telling what the file should look like.");if(this.metadataWritten||this.writeVorbisCommentAndPictureBlock(),!this.format._options.appendOnly){let t=1/0,r=0,s=1/0,n=0,a=0;for(let o=0;o<this.blockSizes.length;o++)s=Math.min(s,this.frameSizes[o]),n=Math.max(n,this.frameSizes[o]),r=Math.max(r,this.blockSizes[o]),a+=this.blockSizes[o],o!==this.blockSizes.length-1&&(t=Math.min(t,this.blockSizes[o]));this.blockSizes.length===0?(t=16,r=65535,s=0,n=0):this.blockSizes.length===1&&(r=Math.max(r,16),t=r),w(this.channels!==null),w(this.bitsPerSample!==null),this.writer.seek(4),this.writeHeader({minimumBlockSize:t,maximumBlockSize:r,minimumFrameSize:s,maximumFrameSize:n,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:a})}e()}}/*!
|
|
333
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
334
|
+
*
|
|
335
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
336
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
337
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
338
|
+
*/class $s{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8===7&&this.writer.write(this.helper);e.length%8!==0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{const t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(const n of e.children)n&&this.writeBox(n);const r=this.writer.getPos(),s=e.size??r-t;this.writer.seek(t),this.writeBoxHeader(e,s),this.writer.seek(r)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){const t=this.offsets.get(e);w(t!==void 0);const r=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(r)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(const r of e.children)r&&(t+=this.measureBox(r));return t}}}const ae=new Uint8Array(8),Tt=new DataView(ae.buffer),Re=i=>[(i%256+256)%256],J=i=>(Tt.setUint16(0,i,!1),[ae[0],ae[1]]),Ts=i=>(Tt.setInt16(0,i,!1),[ae[0],ae[1]]),jd=i=>(Tt.setUint32(0,i,!1),[ae[1],ae[2],ae[3]]),z=i=>(Tt.setUint32(0,i,!1),[ae[0],ae[1],ae[2],ae[3]]),zt=i=>(Tt.setInt32(0,i,!1),[ae[0],ae[1],ae[2],ae[3]]),Vt=i=>(Tt.setUint32(0,Math.floor(i/2**32),!1),Tt.setUint32(4,i,!1),[ae[0],ae[1],ae[2],ae[3],ae[4],ae[5],ae[6],ae[7]]),wl=i=>(Tt.setInt32(0,Math.floor(i/2**32),!1),Tt.setUint32(4,i,!1),[ae[0],ae[1],ae[2],ae[3],ae[4],ae[5],ae[6],ae[7]]),ug=i=>(Tt.setFloat64(0,i,!1),[ae[0],ae[1],ae[2],ae[3],ae[4],ae[5],ae[6],ae[7]]),Kd=i=>(Tt.setInt16(0,2**8*i,!1),[ae[0],ae[1]]),Ct=i=>(Tt.setInt32(0,2**16*i,!1),[ae[0],ae[1],ae[2],ae[3]]),wa=i=>(Tt.setInt32(0,2**30*i,!1),[ae[0],ae[1],ae[2],ae[3]]),ya=(i,e)=>{const t=[];let r=i;do{let s=r&127;r>>=7,t.length>0&&(s|=128),t.push(s)}while(r>0||e);return t.reverse()},be=(i,e=!1)=>{const t=Array(i.length).fill(null).map((r,s)=>i.charCodeAt(s));return e&&t.push(0),t},$d=i=>[Ct(i[0]),Ct(i[1]),wa(i[2]),Ct(i[3]),Ct(i[4]),wa(i[5]),Ct(i[6]),Ct(i[7]),wa(i[8])],ee=(i,e,t)=>({type:i,contents:e&&new Uint8Array(e.flat(10)),children:t}),fe=(i,e,t,r,s)=>ee(i,[Re(e),jd(t),r??[]],s),dg=i=>i.isQuickTime?ee("ftyp",[be("qt "),z(512),be("qt ")]):i.fragmented?i.cmaf?ee("ftyp",[be("iso5"),z(512),be("iso5"),be("iso6"),be("mp41"),be("cmfc"),be("dash")]):ee("ftyp",[be("iso5"),z(512),be("iso5"),be("iso6"),be("mp41")]):ee("ftyp",[be("isom"),z(512),be("isom"),i.holdsAvc?be("avc1"):[],be("mp41")]),yl=()=>ee("styp",[be("iso5"),z(0),be("iso5"),be("iso6"),be("mp41"),be("cmfc"),be("dash")]),bl=(i,e)=>{w(e<2**31);const t=Math.max(0,i.minWrittenTimestamp);let r=Math.max(0,i.maxWrittenEndTimestamp-t);Number.isFinite(r)||(r=0);const s=Se(r,bt);if(s>=2**32)throw new Error("CMAF segments must be shorter than 20.712612 hours.");return fe("sidx",1,0,[z(1),z(bt),Vt(Se(t,bt)),Vt(0),J(0),J(1),z(e),z(s),z(0)])},Qs=i=>({type:"mdat",largeSize:i}),fg=i=>({type:"free",size:i}),Zr=i=>ee("moov",void 0,[hg(i.creationTime,i.trackDatas),...i.trackDatas.map(e=>mg(e,i.creationTime)),i.isFragmented?ew(i.trackDatas):null,hw(i)]),hg=(i,e)=>{const t=Math.max(0,...e.map(a=>Math.max(0,Se(Or(a),bt)+Se(a.startTimestampOffset??0,bt)))),r=Math.max(0,...e.map(a=>a.track.id))+1,s=!gi(i)||!gi(t),n=s?Vt:z;return fe("mvhd",+s,0,[n(i),n(i),z(bt),n(t),Ct(1),Kd(1),Array(10).fill(0),$d(cs),Array(24).fill(0),z(r)])},mg=(i,e)=>{const t=Pw(i),r=i.startTimestampOffset!==null&&i.startTimestampOffset!==0;return ee("trak",void 0,[pg(i,e),r?gg(i):null,wg(i,e),t.name!==void 0?ee("udta",void 0,[ee("name",[...ge.encode(t.name)])]):null])},pg=(i,e)=>{var c;const t=Math.max(0,Se(Or(i),bt)+Se(i.startTimestampOffset??0,bt)),r=!gi(e)||!gi(t),s=r?Vt:z;let n;if(i.type==="video"&&i.track.metadata.transformationMatrix)n=i.track.metadata.transformationMatrix;else if(i.type==="video"){const{rotation:u,flip:l}=i.track.metadata,d=vr(mo(u??0),Ol(l?-1:1,1));n=Dl(d,i.info.width,i.info.height)}else n=cs;let a=2;((c=i.track.metadata.disposition)==null?void 0:c.default)!==!1&&(a|=1);const o=i.type==="video"?0:i.type==="audio"?1:i.type==="subtitle"?2:xe(i);return fe("tkhd",+r,a,[s(e),s(e),z(i.track.id),z(0),s(t),Array(8).fill(0),J(0),J(o),Kd(i.type==="audio"?1:0),J(0),$d(n),Ct(i.type==="video"?i.info.width:0),Ct(i.type==="video"?i.info.height:0)])},gg=i=>{const e=i.startTimestampOffset;if(w(e!==null),e>0){const t=Se(e,bt),r=Se(Or(i),bt),s=!gi(t)||!gi(r),n=s?Vt:z,a=s?wl:zt;return ee("edts",void 0,[fe("elst",s?1:0,0,[z(2),n(t),a(-1),Ct(1),n(r),a(0),Ct(1)])])}else{const t=Se(-e,i.timescale),r=Math.max(0,Se(Or(i),bt)+Se(e,bt)),s=!Nl(t)||!gi(r),n=s?Vt:z,a=s?wl:zt;return ee("edts",void 0,[fe("elst",s?1:0,0,[z(1),n(r),a(t),Ct(1)])])}},wg=(i,e)=>ee("mdia",void 0,[yg(i,e),Yo(!0,bg[i.type],kg[i.type],void 0,i.muxer.isQuickTime),Tg(i)]),yg=(i,e)=>{const t=Se(Or(i),i.timescale),r=!gi(e)||!gi(t),s=r?Vt:z;return fe("mdhd",+r,0,[s(e),s(e),z(i.timescale),s(t),J(ef(i.track.metadata.languageCode??et)),J(0)])},bg={video:"vide",audio:"soun",subtitle:"text"},kg={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Yo=(i,e,t,r="\0\0\0\0",s=!1)=>fe("hdlr",0,0,[i?be("mhlr"):z(0),be(e),be(r),z(0),z(0),s?[Re(t.length),be(t)]:be(t,!0)]),Tg=i=>ee("minf",void 0,[Pg[i.type](),Cg(),Ig(i)]),Sg=()=>fe("vmhd",0,1,[J(0),J(0),J(0),J(0)]),Ag=()=>fe("smhd",0,0,[J(0),J(0)]),xg=()=>fe("nmhd",0,0),Pg={video:Sg,audio:Ag,subtitle:xg},Cg=()=>ee("dinf",void 0,[_g()]),_g=()=>fe("dref",0,0,[z(1)],[Eg()]),Eg=()=>fe("url ",0,1),Ig=i=>{const e=i.compositionTimeOffsetTable.length>1||i.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return ee("stbl",void 0,[vg(i),$g(i),e?Zg(i):null,e?Jg(i):null,Gg(i),Xg(i),Yg(i),Qg(i),...Xd(i.samples,!1)])},vg=i=>{let e;if(i.type==="video")e=Bg(yw(i.track.source._codec,i.info.decoderConfig.codec),i);else if(i.type==="audio"){const t=Jd(i.track.source._codec,i.info.decoderConfig.codec,i.muxer.isQuickTime);w(t),e=Og(t,i)}else i.type==="subtitle"&&(e=jg(kw[i.track.source._codec],i));return w(e),fe("stsd",0,0,[z(1)],[e])},Bg=(i,e)=>{var t;return ee(i,[Array(6).fill(0),J(1),J(0),J(0),Array(12).fill(0),J(e.info.width),J(e.info.height),z(4718592),z(4718592),z(0),J(1),Re(Pr.length),be(Pr),Array(31-Pr.length).fill(0),J(e.info.hasAlphaChannel?32:24),Ts(65535)],[((t=ka[e.track.source._codec])==null?void 0:t.call(ka,e))??null,Fg(e),Vl(e.info.decoderConfig.colorSpace)?null:Rg(e),Zo(e)])},Zo=i=>i.avgBitrate===0&&i.maxBitrate===0?null:ee("btrt",[z(0),z(i.maxBitrate),z(i.avgBitrate)]),Fg=i=>i.info.pixelAspectRatio.num===i.info.pixelAspectRatio.den?null:ee("pasp",[z(i.info.pixelAspectRatio.num),z(i.info.pixelAspectRatio.den)]),Rg=i=>{const e=i.info.decoderConfig.colorSpace;return ee("colr",[be(i.muxer.isQuickTime?"nclc":"nclx"),J((e==null?void 0:e.primaries)!=null?Ui[e.primaries]:2),J((e==null?void 0:e.transfer)!=null?Ni[e.transfer]:2),J((e==null?void 0:e.matrix)!=null?Vi[e.matrix]:2),i.muxer.isQuickTime?[]:Re((e!=null&&e.fullRange?1:0)<<7)])},Mg=i=>i.info.decoderConfig&&ee("avcC",[...me(i.info.decoderConfig.description)]),Dg=i=>i.info.decoderConfig&&ee("hvcC",[...me(i.info.decoderConfig.description)]),kl=i=>{var f,h,p,m;if(!i.info.decoderConfig)return null;const e=i.info.decoderConfig,t=e.codec.split("."),r=Number(t[1]),s=Number(t[2]),n=t[3]?Number(t[3]):8,a=t[4]?Number(t[4]):1,o=t[8]?Number(t[8]):Number(((f=e.colorSpace)==null?void 0:f.fullRange)??0),c=(n<<4)+(a<<1)+o,u=t[5]?Number(t[5]):(h=e.colorSpace)!=null&&h.primaries?Ui[e.colorSpace.primaries]:1,l=t[6]?Number(t[6]):(p=e.colorSpace)!=null&&p.transfer?Ni[e.colorSpace.transfer]:1,d=t[7]?Number(t[7]):(m=e.colorSpace)!=null&&m.matrix?Vi[e.colorSpace.matrix]:1;return fe("vpcC",1,0,[Re(r),Re(s),Re(c),Re(u),Re(l),Re(d),J(0)])},zg=i=>ee("av1C",Od(i.info.decoderConfig.codec)),Og=(i,e)=>{var c,u;let t=0,r,s=16,n=e.info.sampleRate,a=((c=bw(e.track.source._codec,e.muxer.isQuickTime))==null?void 0:c(e))??null;const o=je.includes(e.track.source._codec);if(o){const l=e.track.source._codec,{sampleSize:d}=Bt(l);s=8*d}else if(e.track.source._codec==="flac"){const l=(u=e.info.decoderConfig)==null?void 0:u.description;w(l);const d=new oe(me(l));for(d.skipBits(167),s=d.readBits(5)+1;n>=2**16;)n=Math.floor(n/2)}if(e.muxer.isQuickTime&&e.track.source._codec!=="truehd"&&(t=e.info.sampleRate<2**16&&e.info.numberOfChannels<=2?1:2),t===0)r=[Array(6).fill(0),J(1),J(t),J(0),z(0),J(e.info.numberOfChannels),J(s),J(0),J(0),e.track.source._codec==="truehd"?z(e.info.sampleRate):[J(n<2**16?n:0),J(0)]];else if(t===1){const l=o?0:-2;r=[Array(6).fill(0),J(1),J(t),J(0),z(0),J(e.info.numberOfChannels),J(Math.min(s,16)),Ts(l),J(0),J(e.info.sampleRate<2**16?e.info.sampleRate:0),J(0),o?[z(1),z(s/8),z(e.info.numberOfChannels*s/8)]:[z(0),z(0),z(0)],z(2)]}else if(t===2){let l=0;if(o){const{dataType:d,littleEndian:f}=Bt(e.track.source._codec);d!=="ulaw"&&d!=="alaw"&&(i="lpcm",a=null,l=(d==="float"?1:0)|(f?0:2)|(d==="signed"?4:0)|8)}r=[Array(6).fill(0),J(1),J(t),J(0),z(0),J(3),J(16),Ts(-2),J(0),z(65536),z(72),ug(e.info.sampleRate),z(e.info.numberOfChannels),z(2130706432),o?[z(s),z(l),z(e.info.numberOfChannels*s/8),z(1)]:[z(0),z(0),z(0),z(0)]]}else xe(t),w(!1);return ee(i,r,[(i==="ipcm"||i==="fpcm")&&e.info.sampleRate>=2**16?Ug(e):null,a,Zo(e)])},Ug=i=>fe("srat",0,0,[z(i.info.sampleRate)]),ba=i=>{let e;switch(i.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${i.track.source._codec}`)}let t=[...Re(e),...Re(21),...jd(0),...z(i.maxBitrate),...z(i.avgBitrate)];if(i.info.decoderConfig.description){const r=me(i.info.decoderConfig.description);t=[...t,...Re(5),...ya(r.byteLength),...r]}return t=[...J(1),...Re(0),...Re(4),...ya(t.length),...t,...Re(6),...Re(1),...Re(2)],t=[...Re(3),...ya(t.length),...t],fe("esds",0,0,t)},Lt=i=>ee("wave",void 0,[Ng(i),i.track.source._codec==="ac3"?Qd(i):i.track.source._codec==="eac3"?Gd(i):Vg(i),ee("\0\0\0\0")]),Ng=i=>ee("frma",[be(Jd(i.track.source._codec,i.info.decoderConfig.codec,i.muxer.isQuickTime))]),Vg=i=>{const{littleEndian:e}=Bt(i.track.source._codec);return ee("enda",[J(+e)])},Wg=i=>{var c;let e=i.info.numberOfChannels,t=312,r=i.info.sampleRate,s=0,n=0,a=new Uint8Array(0);const o=(c=i.info.decoderConfig)==null?void 0:c.description;if(o){w(o.byteLength>=18);const u=me(o),l=vs(u);e=l.outputChannelCount,t=l.preSkip,r=l.inputSampleRate,s=l.outputGain,n=l.channelMappingFamily,l.channelMappingTable&&(a=l.channelMappingTable)}return ee("dOps",[Re(0),Re(e),J(t),z(r),Ts(s),Re(n),...a])},Lg=i=>{var r;const e=(r=i.info.decoderConfig)==null?void 0:r.description;w(e);const t=me(e);return fe("dfLa",0,0,[...t.subarray(4)])},Ht=i=>{const{littleEndian:e,sampleSize:t}=Bt(i.track.source._codec),r=+e;return fe("pcmC",0,0,[Re(r),Re(8*t)])},Qd=i=>{w(i.info.primingPacket);const e=cu(i.info.primingPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");const t=new Uint8Array(3),r=new oe(t);return r.writeBits(2,e.fscod),r.writeBits(5,e.bsid),r.writeBits(3,e.bsmod),r.writeBits(3,e.acmod),r.writeBits(1,e.lfeon),r.writeBits(5,e.bitRateCode),r.writeBits(5,0),ee("dac3",[...t])},Gd=i=>{w(i.info.primingPacket);const e=lu(i.info.primingPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let t=16;for(const a of e.substreams)t+=23,a.numDepSub>0?t+=9:t+=1;const r=Math.ceil(t/8),s=new Uint8Array(r),n=new oe(s);n.writeBits(13,e.dataRate),n.writeBits(3,e.substreams.length-1);for(const a of e.substreams)n.writeBits(2,a.fscod),n.writeBits(5,a.bsid),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(3,a.bsmod),n.writeBits(3,a.acmod),n.writeBits(1,a.lfeon),n.writeBits(3,0),n.writeBits(4,a.numDepSub),a.numDepSub>0?n.writeBits(9,a.chanLoc):n.writeBits(1,0);return ee("dec3",[...s])},Hg=i=>{w(i.info.primingPacket);const e=vo(i.info.primingPacket.data);if(!e)throw new Error("Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.");return ee("ddts",[...Sh(e)])},qg=i=>{w(i.info.primingPacket);const e=i.info.primingPacket.data;if(Co("truehd",e)!=="key")throw new Error("Couldn't extract TrueHD stream info from the audio packet. Ensure the first packet is an access unit carrying a major sync.");const t=ie(e),r=t.getUint32(8),s=t.getUint16(18)&32767;return ee("dmlp",[z(r),J(s<<1),z(0)])},jg=(i,e)=>ee(i,[Array(6).fill(0),J(1)],[Tw[e.track.source._codec](e),Zo(e)]),Kg=i=>ee("vttC",[...ge.encode(i.info.config.description)]),$g=i=>fe("stts",0,0,[z(i.timeToSampleTable.length),i.timeToSampleTable.map(e=>[z(e.sampleCount),z(e.sampleDelta)])]),Qg=i=>{if(i.samples.every(t=>t.type==="key"))return null;const e=[...i.samples.entries()].filter(([,t])=>t.type==="key");return fe("stss",0,0,[z(e.length),e.map(([t])=>z(t+1))])},Gg=i=>fe("stsc",0,0,[z(i.compactlyCodedChunkTable.length),i.compactlyCodedChunkTable.map(e=>[z(e.firstChunk),z(e.samplesPerChunk),z(1)])]),Xg=i=>{if(i.type==="audio"&&i.info.requiresPcmTransformation){const{sampleSize:e}=Bt(i.track.source._codec);return fe("stsz",0,0,[z(e*i.info.numberOfChannels),z(i.samples.reduce((t,r)=>t+Se(r.duration,i.timescale),0))])}return fe("stsz",0,0,[z(0),z(i.samples.length),i.samples.map(e=>z(e.size))])},Yg=i=>i.finalizedChunks.length>0&&Te(i.finalizedChunks).offset>=2**32?fe("co64",0,0,[z(i.finalizedChunks.length),i.finalizedChunks.map(e=>Vt(e.offset))]):fe("stco",0,0,[z(i.finalizedChunks.length),i.finalizedChunks.map(e=>z(e.offset))]),Zg=i=>fe("ctts",1,0,[z(i.compositionTimeOffsetTable.length),i.compositionTimeOffsetTable.map(e=>[z(e.sampleCount),zt(e.sampleCompositionTimeOffset)])]),Jg=i=>{if(w(i.compositionTimeOffsetTable.length>0),i.samples.length===0)return null;let e=1/0,t=-1/0,r=1/0,s=-1/0;for(let a=0;a<i.compositionTimeOffsetTable.length;a++){const o=i.compositionTimeOffsetTable[a];e=Math.min(e,o.sampleCompositionTimeOffset),t=Math.max(t,o.sampleCompositionTimeOffset)}for(let a=0;a<i.samples.length;a++){const o=i.samples[a];r=Math.min(r,Se(o.timestamp,i.timescale)),s=Math.max(s,Se(o.timestamp+o.duration,i.timescale))}const n=Math.max(-e,0);return s>=2**31?null:fe("cslg",0,0,[zt(n),zt(e),zt(t),zt(r),zt(s)])},Xd=(i,e)=>{const t=[];for(const n of i)if(t.length===0)t.push({sampleCount:1,prerollSamples:n.prerollSamples});else{const a=t[t.length-1];a.prerollSamples===n.prerollSamples?a.sampleCount++:t.push({sampleCount:1,prerollSamples:n.prerollSamples})}const r=t.filter(n=>n.prerollSamples!==0);if(r.length===0)return[];let s=e?65537:1;return[fe("sgpd",1,0,[be("roll"),z(2),z(r.length),...r.map(n=>Ts(n.prerollSamples))]),fe("sbgp",0,0,[be("roll"),z(t.length),...t.map(n=>[z(n.sampleCount),z(n.prerollSamples!==0?s++:0)])])]},ew=i=>ee("mvex",void 0,i.map(tw)),tw=i=>fe("trex",0,0,[z(i.track.id),z(1),z(0),z(0),z(0)]),Tl=(i,e)=>ee("moof",void 0,[iw(i),...e.map(rw)]),iw=i=>fe("mfhd",0,0,[z(i)]),Yd=i=>{let e=0,t=0;const r=0,s=0,n=i.type==="delta";return t|=+n,n?e|=1:e|=2,e<<24|t<<16|r<<8|s},rw=i=>ee("traf",void 0,[sw(i),nw(i),aw(i),...Xd(i.currentChunk.samples,!0)]),sw=i=>{w(i.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const t=i.currentChunk.samples[1]??i.currentChunk.samples[0],r={duration:t.timescaleUnitsToNextSample,size:t.size,flags:Yd(t)};return fe("tfhd",0,e,[z(i.track.id),z(r.duration),z(r.size),z(r.flags)])},nw=i=>(w(i.currentChunk),fe("tfdt",1,0,[Vt(Se(i.currentChunk.startTimestamp,i.timescale))])),aw=i=>{w(i.currentChunk);const e=i.currentChunk.offset-i.currentChunk.moofOffset||0;w(Nl(e));const t=i.currentChunk.samples.map(g=>g.timescaleUnitsToNextSample),r=i.currentChunk.samples.map(g=>g.size),s=i.currentChunk.samples.map(Yd),n=i.currentChunk.samples.map(g=>Se(g.timestamp-g.decodeTimestamp,i.timescale)),a=new Set(t),o=new Set(r),c=new Set(s),u=new Set(n),l=c.size===2&&s.lastIndexOf(s[0])===0,d=a.size>1,f=o.size>1,h=!l&&c.size>1,p=u.size>1||[...u].some(g=>g!==0);let m=0;return m|=1,m|=4*+l,m|=256*+d,m|=512*+f,m|=1024*+h,m|=2048*+p,fe("trun",1,m,[z(i.currentChunk.samples.length),zt(e),l?z(s[0]):[],i.currentChunk.samples.map((g,y)=>[d?z(t[y]):[],f?z(r[y]):[],h?z(s[y]):[],p?zt(n[y]):[]])])},ow=i=>ee("mfra",void 0,[...i.map(cw),lw()]),cw=i=>{const t=[];for(const r of i.finalizedChunks){const s=r.samples.findIndex(a=>a.type==="key");if(s===-1)continue;const n=r.samples[s];t.push([Vt(Se(n.timestamp,i.timescale)),Vt(r.moofOffset),z(r.trafIndex+1),z(1),z(s+1)])}return fe("tfra",1,0,[z(i.track.id),z(63),z(t.length),t])},lw=()=>fe("mfro",0,0,[z(0)]),uw=()=>ee("vtte"),dw=(i,e,t,r,s)=>ee("vttc",void 0,[s!==null?ee("vsid",[zt(s)]):null,t!==null?ee("iden",[...ge.encode(t)]):null,e!==null?ee("ctim",[...ge.encode(gu(e))]):null,r!==null?ee("sttg",[...ge.encode(r)]):null,ee("payl",[...ge.encode(i)])]),fw=i=>ee("vtta",[...ge.encode(i)]),hw=i=>{const e=[],t=i.format._options.metadataFormat??"auto",r=i.output._metadataTags;if(t==="mdir"||t==="auto"&&!i.isQuickTime){const s=gw(r);s&&e.push(s)}else if(t==="mdta"){const s=ww(r);s&&e.push(s)}else(t==="udta"||t==="auto"&&i.isQuickTime)&&mw(e,i.output._metadataTags);return e.length===0?null:ee("udta",void 0,e)},mw=(i,e)=>{for(const{key:t,value:r}of Nr(e))switch(t){case"title":i.push(qt("©nam",r));break;case"description":i.push(qt("©des",r));break;case"artist":i.push(qt("©ART",r));break;case"album":i.push(qt("©alb",r));break;case"albumArtist":i.push(qt("albr",r));break;case"genre":i.push(qt("©gen",r));break;case"date":i.push(qt("©day",r.toISOString().slice(0,10)));break;case"comment":i.push(qt("©cmt",r));break;case"lyrics":i.push(qt("©lyr",r));break;case"raw":break;case"creationTime":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"beatsPerMinute":case"images":break;default:xe(t)}if(e.raw)for(const t in e.raw){const r=e.raw[t];r==null||t.length!==4||i.some(s=>s.type===t)||(typeof r=="string"?i.push(qt(t,r)):r instanceof Uint8Array&&i.push(ee(t,Array.from(r))))}},qt=(i,e)=>{const t=ge.encode(e);return ee(i,[J(t.length),J(ef("und")),Array.from(t)])},Sl={"image/jpeg":13,"image/png":14,"image/bmp":27},pw=new Set(["HMMT","loci","chpl"]),Zd=(i,e)=>{const t=[];for(const{key:r,value:s}of Nr(i))switch(r){case"title":t.push({key:e?"title":"©nam",value:Rt(s)});break;case"description":t.push({key:e?"description":"©des",value:Rt(s)});break;case"artist":t.push({key:e?"artist":"©ART",value:Rt(s)});break;case"album":t.push({key:e?"album":"©alb",value:Rt(s)});break;case"albumArtist":t.push({key:e?"album_artist":"aART",value:Rt(s)});break;case"comment":t.push({key:e?"comment":"©cmt",value:Rt(s)});break;case"genre":t.push({key:e?"genre":"©gen",value:Rt(s)});break;case"beatsPerMinute":e||t.push({key:"tmpo",value:ee("data",[z(21),z(0),J(s)])});break;case"lyrics":t.push({key:e?"lyrics":"©lyr",value:Rt(s)});break;case"date":t.push({key:e?"date":"©day",value:Rt(s.toISOString().slice(0,10))});break;case"images":for(const n of s)n.kind==="coverFront"&&t.push({key:"covr",value:ee("data",[z(Sl[n.mimeType]??0),z(0),Array.from(n.data)])});break;case"trackNumber":if(e){const n=i.tracksTotal!==void 0?`${s}/${i.tracksTotal}`:s.toString();t.push({key:"track",value:Rt(n)})}else t.push({key:"trkn",value:ee("data",[z(0),z(0),J(0),J(s),J(i.tracksTotal??0),J(0)])});break;case"discNumber":e||t.push({key:"disk",value:ee("data",[z(0),z(0),J(0),J(s),J(i.discsTotal??0),J(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;case"creationTime":break;default:xe(r)}if(i.raw)for(const r in i.raw){const s=i.raw[r];s==null||!e&&(r.length!==4||pw.has(r))||t.some(n=>n.key===r)||(typeof s=="string"?t.push({key:r,value:Rt(s)}):s instanceof Uint8Array?t.push({key:r,value:ee("data",[z(0),z(0),Array.from(s)])}):s instanceof xr&&t.push({key:r,value:ee("data",[z(Sl[s.mimeType]??0),z(0),Array.from(s.data)])}))}return t},gw=i=>{const e=Zd(i,!1);return e.length===0?null:fe("meta",0,0,void 0,[Yo(!1,"mdir","","appl"),ee("ilst",void 0,e.map(t=>ee(t.key,void 0,[t.value])))])},ww=i=>{const e=Zd(i,!0);return e.length===0?null:ee("meta",void 0,[Yo(!1,"mdta",""),fe("keys",0,0,[z(e.length)],e.map(t=>ee("mdta",[...ge.encode(t.key)]))),ee("ilst",void 0,e.map((t,r)=>{const s=String.fromCharCode(...z(r+1));return ee(s,void 0,[t.value])}))])},Rt=i=>ee("data",[z(1),z(0),...ge.encode(i)]),yw=(i,e)=>{switch(i){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";case"prores":return e}},ka={avc:Mg,hevc:Dg,vp8:kl,vp9:kl,av1:zg,prores:null},Jd=(i,e,t)=>{switch(i){case"aac":return"mp4a";case"mp3":return t?".mp3":"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3";case"dts":return e;case"truehd":return"mlpa"}if(t)switch(i){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(i){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},bw=(i,e)=>{switch(i){case"aac":return ba;case"mp3":return e?null:ba;case"opus":return Wg;case"vorbis":return ba;case"flac":return Lg;case"ac3":return e?Lt:Qd;case"eac3":return e?Lt:Gd;case"dts":return Hg;case"truehd":return qg}if(e)switch(i){case"pcm-s24":return Lt;case"pcm-s24be":return Lt;case"pcm-s32":return Lt;case"pcm-s32be":return Lt;case"pcm-f32":return Lt;case"pcm-f32be":return Lt;case"pcm-f64":return Lt;case"pcm-f64be":return Lt}else switch(i){case"pcm-s16":return Ht;case"pcm-s16be":return Ht;case"pcm-s24":return Ht;case"pcm-s24be":return Ht;case"pcm-s32":return Ht;case"pcm-s32be":return Ht;case"pcm-f32":return Ht;case"pcm-f32be":return Ht;case"pcm-f64":return Ht;case"pcm-f64be":return Ht}return null},kw={webvtt:"wvtt"},Tw={webvtt:Kg},ef=i=>{w(i.length===3);let e=0;for(let t=0;t<3;t++)e<<=5,e+=i.charCodeAt(t)-96;return e};/*!
|
|
339
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
340
|
+
*
|
|
341
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
342
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
343
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
344
|
+
*/class Ss{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");if(e._closed)throw new Error("Can't create a Writer for a Target that has already been closed.");this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){w(!this.started),this.target._start(),this.started=!0}write(e){w(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return w(this.started&&!this.finalized),this.target._flush()}async finalize(){w(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=this.trackedStart}const r=t+e.byteLength-this.trackedStart;let s=this.trackedWrites.byteLength;for(;s<r;)s*=2;if(s!==this.trackedWrites.byteLength){const n=new Uint8Array(s);n.set(this.trackedWrites,0),this.trackedWrites=n}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}}/*!
|
|
345
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
346
|
+
*
|
|
347
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
348
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
349
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
350
|
+
*/const Al=typeof an<"u"?an:void 0;class ht extends Ps{constructor(){super(...arguments),this._writerAcquired=!1,this._closed=!1,this._monotonicity=null,this.onwrite=null}_close(){return this._closed=!0,this._release()}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){var r;(r=this.onwrite)==null||r.call(this,e,t),this._emit("write",{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");return new xw(this,e)}}const Ta=2**16,Sa=2**32;class Aa extends ht{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!="object")throw new TypeError("BufferTarget options, when provided, must be an object.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");if(this._options=e,this._supportsResize="resize"in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(Ta,{maxByteLength:Sa})}catch{this._buffer=new ArrayBuffer(Ta),this._supportsResize=!1}else this._buffer=new ArrayBuffer(Ta);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){w(this._buffer),w(this._bytes);let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>Sa)throw new Error(`ArrayBuffer exceeded maximum size of ${Sa} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{const r=new ArrayBuffer(t),s=new Uint8Array(r);s.set(this._bytes,0),this._buffer=r,this._bytes=s}}}_start(){}_write(e,t){w(this._bytes),this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){w(this._buffer),"transferToFixedLength"in this._buffer?this.buffer=this._buffer.transferToFixedLength(this._maxPos):this.buffer=this._buffer.slice(0,this._maxPos),this._buffer=null,this._bytes=null,this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _release(){}_getSlice(e,t){return w(this._bytes),this._bytes.slice(e,t)}}const Sw=2**24,Aw=2;class tf extends ht{constructor(e,t={}){if(super(),this._sections=[],this._lastWriteEnd=0,this._lastFlushEnd=0,this._streamWriter=null,this._writeError=null,this._chunks=[],!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(t!=null&&typeof t!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(t.chunked!==void 0&&typeof t.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=t,this._chunked=t.chunked??!1,this._chunkSize=t.chunkSize??Sw}_start(){this._streamWriter=this._writable.getWriter()}_write(e,t){if(t>this._lastWriteEnd){const r=t-this._lastWriteEnd;this._write(new Uint8Array(r),this._lastWriteEnd)}this._sections.push({data:e.slice(),start:t}),this._lastWriteEnd=Math.max(this._lastWriteEnd,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){if(this._writeError!==null)throw this._writeError;if(w(this._streamWriter),this._sections.length===0)return;const e=[],t=[...this._sections].sort((r,s)=>r.start-s.start);e.push({start:t[0].start,size:t[0].data.byteLength});for(let r=1;r<t.length;r++){const s=e[e.length-1],n=t[r];n.start<=s.start+s.size?s.size=Math.max(s.size,n.start+n.data.byteLength-s.start):e.push({start:n.start,size:n.data.byteLength})}for(const r of e){r.data=new Uint8Array(r.size);for(const s of this._sections)r.start<=s.start&&s.start<r.start+r.size&&r.data.set(s.data,s.start-r.start);if(this._streamWriter.desiredSize!==null&&this._streamWriter.desiredSize<=0&&await this._streamWriter.ready,this._chunked)this._writeDataIntoChunks(r.data,r.start),this._tryToFlushChunks();else{if(this._monotonicity===!0&&r.start!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:r.data,position:r.start}).catch(s=>{this._writeError??(this._writeError=s)}),this._lastFlushEnd=r.start+r.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,t){for(;;){let r=this._chunks.findIndex(c=>c.start<=t&&t<c.start+this._chunkSize);r===-1&&(r=this._createChunk(t));const s=this._chunks[r],n=t-s.start,a=e.subarray(0,Math.min(this._chunkSize-n,e.byteLength));s.data.set(a,n);const o={start:n,end:n+a.byteLength};if(this._insertSectionIntoChunk(s,o),s.written[0].start===0&&s.written[0].end===this._chunkSize&&(s.shouldFlush=!0),this._chunks.length>Aw){for(let c=0;c<this._chunks.length-1;c++)this._chunks[c].shouldFlush=!0;this._tryToFlushChunks()}if(a.byteLength===e.byteLength)break;e=e.subarray(a.byteLength),t+=a.byteLength}}_insertSectionIntoChunk(e,t){let r=0,s=e.written.length-1,n=-1;for(;r<=s;){const a=Math.floor(r+(s-r+1)/2);e.written[a].start<=t.start?(r=a+1,n=a):s=a-1}for(e.written.splice(n+1,0,t),(n===-1||e.written[n].end<t.start)&&n++;n<e.written.length-1&&e.written[n].end>=e.written[n+1].start;)e.written[n].end=Math.max(e.written[n].end,e.written[n+1].end),e.written.splice(n+1,1)}_createChunk(e){const r={start:Math.floor(e/this._chunkSize)*this._chunkSize,data:new Uint8Array(this._chunkSize),written:[],shouldFlush:!1};return this._chunks.push(r),this._chunks.sort((s,n)=>s.start-n.start),this._chunks.indexOf(r)}_tryToFlushChunks(e=!1){w(this._streamWriter);for(let t=0;t<this._chunks.length;t++){const r=this._chunks[t];if(!(!r.shouldFlush&&!e)){for(const s of r.written){const n=r.start+s.start;if(this._monotonicity===!0&&n!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");const a=s.start!==0||s.end!==r.data.byteLength;let o;a&&wi()?o=r.data.slice(s.start,s.end):o=r.data.subarray(s.start,s.end),this._streamWriter.write({type:"write",data:o,position:n}).catch(c=>{this._writeError??(this._writeError=c)}),this._lastFlushEnd=r.start+s.end}this._chunks.splice(t--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;w(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit("finalized")}async _release(){const e=this._streamWriter??this._writable.getWriter();e.desiredSize!==null&&await e.close()}}class v0 extends ht{constructor(e){super(),this._writer=null,this._nextWritePos=0,this._writable=e,this._streamTarget=new tf(new WritableStream({start:()=>{this._writer=this._writable.getWriter()},write:t=>{if(this._monotonicity!==!0)throw new Error("AppendOnlyStreamTarget requires that data be written monotonically (always appended to the end). You must use a format that guarantees this behavior.");return w(t.position===this._nextWritePos),this._nextWritePos+=t.data.byteLength,w(this._writer),this._writer.write(t.data)},close:()=>{var t;return(t=this._writer)==null?void 0:t.close()}}))}_start(){this._streamTarget._start()}_write(e,t){this._streamTarget._write(e,t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._streamTarget._flush()}async _finalize(){await this._streamTarget._finalize(),this._emit("finalized")}_release(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}}class B0 extends ht{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(!Al.fs)throw new Error("FilePathTarget is only available in server-side environments (Node.js, Bun, Deno).");super(),this._fileHandle=null;const r=new WritableStream({start:async()=>{this._fileHandle=await Al.fs.open(e,"w")},write:async s=>{w(this._fileHandle),await this._fileHandle.write(s.data,0,s.data.byteLength,s.position)},close:async()=>{this._fileHandle&&(await this._fileHandle.close(),this._fileHandle=null)}});this._streamTarget=new tf(r,{chunked:!0,...t})}_start(){this._streamTarget._start()}_write(e,t){this._streamTarget._write(e,t),this._dispatchWrite(t,t+e.byteLength)}async _flush(){return this._streamTarget._flush()}async _finalize(){await this._streamTarget._finalize(),this._emit("finalized")}async _release(){var e;try{await this._streamTarget._close()}finally{await((e=this._fileHandle)==null?void 0:e.close()),this._fileHandle=null}}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}}class rf extends ht{_start(){}_write(e,t){this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this._emit("finalized")}async _release(){}}class xw extends ht{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _release(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}}class vi{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("getTarget must be a function.")}}/*!
|
|
351
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
352
|
+
*
|
|
353
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
354
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
355
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
356
|
+
*/const bt=57600,xl=.5,Pw=i=>{const e={},t=i.track;return t.metadata.name!==void 0&&(e.name=t.metadata.name),e},Se=(i,e,t=!0)=>{const r=i*e;return t?Math.round(r):r},Or=i=>{if(i.samples.length===0)return 0;let e=1/0,t=-1/0;for(let r=0;r<i.samples.length;r++){const s=i.samples[r];s.timestamp<e&&(e=s.timestamp),s.timestamp+s.duration>t&&(t=s.timestamp+s.duration)}return e===1/0?0:t-e};class Cw extends ti{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Aa,this.auxWriter=new Ss(this.auxTarget,!1),this.auxBoxWriter=new $s(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.closedTracks=new Set,this.allTracksKnown=Ae(),this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.formatOptions={...t._options},this.isQuickTime=t instanceof of,this.isCmaf=t instanceof vl,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof vl?1/0:1),this.auxWriter.start()}async start(){var t;const e=await this.mutex.acquire();try{const r=this.output._metadataTags.creationTime===void 0?new Date:this.output._metadataTags.creationTime;if(this.creationTime=r?Math.floor(r.getTime()/1e3)+_u:0,r&&this.creationTime<=0)throw new Error("creationTime must be after 1904-01-01T00:00:00Z for MP4/QuickTime files.");if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(n=>this.formatOptions.fastStart!==void 0?this.formatOptions.fastStart==="in-memory"||this.formatOptions.fastStart==="fragmented":n instanceof Aa),this.boxWriter=new $s(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof Aa?"in-memory":!1),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");const n=await this.output._getInitTarget(),a=new Ss(n,!0);a.start(),this.initWriter=a,this.initBoxWriter=new $s(a)}const s=this.output.tracks.some(n=>n.isVideoTrack()&&n.source._codec==="avc");{const n=this.initBoxWriter??this.boxWriter;if(w(n),this.formatOptions.onFtyp&&n.writer.startTrackingWrites(),n.writeBox(dg({isQuickTime:this.isQuickTime,holdsAvc:s,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){const{data:a,start:o}=n.writer.stopTrackingWrites();this.formatOptions.onFtyp(a,o)}this.ftypSize=n.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve")for(const n of this.output.tracks){if(n.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.");if(n.metadata.maximumPacketCount>2**32-1)throw new Error(`Track #${n.id} has a maximumPacketCount of ${n.metadata.maximumPacketCount}, which exceeds the maximum of ${2**32-1} packets per track that a non-fragmented file can hold.`)}else this.isFragmented||(w(this.writer),w(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Qs(!0),this.boxWriter.writeBox(this.mdat));await((t=this.writer)==null?void 0:t.flush());for(const n of this.output.tracks)n.isVideoTrack()&&n.metadata.decoderConfig?this.getVideoTrackData(n,n.metadata.primingPacket??null,{decoderConfig:n.metadata.decoderConfig}):n.isAudioTrack()&&n.metadata.decoderConfig&&this.getAudioTrackData(n,n.metadata.primingPacket??null,{decoderConfig:n.metadata.decoderConfig})}finally{e()}}allTracksAreKnown(){for(const e of this.output.tracks)if(!this.closedTracks.has(e)&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return Eu({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,r){const s=this.trackDatas.find(h=>h.track===e);if(s)return s;Ds(r,e.source._codec),w(r),w(r.decoderConfig);const n={...r.decoderConfig};w(n.codedWidth!==void 0),w(n.codedHeight!==void 0);let a=!1;if(e.source._codec==="avc"&&!n.description){if(!t)throw new Error("No AVC description provided; you must therefore provide a priming packet.");const h=_s(t.data);if(!h)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");n.description=So(h),a=!0}else if(e.source._codec==="hevc"&&!n.description){if(!t)throw new Error("No HEVC description provided; you must therefore provide a priming packet.");const h=Is(t.data);if(!h)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");n.description=eh(h),a=!0}const o=Af(1/(e.metadata.frameRate??bt),1e6).den,c=n.displayAspectWidth,u=n.displayAspectHeight,l=c===void 0||u===void 0?{num:1,den:1}:xs({num:c*n.codedHeight,den:u*n.codedWidth}),d=n.codec==="ap4h"||n.codec==="ap4x",f={muxer:this,track:e,type:"video",info:{width:n.codedWidth,height:n.codedHeight,pixelAspectRatio:l,decoderConfig:n,requiresAnnexBTransformation:a,hasAlphaChannel:d},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(f),this.trackDatas.sort((h,p)=>h.track.id-p.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),f}getAudioTrackData(e,t,r){const s=this.trackDatas.find(c=>c.track===e);if(s)return s;Nt(r,e.source._codec),w(r),w(r.decoderConfig);const n={...r.decoderConfig};let a=!1;if(e.source._codec==="aac"&&!n.description){if(!t)throw new Error("No AAC description provided; you must therefore provide a priming packet.");const c=Ti(at.tempFromBytes(t.data));if(!c)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let u,l=null;if(c.channelConfiguration===0){const d=c.crcCheck===null?Ut:Et,f=Rr(t.data.subarray(d));if(!f)throw new Error("ADTS frames with channel configuration 0 must begin with a program config element.");l=f.programConfigElement,u=Cs(l)}else u=Vr[c.channelConfiguration];n.description=Rn({objectType:c.objectType,outputSampleRate:Ot[c.samplingFrequencyIndex],outputNumberOfChannels:u,programConfigElement:l}),a=!0}if(!t){if(e.source._codec==="ac3"||e.source._codec==="eac3")throw new Error("AC-3/E-AC-3 require a priming packet.");if(e.source._codec==="dts")throw new Error("DTS requires a priming packet.");if(e.source._codec==="truehd")throw new Error("TrueHD requires a priming packet.")}const o={muxer:this,track:e,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:n,requiresPcmTransformation:!this.isFragmented&&je.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,primingPacket:t,pendingEac3Packets:[],preroll:{packetCount:0,accumulatedAudioSamples:0,audioSampleDurationHistory:[]}},timescale:n.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(o),this.trackDatas.sort((c,u)=>c.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){const r=this.trackDatas.find(n=>n.track===e);if(r)return r;qd(t),w(t),w(t.config);const s={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(s),this.trackDatas.sort((n,a)=>n.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}async addEncodedVideoPacket(e,t,r){const s=await this.mutex.acquire();try{const n=this.getVideoTrackData(e,t,r);let a=t.data;if(n.info.requiresAnnexBTransformation){const c=[...Wr(a)].map(u=>a.subarray(u.offset,u.offset+u.length));if(c.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");a=To(c,4)}this.validateTimestamp(n.track,t.timestamp,t.type==="key");const o=this.createSampleForTrack(n,a,t.timestamp,t.duration,t.type,0);await this.registerSample(n,o)}finally{s()}}async addEncodedAudioPacket(e,t,r){const s=await this.mutex.acquire();try{const n=this.getAudioTrackData(e,t,r);let a=t.data;if(n.info.requiresAdtsStripping){const f=Ti(at.tempFromBytes(a));if(!f)throw new Error("Expected ADTS frame, didn't get one.");const h=f.crcCheck===null?Ut:Et;if(a=a.subarray(h),f.channelConfiguration===0){const p=Rr(a);p&&(a=a.subarray(p.size))}}if(this.validateTimestamp(n.track,t.timestamp,t.type==="key"),e.source._codec==="eac3"){const f=uu(a),h=f?f.reduce((g,y)=>g+y.blockCount,0):6,p=n.info.pendingEac3Packets,m=p.reduce((g,y)=>g+y.blockCount,0)+h;if(m>6)throw new Error("E-AC-3 frames must add up to exactly six blocks to be muxed into MP4 samples.");p.push({packet:t,blockCount:h}),m===6&&await this.writePendingEac3Packets(n);return}let o=t.timestamp,c=t.duration;if(n.info.requiresPcmTransformation){const h=Bt(n.info.decoderConfig.codec).sampleSize*n.info.numberOfChannels;if(c=a.byteLength/h/n.info.sampleRate,n.info.expectedNextPcmPacketTimestamp!==null){const p=o-n.info.expectedNextPcmPacketTimestamp;if(p<.01)o=n.info.expectedNextPcmPacketTimestamp;else{const m=await this.padWithSilence(n,n.info.expectedNextPcmPacketTimestamp,p);o=n.info.expectedNextPcmPacketTimestamp+m}}n.info.expectedNextPcmPacketTimestamp=o+c}const{preroll:u}=n.info;let l=0;if(e.source._codec==="aac"||e.source._codec==="vorbis")l=-Math.min(1,u.packetCount);else if(e.source._codec==="mp3")l=-Math.min(2,u.packetCount);else if(e.source._codec==="opus"){const f=Math.round(Wd*Wi);l=-u.audioSampleDurationHistory.length;const h=au(a);for(u.accumulatedAudioSamples+=h.durationInSamples,u.audioSampleDurationHistory.push(h.durationInSamples);u.accumulatedAudioSamples-u.audioSampleDurationHistory[0]>=f;)u.accumulatedAudioSamples-=u.audioSampleDurationHistory.shift(),w(u.audioSampleDurationHistory.length>0)}u.packetCount++;const d=this.createSampleForTrack(n,a,o,c,t.type,l);await this.registerSample(n,d)}finally{s()}}async padWithSilence(e,t,r){const s=Se(r,e.timescale),{sampleSize:n,silentValue:a}=Bt(e.info.decoderConfig.codec),o=n*e.info.numberOfChannels,c=new Uint8Array(o*Math.min(s,e.timescale)).fill(a);for(let u=0;u<s;u+=e.timescale){const l=Math.min(s-u,e.timescale),d=this.createSampleForTrack(e,c.subarray(0,o*l),t+u/e.timescale,l/e.timescale,"key",0);await this.registerSample(e,d)}return s/e.timescale}async addSubtitleCue(e,t,r){const s=await this.mutex.acquire();try{const n=this.getSubtitleTrackData(e,r);if(this.validateTimestamp(n.track,t.timestamp,!0),e.source._codec==="webvtt"){const a=Se(t.timestamp,n.timescale)/n.timescale,o=Se(t.timestamp+t.duration,n.timescale)/n.timescale;o>a&&n.cueQueue.push({cue:t,start:a,end:o}),await this.processWebVTTCues(n,a)}}finally{s()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??(e.lastCueEndTimestamp=Math.min(0,e.cueQueue[0].start));const r=new Set([]);for(const{start:u,end:l}of e.cueQueue)w(u<=t),w(e.lastCueEndTimestamp<=l),r.add(Math.max(u,e.lastCueEndTimestamp)),r.add(l);const s=[...r].sort((u,l)=>u-l),n=s[0],a=s[1]??n;if(t<a)break;if(e.lastCueEndTimestamp<n){this.auxWriter.seek(0);const u=uw();this.auxBoxWriter.writeBox(u);const l=this.auxTarget._getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,l,e.lastCueEndTimestamp,n-e.lastCueEndTimestamp,"key",0);await this.registerSample(e,d),e.lastCueEndTimestamp=n}this.auxWriter.seek(0);for(let u=0;u<e.cueQueue.length;u++){const{cue:l,start:d,end:f}=e.cueQueue[u];if(d>=a)break;gn.lastIndex=0;const h=gn.test(l.text);let p=e.cueToSourceId.get(l);if(p===void 0&&a<f&&(p=e.nextSourceId++,e.cueToSourceId.set(l,p)),l.notes){const g=fw(l.notes);this.auxBoxWriter.writeBox(g)}const m=dw(l.text,h?n:null,l.identifier??null,l.settings??null,p??null);this.auxBoxWriter.writeBox(m),f===a&&e.cueQueue.splice(u--,1)}const o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,o,n,a-n,"key",0);await this.registerSample(e,c),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,r,s,n,a){return{timestamp:r,decodeTimestamp:r,duration:s,data:t,size:t.byteLength,type:n,timescaleUnitsToNextSample:Se(s,e.timescale),prerollSamples:a}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){w(!this.isFragmented),e.startTimestampOffset??(e.startTimestampOffset=e.timestampProcessingQueue[0].timestamp);let s=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){const a=e.timestampProcessingQueue[n],o=Se(a.duration,e.timescale);s+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:s,sampleDelta:1});else{const n=Te(e.timeToSampleTable);n.sampleCount+=s}e.timestampProcessingQueue.length=0;return}const r=e.timestampProcessingQueue.map(s=>s.timestamp).sort((s,n)=>s-n);this.isFragmented?e.startTimestampOffset??(e.startTimestampOffset=Math.min(r[0],0)):e.startTimestampOffset??(e.startTimestampOffset=r[0]);for(let s=0;s<e.timestampProcessingQueue.length;s++){const n=e.timestampProcessingQueue[s];n.decodeTimestamp=r[s];const a=Se(n.timestamp-n.decodeTimestamp,e.timescale),o=Se(n.duration,e.timescale);if(e.lastTimescaleUnits!==null){w(e.lastSample);const c=Se(n.decodeTimestamp,e.timescale,!1),u=Math.round(c-e.lastTimescaleUnits);if(w(u>=0),e.lastTimescaleUnits+=u,e.lastSample.timescaleUnitsToNextSample=u,!this.isFragmented){let l=Te(e.timeToSampleTable);if(w(l),l.sampleCount===1){l.sampleDelta=u;const f=e.timeToSampleTable[e.timeToSampleTable.length-2];f&&f.sampleDelta===u&&(f.sampleCount++,e.timeToSampleTable.pop(),l=f)}else l.sampleDelta!==u&&(l.sampleCount--,e.timeToSampleTable.push(l={sampleCount:1,sampleDelta:u}));l.sampleDelta===o?l.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const d=Te(e.compositionTimeOffsetTable);w(d),d.sampleCompositionTimeOffset===a?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=Se(n.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=n}if(e.timestampProcessingQueue.length=0,w(e.lastSample),w(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){w(t.type==="key");const s=Se(t.timestamp,e.timescale,!1),n=Math.round(s-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=n}}async registerSample(e,t){t.type==="key"&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),e.sampleQueue.push(t),await this.interleaveSamples()}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart==="reserve")){const s=e.track.metadata.maximumPacketCount;if(w(s!==void 0),e.samples.length>s)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${s}). Either add fewer packets or increase the maximum packet count.`)}let r=!1;if(!e.currentChunk)r=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);const s=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const n=this.trackDatas.every(o=>{if(e===o)return t.type==="key";const c=o.sampleQueue[0];return c?c.type==="key":this.closedTracks.has(o.track)}),a=this.wroteFragmentedHeader||this.trackDatas.every(o=>o.startTimestampOffset!==null||this.closedTracks.has(o.track));s>=this.minimumFragmentDuration&&n&&t.timestamp>this.maxWrittenTimestamp&&a&&(r=!0,await this.finalizeFragment())}else r=s>=xl}if(r){if(!this.isFragmented){const s=this.trackDatas.filter(n=>n.currentChunk&&t.timestamp-n.currentChunk.startTimestamp>=xl).sort((n,a)=>n.currentChunk.startTimestamp-a.currentChunk.startTimestamp);for(const n of s)await this.finalizeCurrentChunk(n)}e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}}w(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){w(!this.isFragmented),w(this.writer);const t=e.currentChunk;w(t),e.currentChunk=null,e.finalizedChunks.push(t),this.finalizedChunks.push(t);let r=t.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(r=t.samples.reduce((s,n)=>s+Se(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||Te(e.compactlyCodedChunkTable).samplesPerChunk!==r)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:r}),this.fastStart==="in-memory"){t.offset=0;return}t.offset=this.writer.getPos();for(const s of t.samples)w(s.data),this.writer.write(s.data),s.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(!(!e&&!this.allTracksAreKnown())){this.fastStart==="reserve"&&!this.mdat&&await this.createFastStartReserveMdat();e:for(;;){let t=null,r=1/0;for(const n of this.trackDatas){if(!e&&n.sampleQueue.length===0&&!this.closedTracks.has(n.track))break e;n.sampleQueue.length>0&&n.sampleQueue[0].timestamp<r&&(t=n,r=n.sampleQueue[0].timestamp)}if(!t)break;const s=t.sampleQueue.shift();await this.addSampleToTrack(t,s)}}}async finalizeFragment(e=!this.isCmaf){if(w(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;const h=this.initBoxWriter??this.boxWriter;w(h),this.formatOptions.onMoov&&h.writer.startTrackingWrites(),this.ensureOneEnabledTrack();const p=Zr(this);if(h.writeBox(p),this.formatOptions.onMoov){const{data:m,start:g}=h.writer.stopTrackingWrites();this.formatOptions.onMoov(m,g)}if(this.isCmaf){w(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new $s(this.writer);const m=this.boxWriter.measureBox(yl()),g=this.boxWriter.measureBox(bl(this,0));this.segmentHeaderSize=m+g,this.writer.seek(this.segmentHeaderSize)}}w(this.writer),w(this.boxWriter);const t=this.trackDatas.filter(h=>h.currentChunk);if(t.length===0){e&&await this.writer.flush();return}const r=this.nextFragmentNumber++,s=Tl(r,t),n=this.writer.getPos(),a=n+this.boxWriter.measureBox(s);let o=a+Xt,c=1/0;for(let h=0;h<t.length;h++){const p=t[h];w(p.currentChunk),w(p.startTimestampOffset!==null),c=Math.min(c,p.currentChunk.startTimestamp),p.currentChunk.offset=o,p.currentChunk.moofOffset=n,p.currentChunk.trafIndex=h,p.currentChunk.startTimestamp-=p.startTimestampOffset;for(const m of p.currentChunk.samples)o+=m.size,m.timestamp-=p.startTimestampOffset,m.decodeTimestamp-=p.startTimestampOffset}let u=o-a;const l=u>=2**32;if(l){for(const h of t)h.currentChunk.offset+=Di-Xt;u+=Di-Xt}if(Te(t).currentChunk.offset-n>=2**31)throw new Error("The data of a fragment's track must start less than 2 GiB after its moof box; use shorter fragments.");this.formatOptions.onMoof&&this.writer.startTrackingWrites();const d=Tl(r,t);if(this.boxWriter.writeBox(d),this.formatOptions.onMoof){const{data:h,start:p}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(h,p,c)}w(this.writer.getPos()===a),this.formatOptions.onMdat&&this.writer.startTrackingWrites();const f=Qs(l);f.size=u,this.boxWriter.writeBox(f),this.writer.seek(a+(l?Di:Xt));for(const h of t)for(const p of h.currentChunk.samples)this.writer.write(p.data),p.data=null;if(this.formatOptions.onMdat){const{data:h,start:p}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(h,p)}for(const h of t)h.finalizedChunks.push(h.currentChunk),this.finalizedChunks.push(h.currentChunk),h.currentChunk=null;e&&await this.writer.flush()}async createFastStartReserveMdat(){w(this.writer),w(this.boxWriter),this.ensureOneEnabledTrack();const e=Zr(this),r=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;w(this.ftypSize!==null),this.writer.seek(this.ftypSize+r),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Qs(!0),this.boxWriter.writeBox(this.mdat)}computeSampleTableSizeUpperBound(){w(this.fastStart==="reserve");let e=0;for(const t of this.trackDatas){const r=t.track.metadata.maximumPacketCount;w(r!==void 0),e+=8*Math.ceil(2/3*r),e+=4*r,e+=8*Math.ceil(2/3*r),e+=12*Math.ceil(2/3*r),e+=4*r,e+=8*r,t.type==="audio"&&(e+=2*r,e+=8*r)}return e}async onTrackClose(e){const t=await this.mutex.acquire();try{const r=this.trackDatas.find(s=>s.track===e);(r==null?void 0:r.type)==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),(r==null?void 0:r.type)==="audio"&&r.info.pendingEac3Packets.length>0&&await this.writePendingEac3Packets(r),this.closedTracks.add(e),r&&this.processTimestamps(r),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveSamples()}finally{t()}}ensureOneEnabledTrack(){for(const e of["video","audio","subtitle"]){const t=this.trackDatas.filter(s=>s.type===e);if(t.length===0)continue;if(!t.some(s=>{var n;return((n=s.track.metadata.disposition)==null?void 0:n.default)!==!1})){const s=t[0];s.track.metadata.disposition={...s.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){w(this.isFragmented);const e=await this.mutex.acquire();try{for(const t of this.trackDatas)t.type==="subtitle"&&t.track.source._codec==="webvtt"&&await this.processWebVTTCues(t,1/0),this.processTimestamps(t);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async writePendingEac3Packets(e){const t=e.info.pendingEac3Packets.map(a=>a.packet);e.info.pendingEac3Packets.length=0;let r=t[0].data;if(t.length>1){r=new Uint8Array(t.reduce((o,c)=>o+c.data.byteLength,0));let a=0;for(const o of t)r.set(o.data,a),a+=o.data.byteLength}const s=t.reduce((a,o)=>a+o.duration,0),n=this.createSampleForTrack(e,r,t[0].timestamp,s,"key",0);await this.registerSample(e,n)}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack();for(const t of this.trackDatas)t.type==="subtitle"&&t.track.source._codec==="webvtt"&&await this.processWebVTTCues(t,1/0),t.type==="audio"&&t.info.pendingEac3Packets.length>0&&await this.writePendingEac3Packets(t),this.closedTracks.add(t.track),this.processTimestamps(t);if(await this.interleaveSamples(!0),this.isFragmented)await this.finalizeFragment(!1);else{const t=this.trackDatas.filter(r=>r.currentChunk).sort((r,s)=>r.currentChunk.startTimestamp-s.currentChunk.startTimestamp);for(const r of t)await this.finalizeCurrentChunk(r);for(const r of this.trackDatas){const s=Or(r);if(s>0){let c=0;for(const u of r.samples)c+=u.size;r.avgBitrate=Math.round(8*c/s)}else r.avgBitrate=0;let n=0,a=0,o=0;for(let c=0;c<r.samples.length;c++){const u=r.samples[c];for(a+=u.size;u.decodeTimestamp-r.samples[n].decodeTimestamp>=1;)a-=r.samples[n].size,n++;o=Math.max(o,a)}if(r.maxBitrate=8*o,r.startTimestampOffset!==null)for(let c=0;c<r.samples.length;c++){const u=r.samples[c];u.timestamp-=r.startTimestampOffset,u.decodeTimestamp-=r.startTimestampOffset}}}if(w(this.writer),w(this.boxWriter),this.fastStart==="in-memory"){this.mdat=Qs(!1);let t,r=null;for(;;){const n=this.boxWriter.measureBox(Zr(this)),a=this.boxWriter.measureBox(this.mdat),o=n+a;if(o===r)break;r=o,t=a;let c=this.writer.getPos()+o;for(const u of this.finalizedChunks){u.offset=c;for(const{data:l}of u.samples)w(l),c+=l.byteLength,t+=l.byteLength}t>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();const s=Zr(this);if(this.boxWriter.writeBox(s),this.formatOptions.onMoov){const{data:n,start:a}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(n,a)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const n of this.finalizedChunks){for(const a of n.samples)w(a.data),this.writer.write(a.data),a.data=null;await this.writer.flush()}if(this.formatOptions.onMdat){const{data:n,start:a}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(n,a)}}else if(this.isFragmented)if(this.isCmaf){const t=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;if(t>=2**31)throw new Error("CMAF segments must be smaller than 2 GiB, as their sidx box can't index anything larger.");this.writer.seek(0),this.boxWriter.writeBox(yl()),this.boxWriter.writeBox(bl(this,t))}else{const t=this.writer.getPos(),r=ow(this.trackDatas);this.boxWriter.writeBox(r);const s=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(s)}else{w(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);w(t!==void 0);const r=this.writer.getPos()-t;if(this.mdat.size=r,this.mdat.largeSize=r>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){const{data:n,start:a}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(n,a)}const s=Zr(this);if(this.fastStart==="reserve"){w(this.ftypSize!==null);const n=this.boxWriter.offsets.get(this.mdat)-this.ftypSize,a=this.boxWriter.measureBox(s);if(a+8>n)throw new Error(`The moov box (${a} bytes) plus a free box (8 bytes) exceed the space reserved for them (${n} bytes) with fastStart: 'reserve'. This is a bug; please report it.`);this.writer.seek(this.ftypSize+a),this.boxWriter.writeBox(fg(n-a)),this.writer.seek(this.ftypSize)}if(this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(s),this.formatOptions.onMoov){const{data:n,start:a}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(n,a)}}e()}}/*!
|
|
357
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
358
|
+
*
|
|
359
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
360
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
361
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
362
|
+
*/const _w=-32768,Ew=2**15-1,Pl=6,Iw=6,vw={video:1,audio:2,subtitle:17};class Bw extends ti{constructor(e,t){super(e),this.trackDatas=[],this.closedTracks=new Set,this.allTracksKnown=Ae(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentClusterBlocks=[],this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.endTimestamp=-1/0,this.warnedAboutTooNegativeTimestamp=!1,this.format=t}async start(){const e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new um(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush();for(const t of this.output.tracks)t.isVideoTrack()&&t.metadata.decoderConfig?this.getVideoTrackData(t,t.metadata.primingPacket??null,{decoderConfig:t.metadata.decoderConfig}):t.isAudioTrack()&&t.metadata.decoderConfig&&this.getAudioTrackData(t,t.metadata.primingPacket??null,{decoderConfig:t.metadata.decoderConfig})}finally{e()}}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();const e={id:E.EBML,data:[{id:E.EBMLVersion,data:1},{id:E.EBMLReadVersion,data:1},{id:E.EBMLMaxIDLength,data:4},{id:E.EBMLMaxSizeLength,data:8},{id:E.DocType,data:this.format instanceof mr?"webm":"matroska"},{id:E.DocTypeVersion,data:4},{id:E.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){const{data:t,start:r}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(t,r)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;const t=new Uint8Array([28,83,187,107]),r=new Uint8Array([21,73,169,102]),s=new Uint8Array([22,84,174,107]),n=new Uint8Array([25,65,164,105]),a=new Uint8Array([18,84,195,103]),o={id:E.SeekHead,data:[{id:E.Seek,data:[{id:E.SeekID,data:r},{id:E.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:E.Seek,data:[{id:E.SeekID,data:s},{id:E.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:E.Seek,data:[{id:E.SeekID,data:n},{id:E.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:E.Seek,data:[{id:E.SeekID,data:a},{id:E.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null,{id:E.Seek,data:[{id:E.SeekID,data:t},{id:E.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]}]};this.seekHead=o}createSegmentInfo(){const e={id:E.Duration,data:new kn(0)};this.segmentDuration=e;const t=this.output._metadataTags.creationTime===void 0?new Date:this.output._metadataTags.creationTime;let r=null;if(t){const n=1000000n*BigInt(t.getTime()-Vu);if(BigInt.asIntN(64,n)!==n)throw new Error("creationTime is out of the range representable by Matroska files.");r={id:E.DateUTC,size:8,data:BigInt.asUintN(64,n)}}const s={id:E.Info,data:[{id:E.TimestampScale,data:1e6},this.format._options.appendOnly?null:e,r,{id:E.MuxingApp,data:Pr},{id:E.WritingApp,data:Pr}]};this.segmentInfo=s}createTracks(){var t,r,s,n,a,o;const e={id:E.Tracks,data:[]};this.tracksElement=e;for(const c of this.trackDatas){let u=rt[c.track.source._codec];w(u),c.type==="audio"&&c.track.source._codec==="dts"?c.info.decoderConfig.codec==="dtse"?u="A_DTS/EXPRESS":c.info.decoderConfig.codec==="dtsl"&&(u="A_DTS/LOSSLESS"):c.type==="subtitle"&&this.format instanceof mr&&(u="D_WEBVTT/SUBTITLES");let l=0;if(c.type==="audio"){const d=Vd(c.track.source._codec,c.info.decoderConfig);l=Math.round(1e9*d)}e.data.push({id:E.TrackEntry,data:[{id:E.TrackNumber,data:c.track.id},{id:E.TrackUID,data:c.track.id},{id:E.TrackType,data:vw[c.type]},((t=c.track.metadata.disposition)==null?void 0:t.default)===!1?{id:E.FlagDefault,data:0}:null,(r=c.track.metadata.disposition)!=null&&r.forced?{id:E.FlagForced,data:1}:null,(s=c.track.metadata.disposition)!=null&&s.hearingImpaired?{id:E.FlagHearingImpaired,data:1}:null,(n=c.track.metadata.disposition)!=null&&n.visuallyImpaired?{id:E.FlagVisualImpaired,data:1}:null,(a=c.track.metadata.disposition)!=null&&a.original?{id:E.FlagOriginal,data:1}:null,(o=c.track.metadata.disposition)!=null&&o.commentary?{id:E.FlagCommentary,data:1}:null,{id:E.FlagLacing,data:0},c.type==="video"&&c.info.alphaMode||c.type==="subtitle"&&!(this.format instanceof mr)?{id:E.MaxBlockAdditionID,data:1}:null,{id:E.Language,data:c.track.metadata.languageCode??et},{id:E.CodecID,data:u},c.codecPrivate?{id:E.CodecPrivate,data:me(c.codecPrivate)}:null,c.type==="audio"&&c.info.codecDelay?{id:E.CodecDelay,data:Math.round(1e9*c.info.codecDelay)}:null,l>0?{id:E.SeekPreRoll,data:l}:null,c.track.metadata.name!==void 0?{id:E.Name,data:new oi(c.track.metadata.name)}:null,c.type==="video"?this.videoSpecificTrackInfo(c):null,c.type==="audio"?this.audioSpecificTrackInfo(c):null,c.type==="subtitle"?this.subtitleSpecificTrackInfo(c):null]})}}videoSpecificTrackInfo(e){const{frameRate:t,transformationMatrix:r}=e.track.metadata,s=[t?{id:E.DefaultDuration,data:Math.round(1e9/t)}:null];let n,a,o;if(r){n=es(r);const p=vr(mo(-n),r);a=Math.sign(p[0]),o=Math.sign(p[4]),o===-1&&(o=1,a=-a,n=Ir(n+180))}else n=e.track.metadata.rotation??0,a=e.track.metadata.flip?-1:1,o=1;const c=n?Ir(a===-1?n:-n):0,u=Math.round(Math.acos(a)*Ea),l=Math.round(Math.acos(o)*Ea),d=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,f=e.info.decoderConfig.colorSpace,h={id:E.Video,data:[{id:E.PixelWidth,data:e.info.width},{id:E.PixelHeight,data:e.info.height},d?{id:E.DisplayWidth,data:e.info.aspectRatio.num}:null,d?{id:E.DisplayHeight,data:e.info.aspectRatio.den}:null,d?{id:E.DisplayUnit,data:3}:null,e.info.alphaMode?{id:E.AlphaMode,data:1}:null,Vl(f)?null:{id:E.Colour,data:[{id:E.MatrixCoefficients,data:(f==null?void 0:f.matrix)!=null?Vi[f.matrix]:2},{id:E.TransferCharacteristics,data:(f==null?void 0:f.transfer)!=null?Ni[f.transfer]:2},{id:E.Primaries,data:(f==null?void 0:f.primaries)!=null?Ui[f.primaries]:2},{id:E.Range,data:(f==null?void 0:f.fullRange)!=null?f.fullRange?2:1:0}]},c||u||l?{id:E.Projection,data:[{id:E.ProjectionType,data:0},u?{id:E.ProjectionPoseYaw,data:new Gi(u)}:null,l?{id:E.ProjectionPosePitch,data:new Gi(l)}:null,c?{id:E.ProjectionPoseRoll,data:new Gi((c+180)%360-180)}:null]}:null]};return s.push(h),s}audioSpecificTrackInfo(e){const t=je.includes(e.track.source._codec)?Bt(e.track.source._codec):null;let r=e.info.sampleRate;return e.track.source._codec==="aac"&&(w(e.codecPrivate),r=nr(me(e.codecPrivate)).coreSampleRate??r),[{id:E.Audio,data:[{id:E.SamplingFrequency,data:new Gi(r)},r!==e.info.sampleRate?{id:E.OutputSamplingFrequency,data:new Gi(e.info.sampleRate)}:null,{id:E.Channels,data:e.info.numberOfChannels},t?{id:E.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[]}maybeCreateTags(){const e=[],t=(n,a)=>{e.push({id:E.SimpleTag,data:[{id:E.TagName,data:new oi(n)},typeof a=="string"?{id:E.TagString,data:new oi(a)}:{id:E.TagBinary,data:a}]})},r=this.output._metadataTags,s=new Set;for(const{key:n,value:a}of Nr(r))switch(n){case"title":t("TITLE",a),s.add("TITLE");break;case"description":t("DESCRIPTION",a),s.add("DESCRIPTION");break;case"artist":t("ARTIST",a),s.add("ARTIST");break;case"album":t("ALBUM",a),s.add("ALBUM");break;case"albumArtist":t("ALBUM_ARTIST",a),s.add("ALBUM_ARTIST");break;case"genre":t("GENRE",a),s.add("GENRE");break;case"beatsPerMinute":t("BPM",a.toString()),s.add("BPM");break;case"comment":t("COMMENT",a),s.add("COMMENT");break;case"lyrics":t("LYRICS",a),s.add("LYRICS");break;case"date":t("DATE",a.toISOString().slice(0,10)),s.add("DATE");break;case"trackNumber":{const o=r.tracksTotal!==void 0?`${a}/${r.tracksTotal}`:a.toString();t("PART_NUMBER",o),s.add("PART_NUMBER")}break;case"discNumber":{const o=r.discsTotal!==void 0?`${a}/${r.discsTotal}`:a.toString();t("DISC",o),s.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":case"creationTime":break;default:xe(n)}if(r.raw)for(const n in r.raw){const a=r.raw[n];a==null||s.has(n)||(typeof a=="string"||a instanceof Uint8Array)&&t(n,a)}e.length!==0&&(this.tagsElement={id:E.Tags,data:[{id:E.Tag,data:[{id:E.Targets,data:[{id:E.TargetTypeValue,data:50},{id:E.TargetType,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){const e=this.output._metadataTags,t=[],r=new Set,s=e.images??[];for(const n of s){let a=n.name;a===void 0&&(a=(n.kind==="coverFront"?"cover":n.kind==="coverBack"?"back":"image")+(Ef(n.mimeType)??""));let o;for(;;){o=0n;for(let c=0;c<8;c++)o<<=8n,o|=BigInt(Math.floor(Math.random()*256));if(o!==0n&&!r.has(o))break}r.add(o),t.push({id:E.AttachedFile,data:[n.description!==void 0?{id:E.FileDescription,data:new oi(n.description)}:null,{id:E.FileName,data:new oi(a)},{id:E.FileMediaType,data:n.mimeType},{id:E.FileData,data:n.data},{id:E.FileUID,data:o}]})}for(const[n,a]of Object.entries(e.raw??{}))!(a instanceof bo)||!/^\d+$/.test(n)||s.find(c=>c.mimeType===a.mimeType&&ql(c.data,a.data))||t.push({id:E.AttachedFile,data:[a.description!==void 0?{id:E.FileDescription,data:new oi(a.description)}:null,{id:E.FileName,data:new oi(a.name??"")},{id:E.FileMediaType,data:a.mimeType??""},{id:E.FileData,data:a.data},{id:E.FileUID,data:BigInt(n)}]});t.length!==0&&(this.attachmentsElement={id:E.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const e={id:E.Segment,size:this.format._options.appendOnly?-1:Pl,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){const{data:t,start:r}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(t,r)}}createCues(){this.cues={id:E.Cues,data:[]}}get segmentDataOffset(){return w(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const e of this.output.tracks)if(!this.closedTracks.has(e)&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return $u({isWebM:this.format instanceof mr,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,r){const s=this.trackDatas.find(u=>u.track===e);if(s)return s;Ds(r,e.source._codec),w(r),w(r.decoderConfig),w(r.decoderConfig.codedWidth!==void 0),w(r.decoderConfig.codedHeight!==void 0);const n=r.decoderConfig.displayAspectWidth,a=r.decoderConfig.displayAspectHeight,o=n===void 0||a===void 0?null:xs({num:n,den:a}),c={track:e,type:"video",info:{width:r.decoderConfig.codedWidth,height:r.decoderConfig.codedHeight,aspectRatio:o,decoderConfig:r.decoderConfig,alphaMode:e.metadata.canBeTransparent||(t?!!t.sideData.alpha:null)},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:r.decoderConfig.description??null};return e.source._codec==="vp9"?c.codecPrivate=new Uint8Array(Qp(c.info.decoderConfig.codec)):e.source._codec==="av1"?c.codecPrivate=new Uint8Array(Od(c.info.decoderConfig.codec)):e.source._codec==="prores"&&(c.codecPrivate=ge.encode(r.decoderConfig.codec)),this.trackDatas.push(c),this.trackDatas.sort((u,l)=>u.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,t,r){const s=this.trackDatas.find(c=>c.track===e);if(s)return s;Nt(r,e.source._codec),w(r),w(r.decoderConfig);const n={...r.decoderConfig};let a=!1;if(e.source._codec==="aac"&&!n.description){if(!t)throw new Error("No AAC description provided; you must therefore provide a priming packet.");const c=Ti(at.tempFromBytes(t.data));if(!c)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let u,l=null;if(c.channelConfiguration===0){const d=c.crcCheck===null?Ut:Et,f=Rr(t.data.subarray(d));if(!f)throw new Error("ADTS frames with channel configuration 0 must begin with a program config element.");l=f.programConfigElement,u=Cs(l)}else u=Vr[c.channelConfiguration];n.description=Rn({objectType:c.objectType,outputSampleRate:Ot[c.samplingFrequencyIndex],outputNumberOfChannels:u,programConfigElement:l}),a=!0}const o={track:e,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:n,requiresAdtsStripping:a,codecDelay:null},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:n.description??null};return this.trackDatas.push(o),this.trackDatas.sort((c,u)=>c.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){const r=this.trackDatas.find(n=>n.track===e);if(r)return r;qd(t),w(t),w(t.config);const s={track:e,type:"subtitle",info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:ge.encode(t.config.description)};return this.trackDatas.push(s),this.trackDatas.sort((n,a)=>n.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}async addEncodedVideoPacket(e,t,r){var n;const s=await this.mutex.acquire();try{const a=this.getVideoTrackData(e,t,r);(n=a.info).alphaMode??(n.alphaMode=!!t.sideData.alpha);let o=t.data;if(e.source._codec==="prores"){if(o.byteLength<8)throw new Error("ProRes packet too small, expected at least 8 bytes.");o=o.subarray(8)}const c=t.type==="key";this.validateTimestamp(a.track,t.timestamp,c);let u=t.timestamp,l=t.duration;e.metadata.frameRate!==void 0&&(u=tr(u,e.metadata.frameRate),l=tr(l,e.metadata.frameRate));const d=a.info.alphaMode?t.sideData.alpha??null:null,f=this.createInternalChunk(o,u,l,t.type,d);a.chunkQueue.push(f),await this.interleaveChunks()}finally{s()}}async addEncodedAudioPacket(e,t,r){var n;const s=await this.mutex.acquire();try{const a=this.getAudioTrackData(e,t,r);let o=t.data;if(a.info.requiresAdtsStripping){const l=Ti(at.tempFromBytes(o));if(!l)throw new Error("Expected ADTS frame, didn't get one.");const d=l.crcCheck===null?Ut:Et;if(o=o.subarray(d),l.channelConfiguration===0){const f=Rr(o);f&&(o=o.subarray(f.size))}}const c=t.type==="key";this.validateTimestamp(a.track,t.timestamp,c),(n=a.info).codecDelay??(n.codecDelay=Math.max(-t.timestamp,0));const u=this.createInternalChunk(o,t.timestamp+a.info.codecDelay,t.duration,t.type);a.chunkQueue.push(u),await this.interleaveChunks()}finally{s()}}async addSubtitleCue(e,t,r){const s=await this.mutex.acquire();try{const n=this.getSubtitleTrackData(e,r);this.validateTimestamp(n.track,t.timestamp,!0);let a=t.text;const o=Math.round(t.timestamp*1e3);gn.lastIndex=0,a=a.replace(gn,u=>{const d=Va(u.slice(1,-1))-o;return`<${gu(d/1e3)}>`});let c;if(this.format instanceof mr){const u=ge.encode(`${t.identifier??""}
|
|
363
|
+
${t.settings??""}
|
|
364
|
+
${a}`);c=this.createInternalChunk(u,t.timestamp,t.duration,"key")}else{const u=ge.encode(a),l=`${t.settings??""}
|
|
365
|
+
${t.identifier??""}
|
|
366
|
+
${t.notes??""}`;c=this.createInternalChunk(u,t.timestamp,t.duration,"key",l.trim()?ge.encode(l):null)}n.chunkQueue.push(c),await this.interleaveChunks()}finally{s()}}async interleaveChunks(e=!1){if(!(!e&&!this.allTracksAreKnown())){e:for(;;){let t=null,r=1/0;for(const n of this.trackDatas){if(!e&&n.chunkQueue.length===0&&!this.closedTracks.has(n.track))break e;n.chunkQueue.length>0&&n.chunkQueue[0].timestamp<r&&(t=n,r=n.chunkQueue[0].timestamp)}if(!t)break;const s=t.chunkQueue.shift();this.addBlock(t,s)}e||await this.writer.flush()}}createInternalChunk(e,t,r,s,n=null){return{data:e,type:s,timestamp:t,duration:r,additions:n}}addBlock(e,t){this.segment||this.createSegment();const r=Math.round(1e3*t.timestamp),s=this.trackDatas.every(o=>{if(e===o)return t.type==="key";const c=o.chunkQueue[0];return c?c.type==="key":this.closedTracks.has(o.track)});let n=!1;if(this.currentClusterStartMsTimestamp===null)n=!0;else{w(this.currentClusterMaxMsTimestamp!==null);const o=r-this.currentClusterStartMsTimestamp;n=s&&r>this.currentClusterMaxMsTimestamp&&o>=1e3*(this.format._options.minimumClusterDuration??1)||o>Ew}if(n&&this.startNewCluster(r),r-this.currentClusterStartMsTimestamp<_w){if(!this.warnedAboutTooNegativeTimestamp){const o=this.format instanceof mr?"WebM":"Matroska";K._warn(`Packets had to be discarded because their timestamp is too negative to represent in ${o}.`),this.warnedAboutTooNegativeTimestamp=!0}return}this.currentClusterBlocks.push({trackData:e,chunk:t,msTimestamp:r,previousMsTimestamp:e.lastWrittenMsTimestamp}),this.endTimestamp=Math.max(this.endTimestamp,r+Math.round(1e3*t.duration)),e.lastWrittenMsTimestamp=r,this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,r)}startNewCluster(e){this.currentClusterStartMsTimestamp!==null&&this.writeCurrentCluster();const t=Math.max(0,e);this.currentClusterStartMsTimestamp=t,this.currentClusterMaxMsTimestamp=t}writeCurrentCluster(){w(this.currentClusterStartMsTimestamp!==null);const e=this.currentClusterStartMsTimestamp,t=new Map,r=new Map;for(const l of this.currentClusterBlocks){l.chunk.type==="key"&&!t.has(l.trackData)&&t.set(l.trackData,l);const d=r.get(l.trackData);(!d||l.msTimestamp>=d.msTimestamp)&&r.set(l.trackData,l)}const s=new Map;for(const l of this.currentClusterBlocks)s.set(l,this.createBlockElement(l,e,r.get(l.trackData)===l));const n={id:E.Cluster,size:this.format._options.appendOnly?-1:Iw,data:[{id:E.Timestamp,data:e},...s.values()]};if(this.format._options.onCluster&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(n),this.currentClusterBlocks=[],this.format._options.onCluster){const{data:l,start:d}=this.writer.stopTrackingWrites();this.format._options.onCluster(l,d,e/1e3)}const a=this.ebmlWriter.offsets.get(n)-this.segmentDataOffset,o=this.ebmlWriter.dataOffsets.get(n),c=new Map;for(const l of t.values())c.has(l.msTimestamp)||c.set(l.msTimestamp,[]),c.get(l.msTimestamp).push(l);const u=[...c.entries()].sort((l,d)=>l[0]-d[0]);for(const[l,d]of u)w(this.cues),this.cues.data.push({id:E.CuePoint,data:[{id:E.CueTime,data:Math.max(0,l)},...d.map(f=>{const h=this.ebmlWriter.offsets.get(s.get(f));return{id:E.CueTrackPositions,data:[{id:E.CueTrack,data:f.trackData.track.id},{id:E.CueClusterPosition,data:a},{id:E.CueRelativePosition,data:h-o}]}})]})}createBlockElement(e,t,r){const{trackData:s,chunk:n,msTimestamp:a}=e,o=new Uint8Array(4),c=new DataView(o.buffer);c.setUint8(0,128|s.track.id),c.setInt16(1,a-t,!1);const u=Math.round(1e3*n.duration);return!!n.additions||s.type==="subtitle"||r&&u>0?{id:E.BlockGroup,data:[{id:E.Block,data:[o,n.data]},n.type==="delta"?{id:E.ReferenceBlock,data:new Uo(e.previousMsTimestamp-a)}:null,n.additions?{id:E.BlockAdditions,data:[{id:E.BlockMore,data:[{id:E.BlockAddID,data:1},{id:E.BlockAdditional,data:n.additions}]}]}:null,u>0?{id:E.BlockDuration,data:u}:null]}:(c.setUint8(3,+(n.type==="key")<<7),{id:E.SimpleBlock,data:[o,n.data]})}async onTrackClose(e){const t=await this.mutex.acquire();try{this.closedTracks.add(e),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks()}finally{t()}}async finalize(){const e=await this.mutex.acquire();try{this.allTracksKnown.resolve();for(const t of this.trackDatas)this.closedTracks.add(t.track);if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentClusterStartMsTimestamp!==null&&this.writeCurrentCluster(),w(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){const t=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(t,Pl);const r=Math.max(this.endTimestamp,0);this.segmentDuration.data=new kn(r),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),w(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}}finally{e()}}}/*!
|
|
367
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
368
|
+
*
|
|
369
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
370
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
371
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
372
|
+
*/class Fw{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.crc=0}writeAndUpdateCrc(e){for(const t of e){this.crc^=t;for(let r=0;r<8;r++)this.crc=this.crc>>>1^(this.crc&1?40961:0)}this.writer.write(e)}writeU32(e){this.helperView.setUint32(0,e,!1),this.writeAndUpdateCrc(this.helper.subarray(0,4))}writeXingFrame(e){const t=this.writer.getPos();this.crc=0;const r=255,s=224|e.mpegVersionId<<3|e.layer<<1|1;let n;e.mpegVersionId&2?n=e.mpegVersionId&1?0:1:n=1;const a=0,o=Dn(e.mpegVersionId,e.channel),c=e.encoderDelayInSamples===null?155:o+8+4+4+100+36;let u=-1;const l=n*16*4+e.layer*16;for(let g=0;g<16;g++){const y=Da[l+g];if(1e3*y<(e.targetBitrate??0))continue;if(za(n,e.layer,1e3*y,e.sampleRate,a)>=c){u=g;break}}if(u===-1)throw new Error("No suitable bitrate found.");const d=u<<4|e.frequencyIndex<<2|a<<1,f=e.channel<<6|e.modeExtension<<4|e.copyright<<3|e.original<<2|e.emphasis;this.helper[0]=r,this.helper[1]=s,this.helper[2]=d,this.helper[3]=f,this.writeAndUpdateCrc(this.helper.subarray(0,4)),this.writeAndUpdateCrc(new Uint8Array(o-4)),this.writeU32(e.isCbr?Mn:fs);let h=0;if(e.frameCount!==null&&(h|=Gt.FrameCount),e.fileSize!==null&&(h|=Gt.FileSize),e.toc!==null&&(h|=Gt.Toc),this.writeU32(h),this.writeU32(e.frameCount??0),this.writeU32(e.fileSize??0),this.writeAndUpdateCrc(e.toc??new Uint8Array(100)),e.encoderDelayInSamples!==null){const g=new Uint8Array(36);g.set([76,65,77,69]),g[21]=e.encoderDelayInSamples>>4,g[22]=(e.encoderDelayInSamples&15)<<4|dn>>8,g[23]=dn&255,this.writeAndUpdateCrc(g.subarray(0,34)),new DataView(g.buffer).setUint16(34,this.crc),this.writer.write(g.subarray(34))}const p=Da[l+u],m=za(n,e.layer,1e3*p,e.sampleRate,a);this.writer.write(new Uint8Array(t+m-this.writer.getPos()))}}/*!
|
|
373
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
374
|
+
*
|
|
375
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
376
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
377
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
378
|
+
*/class Rw extends ti{constructor(e,t){super(e),this.xingFrameData=null,this.frameCount=0,this.frameBitrate=null,this.hasVariableBitrate=!1,this.framePositions=[],this.xingFramePos=null,this.format=t,this.writeXingHeader=t._options.xingHeader!==!1}async start(){const e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!this.writeXingHeader),this.mp3Writer=new Fw(this.writer),ds(this.output._metadataTags)||new No(this.writer).writeId3V2Tag(this.output._metadataTags)}finally{e()}}async getMimeType(){return"audio/mpeg"}async addEncodedVideoPacket(){throw new Error("MP3 does not support video.")}async addEncodedAudioPacket(e,t){const r=await this.mutex.acquire();try{if(this.writeXingHeader){const s=ie(t.data);if(s.byteLength<4)throw new Error("Invalid MP3 header in sample.");const n=s.getUint32(0,!1),a=Mr(n,null).header;if(!a)throw new Error("Invalid MP3 header in sample.");if(!this.xingFrameData&&a.layer!==1)this.writeXingHeader=!1;else if(!this.xingFrameData){const o=Dn(a.mpegVersionId,a.channel);if(s.byteLength>=o+4){const u=s.getUint32(o,!1);if(u===fs||u===Mn)return}let c=t.timestamp<0?Math.round(-t.timestamp*a.sampleRate)-dn:null;c!==null&&(c<0||c>4095)&&(c=null),this.xingFrameData={mpegVersionId:a.mpegVersionId,layer:a.layer,frequencyIndex:a.frequencyIndex,sampleRate:a.sampleRate,channel:a.channel,modeExtension:a.modeExtension,copyright:a.copyright,original:a.original,emphasis:a.emphasis,targetBitrate:a.bitrate,isCbr:!1,frameCount:null,fileSize:null,toc:null,encoderDelayInSamples:c},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData)}this.frameBitrate===null?this.frameBitrate=a.bitrate:a.bitrate!==this.frameBitrate&&(this.hasVariableBitrate=!0)}this.validateTimestamp(e,t.timestamp,t.type==="key"),this.writeXingHeader&&this.framePositions.push(this.writer.getPos()),this.writer.write(t.data),this.frameCount++,await this.writer.flush()}finally{r()}}async addSubtitleCue(){throw new Error("MP3 does not support subtitles.")}async finalize(){const e=await this.mutex.acquire();if(this.frameCount===0){if(!this.writeXingHeader)throw new Error("Cannot finalize an empty MP3 file: not a single packet was added and the Xing header is disabled, so there's no frame we could write.");const r=this.output.tracks[0];w(r==null?void 0:r.isAudioTrack());const s=r.metadata.primingPacket;if(s){const n=ie(s.data);if(n.byteLength<4)throw new Error("Invalid MP3 header in priming packet.");const a=n.getUint32(0,!1),o=Mr(a,null).header;if(!o)throw new Error("Invalid MP3 header in priming packet.");this.xingFrameData={mpegVersionId:o.mpegVersionId,layer:o.layer,frequencyIndex:o.frequencyIndex,sampleRate:o.sampleRate,channel:o.channel,modeExtension:o.modeExtension,copyright:o.copyright,original:o.original,emphasis:o.emphasis,targetBitrate:o.bitrate,isCbr:!1,frameCount:null,fileSize:null,toc:null,encoderDelayInSamples:null}}else if(r.metadata.decoderConfig){const{sampleRate:n,numberOfChannels:a}=r.metadata.decoderConfig,o=[3,2,0];let c=null,u=-1;for(let l=0;l<o.length;l++)if(u=Jl.indexOf(n<<l),u!==-1){c=o[l];break}if(c===null)throw new Error(`${n} Hz is not a valid MP3 sample rate.`);this.xingFrameData={mpegVersionId:c,layer:1,frequencyIndex:u,sampleRate:n,channel:a===1?3:0,modeExtension:0,copyright:0,original:0,emphasis:0,targetBitrate:null,isCbr:!1,frameCount:null,fileSize:null,toc:null,encoderDelayInSamples:null}}else throw new Error("Cannot finalize an empty MP3 file: no packets were added and the track specified neither a decoderConfig nor a primingPacket in its metadata, so there's no telling what the file should look like.");this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData)}if(this.writeXingHeader){w(this.xingFrameData),w(this.xingFramePos!==null);const s=this.writer.getPos()-this.xingFramePos;if(this.writer.seek(this.xingFramePos),this.framePositions.length>0){const n=new Uint8Array(100);for(let a=0;a<100;a++){const o=Math.floor(this.framePositions.length*(a/100)),c=this.framePositions[o]-this.xingFramePos;n[a]=256*(c/s)}this.xingFrameData.toc=n}if(this.xingFrameData.isCbr=this.frameBitrate!==null&&!this.hasVariableBitrate,this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=s,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){const{data:n,start:a}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(n,a)}}e()}}/*!
|
|
379
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
380
|
+
*
|
|
381
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
382
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
383
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
384
|
+
*/const Mw=8192;class Dw extends ti{constructor(e,t){super(e),this.trackDatas=[],this.closedTracks=new Set,this.bosPagesWritten=!1,this.allTracksKnown=Ae(),this.warnedAboutTooNegativeTimestamp=!1,this.pageBytes=new Uint8Array(Zu),this.pageView=new DataView(this.pageBytes.buffer),this.format=t}async start(){const e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!0);for(const t of this.output.tracks)w(t.isAudioTrack()),t.metadata.decoderConfig&&this.getTrackData(t,{decoderConfig:t.metadata.decoderConfig})}finally{e()}}async getMimeType(){return await this.allTracksKnown.promise,Yu({codecStrings:this.trackDatas.map(e=>e.codecInfo.codec)})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(e,t){const r=this.trackDatas.find(o=>o.track===e);if(r)return r;let s;do s=Math.floor(2**32*Math.random());while(this.trackDatas.some(o=>o.serialNumber===s));w(e.source._codec==="vorbis"||e.source._codec==="opus"),Nt(t,e.source._codec),w(t),w(t.decoderConfig);let n;e.source._codec==="vorbis"?n=t.decoderConfig.sampleRate:e.source._codec==="opus"?n=Wi:(xe(e.source._codec),w(!1));const a={track:e,serialNumber:s,internalSampleRate:n,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],leadingPackets:[],startOffsetInSamples:0,currentTimestampInSamples:null,audioPacketCount:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0,currentPageStartTimestampInSamples:0};return this.queueHeaderPackets(a,t),this.trackDatas.push(a),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}queueHeaderPackets(e,t){if(w(t.decoderConfig),e.codecInfo.codec==="vorbis"){w(t.decoderConfig.description);const r=me(t.decoderConfig.description);if(r[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let s=1;const n=()=>{let g=0;for(;;){const y=r[s++];if(y===void 0)throw new TypeError("Vorbis decoder description is too short.");if(g+=y,y<255)return g}},a=n(),o=n();if(r.length-s<=0)throw new TypeError("Vorbis decoder description is too short.");const u=r.subarray(s,s+=a);s+=o;const l=r.subarray(s),d=new Uint8Array(7);d[0]=3,d[1]=118,d[2]=111,d[3]=114,d[4]=98,d[5]=105,d[6]=115;const f=Ua(d,this.output._metadataTags,!0),h=new Uint8Array(f.length+1);h.set(f),h[f.length]=1,e.packetQueue.push({data:u,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0,holdPage:!1,isHeader:!0},{data:h,timestampInSamples:0,durationInSamples:0,forcePageFlush:!1,holdPage:!1,isHeader:!0},{data:l,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0,holdPage:!1,isHeader:!0});const m=ie(u).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(m&15),1<<(m>>4)],modeBlockflags:ou(l).modeBlockflags}}else if(e.codecInfo.codec==="opus"){if(!t.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");const r=me(t.decoderConfig.description),s=new Uint8Array(8),n=ie(s);n.setUint32(0,1332770163,!1),n.setUint32(4,1415669619,!1);const a=Ua(s,this.output._metadataTags,!0);e.packetQueue.push({data:r,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0,holdPage:!1,isHeader:!0},{data:a,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0,holdPage:!1,isHeader:!0}),e.codecInfo.opusInfo={preSkip:vs(r).preSkip}}else xe(e.codecInfo.codec)}async addEncodedAudioPacket(e,t,r){const s=await this.mutex.acquire();try{const n=this.getTrackData(e,r);this.validateTimestamp(n.track,t.timestamp,t.type==="key");const{durationInSamples:a,vorbisBlockSize:o}=to(t.data,n.codecInfo,n.vorbisLastBlocksize);if(n.vorbisLastBlocksize=o,n.currentTimestampInSamples===null){const u=Math.round(t.timestamp*n.internalSampleRate);if(n.codecInfo.codec==="vorbis")n.currentTimestampInSamples=u;else if(n.codecInfo.codec==="opus"){const l=n.codecInfo.opusInfo;if(w(l),n.pagesWritten===0){const d=Be(-u,l.preSkip,65535),f=n.packetQueue[0];w(f==null?void 0:f.isHeader),f.data=f.data.slice(),ie(f.data).setUint16(10,d,!0),l.preSkip=d}n.currentTimestampInSamples=u+l.preSkip}else xe(n.codecInfo.codec),w(!1)}const c={data:t.data,timestampInSamples:n.currentTimestampInSamples,durationInSamples:a,forcePageFlush:!1,holdPage:!1,isHeader:!1};if(n.currentTimestampInSamples+=a,n.audioPacketCount===0){const u=c.timestampInSamples+a;if(n.codecInfo.codec==="opus"){if(c.timestampInSamples<0){this.warnAboutDiscardedPackets();return}n.startOffsetInSamples=c.timestampInSamples}else if(n.codecInfo.codec==="vorbis"){if(u<0){n.leadingPackets.push(c);return}let l=Math.floor(c.data.length/255)+1,d=n.leadingPackets.length;for(;d>0;){const h=n.leadingPackets[d-1],p=Math.floor(h.data.length/255)+1;if(l+p>255)break;l+=p,d--}d>0&&this.warnAboutDiscardedPackets();const f=n.leadingPackets.slice(d);if(n.leadingPackets.length=0,f.length>0){for(const h of f)h.holdPage=!0,n.packetQueue.push(h);c.holdPage=!0,c.forcePageFlush=!0,n.audioPacketCount+=f.length}else n.startOffsetInSamples=u}else xe(n.codecInfo.codec)}n.startOffsetInSamples>0&&n.audioPacketCount===1&&(c.forcePageFlush=!0),n.audioPacketCount++,n.packetQueue.push(c),await this.interleavePages()}finally{s()}}addSubtitleCue(){throw new Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(const e of this.output.tracks)if(!this.closedTracks.has(e)&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async interleavePages(e=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown()&&!e)return;for(const t of this.trackDatas)for(;t.packetQueue.length>0;){const r=t.packetQueue.shift();if(this.writePacket(t,r,!1),r.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let t=null,r=1/0;for(const a of this.trackDatas){if(!e&&a.packetQueue.length<=1&&!this.closedTracks.has(a.track))break e;if(a.packetQueue.length===0)continue;const o=a.packetQueue[0],c=o.isHeader?-1/0:o.timestampInSamples/a.internalSampleRate;c<r&&(t=a,r=c)}if(!t)break;const s=t.packetQueue.shift(),n=t.packetQueue.length===0;this.writePacket(t,s,n)}e||await this.writer.flush()}writePacket(e,t,r){const s=t.timestampInSamples+t.durationInSamples;if(e.currentLacingValues.length===0&&(e.currentPageStartTimestampInSamples=t.timestampInSamples),this.format._options.maximumPageDuration!==void 0&&!t.holdPage){const u=this.format._options.maximumPageDuration*e.internalSampleRate;e.currentLacingValues.length>0&&s-e.currentPageStartTimestampInSamples>u&&this.writePage(e,!1)}let n=t.data.length,a=0,o=0;for(;;){e.currentLacingValues.length===0&&a>0&&(e.currentPageStartsWithFreshPacket=!1);const u=Math.min(255,n);e.currentLacingValues.push(u),e.currentPageSize++,o+=u;const l=n<255;if(e.currentLacingValues.length===255){const d=t.data.subarray(a,o);if(a=o,e.currentPageData.push(d),e.currentPageSize+=d.length,l&&(e.currentGranulePosition=s),this.writePage(e,r&&l),l)return}if(l)break;n-=255}const c=t.data.subarray(a);e.currentPageData.push(c),e.currentPageSize+=c.length,e.currentGranulePosition=s,(e.currentPageSize>=Mw&&!t.holdPage||t.forcePageFlush||r)&&this.writePage(e,r)}writePage(e,t){this.pageView.setUint32(0,Vo,!0),this.pageView.setUint8(4,0);let r=0;e.currentPageStartsWithFreshPacket||(r|=1),e.pagesWritten===0&&(r|=2),t&&(r|=4),this.pageView.setUint8(5,r);const s=e.currentLacingValues.every(c=>c===255)?-1:e.currentGranulePosition;bf(this.pageView,6,s),this.pageView.setUint32(14,e.serialNumber,!0),this.pageView.setUint32(18,e.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,e.currentLacingValues.length),this.pageBytes.set(e.currentLacingValues,27);let n=27+e.currentLacingValues.length;for(const c of e.currentPageData)this.pageBytes.set(c,n),n+=c.length;const a=this.pageBytes.subarray(0,n),o=Tm(a);if(this.pageView.setUint32(22,o,!0),e.pagesWritten++,e.currentLacingValues.length=0,e.currentPageData.length=0,e.currentPageSize=27,e.currentPageStartsWithFreshPacket=!0,e.currentPageStartTimestampInSamples=e.currentGranulePosition,this.format._options.onPage&&this.writer.startTrackingWrites(),this.writer.write(a),this.format._options.onPage){const{data:c,start:u}=this.writer.stopTrackingWrites();this.format._options.onPage(c,u,e.track.source)}}async onTrackClose(e){const t=await this.mutex.acquire();try{this.closedTracks.add(e);const r=this.trackDatas.find(s=>s.track===e);r&&r.leadingPackets.length>0&&(r.leadingPackets.length=0,this.warnAboutDiscardedPackets()),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages()}finally{t()}}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)this.closedTracks.add(t.track),t.leadingPackets.length>0&&(t.leadingPackets.length=0,this.warnAboutDiscardedPackets());await this.interleavePages(!0),e()}warnAboutDiscardedPackets(){this.warnedAboutTooNegativeTimestamp||(K._warn("Packets had to be discarded because their timestamp is too negative to represent in Ogg."),this.warnedAboutTooNegativeTimestamp=!0)}}/*!
|
|
385
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
386
|
+
*
|
|
387
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
388
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
389
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
390
|
+
*/const zw=0,sf=4096,Cl=256,Ow=224,_l=192;class Uw extends ti{constructor(e,t){super(e),this.trackDatas=[],this.closedTracks=new Set,this.tablesWritten=!1,this.continuityCounters=new Map,this.packetBuffer=new Uint8Array(ct),this.packetView=ie(this.packetBuffer),this.allTracksKnown=Ae(),this.adaptationFieldBuffer=new Uint8Array(184),this.payloadBuffer=new Uint8Array(184),this.format=t,this.timestampOffset=t._options.timestampOffset??0}async start(){const e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!0)}finally{e()}}async getMimeType(){return await this.allTracksKnown.promise,id(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,t){const r=this.trackDatas.find(u=>u.track===e);if(r)return r;Ds(t,e.source._codec),w(t==null?void 0:t.decoderConfig);const s=e.source._codec;w(s==="avc"||s==="hevc");const n=s==="avc"?27:36,a=Cl+this.output.tracks.indexOf(e),o=Ow+this.output.tracks.filter(u=>u.type==="video").indexOf(e),c={track:e,pid:a,streamType:n,streamId:o,codecString:t.decoderConfig.codec,timestampProcessingQueue:[],reorderDelay:0,lastDecodeTimestamp:-1/0,packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1};return this.trackDatas.push(c),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,t){const r=this.trackDatas.find(l=>l.track===e);if(r)return r;Nt(t,e.source._codec),w(t==null?void 0:t.decoderConfig);const s=e.source._codec;w(s==="aac"||s==="mp3"||s==="ac3"||s==="eac3"||s==="dts");const n=Cl+this.output.tracks.indexOf(e),a=this.output.tracks.filter(l=>l.type==="audio").indexOf(e);let o,c;switch(s){case"aac":o=15,c=_l+a;break;case"mp3":o=3,c=_l+a;break;case"ac3":o=129,c=189;break;case"eac3":o=135,c=189;break;case"dts":o=130,c=189;break}const u={track:e,pid:n,streamType:o,streamId:c,codecString:t.decoderConfig.codec,timestampProcessingQueue:[],reorderDelay:0,lastDecodeTimestamp:-1/0,packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1};return this.trackDatas.push(u),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}async addEncodedVideoPacket(e,t,r){const s=await this.mutex.acquire();try{const n=this.getVideoTrackData(e,r);this.validateTimestamp(n.track,t.timestamp,t.type==="key");const a=this.prepareVideoPacket(n,t,r);t.type==="key"&&await this.flushTimestampQueue(n),n.timestampProcessingQueue.push({data:a,presentationTimestamp:t.timestamp,decodeTimestamp:null,isKeyframe:t.type==="key"})}finally{s()}}async addEncodedAudioPacket(e,t,r){const s=await this.mutex.acquire();try{const n=this.getAudioTrackData(e,r);this.validateTimestamp(n.track,t.timestamp,t.type==="key");const a=this.prepareAudioPacket(n,t,r);t.type==="key"&&await this.flushTimestampQueue(n),n.timestampProcessingQueue.push({data:a,presentationTimestamp:t.timestamp,decodeTimestamp:null,isKeyframe:t.type==="key"})}finally{s()}}async addSubtitleCue(){throw new Error("MPEG-TS does not support subtitles.")}prepareVideoPacket(e,t,r){var n;const s=e.track.source._codec;if(e.inputIsAnnexB===null){const a=(n=r==null?void 0:r.decoderConfig)==null?void 0:n.description;if(a){const o=me(a);s==="avc"?e.avcDecoderConfig=Es(o):e.hevcDecoderConfig=xo(o)}e.inputIsAnnexB=!a}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(t.data,s):this.prepareLengthPrefixedVideoPacket(e,t,s)}prepareAnnexBVideoPacket(e,t){const r=[];for(const s of Wr(e)){const n=e.subarray(s.offset,s.offset+s.length);(t==="avc"?rr(n[0])===Ve.AUD:zi(n[0])===ke.AUD_NUT)||r.push(n)}return r.unshift(this.createAud(r,t)),hn(r)}prepareLengthPrefixedVideoPacket(e,t,r){const s=t.data,n=r==="avc"?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,a=[];for(const o of ko(s,n)){const c=s.subarray(o.offset,o.offset+o.length);(r==="avc"?rr(c[0])===Ve.AUD:zi(c[0])===ke.AUD_NUT)||a.push(c)}if(t.type==="key")if(r==="avc"){const o=e.avcDecoderConfig;for(const c of o.pictureParameterSets)a.unshift(c);for(const c of o.sequenceParameterSets)a.unshift(c)}else{const o=e.hevcDecoderConfig;for(const c of o.arrays)if(c.nalUnitType===ke.PPS_NUT)for(const u of c.nalUnits)a.unshift(u);for(const c of o.arrays)if(c.nalUnitType===ke.SPS_NUT)for(const u of c.nalUnits)a.unshift(u);for(const c of o.arrays)if(c.nalUnitType===ke.VPS_NUT)for(const u of c.nalUnits)a.unshift(u)}return a.unshift(this.createAud(a,r)),hn(a)}createAud(e,t){if(t==="avc")return new Uint8Array([9,240]);const r=e.find(n=>zi(n[0])<32),s=r?r[1]&7:1;return new Uint8Array([70,s,80])}prepareAudioPacket(e,t,r){var c;const s=e.track.source._codec;if(s==="mp3"||s==="ac3"||s==="eac3"||s==="dts")return t.data;if(e.inputIsAdts===null){const u=(c=r==null?void 0:r.decoderConfig)==null?void 0:c.description;if(u){const l=nr(me(u)),d=Ql(l);e.adtsHeader=d.header,e.adtsHeaderBitstream=d.bitstream}e.inputIsAdts=!u}if(e.inputIsAdts)return t.data;w(e.adtsHeader),w(e.adtsHeaderBitstream);const n=e.adtsHeader,a=t.data.byteLength+n.byteLength;Yl(e.adtsHeaderBitstream,a);const o=new Uint8Array(a);return o.set(n,0),o.set(t.data,n.byteLength),o}allTracksAreKnown(){for(const e of this.output.tracks)if(!this.closedTracks.has(e)&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async flushTimestampQueue(e,t=!0){if(e.timestampProcessingQueue.length===0)return;const r=e.timestampProcessingQueue.map(s=>s.presentationTimestamp).sort((s,n)=>s-n);for(let s=0;s<e.timestampProcessingQueue.length;s++){const n=e.timestampProcessingQueue[s];e.reorderDelay=Math.max(e.reorderDelay,r[s]-n.presentationTimestamp)}for(let s=0;s<e.timestampProcessingQueue.length;s++){const n=e.timestampProcessingQueue[s],a=Math.max(r[s]-e.reorderDelay,e.lastDecodeTimestamp+1/lt);n.decodeTimestamp=a,n.presentationTimestamp=Math.max(n.presentationTimestamp,a),e.lastDecodeTimestamp=a,e.packetQueue.push(n)}e.timestampProcessingQueue.length=0,t&&await this.interleavePackets()}async interleavePackets(e=!1){if(!this.tablesWritten){if(!this.allTracksAreKnown()&&!e)return;this.writeTables()}e:for(;;){let t=null,r=1/0;for(const n of this.trackDatas){if(!e&&n.packetQueue.length===0&&!this.closedTracks.has(n.track))break e;n.packetQueue.length>0&&n.packetQueue[0].presentationTimestamp<r&&(t=n,r=n.packetQueue[0].presentationTimestamp)}if(!t)break;const s=t.packetQueue.shift();this.writePesPacket(t,s)}e||await this.writer.flush()}writeTables(){w(!this.tablesWritten),this.writePsiSection(zw,$i),this.writePsiSection(sf,Vw(this.trackDatas)),this.tablesWritten=!0}writePsiSection(e,t){let r=0,s=!0;for(;r<t.length;){const a=184-(s?1:0),o=t.length-r,c=Math.min(a,o);let u;s?(u=this.payloadBuffer.subarray(0,1+c),u[0]=0,u.set(t.subarray(r,r+c),1)):u=t.subarray(r,r+c),this.writeTsPacket(e,s,null,u),r+=c,s=!1}}writePesPacket(e,t){const r=e.track.type==="video",s=r?10:5,n=new Uint8Array(9+s),a=ie(n),o=new oe(n.subarray(9));In(a,0,1,!1),n[3]=e.streamId;const c=e.track.type==="video"||8+t.data.length>65535?0:8+t.data.length;a.setUint16(4,c,!1),a.setUint8(6,132),a.setUint8(7,r?192:128),a.setUint8(8,s);const u=so(t.presentationTimestamp+this.timestampOffset);if(o.pos=0,o.writeBits(4,r?3:2),o.writeBits(3,Math.floor(u/2**30)),o.writeBits(1,1),o.writeBits(15,Math.floor(u/2**15)%2**15),o.writeBits(1,1),o.writeBits(15,u%2**15),o.writeBits(1,1),r){w(t.decodeTimestamp!==null);const h=so(t.decodeTimestamp+this.timestampOffset);o.writeBits(4,1),o.writeBits(3,Math.floor(h/2**30)),o.writeBits(1,1),o.writeBits(15,Math.floor(h/2**15)%2**15),o.writeBits(1,1),o.writeBits(15,h%2**15),o.writeBits(1,1)}const l=n.length+t.data.length;let d=0,f=!0;for(;d<l;){const h=f,p=l-d,m=f&&t.isKeyframe,g=f&&!e.firstPacketWritten,y=Math.max(0,184-p);let b;m||g?b=Math.max(2,y):b=y;let S=null;if(b>0){const _=this.adaptationFieldBuffer;b===1?_[0]=0:(_[0]=b-1,_[1]=Number(g)<<7|Number(m)<<6,_.fill(255,2,b)),S=_.subarray(0,b)}const A=Math.min(184-b,p),x=this.payloadBuffer.subarray(0,A);let T=0;if(d<n.length){const _=Math.min(n.length-d,A);x.set(n.subarray(d,d+_),0),T=_}const P=Math.max(0,d-n.length),C=P+(A-T);T<A&&x.set(t.data.subarray(P,C),T),this.writeTsPacket(e.pid,h,S,x),d+=A,f=!1}e.firstPacketWritten=!0}writeTsPacket(e,t,r,s){const n=this.continuityCounters.get(e)??0,a=s.length>0,o=r?a?3:2:a?1:0;this.packetBuffer[0]=71,this.packetView.setUint16(1,(t?16384:0)|e&8191,!1),this.packetBuffer[3]=o<<4|n&15,a&&this.continuityCounters.set(e,n+1&15);let c=4;r&&(this.packetBuffer.set(r,c),c+=r.length),this.packetBuffer.set(s,c),c+=s.length,c<ct&&this.packetBuffer.fill(255,c);const u=this.writer.getPos();this.writer.write(this.packetBuffer),this.format._options.onPacket&&this.format._options.onPacket(this.packetBuffer.slice(),u)}async onTrackClose(e){const t=await this.mutex.acquire();try{this.closedTracks.add(e);const r=this.trackDatas.find(s=>s.track===e);r&&await this.flushTimestampQueue(r,!1),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePackets()}finally{t()}}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)this.closedTracks.add(t.track),await this.flushTimestampQueue(t,!1);await this.interleavePackets(!0),e()}}const Nw=79764919,nf=new Uint32Array(256);for(let i=0;i<256;i++){let e=i<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^Nw:e<<1;nf[i]=e>>>0&4294967295}const af=i=>{let e=4294967295;for(let t=0;t<i.length;t++){const r=i[t];e=(e<<8^nf[e>>>24^r])>>>0}return e},$i=new Uint8Array(16);{const i=ie($i);$i[0]=0,i.setUint16(1,45069,!1),i.setUint16(3,1,!1),$i[5]=193,$i[6]=0,$i[7]=0,i.setUint16(8,1,!1),i.setUint16(10,57344|sf&8191,!1),i.setUint32(12,af($i.subarray(0,12)),!1)}const Vw=i=>{let e=0;for(const c of i)e+=5,c.streamType===129?e+=Vs.length:c.streamType===135&&(e+=Ws.length);const t=9+e+4,r=new Uint8Array(3+t-4),s=ie(r);r[0]=2,s.setUint16(1,45056|t&4095,!1),s.setUint16(3,1,!1),r[5]=193,r[6]=0,r[7]=0,s.setUint16(8,65535,!1),s.setUint16(10,61440,!1);let n=12;for(const c of[...i].sort((u,l)=>u.pid-l.pid))r[n++]=c.streamType,s.setUint16(n,57344|c.pid&8191,!1),n+=2,c.streamType===129?(s.setUint16(n,61440|Vs.length,!1),n+=2,r.set(Vs,n),n+=Vs.length):c.streamType===135?(s.setUint16(n,61440|Ws.length,!1),n+=2,r.set(Ws,n),n+=Ws.length):(s.setUint16(n,61440,!1),n+=2);const a=af(r),o=new Uint8Array(r.length+4);return o.set(r,0),ie(o).setUint32(r.length,a,!1),o};/*!
|
|
391
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
392
|
+
*
|
|
393
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
394
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
395
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
396
|
+
*/class Ww{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU16(e){this.helperView.setUint16(0,e,!0),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!0),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,e,!0),this.helperView.setUint32(4,Math.floor(e/2**32),!0),this.writer.write(this.helper)}writeAscii(e){this.writer.write(ge.encode(e))}}/*!
|
|
397
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
398
|
+
*
|
|
399
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
400
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
401
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
402
|
+
*/class Lw extends ti{constructor(e,t){super(e),this.headerWritten=!1,this.dataSize=0,this.sampleRate=null,this.sampleCount=0,this.riffSizePos=null,this.dataSizePos=null,this.factSampleCountPos=null,this.ds64RiffSizePos=null,this.ds64DataSizePos=null,this.ds64SampleCountPos=null,this.format=t,this.isRf64=!!t._options.large,this.appendOnly=!!t._options.appendOnly}async start(){const e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(this.appendOnly),this.riffWriter=new Ww(this.writer);const t=this.output.tracks[0];w(t==null?void 0:t.isAudioTrack()),t.metadata.decoderConfig&&(Nt({decoderConfig:t.metadata.decoderConfig},t.source._codec),this.writeHeader(t,t.metadata.decoderConfig),this.sampleRate=t.metadata.decoderConfig.sampleRate,this.headerWritten=!0)}finally{e()}}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,t,r){const s=await this.mutex.acquire();try{if(this.headerWritten||(Nt(r,e.source._codec),w(r),w(r.decoderConfig),this.writeHeader(e,r.decoderConfig),this.sampleRate=r.decoderConfig.sampleRate,this.headerWritten=!0),this.validateTimestamp(e,t.timestamp,t.type==="key"),!this.isRf64&&this.writer.getPos()+t.data.byteLength>=2**32)throw new Error("Adding more audio data would exceed the maximum RIFF size of 4 GiB. To write larger files, use RF64 by setting `large: true` in the WavOutputFormatOptions.");this.writer.write(t.data),this.dataSize+=t.data.byteLength,this.sampleCount+=Math.round(t.duration*this.sampleRate),await this.writer.flush()}finally{s()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(e,t){this.format._options.onHeader&&this.writer.startTrackingWrites();let r;const s=e.source._codec,n=Bt(s);n.dataType==="ulaw"?r=ze.MULAW:n.dataType==="alaw"?r=ze.ALAW:n.dataType==="float"?r=ze.IEEE_FLOAT:r=ze.PCM;const a=t.numberOfChannels,o=t.sampleRate,c=8*n.sampleSize,u=n.sampleSize*a,l=a>2||r===ze.PCM&&c>16,d=this.appendOnly?4294967295:0,f=()=>{this.appendOnly?(this.riffWriter.writeU32(4294967295),this.riffWriter.writeU32(2147483647)):this.riffWriter.writeU64(0)};if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.riffSizePos=this.writer.getPos(),this.riffWriter.writeU32(d)),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.ds64RiffSizePos=this.writer.getPos(),f(),this.ds64DataSizePos=this.writer.getPos(),f(),this.ds64SampleCountPos=this.writer.getPos(),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(l?40:16),this.riffWriter.writeU16(l?ze.EXTENSIBLE:r),this.riffWriter.writeU16(a),this.riffWriter.writeU32(o),this.riffWriter.writeU32(o*u),this.riffWriter.writeU16(u),this.riffWriter.writeU16(c),l){const h={1:4,2:3,3:7,4:51,5:55,6:63,7:1807,8:1599},p=new Uint8Array([0,0,16,0,128,0,0,170,0,56,155,113]);this.riffWriter.writeU16(22),this.riffWriter.writeU16(c),this.riffWriter.writeU32(h[a]??0),this.riffWriter.writeU32(r),this.writer.write(p)}if(r!==ze.PCM&&!this.appendOnly&&(this.riffWriter.writeAscii("fact"),this.riffWriter.writeU32(4),this.factSampleCountPos=this.writer.getPos(),this.riffWriter.writeU32(0)),!ds(this.output._metadataTags)){const h=this.format._options.metadataFormat??"info";h==="info"?this.writeInfoChunk(this.output._metadataTags):h==="id3"?this.writeId3Chunk(this.output._metadataTags):xe(h)}if(this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(d)),this.format._options.onHeader){const{data:h,start:p}=this.writer.stopTrackingWrites();this.format._options.onHeader(h,p)}}writeInfoChunk(e){const t=this.writer.getPos();this.riffWriter.writeAscii("LIST"),this.riffWriter.writeU32(0),this.riffWriter.writeAscii("INFO");const r=new Set,s=(o,c)=>{if(!ri(c)){K._warn(`Didn't write tag '${o}' because '${c}' is not ISO 8859-1-compatible.`);return}const u=c.length+1,l=new Uint8Array(u);for(let d=0;d<c.length;d++)l[d]=c.charCodeAt(d);this.riffWriter.writeAscii(o),this.riffWriter.writeU32(u),this.writer.write(l),u&1&&this.writer.write(new Uint8Array(1)),r.add(o)};for(const{key:o,value:c}of Nr(e))switch(o){case"title":s("INAM",c),r.add("INAM");break;case"artist":s("IART",c),r.add("IART");break;case"album":s("IPRD",c),r.add("IPRD");break;case"trackNumber":{const u=e.tracksTotal!==void 0?`${c}/${e.tracksTotal}`:c.toString();s("ITRK",u),r.add("ITRK")}break;case"genre":s("IGNR",c),r.add("IGNR");break;case"date":s("ICRD",c.toISOString().slice(0,10)),r.add("ICRD");break;case"comment":s("ICMT",c),r.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"beatsPerMinute":case"description":case"lyrics":case"images":case"creationTime":break;case"raw":break;default:xe(o)}if(e.raw)for(const o in e.raw){const c=e.raw[o];c==null||o.length!==4||r.has(o)||typeof c=="string"&&s(o,c)}const n=this.writer.getPos(),a=n-t-8;this.writer.seek(t+4),this.riffWriter.writeU32(a),this.writer.seek(n),a&1&&this.writer.write(new Uint8Array(1))}writeId3Chunk(e){const t=this.writer.getPos();this.riffWriter.writeAscii("ID3 "),this.riffWriter.writeU32(0);const s=new No(this.writer).writeId3V2Tag(e),n=this.writer.getPos();this.writer.seek(t+4),this.riffWriter.writeU32(s),this.writer.seek(n),s&1&&this.writer.write(new Uint8Array(1))}async finalize(){const e=await this.mutex.acquire();if(!this.headerWritten)throw new Error("Cannot finalize an empty WAVE file: no packets were added and the track specified no decoderConfig in its metadata, so there's no telling what the file should look like.");this.dataSize&1&&!this.appendOnly&&this.writer.write(new Uint8Array(1));const t=this.writer.getPos();this.factSampleCountPos!==null&&(this.writer.seek(this.factSampleCountPos),this.riffWriter.writeU32(Math.min(this.sampleCount,4294967295))),this.appendOnly||(this.isRf64?(w(this.ds64RiffSizePos!==null),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(t-8),w(this.ds64DataSizePos!==null),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),w(this.ds64SampleCountPos!==null),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount)):(w(this.riffSizePos!==null),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(t-8),w(this.dataSizePos!==null),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize))),e()}}/*!
|
|
403
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
404
|
+
*
|
|
405
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
406
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
407
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
408
|
+
*/const El=i=>i==="opus"?"Opus":i==="flac"?"fLaC":i==="mp3"||i==="mp4a.69"||i==="mp4a.6B"||i==="mp4a.6b"?"mp4a.40.34":i;class Hw extends ti{constructor(e,t){if(!(e._target instanceof vi))throw new TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(e),this.trackDatas=[],this.closedTracks=new Set,this.firstPacketTimestamp=null,this.isRelativeToUnixEpoch=!1,this.numWrittenMasterPlaylists=0,this.playlists=[],this.playlistDeclarations=[],this.format=t,this.targetSegmentDuration=t._options.targetDuration??2,this.singleFilePerPlaylist=t._options.singleFilePerPlaylist??!1,this.isLive=t._options.live??!1,this.maxLiveSegmentCount=t._options.maxLiveSegmentCount??1/0,this.mediaTimestampBase=t._options.mediaTimestampBase??10,this.globalTargetDuration=0,this.getPlaylistPath=t._options.getPlaylistPath??(({n:r})=>`playlist-${r}.m3u8`),this.getSegmentPath=t._options.getSegmentPath??(r=>r.isSingleFile?`segments-${r.playlist.n}${r.format.fileExtension}`:`segment-${r.playlist.n}-${r.n}${r.format.fileExtension}`),this.getInitPath=t._options.getInitPath??(r=>`init-${r.n}${r.segmentFormat.fileExtension}`)}async start(){const e=await this.mutex.acquire();try{const t=this.output.tracks.some(g=>g.metadata.isRelativeToUnixEpoch),r=this.output.tracks.some(g=>!g.metadata.isRelativeToUnixEpoch);if(t&&r)throw new Error("All tracks must agree on `relativeToUnixEpoch`: some tracks are relative to the Unix epoch and some are not.");this.isRelativeToUnixEpoch=t;const s=new Map,n=[];let a=!1,o=!1,c=!1;for(const g of this.output.tracks){g.type==="video"&&(a=!0);const y=new Map;for(const b of this.output.tracks){if(g===b||!g.canBePairedWith(b))continue;if(g.type===b.type){o||(K._warn(`Illegal pairing of two ${g.type} tracks detected, which is not possible in HLS; treating them as unpaired.`),o=!0);continue}if(g.isVideoTrack()&&g.metadata.hasOnlyKeyPackets||b.isVideoTrack()&&b.metadata.hasOnlyKeyPackets){c||(K._warn("A key-packets-only video track is pairable with another track, which is not possible in HLS; treating them as unpaired."),c=!0);continue}let S=y.get(b.source._codec);S||y.set(b.source._codec,S=[]),S.push(b)}for(const[,b]of y){const S=b.map(T=>T.id).join("-");n.find(T=>T.key===S)||n.push({name:b[0].type+"-"+(n.length+1),key:S,tracks:b,needsEmit:!1,firstNoUri:!1});let x=s.get(g);x||s.set(g,x=[]),x.push(S)}}const u=a?"video":"audio",l=[],d=[],f=[],h=g=>{const y=[];let b=0,S=0,A=!1,x=null,T=-1/0;for(const P of g)P.isVideoTrack()?(b++,A||(A=(P.metadata.rotation??0)!==0||!!P.metadata.flip||!!P.metadata.transformationMatrix)):P.isAudioTrack()&&S++,y.push(P.source._codec);for(const P of Fi(this.format._options.segmentFormat)){const C=P.getSupportedCodecs(),_=P.getSupportedTrackCounts();if(y.some(v=>!C.includes(v))||b<_.video.min||b>_.video.max||S<_.audio.min||S>_.audio.max)continue;let I=0;A&&P.supportsVideoTransformationMetadata&&I++,I>T&&(x=P,T=I)}return x};for(const g of this.output.tracks){const y=s.get(g);if(y){if(w(y.length>0),g.type!==u)continue;for(const b of y){const S=n.find(A=>A.key===b);if(w(S),y.length===1&&S.tracks.length===1){const A=s.get(S.tracks[0]);if(w(A!==void 0),A.length===1){const x=n.find(T=>T.key===A[0]);if(x.tracks.length===1&&(w(x.tracks[0]===g),!!h([g,S.tracks[0]]))){l.push({tracks:[g,S.tracks[0]],linkedGroup:null});continue}}}l.push({tracks:[g],linkedGroup:S}),S.needsEmit=!0}}else g.type==="video"?d.push(g):g.type==="audio"&&f.push(g)}const p=({metadata:g})=>{var b,S,A;let y="";return y+=`${g.languageCode??et}-`,y+=`${g.name??""}-`,y+=`${((b=g.disposition)==null?void 0:b.default)??!0}-`,y+=`${((S=g.disposition)==null?void 0:S.primary)??!1}-`,y+=`${((A=g.disposition)==null?void 0:A.forced)??!1}-`,y};if(d.length>0){const g=d.filter(S=>S.isVideoTrack()&&S.metadata.hasOnlyKeyPackets),y=d.filter(S=>!g.includes(S));if(new Set(y.map(p)).size>1){const S={key:y.map(A=>A.id).join("-"),name:"video-"+(n.length+1),tracks:y,needsEmit:!0,firstNoUri:!0};n.push(S),l.push({tracks:[y[0]],linkedGroup:S});for(const A of g)l.push({tracks:[A],linkedGroup:null})}else for(const S of d)l.push({tracks:[S],linkedGroup:null})}if(f.length>0)if(new Set(f.map(p)).size>1){const y={key:f.map(b=>b.id).join("-"),name:"audio-"+(n.length+1),tracks:f,needsEmit:!0,firstNoUri:!0};n.push(y),l.push({tracks:[f[0]],linkedGroup:y})}else for(const y of f)l.push({tracks:[y],linkedGroup:null});const m=async g=>{if(g.some(x=>this.playlists.some(T=>T.tracks.includes(x))))throw new Error("Internal error: track is already registered in a playlist.");const y=h(g);w(y);const b=this.playlists.length+1,S=await this.getPlaylistPath({n:b,tracks:g,segmentFormat:y});qw(S);const A={id:this.playlists.length+1,path:S,tracks:g,segmentFormat:y,currentSegmentStartTimestamp:null,currentSegmentStartTimestampIsFixed:!1,nextSegmentId:1,initSegment:null,writtenSegments:[],peakBitrate:null,averageBitrate:null,mediaSequence:0,done:!1,singleFile:null,mutex:new Jt};return this.playlists.push(A),A};for(const g of n)if(g.needsEmit)for(let y=0;y<g.tracks.length;y++){const b=g.tracks[y];let S=this.playlists.find(A=>A.tracks[0].id===b.id);S??(S=await m([b])),this.playlistDeclarations.push({playlist:S,groupId:g.name,noUri:g.firstNoUri&&y===0,references:[]})}for(const g of l){let y=this.playlists.find(b=>b.tracks[0].id===g.tracks[0].id);y??(y=await m(g.tracks)),this.playlistDeclarations.push({playlist:y,groupId:null,noUri:!1,references:g.linkedGroup?this.playlistDeclarations.filter(b=>b.groupId===g.linkedGroup.name):[]})}for(const g of this.output.tracks)g.isVideoTrack()&&g.metadata.decoderConfig?this.getVideoTrackData(g,g.metadata.primingPacket??null,{decoderConfig:g.metadata.decoderConfig}):g.isAudioTrack()&&g.metadata.decoderConfig&&this.getAudioTrackData(g,g.metadata.primingPacket??null,{decoderConfig:g.metadata.decoderConfig})}finally{e()}}async getMimeType(){return _r}allTracksAreKnown(e){for(const t of e.tracks)if(!this.closedTracks.has(t)&&!this.trackDatas.some(r=>r.track===t))return!1;return!0}async onTrackClose(e){const t=this.playlists.find(s=>s.tracks.includes(e));w(t);const r=await t.mutex.acquire();try{this.closedTracks.add(e),t.done||await this.advancePlaylist(t)}finally{r()}}getVideoTrackData(e,t,r){let s=this.trackDatas.find(a=>a.track===e);if(s)return s;Ds(r,e.source._codec),w(r),w(r==null?void 0:r.decoderConfig);const n=this.playlists.filter(a=>a.tracks.includes(e));return w(n.length===1),s={track:e,packets:[],playlist:n[0],info:{type:"video",decoderConfig:r.decoderConfig,primingPacket:t}},this.trackDatas.push(s),s}getAudioTrackData(e,t,r){let s=this.trackDatas.find(a=>a.track===e);if(s)return s;Nt(r,e.source._codec),w(r),w(r==null?void 0:r.decoderConfig);const n=this.playlists.filter(a=>a.tracks.includes(e));return w(n.length===1),s={track:e,packets:[],playlist:n[0],info:{type:"audio",decoderConfig:r.decoderConfig,primingPacket:t}},this.trackDatas.push(s),s}async addEncodedVideoPacket(e,t,r){const s=this.getVideoTrackData(e,t,r),n=s.playlist,a=await n.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type==="key"),s.packets.push(t),this.firstPacketTimestamp??(this.firstPacketTimestamp=t.timestamp),n.currentSegmentStartTimestamp===null?n.currentSegmentStartTimestamp=t.timestamp:n.currentSegmentStartTimestampIsFixed||(n.currentSegmentStartTimestamp=Math.min(n.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(n)}finally{a()}}async addEncodedAudioPacket(e,t,r){const s=this.getAudioTrackData(e,t,r),n=s.playlist,a=await n.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type==="key"),s.packets.push(t),this.firstPacketTimestamp??(this.firstPacketTimestamp=t.timestamp),n.currentSegmentStartTimestamp===null?n.currentSegmentStartTimestamp=t.timestamp:n.currentSegmentStartTimestampIsFixed||(n.currentSegmentStartTimestamp=Math.min(n.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(n)}finally{a()}}async addSubtitleCue(e,t,r){throw new Error("Unreachable.")}async advancePlaylist(e){var u,l,d,f,h,p;if(w(!e.done),!this.allTracksAreKnown(e))return;const t=this.trackDatas.filter(m=>e.tracks.includes(m.track)),r=t.every(m=>this.closedTracks.has(m.track));if(e.currentSegmentStartTimestamp===null){r&&await this.onPlaylistDone(e);return}const s=t.find(m=>m.info.type==="video"),n=t.find(m=>m.info.type==="audio"),a=!!s&&this.closedTracks.has(s.track),o=!!n&&this.closedTracks.has(n.track),c=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets;for(;;){const m=e.currentSegmentStartTimestamp+this.targetSegmentDuration;let g=0,y=0;if(s&&(!a||s.packets.length>0)){const O=s.packets.every(Q=>Q.timestamp<m);let U=null,L=null;if(O&&!c){if(!a)return}else for(let Q=0;Q<s.packets.length;Q++){const re=s.packets[Q];if(U!==null&&re.timestamp>m||Q>0&&re.type==="key"&&(U=re,L=Q,c))break}if(L!==null){if(g=L,n){const Q=n.packets.findIndex(re=>re.timestamp>=U.timestamp);if(Q!==-1)y=Q;else if(o)y=n.packets.length;else return}}else{if(!a)return;g=s.packets.length;const Q=Bf(s.packets,Y=>Y.timestamp),re=s.packets[Q];if(w(re),n)if(re.timestamp<m){const Y=n.packets.findIndex(se=>se.timestamp>=m);if(Y!==-1)y=Y;else if(o)y=n.packets.length;else return}else{const Y=n.packets.findIndex(se=>se.timestamp>re.timestamp);if(Y!==-1)y=Y;else if(o)y=n.packets.length;else return}}}else if(n&&(!o||n.packets.length>0))if(n.packets.every(U=>U.timestamp<m))if(o)y=n.packets.length;else return;else{const U=Br(n.packets,L=>L.timestamp<=m);y=Math.max(U,1)}if(g===0&&y===0){r&&await this.onPlaylistDone(e);return}let b=null,S,A;w(this.output._target instanceof vi);const x=this.output._target;if(this.singleFilePerPlaylist)if(e.singleFile===null){const O={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!0,playlist:Gs(e)};S=await this.getSegmentPath(O),Il(S),A=st(st(x.rootPath,e.path),S);const U=await this.output._getTarget({path:A,isRoot:!1,mimeType:e.segmentFormat.mimeType});let L=null;if(e.segmentFormat._isFragmentedIsobmff()){L={output:new _n({format:e.segmentFormat,target:U}),videoSource:null,audioSource:null,firstMoofPosition:null,currentFileSize:0},U.on("write",({end:Y})=>{L.currentFileSize=Math.max(L.currentFileSize,Y)});const Q=L.output._muxer;Q.minimumFragmentDuration=1/0;const re=Q.formatOptions.onMoof;Q.formatOptions.onMoof=(Y,se,pe)=>{L.firstMoofPosition=se,re==null||re(Y,se,pe),Q.formatOptions.onMoof=re},s&&(L.videoSource=new uo(s.track.source._codec),L.output.addVideoTrack(L.videoSource,{...s.track.metadata,decoderConfig:s.info.decoderConfig,primingPacket:s.info.primingPacket??void 0})),n&&(L.audioSource=new fo(n.track.source._codec),L.output.addAudioTrack(L.audioSource,{...n.track.metadata,decoderConfig:n.info.decoderConfig,primingPacket:n.info.primingPacket??void 0})),await L.output.start()}else U._start();e.singleFile={target:U,path:S,nextOffset:0,info:O,fragmentedIsobmffOutput:L}}else S=e.singleFile.path,A=st(st(x.rootPath,e.path),S);else b={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!1,playlist:Gs(e)},S=await this.getSegmentPath(b),Il(S),A=st(st(x.rootPath,e.path),S),e.nextSegmentId++;let T=0,P=null,C=-1/0,_=null,I=null,v=null;try{if((u=e.singleFile)!=null&&u.fragmentedIsobmffOutput)_=e.singleFile.fragmentedIsobmffOutput.output,I=e.singleFile.fragmentedIsobmffOutput.videoSource,v=e.singleFile.fragmentedIsobmffOutput.audioSource;else{if(_=new _n({format:e.segmentFormat._withoutXingHeader(),target:new vi(A,async O=>{const U={...O,isRoot:!1};if(O.isRoot)if(e.singleFile){const L=e.singleFile.target.slice(e.singleFile.nextOffset);return L.on("write",({end:Q})=>T=Math.max(T,Q)),L}else{const L=await this.output._getTarget(U);return P=L,L.on("write",({end:Q})=>T=Math.max(T,Q)),L}return this.output._getTarget(U)}),initTarget:async()=>{if(e.initSegment)return new rf;if(e.singleFile){e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:0,byteOffset:0,info:null};const O=e.singleFile.target.slice(e.singleFile.nextOffset);return O.on("write",({end:U})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,U)}),O.on("finalized",()=>{e.singleFile.nextOffset=e.initSegment.byteSize}),O}else{const O=Gs(e),U=await this.getInitPath(O);jw(U),e.initSegment={path:U,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null};const L=st(st(x.rootPath,e.path),U),Q=await this.output._getTarget({path:L,isRoot:!1,mimeType:e.segmentFormat.mimeType});return Q.on("write",({end:re})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,re)}),Q.on("finalized",()=>{var re,Y;(Y=(re=this.format._options).onInit)==null||Y.call(re,Q,O)}),Q}}}),s&&(I=new uo(s.track.source._codec),_.addVideoTrack(I,{...s.track.metadata,decoderConfig:s.info.decoderConfig,primingPacket:s.info.primingPacket??void 0,maximumPacketCount:g})),n&&(v=new fo(n.track.source._codec),_.addAudioTrack(v,{...n.track.metadata,decoderConfig:n.info.decoderConfig,primingPacket:n.info.primingPacket??void 0,maximumPacketCount:y}),!e.segmentFormat.supportsTimestampedMediaData&&y>0)){const O=this.toMediaTimestamp(n.packets[0].timestamp),U=so(O),L=new Uint8Array(Qt.length+1+8);L.set(ge.encode(Qt),0);const Q=ie(L);Q.setUint32(Qt.length+1,Math.floor(U/2**32)),Q.setUint32(Qt.length+5,U%2**32),_.setMetadataTags({raw:{PRIV:L}})}await _.start()}if(s){w(I);const O={decoderConfig:s.info.decoderConfig};for(let U=0;U<g;U++){const L=s.packets[U],Q=L.clone({timestamp:this.toMediaTimestamp(L.timestamp)});await I.add(Q,O),C=Math.max(C,L.timestamp+L.duration)}}if(n){w(v);const O={decoderConfig:n.info.decoderConfig};for(let U=0;U<y;U++){const L=n.packets[U],Q=L.clone({timestamp:this.toMediaTimestamp(L.timestamp)});await v.add(Q,O),C=Math.max(C,L.timestamp+L.duration)}}(l=e.singleFile)!=null&&l.fragmentedIsobmffOutput?(await e.singleFile.fragmentedIsobmffOutput.output._muxer.forceFragmentFinalization(),e.singleFile.fragmentedIsobmffOutput.firstMoofPosition!==null&&!e.initSegment&&(e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:e.singleFile.fragmentedIsobmffOutput.firstMoofPosition,byteOffset:0,info:null},e.singleFile.nextOffset=e.singleFile.fragmentedIsobmffOutput.firstMoofPosition),T=e.singleFile.fragmentedIsobmffOutput.currentFileSize-e.singleFile.nextOffset):await _.finalize()}catch(O){throw await(_==null?void 0:_.cancel()),O}b&&(w(P),(f=(d=this.format._options).onSegment)==null||f.call(d,P,b)),g>0&&(w(s),s.packets.splice(0,g)),y>0&&(w(n),n.packets.splice(0,y));let R=1/0;s&&s.packets.length>0&&(R=s.packets[0].timestamp),n&&n.packets.length>0&&(R=Math.min(R,n.packets[0].timestamp));const F=R<1/0?R:C;w(Number.isFinite(F));const H=F-e.currentSegmentStartTimestamp;if(w(H>=0),e.writtenSegments.push({path:S,duration:H,timestamp:e.currentSegmentStartTimestamp,byteSize:T,byteOffset:e.singleFile?e.singleFile.nextOffset:null,info:b??null}),this.globalTargetDuration=Math.max(this.globalTargetDuration,H),e.currentSegmentStartTimestamp=F,e.currentSegmentStartTimestampIsFixed=!0,e.singleFile&&(e.singleFile.nextOffset+=T),this.isLive){for(;e.writtenSegments.length>this.maxLiveSegmentCount;){const O=e.writtenSegments.shift();e.mediaSequence++,this.singleFilePerPlaylist||(w(O.info),(p=(h=this.format._options).onSegmentPopped)==null||p.call(h,O.path,O.info))}await this.writePlaylist(e),await this.tryWriteMasterPlaylist()}}}toMediaTimestamp(e){return w(this.firstPacketTimestamp!==null),e-this.firstPacketTimestamp+this.mediaTimestampBase}async onPlaylistDone(e){var t,r;w(!e.done),e.done=!0,e.singleFile&&(e.singleFile.fragmentedIsobmffOutput?await e.singleFile.fragmentedIsobmffOutput.output.finalize():(await e.singleFile.target._flush(),await e.singleFile.target._finalize()),(r=(t=this.format._options).onSegment)==null||r.call(t,e.singleFile.target,e.singleFile.info)),this.isLive&&(await this.writePlaylist(e),e.writtenSegments.length===0&&await this.tryWriteMasterPlaylist())}updatePlaylistBitrates(e,t){const r=e.writtenSegments;let s=0,n=0,a=0;for(let c=0;c<r.length;c++){a+=r[c].duration;let u=0,l=0;for(let d=c;d<r.length&&(u+=r[d].byteSize,l+=r[d].duration,l>=.5*t&&l<=1.5*t&&(s=Math.max(s,8*u/l)),!(l>1.5*t));d++);}if(s===0)for(const c of r){const u=c.duration||1;s=Math.max(s,8*c.byteSize/u)}for(const c of r)n+=8*c.byteSize;let o=n/(a||1);if(r.length===0)for(const c of e.tracks){const u=this.trackDatas.find(d=>d.track===c);let l=c.source._nominalBitrate??c.metadata.bitrate??0;if(o+=c.source._nominalBitrate??c.metadata.averageBitrate??0,l===0){const d=new Me("medium");if(c.isVideoTrack()){const f=u==null?void 0:u.info.decoderConfig;l=d._toVideoBitrate(c.source._codec,(f==null?void 0:f.codedWidth)??1920,(f==null?void 0:f.codedHeight)??1080)}else if(c.isAudioTrack()){const f=u==null?void 0:u.info.decoderConfig;l=d._toAudioBitrate(c.source._codec,(f==null?void 0:f.numberOfChannels)??2)??0}}s+=l}e.peakBitrate=s,e.averageBitrate=o}async writePlaylist(e){var d,f;w(this.output._target instanceof vi);const t=this.output._target,r=Math.max(Math.ceil(+(this.isLive?this.targetSegmentDuration:this.globalTargetDuration).toFixed(12)),1);this.updatePlaylistBitrates(e,r);let s=!1;for(const h of e.writtenSegments)s||(s=h.byteOffset!==null);const n=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets;let a=3;(n||s)&&(a=4),e.initSegment&&(a=5),e.initSegment&&!n&&(a=6);const o=st(t.rootPath,e.path),c=`#EXTM3U
|
|
409
|
+
#EXT-X-VERSION:${a}
|
|
410
|
+
`+(this.isLive?"":`#EXT-X-PLAYLIST-TYPE:VOD
|
|
411
|
+
`)+`#EXT-X-TARGETDURATION:${r}
|
|
412
|
+
`+(Number.isFinite(this.maxLiveSegmentCount)?`#EXT-X-MEDIA-SEQUENCE:${e.mediaSequence}
|
|
413
|
+
`:"")+`#EXT-X-INDEPENDENT-SEGMENTS
|
|
414
|
+
`+(n?`#EXT-X-I-FRAMES-ONLY
|
|
415
|
+
`:"")+(e.initSegment?`#EXT-X-MAP:URI="${e.initSegment.path}"`+(e.initSegment.byteOffset!==null?`,BYTERANGE="${e.initSegment.byteSize}@${e.initSegment.byteOffset}"`:"")+`
|
|
416
|
+
`:"")+`
|
|
417
|
+
`+e.writtenSegments.map(h=>`#EXTINF:${+h.duration.toFixed(12)},
|
|
418
|
+
`+(this.isRelativeToUnixEpoch?`#EXT-X-PROGRAM-DATE-TIME:${new Date(1e3*h.timestamp).toISOString()}
|
|
419
|
+
`:"")+(h.byteOffset!==null?`#EXT-X-BYTERANGE:${h.byteSize}@${h.byteOffset}
|
|
420
|
+
`:"")+`${h.path}
|
|
421
|
+
`).join("")+(e.done?(e.writtenSegments.length>0?`
|
|
422
|
+
`:"")+`#EXT-X-ENDLIST
|
|
423
|
+
`:"");(f=(d=this.format._options).onPlaylist)==null||f.call(d,c,Gs(e));const u=await this.output._getTarget({path:o,isRoot:!1,mimeType:_r}),l=new Ss(u,!0);l.start(),l.write(ge.encode(c)),await l.flush(),await l.finalize()}async writeMasterPlaylist(){var u,l;w(this.output._target instanceof vi);const e=this.output._target;let t=`#EXTM3U
|
|
424
|
+
`,r=!1,s=null,n=0,a=!1;const o=new Set;for(const d of this.playlistDeclarations)if(d.groupId===null){const f=d.playlist.tracks[0].isVideoTrack()&&d.playlist.tracks[0].metadata.hasOnlyKeyPackets,h=[];for(const T of d.playlist.tracks){const P=this.trackDatas.find(_=>_.track===T),C=(P==null?void 0:P.info.decoderConfig.codec)??T.source._codec;h.push(El(C))}let p=0,m=0;const g=d.references.some(T=>T.playlist===d.playlist);for(const T of d.references){for(const P of T.playlist.tracks){const C=this.trackDatas.find(I=>I.track===P),_=(C==null?void 0:C.info.decoderConfig.codec)??P.source._codec;h.push(El(_))}w(T.playlist.peakBitrate!==null),p=Math.max(p,T.playlist.peakBitrate),m=Math.max(m,T.playlist.averageBitrate??0)}w(d.playlist.peakBitrate!==null);const y=g?0:d.playlist.peakBitrate,b=g?0:d.playlist.averageBitrate??0,S=y+p,A=b+m;r||(t+=`
|
|
425
|
+
`,r=!0),f?t+="#EXT-X-I-FRAME-STREAM-INF:":t+="#EXT-X-STREAM-INF:",t+=`BANDWIDTH=${Math.ceil(S)}`,A>0&&(t+=`,AVERAGE-BANDWIDTH=${Math.ceil(A)}`),t+=`,CODECS="${[...new Set(h)].join(",")}"`;const x=d.playlist.tracks.find(T=>T.isVideoTrack());if(x!=null&&x.isVideoTrack()){const T=this.trackDatas.find(C=>C.track===x),P=T==null?void 0:T.info.decoderConfig;if(P){w(P.codedWidth!==void 0),w(P.codedHeight!==void 0);let C=P.codedWidth,_=P.codedHeight;if(P.displayAspectWidth!==void 0&&P.displayAspectHeight!==void 0){const I=P.displayAspectWidth*P.codedHeight,v=P.displayAspectHeight*P.codedWidth;I>v?C=Math.round(C*I/v):_=Math.round(_*v/I)}x.metadata.rotation!==void 0&&x.metadata.rotation%180===90&&([C,_]=[_,C]),t+=`,RESOLUTION=${C}x${_}`}!f&&x.metadata.frameRate!==void 0&&(t+=`,FRAME-RATE=${+x.metadata.frameRate.toFixed(3)}`)}if(!f){const T=new Map;for(const P of d.references){w(P.groupId!==null);const C=P.playlist.tracks[0].type;T.set(C,P.groupId)}for(const[P,C]of T)t+=`,${P.toUpperCase()}="${C}"`}f?(t+=`,URI="${d.playlist.path}"`,t+=`
|
|
426
|
+
`):(t+=`
|
|
427
|
+
`,t+=`${d.playlist.path}
|
|
428
|
+
`)}else{w(d.playlist.tracks.length===1);const f=d.playlist.tracks[0],h=f.type;let p=f.metadata.name??null;const m=f.metadata.languageCode,g=f.metadata.disposition;(s===null||d.groupId!==s)&&(n=0,t+=`
|
|
429
|
+
`,a=!1,o.clear()),s=d.groupId,n++,t+=`#EXT-X-MEDIA:TYPE=${h.toUpperCase()},GROUP-ID="${d.groupId}"`,p!==null&&/[\n\r"]/.test(p)&&(K._warn("Dropping track name since it includes a line feed, carriage return, or double quote character, which are not allowed in HLS playlist attributes."),p=null),p??(p=`${m??d.groupId}-${n}`);let y=p;for(let x=2;o.has(y);x++)y=`${p} (${x})`;o.add(y),t+=`,NAME="${y}"`,m!==void 0&&(t+=`,LANGUAGE="${m}"`);const b=(g==null?void 0:g.primary)??!1,S=(g==null?void 0:g.default)??!0,A=(g==null?void 0:g.forced)??!1;if(b&&!a&&(t+=",DEFAULT=YES",a=!0),(b||S)&&(t+=",AUTOSELECT=YES"),A&&h==="subtitle"&&(t+=",FORCED=YES"),h==="audio"){const x=this.trackDatas.find(P=>P.track===f),T=x==null?void 0:x.info.decoderConfig;T&&(t+=`,CHANNELS="${T.numberOfChannels}"`)}d.noUri||(t+=`,URI="${d.playlist.path}"`),t+=`
|
|
430
|
+
`}(l=(u=this.format._options).onMaster)==null||l.call(u,t);const c=await this.mutex.acquire();try{let d;if(this.numWrittenMasterPlaylists===0)d=await this.output._getRootWriter(!0);else{const f=await this.output._getTarget({path:e.rootPath,isRoot:!0,mimeType:_r});d=new Ss(f,!0),d.start()}d.write(ge.encode(t)),await d.flush(),await d.finalize(),this.numWrittenMasterPlaylists++}finally{c()}}async tryWriteMasterPlaylist(){w(this.isLive);for(const e of this.playlists)if(e.writtenSegments.length===0&&!e.done)return;await this.writeMasterPlaylist()}async finalize(){(await Promise.all(this.playlists.map(t=>t.mutex.acquire()))).forEach(t=>t());for(const t of this.output.tracks)this.closedTracks.add(t);await Promise.all(this.playlists.map(t=>t.done?Promise.resolve():this.advancePlaylist(t))),this.isLive||(await Promise.all(this.playlists.map(t=>this.writePlaylist(t))),await this.writeMasterPlaylist())}}const qw=i=>{if(typeof i!="string")throw new TypeError("options.getPlaylistPath must return or resolve to a string");if(/[\n\r"]/.test(i))throw new TypeError("Playlist paths cannot contain line feed, carriage return, or double quote characters.")},Il=i=>{if(typeof i!="string")throw new TypeError("options.getSegmentPath must return or resolve to a string");if(/[\n\r"]/.test(i))throw new TypeError("Segment paths cannot contain line feed or carriage return characters.")},jw=i=>{if(typeof i!="string")throw new TypeError("options.getInitPath must return or resolve to a string");if(/[\n\r"]/.test(i))throw new TypeError("Init paths cannot contain line feed, carriage return, or double quote characters.")},Gs=i=>({n:i.id,tracks:i.tracks,segmentFormat:i.segmentFormat});/*!
|
|
431
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
432
|
+
*
|
|
433
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
434
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
435
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
436
|
+
*/class kt{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}get requiresMaximumPacketCount(){return!1}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Oe.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Ke.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>vt.includes(e))}_codecUnsupportedHint(e){return""}_isFragmentedIsobmff(){return!1}_withoutXingHeader(){return this}}class Jo extends kt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!ut(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:0,max:4294967295}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"full"}get requiresMaximumPacketCount(){return this._options.fastStart==="reserve"}_createMuxer(e){return new Cw(e,this)}_isFragmentedIsobmff(){return this._options.fastStart==="fragmented"}}class Kw extends Jo{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Oe,...Ji,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...vt]}_codecUnsupportedHint(e){return new of().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class vl extends Jo{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Oe,...Ji,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...vt]}}class of extends Jo{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Oe,...Ke]}_codecUnsupportedHint(e){return new Kw().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}class Bl extends kt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(e.minimumClusterDuration!==void 0&&(!ut(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(e.onEbmlHeader!==void 0&&typeof e.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(e.onSegmentHeader!==void 0&&typeof e.onSegmentHeader!="function")throw new TypeError("options.onSegmentHeader, when provided, must be a function.");if(e.onCluster!==void 0&&typeof e.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Bw(e,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:0,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...Oe,...Ji,...je.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...vt]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}}class mr extends Bl{constructor(e){super(e)}getSupportedCodecs(){return[...Oe.filter(e=>["vp8","vp9","av1"].includes(e)),...Ke.filter(e=>["opus","vorbis"].includes(e)),...vt]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new Bl().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}}class cf extends kt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.xingHeader!==void 0&&typeof e.xingHeader!="boolean")throw new TypeError("options.xingHeader, when provided, must be a boolean.");if(e.onXingFrame!==void 0&&typeof e.onXingFrame!="function")throw new TypeError("options.onXingFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Rw(e,this)}get _name(){return"MP3"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".mp3"}get mimeType(){return"audio/mpeg"}getSupportedCodecs(){return["mp3"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}_withoutXingHeader(){return new cf({...this._options,xingHeader:!1})}}class F0 extends kt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(e.large!==void 0&&typeof e.large!="boolean")throw new TypeError("options.large, when provided, must be a boolean.");if(e.metadataFormat!==void 0&&!["info","id3"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'info' or 'id3'.");if(e.onHeader!==void 0&&typeof e.onHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Lw(e,this)}get _name(){return"WAVE"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".wav"}get mimeType(){return"audio/wav"}getSupportedCodecs(){return[...je.filter(e=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-f64","pcm-u8","ulaw","alaw"].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}}class R0 extends kt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.maximumPageDuration!==void 0&&(!ut(e.maximumPageDuration)||e.maximumPageDuration<=0))throw new TypeError("options.maximumPageDuration, when provided, must be a positive number.");if(e.onPage!==void 0&&typeof e.onPage!="function")throw new TypeError("options.onPage, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Dw(e,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:4294967296},subtitle:{min:0,max:0},total:{min:0,max:4294967296}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...Ke.filter(e=>["vorbis","opus"].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}}class M0 extends kt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.onFrame!==void 0&&typeof e.onFrame!="function")throw new TypeError("options.onFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new ag(e,this)}get _name(){return"ADTS"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".aac"}get mimeType(){return"audio/aac"}getSupportedCodecs(){return["aac"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}}class D0 extends kt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(e.onFrame!==void 0&&typeof e.onFrame!="function")throw new TypeError("options.onFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new lg(e,this)}get _name(){return"FLAC"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".flac"}get mimeType(){return"audio/flac"}getSupportedCodecs(){return["flac"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}}class z0 extends kt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.timestampOffset!==void 0&&(!Number.isFinite(e.timestampOffset)||e.timestampOffset<0))throw new TypeError("options.timestampOffset, when provided, must be a non-negative number.");if(e.onPacket!==void 0&&typeof e.onPacket!="function")throw new TypeError("options.onPacket, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Uw(e,this)}get _name(){return"MPEG-TS"}getSupportedTrackCounts(){return{video:{min:0,max:16},audio:{min:0,max:32},subtitle:{min:0,max:0},total:{min:0,max:48}}}get fileExtension(){return".ts"}get mimeType(){return"video/MP2T"}getSupportedCodecs(){return[...Oe.filter(e=>["avc","hevc"].includes(e)),...Ke.filter(e=>["aac","mp3","ac3","eac3","dts"].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}}class O0 extends kt{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.segmentFormat instanceof kt)&&(!Array.isArray(e.segmentFormat)||e.segmentFormat.length===0||!e.segmentFormat.every(t=>t instanceof kt)))throw new TypeError("options.segmentFormat must be an OutputFormat or a non-empty array of OutputFormat instances.");if(e.targetDuration!==void 0&&(!ut(e.targetDuration)||e.targetDuration<=0))throw new TypeError("options.targetDuration, when provided, must be a positive number.");if(e.singleFilePerPlaylist!==void 0&&typeof e.singleFilePerPlaylist!="boolean")throw new TypeError("options.singleFilePerPlaylist, when provided, must be a boolean.");if(e.live!==void 0&&typeof e.live!="boolean")throw new TypeError("options.live, when provided, must be a boolean.");if(e.live&&e.targetDuration===1/0)throw new TypeError("options.targetDuration must be finite in live mode.");if(e.maxLiveSegmentCount!==void 0&&(!ut(e.maxLiveSegmentCount)||e.maxLiveSegmentCount<1||Number.isFinite(e.maxLiveSegmentCount)&&!Number.isInteger(e.maxLiveSegmentCount)))throw new TypeError("options.maxLiveSegmentCount, when provided, must be a positive integer or Infinity.");if(e.mediaTimestampBase!==void 0&&!Number.isFinite(e.mediaTimestampBase))throw new TypeError("options.mediaTimestampBase, when provided, must be a finite number.");if(e.getPlaylistPath!==void 0&&typeof e.getPlaylistPath!="function")throw new TypeError("options.getPlaylistPath, when provided, must be a function.");if(e.getSegmentPath!==void 0&&typeof e.getSegmentPath!="function")throw new TypeError("options.getSegmentPath, when provided, must be a function.");if(e.getInitPath!==void 0&&typeof e.getInitPath!="function")throw new TypeError("options.getInitPath, when provided, must be a function.");if(e.onMaster!==void 0&&typeof e.onMaster!="function")throw new TypeError("options.onMaster, when provided, must be a function.");if(e.onPlaylist!==void 0&&typeof e.onPlaylist!="function")throw new TypeError("options.onPlaylist, when provided, must be a function.");if(e.onSegment!==void 0&&typeof e.onSegment!="function")throw new TypeError("options.onSegment, when provided, must be a function.");if(e.onInit!==void 0&&typeof e.onInit!="function")throw new TypeError("options.onInit, when provided, must be a function.");if(e.onSegmentPopped!==void 0&&typeof e.onSegmentPopped!="function")throw new TypeError("options.onSegmentPopped, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Hw(e,this)}get _name(){return"HTTP Live Streaming (HLS)"}get fileExtension(){return".m3u8"}get mimeType(){return _r}getSupportedCodecs(){const e=new Set(Fi(this._options.segmentFormat).flatMap(t=>t.getSupportedCodecs()));for(const t of An)e.delete(t);for(const t of vt)e.delete(t);return[...e]}getSupportedTrackCounts(){let e=!1,t=!1,r=!1;for(const s of Fi(this._options.segmentFormat)){const n=s.getSupportedTrackCounts();e||(e=n.video.max>0),t||(t=n.audio.max>0),r||(r=n.subtitle.max>0)}return{video:{min:0,max:e?1/0:0},audio:{min:0,max:t?1/0:0},subtitle:{min:0,max:0},total:{min:0,max:1/0}}}get supportsVideoTransformationMetadata(){return Fi(this._options.segmentFormat).some(e=>e.supportsVideoTransformationMetadata)}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){const e=Fi(this._options.segmentFormat);return e.some(t=>t.negativeTimestampSupport==="none")?"none":e.some(t=>t.negativeTimestampSupport==="prefer-non-negative")?"prefer-non-negative":e.some(t=>t.negativeTimestampSupport==="full")?"full":null}_codecUnsupportedHint(e){return An.includes(e)?"":" Using different segment formats may grant support for this codec."}}class $w extends kt{_createMuxer(e){return new ng(e)}get _name(){return"Null"}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:0,max:1/0}}}get fileExtension(){return""}get mimeType(){return"application/x-black-hole"}getSupportedCodecs(){return[...Oe,...Ke,...vt]}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"full"}}/*!
|
|
437
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
438
|
+
*
|
|
439
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
440
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
441
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
442
|
+
*/const Fl=["video","audio","subtitle"];class zs{constructor(e,t,r,s,n){this.id=e,this.output=t,this.type=r,this.source=s,this.metadata=n}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(e){if(!(e instanceof zs))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;const t=Fi(this.metadata.group),r=Fi(e.metadata.group);for(const s of t)if(this.type!==e.type&&r.some(o=>s===o)||r.some(o=>s._pairedGroups.has(o)))return!0;return!1}}class Qw extends zs{constructor(e,t,r,s){super(e,t,"video",r,s)}}class Gw extends zs{constructor(e,t,r,s){super(e,t,"audio",r,s)}}class Xw extends zs{constructor(e,t,r,s){super(e,t,"subtitle",r,s)}}class Wt{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof Wt))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}}const xa=i=>{if(!i||typeof i!="object")throw new TypeError("metadata must be an object.");if(i.languageCode!==void 0&&!us(i.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(i.name!==void 0&&typeof i.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(i.disposition!==void 0&&Uf(i.disposition),i.maximumPacketCount!==void 0&&(!Number.isInteger(i.maximumPacketCount)||i.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(i.bitrate!==void 0&&(!Number.isFinite(i.bitrate)||i.bitrate<0))throw new TypeError("metadata.bitrate, when provided, must be a non-negative number.");if(i.averageBitrate!==void 0&&(!Number.isFinite(i.averageBitrate)||i.averageBitrate<0))throw new TypeError("metadata.averageBitrate, when provided, must be a non-negative number.");if(i.group!==void 0&&!(i.group instanceof Wt)&&(!Array.isArray(i.group)||i.group.some(e=>!(e instanceof Wt))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")};class _n extends Ps{get target(){const e="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(e);const t=this._getRootTarget();if(D(t))throw t.catch(()=>{}),new TypeError(e);return t}constructor(e){if(super(),this.state="pending",this.defaultTrackGroup=new Wt,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._targetsClosed=!1,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._canceled=Ae(),this._finalizePromise=null,this._mutex=new Jt,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof kt))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof ht||e.target instanceof vi))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof ht&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof ht)&&typeof e.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof ht&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){w(this._target instanceof vi);const t=this._target.getTarget(e),r=s=>{if(!(s instanceof ht))throw new TypeError("getTarget must return a Target.");return s};return D(t)?t.then(r):r(t)}async _getTarget(e){w(this._target instanceof vi);const t=await this._getTargetValidated(e);if(this._emit("target",{target:t,request:e,isRoot:e.isRoot}),this._targetsClosed)throw await t._close(),new Error(this.state==="canceled"?"Output has been canceled.":"Output has already been finalized.");return this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(w(this._initTarget!==null),this._initTarget instanceof ht)return this._initTarget;const e=await this._initTarget();if(!(e instanceof ht))throw new TypeError("initTarget must return or resolve to a Target.");return this._targetsClosed?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof ht)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;const e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),r=s=>(this._targetsClosed?s._close().catch(()=>{}):this._rememberTarget(s),this._emit("target",{target:s,request:e,isRoot:!0}),this._rootTarget=s,s);return D(t)?this._rootTargetPromise=t.then(r):r(t)}_getRootWriter(e){return this._rootWriterPromise??(this._rootWriterPromise=(async()=>{const t=await this._getRootTarget(),r=new Ss(t,typeof e=="boolean"?e:e(t));return r.start(),r})())}addVideoTrack(e,t={}){if(!(e instanceof Rs))throw new TypeError("source must be a VideoSource.");if(xa(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("metadata.flip, when provided, must be a boolean.");if(t.transformationMatrix!==void 0&&(!Array.isArray(t.transformationMatrix)||t.transformationMatrix.length!==9||!t.transformationMatrix.every(s=>Number.isFinite(s))))throw new TypeError("metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.");if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);if(t.hasOnlyKeyPackets!==void 0&&typeof t.hasOnlyKeyPackets!="boolean")throw new TypeError("metadata.hasOnlyKeyPackets, when provided, must be a boolean.");if(t.canBeTransparent!==void 0&&typeof t.canBeTransparent!="boolean")throw new TypeError("metadata.canBeTransparent, when provided, must be a boolean.");if(t.decoderConfig!==void 0&&Ds({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof Ce))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(t.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}const r={...t};return r.group??(r.group=this.defaultTrackGroup),this._addTrack(new Qw(this.tracks.length+1,this,e,r))}addAudioTrack(e,t={}){if(!(e instanceof Ms))throw new TypeError("source must be an AudioSource.");if(xa(t),t.decoderConfig!==void 0&&Nt({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof Ce))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(t.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}const r={...t};return r.group??(r.group=this.defaultTrackGroup),this._addTrack(new Gw(this.tracks.length+1,this,e,r))}addSubtitleTrack(e,t={}){if(!(e instanceof Dd))throw new TypeError("source must be a SubtitleSource.");xa(t);const r={...t};return r.group??(r.group=this.defaultTrackGroup),this._addTrack(new Xw(this.tracks.length+1,this,e,r))}setMetadataTags(e){if(Ra(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(e.source._connectedTrack)throw new Error("Source is already used for a track.");const t=this.format.getSupportedTrackCounts(),r=this.tracks.reduce((a,o)=>a+(o.type===e.type?1:0),0),s=t[e.type].max;if(r===s)throw new Error(s===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${s} ${e.type} track${s===1?"":"s"}.`);const n=t.total.max;if(this.tracks.length===n)throw new Error(`${this.format._name} does not support more than ${n} track${n===1?"":"s"} in total.`);if(e.isVideoTrack()){const a=this.format.getSupportedVideoCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){const a=this.format.getSupportedAudioCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){const a=this.format.getSupportedSubtitleCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){const e=this.format.getSupportedTrackCounts();for(const r of Fl){const s=this.tracks.reduce((a,o)=>a+(o.type===r?1:0),0),n=e[r].min;if(s<n)return!1}const t=e.total.min;return!(this.tracks.length<t)}async start(){const e=this.format.getSupportedTrackCounts();for(const r of Fl){const s=this.tracks.reduce((a,o)=>a+(o.type===r?1:0),0),n=e[r].min;if(s<n)throw new Error(n===e[r].max?`${this.format._name} requires exactly ${n} ${r} track${n===1?"":"s"}.`:`${this.format._name} requires at least ${n} ${r} track${n===1?"":"s"}.`)}const t=e.total.min;if(this.tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?"":"s"}.`:`${this.format._name} requires at least ${t} track${t===1?"":"s"}.`);if(this._cancelPromise||this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(K._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";const r=this._mutex.acquire();try{try{await this._muxer.start();const s=this.tracks.map(n=>n.source._start());await Promise.all(s)}finally{(await r)()}}catch(s){throw await this.cancel(),s}})()}getMimeType(){return Promise.race([this._muxer.getMimeType(),this._canceled.promise.then(()=>{throw new Error("Output has been canceled.")})])}async cancel(){if(this._cancelPromise||this.state==="canceled")return this._cancelPromise??void 0;if(this.state==="finalized"){K._warn("Output has already been finalized.");return}else if(this._finalizePromise)return this._finalizePromise.catch(()=>{});return this._cancelPromise=(async()=>{const e=await this._mutex.acquire();try{this.state="canceled",this._canceled.resolve();const t=this.tracks.map(r=>r.source._flushOrWaitForOngoingClose(!0).catch(()=>{}));await Promise.all(t),this._targetsClosed=!0,await Promise.all([...this._unfinalizedTargets].map(r=>r._close().catch(()=>{}))),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this._cancelPromise||this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(K._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{const e=await this._mutex.acquire();try{this.state="finalizing";const t=this.tracks.map(r=>r.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(t),await this._muxer.finalize(),this._rootWriterPromise){const r=await this._rootWriterPromise;r.finalized||(await r.flush(),await r.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}catch(t){throw this.state="canceled",this._canceled.resolve(),t}finally{this._targetsClosed=!0,await Promise.all([...this._unfinalizedTargets].map(t=>t._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}}/*!
|
|
443
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
444
|
+
*
|
|
445
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
446
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
447
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
448
|
+
*/var Jr=function(i,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,s;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],t&&(s=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");s&&(r=function(){try{s.call(this)}catch(n){return Promise.reject(n)}}),i.stack.push({value:e,dispose:r,async:t})}else t&&i.stack.push({async:!0});return e},Xs=(function(i){return function(e){function t(a){e.error=e.hasError?new i(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var r,s=0;function n(){for(;r=e.stack.pop();)try{if(!r.async&&s===1)return s=0,e.stack.push(r),Promise.resolve().then(n);if(r.dispose){var a=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(a).then(n,function(o){return t(o),n()})}else s|=1}catch(o){t(o)}if(s===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return n()}})(typeof SuppressedError=="function"?SuppressedError:function(i,e,t){var r=new Error(t);return r.name="SuppressedError",r.error=i,r.suppressed=e,r});const Ys=i=>{if(!i||typeof i!="object")throw new TypeError("options.video, when provided, must be an object.");if((i==null?void 0:i.discard)!==void 0&&typeof i.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if((i==null?void 0:i.forceTranscode)!==void 0&&typeof i.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if((i==null?void 0:i.codec)!==void 0&&!Oe.includes(i.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${Oe.join(", ")}.`);const e=i==null?void 0:i.bitrate;if((i==null?void 0:i.quality)!==void 0&&!(i.quality instanceof Me))throw new TypeError("options.video.quality, when provided, must be a Quality.");if((i==null?void 0:i.quality)!==void 0&&e!==void 0)throw new TypeError("options.video.quality and options.video.bitrate cannot both be provided.");if(e!==void 0&&!(e instanceof Me)&&(!Number.isInteger(e)||e<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if((i==null?void 0:i.width)!==void 0&&(!Number.isInteger(i.width)||i.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if((i==null?void 0:i.height)!==void 0&&(!Number.isInteger(i.height)||i.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if((i==null?void 0:i.fit)!==void 0&&!["fill","contain","cover"].includes(i.fit))throw new TypeError("options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.");if((i==null?void 0:i.width)!==void 0&&i.height!==void 0&&i.fit===void 0)throw new TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if((i==null?void 0:i.rotate)!==void 0&&![0,90,180,270].includes(i.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if((i==null?void 0:i.flip)!==void 0&&typeof i.flip!="boolean")throw new TypeError("options.video.flip, when provided, must be a boolean.");if((i==null?void 0:i.allowTransformationMetadata)!==void 0&&typeof i.allowTransformationMetadata!="boolean")throw new TypeError("options.video.allowTransformationMetadata, when provided, must be a boolean.");if((i==null?void 0:i.allowRotationMetadata)!==void 0&&typeof i.allowRotationMetadata!="boolean")throw new TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if((i==null?void 0:i.crop)!==void 0&&ps(i.crop,"options.video."),(i==null?void 0:i.frameRate)!==void 0&&(!Number.isFinite(i.frameRate)||i.frameRate<=0))throw new TypeError("options.video.frameRate, when provided, must be a finite positive number.");if((i==null?void 0:i.alpha)!==void 0&&!["discard","keep"].includes(i.alpha))throw new TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if((i==null?void 0:i.keyFrameInterval)!==void 0&&(!Number.isFinite(i.keyFrameInterval)||i.keyFrameInterval<0))throw new TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if((i==null?void 0:i.process)!==void 0&&typeof i.process!="function")throw new TypeError("options.video.process, when provided, must be a function.");if((i==null?void 0:i.processedWidth)!==void 0&&(!Number.isInteger(i.processedWidth)||i.processedWidth<=0))throw new TypeError("options.video.processedWidth, when provided, must be a positive integer.");if((i==null?void 0:i.processedHeight)!==void 0&&(!Number.isInteger(i.processedHeight)||i.processedHeight<=0))throw new TypeError("options.video.processedHeight, when provided, must be a positive integer.");if((i==null?void 0:i.hardwareAcceleration)!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(i.hardwareAcceleration))throw new TypeError("options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if((i==null?void 0:i.group)!==void 0&&!(i.group instanceof Wt||Array.isArray(i.group)&&i.group.every(t=>t instanceof Wt)))throw new TypeError("options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.");if((i==null?void 0:i.maximumPacketCount)!==void 0&&(!Number.isInteger(i.maximumPacketCount)||i.maximumPacketCount<0))throw new TypeError("options.video.maximumPacketCount, when provided, must be a non-negative integer.")},Zs=i=>{if(!i||typeof i!="object")throw new TypeError("options.audio, when provided, must be an object.");if((i==null?void 0:i.discard)!==void 0&&typeof i.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if((i==null?void 0:i.forceTranscode)!==void 0&&typeof i.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if((i==null?void 0:i.codec)!==void 0&&!Ke.includes(i.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${Ke.join(", ")}.`);const e=i==null?void 0:i.bitrate;if((i==null?void 0:i.quality)!==void 0&&!(i.quality instanceof Me))throw new TypeError("options.audio.quality, when provided, must be a Quality.");if((i==null?void 0:i.quality)!==void 0&&e!==void 0)throw new TypeError("options.audio.quality and options.audio.bitrate cannot both be provided.");if(e!==void 0&&!(e instanceof Me)&&(!Number.isInteger(e)||e<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if((i==null?void 0:i.numberOfChannels)!==void 0&&(!Number.isInteger(i.numberOfChannels)||i.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if((i==null?void 0:i.sampleRate)!==void 0&&(!Number.isInteger(i.sampleRate)||i.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if((i==null?void 0:i.sampleFormat)!==void 0&&!["u8","s16","s32","f32"].includes(i.sampleFormat))throw new TypeError("options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if((i==null?void 0:i.process)!==void 0&&typeof i.process!="function")throw new TypeError("options.audio.process, when provided, must be a function.");if((i==null?void 0:i.processedNumberOfChannels)!==void 0&&(!Number.isInteger(i.processedNumberOfChannels)||i.processedNumberOfChannels<=0))throw new TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if((i==null?void 0:i.processedSampleRate)!==void 0&&(!Number.isInteger(i.processedSampleRate)||i.processedSampleRate<=0))throw new TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.");if((i==null?void 0:i.group)!==void 0&&!(i.group instanceof Wt||Array.isArray(i.group)&&i.group.every(t=>t instanceof Wt)))throw new TypeError("options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.");if((i==null?void 0:i.maximumPacketCount)!==void 0&&(!Number.isInteger(i.maximumPacketCount)||i.maximumPacketCount<0))throw new TypeError("options.audio.maximumPacketCount, when provided, must be a non-negative integer.")},Pa=2,Ca=48e3,Yw=256;class lf{get state(){return this._state}static async init(e){const t=new lf(e);return await t._init(),t}constructor(e){var r,s,n,a,o,c,u;if(this._state="idle",this._timestampOffset=0,this._timestampOffsetAdjusted=!1,this._copyTimestampPossible=new Map,this._copyStartPackets=new Map,this._trackDurations=new Map,this._nextOutputTrackId=0,this._outputTrackIds=[],this._outputOwnTrackGroups=[],this._trackPumps=[],this._composable=!1,this._executed=!1,this._executionUntil=1/0,this._pauseRequested=!1,this._synchronizer=new Zw(this),this._totalDuration=null,this._maxTimestamps=new Map,this.onProgress=void 0,this._computeProgress=!1,this._lastProgress=0,this._lastProcessedTime=0,this.isValid=!1,this.utilizedTracks=[],this.discardedTracks=[],!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.input instanceof qn))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof _n))throw new TypeError("options.output must be an Output.");if(e.tracks!==void 0&&e.tracks!=="all"&&e.tracks!=="primary")throw new TypeError("options.tracks, when provided, must be either 'all' or 'primary'.");if(e.composable!==void 0&&typeof e.composable!="boolean")throw new TypeError("options.composable, when provided, must be a boolean.");if(e.copy!==void 0&&e.copy!==!1){if(!e.copy||typeof e.copy!="object")throw new TypeError("options.copy, when provided, must be an object or false.");if(e.copy.mode!==void 0&&!["forced","preferred"].includes(e.copy.mode))throw new TypeError("options.copy.mode, when provided, must be 'forced' or 'preferred'.");if(e.copy.shiftTolerance!==void 0&&(!ut(e.copy.shiftTolerance)||e.copy.shiftTolerance<0))throw new TypeError("options.copy.shiftTolerance, when provided, must be a non-negative number.");if(e.copy.boundaryPolicy!==void 0&&!["expand","shrink"].includes(e.copy.boundaryPolicy))throw new TypeError("options.copy.boundaryPolicy, when provided, must be 'expand' or 'shrink'.");if(e.copy.boundaryTolerance!==void 0&&(!ut(e.copy.boundaryTolerance)||e.copy.boundaryTolerance<0))throw new TypeError("options.copy.boundaryTolerance, when provided, must be a non-negative number.")}const t=e.composable??!1;if(t){if(e.tags!==void 0)throw new TypeError("options.tags cannot be set by a composable conversion; set metadata directly on the output instead.");if(e.output.state!=="pending")throw new TypeError("options.output must not have been started yet.")}else if(e.output.tracks.length>0||Object.keys(e.output._metadataTags).length>0||e.output.state!=="pending")throw new TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");if(e.video!==void 0&&typeof e.video!="function")if(Array.isArray(e.video))for(const l of e.video)Ys(l);else Ys(e.video);if(e.audio!==void 0&&typeof e.audio!="function")if(Array.isArray(e.audio))for(const l of e.audio)Zs(l);else Zs(e.audio);if(e.trim!==void 0&&(!e.trim||typeof e.trim!="object"))throw new TypeError("options.trim, when provided, must be an object.");if(((r=e.trim)==null?void 0:r.start)!==void 0&&!Number.isFinite(e.trim.start))throw new TypeError("options.trim.start, when provided, must be a finite number.");if(((s=e.trim)==null?void 0:s.end)!==void 0&&!ut(e.trim.end))throw new TypeError("options.trim.end, when provided, must be a number.");if(((n=e.trim)==null?void 0:n.start)!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");if(e.tags!==void 0&&(typeof e.tags!="object"||!e.tags)&&typeof e.tags!="function")throw new TypeError("options.tags, when provided, must be an object or a function.");if(typeof e.tags=="object"&&Ra(e.tags),e.showWarnings!==void 0&&typeof e.showWarnings!="boolean")throw new TypeError("options.showWarnings, when provided, must be a boolean.");this._options=e,this._copyMode=e.copy===!1?!1:((a=e.copy)==null?void 0:a.mode)??"preferred",this._copyTimestampShiftTolerance=e.copy===!1?0:((o=e.copy)==null?void 0:o.shiftTolerance)??0,this._copyBoundaryPolicy=e.copy===!1?"expand":((c=e.copy)==null?void 0:c.boundaryPolicy)??"expand",this._copyBoundaryTolerance=e.copy===!1?1/0:((u=e.copy)==null?void 0:u.boundaryTolerance)??1/0,this._composable=t,this.input=e.input,this.output=e.output}async _init(){var o,c;const e=await this.input.getFormat();let t,r=this._options.tracks;if(r===void 0&&(r=e.name.includes("(HLS)")?"primary":"all"),r==="all")t=await this.input.getTracks();else if(r==="primary"){const u=await this.input.getPrimaryVideoTrack(),l=await this.input.getPrimaryAudioTrack();t=[u,l].filter(d=>d!==null)}else xe(r),w(!1);const s=this.output.format.getSupportedTrackCounts(),n=[],a=[];for(const u of t){let l;if(u.isVideoTrack())if(this._options.video)if(typeof this._options.video=="function"){const h=await this._options.video(u,u.number)??{};if(Array.isArray(h))for(const p of h)Ys(p);else Ys(h);l=Array.isArray(h)?h:[h]}else l=Array.isArray(this._options.video)?this._options.video:[this._options.video];else l=[{}];else if(u.isAudioTrack())if(this._options.audio)if(typeof this._options.audio=="function"){const h=await this._options.audio(u,u.number)??{};if(Array.isArray(h))for(const p of h)Zs(p);else Zs(h);l=Array.isArray(h)?h:[h]}else l=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio];else l=[{}];else w(!1);const d=l.filter(h=>h.discard);for(const h of d)this.discardedTracks.push({track:u,reason:"discarded_by_user",trackOptions:h});if(l.length===d.length){l.length===0&&this.discardedTracks.push({track:u,reason:"discarded_by_user",trackOptions:{}});continue}const f=l.filter(h=>!h.discard);n.push(u),a.push(f)}((o=this._options.trim)==null?void 0:o.start)!==void 0?this._startTimestamp=this._options.trim.start:this._startTimestamp=Math.max(await this.input.getFirstTimestamp(n),0),this._endTimestamp=Math.max(((c=this._options.trim)==null?void 0:c.end)??1/0,this._startTimestamp),this._timestampOffset=-this._startTimestamp;for(let u=0;u<n.length;u++){const l=n[u],d=a[u];for(const f of d){if(this.output.tracks.length===s.total.max){this.discardedTracks.push({track:l,reason:"max_track_count_reached",trackOptions:f});continue}if(this.output.tracks.reduce((m,g)=>m+(g.type===l.type?1:0),0)===s[l.type].max){this.discardedTracks.push({track:l,reason:"max_track_count_of_type_reached",trackOptions:f});continue}const p=this._nextOutputTrackId++;l.isVideoTrack()?await this._processVideoTrack(l,f,p):l.isAudioTrack()?await this._processAudioTrack(l,f,p):w(!1)}}for(let u=0;u<this.utilizedTracks.length-1;u++)for(let l=u+1;l<this.utilizedTracks.length;l++){const d=this.utilizedTracks[u],f=this.utilizedTracks[l],h=this._outputOwnTrackGroups[u],p=this._outputOwnTrackGroups[l];w(h!==void 0),w(p!==void 0),h&&p&&d.canBePairedWith(f)&&h.pairWith(p)}if(!this._composable){const u={...await this.input.getMetadataTags()};delete u.creationTime;let l;if(this._options.tags){const h=typeof this._options.tags=="function"?await this._options.tags(u):this._options.tags;Ra(h),l=h}else l=u;const d=e.mimeType===this.output.format.mimeType;u.raw===l.raw&&!d&&delete l.raw,this.output.setMetadataTags(l)}if(this._composable?this.isValid=!0:this.isValid=this.output.hasEnoughTracks()&&this.output.tracks.length>0,this._options.showWarnings??!0){const u=[],l=this.discardedTracks.filter(d=>d.reason!=="discarded_by_user");l.length>0&&u.push("Some tracks had to be discarded from the conversion:",l),this.isValid||(u.length>0&&u.push(`
|
|
449
|
+
|
|
450
|
+
`),u.push(this._getInvalidityExplanation().join(""))),u.length>0&&K._warn(...u)}}_getInvalidityExplanation(){const e=[];if(this.discardedTracks.length===0)e.push("Due to missing tracks, this conversion cannot be executed.");else{const t=this.discardedTracks.every(r=>r.reason==="discarded_by_user"||r.reason==="no_encodable_target_codec")&&this.discardedTracks.some(r=>r.reason==="no_encodable_target_codec");if(e.push("Due to discarded tracks, this conversion cannot be executed."),t){const r=[],s=[];for(const o of this.discardedTracks){if(o.reason==="discarded_by_user")continue;let c;o.track.type==="video"?c=this.output.format.getSupportedVideoCodecs():o.track.type==="audio"?c=this.output.format.getSupportedAudioCodecs():c=this.output.format.getSupportedSubtitleCodecs();const u=o.trackOptions.codec;u&&!c.includes(u)?s.push(u):r.push(...c.filter(l=>!u||l===u))}const n=[...new Set(r)],a=[...new Set(s)];a.length>0&&e.push(`
|
|
451
|
+
Tracks were discarded because the output format cannot contain the requested codecs ${a.map(o=>`'${o}'`).join(", ")}.`),n.length===1?e.push(`
|
|
452
|
+
Tracks were discarded because your environment is not able to encode '${n[0]}' with the provided parameters.`):n.length>1&&e.push(`
|
|
453
|
+
Tracks were discarded because your environment is not able to encode any of the codecs ${n.map(o=>`'${o}'`).join(", ")} with the provided parameters.`),n.includes("mp3")&&e.push(`
|
|
454
|
+
The @mediabunny/mp3-encoder extension package provides support for encoding MP3.`),n.includes("aac")&&e.push(`
|
|
455
|
+
The @mediabunny/aac-encoder extension package provides support for encoding AAC.`),(n.includes("ac3")||n.includes("eac3"))&&e.push(`
|
|
456
|
+
The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),n.includes("flac")&&e.push(`
|
|
457
|
+
The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`),n.includes("dts")&&e.push(`
|
|
458
|
+
The @mediabunny/dts extension package provides support for encoding and decoding DTS.`),n.includes("truehd")&&e.push(`
|
|
459
|
+
The @mediabunny/truehd extension package provides support for encoding and decoding TrueHD.`),n.length>0&&typeof VideoEncoder>"u"&&e.push(`
|
|
460
|
+
In server-side environments, the @mediabunny/server extension package provides support for encoding and decoding all common codecs.`)}else e.push(`
|
|
461
|
+
Check the discardedTracks field for more info.`)}return e}async execute(e={}){var s,n,a,o,c,u;if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.until!==void 0&&(typeof e.until!="number"||Number.isNaN(e.until)))throw new TypeError("options.until, when provided, must be a number.");if(e.pauseSignal!==void 0&&!(e.pauseSignal instanceof AbortSignal))throw new TypeError("options.pauseSignal, when provided, must be an AbortSignal.");if(!this.isValid)throw new Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.
|
|
462
|
+
`+this._getInvalidityExplanation().join(""));if(this._state==="executing")throw new Error("Cannot call execute() while a previous call to execute() is still running.");if(this._state==="canceled")throw new _a;if(this._state==="done")return;if(this._composable&&this.output.state==="pending")throw new Error("A composable conversion requires the output to be started. Call start() on the output before executing the conversion.");this._state="executing",this._executionUntil=e.until??1/0,this._pauseRequested=((s=e.pauseSignal)==null?void 0:s.aborted)??!1;const t=()=>{this._state==="executing"&&(this._pauseRequested=!0,this._synchronizer.resolveAll())};(n=e.pauseSignal)==null||n.addEventListener("abort",t);for(const l of this._trackPumps)l.done||(l.resolvers=Ae());try{if(this._executed)for(const l of this._trackPumps)(o=l.wake)==null||o.call(l);else{this._executed=!0;for(const l of this._outputTrackIds)this._synchronizer.declareTrack(l);if(this.onProgress){const d=[...new Set(this.utilizedTracks)].map(h=>this._getTrackDuration(h)),f=Math.max(0,...await Promise.all(d));this._computeProgress=!0,this._totalDuration=Math.min(f-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(const h of this._outputTrackIds)this._maxTimestamps.set(h,0);(a=this.onProgress)==null||a.call(this,0,0)}this._composable||await this.output.start();for(const l of this._trackPumps)l.start()}await Promise.all(this._trackPumps.map(l=>l.resolvers.promise))}catch(l){if(this._state!=="canceled")throw this.cancel().catch(()=>{}),l}finally{(c=e.pauseSignal)==null||c.removeEventListener("abort",t)}if(this._state==="canceled")throw new _a;if(!this._trackPumps.every(l=>l.done)){this._state="idle";return}if(!this._composable){try{await this.output.finalize()}catch(l){throw this._state="canceled",l}if(this._state==="canceled")throw new _a}this._state="done",this._computeProgress&&((u=this.onProgress)==null||u.call(this,1,this._lastProcessedTime))}async cancel(){var e;if(this._state!=="done"){if(this._state==="canceled"){K._warn("Conversion already canceled.");return}this._state="canceled";for(const t of this._trackPumps)(e=t.wake)==null||e.call(t);this._synchronizer.resolveAll(),this._composable||await this.output.cancel()}}async _processVideoTrack(e,t,r){const s=await e.getCodec();if(!s){this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});return}if(this.output.format.requiresMaximumPacketCount&&t.maximumPacketCount===void 0&&this._endTimestamp===1/0&&await e.isLive()){this.discardedTracks.push({track:e,reason:"unknown_maximum_packet_count",trackOptions:t});return}let n;const a=await e.getRotation(),o=await e.getFlip(),{rotation:c,flip:u}=Ul(a,o,t.rotate??0,t.flip??!1);let l=c,d=u,f=t.rotate||t.flip?null:await e.getTransformationMatrix();const h=this.output.format.supportsVideoTransformationMetadata&&(t.allowTransformationMetadata??t.allowRotationMetadata??!0),p=await e.getSquarePixelWidth(),m=await e.getSquarePixelHeight(),[g,y]=c%180===0?[p,m]:[m,p];let b=t.crop;b&&(b=wn(b,g,y));const[S,A]=b?[b.width,b.height]:[g,y];let x=S,T=A;const P=x/T;t.width!==void 0&&t.height===void 0?(x=cr(t.width),T=cr(Math.round(x/P))):t.width===void 0&&t.height!==void 0?(T=cr(t.height),x=cr(Math.round(T*P))):t.width!==void 0&&t.height!==void 0&&(x=cr(t.width),T=cr(t.height));let C=this.output.format.getSupportedVideoCodecs();const _=t.alpha??"discard";let I=!this._copyMode||!!t.forceTranscode||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.quality!==void 0||t.bitrate!==void 0||!C.includes(s)||t.codec&&t.codec!==s||x!==S||T!==A||c!==0&&!h||u&&!h||!!b,v=null;if(!I){const Y=new Ri(e);let se=await Y.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await Y.getFirstKeyPacket({verifyKeyPackets:!0});if(se&&se.timestamp<this._startTimestamp&&se.timestamp+se.duration<=this._startTimestamp&&this._copyBoundaryPolicy==="shrink"&&(se=await Y.getNextKeyPacket(se,{verifyKeyPackets:!0})),v=se,se){const pe=this._copyBoundaryPolicy==="shrink"?Math.max(se.timestamp,this._startTimestamp):se.timestamp;if((this._copyBoundaryPolicy==="shrink"?pe-this._startTimestamp:Math.max(this._startTimestamp-pe,0))>this._copyBoundaryTolerance)I=!0;else if(this.output.format.supportsTimestampedMediaData){if(this.output.format.negativeTimestampSupport!=="full"&&pe<this._startTimestamp){const Pe=Math.min(this._startTimestamp-pe,this._copyTimestampShiftTolerance);pe+Pe>=this._startTimestamp||this.output.format.negativeTimestampSupport==="prefer-non-negative"&&this._copyMode==="forced"?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+Pe):I=!0}}else if(this._timestampOffsetAdjusted)pe+this._timestampOffset===0||(I=!0);else{const Pe=Be(this._startTimestamp-pe,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);pe+Pe===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+Pe,this._timestampOffsetAdjusted=!0):I=!0}}}if(I&&this._copyMode==="forced"){this.discardedTracks.push({track:e,reason:"cannot_copy",trackOptions:t});return}if(I){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});return}t.codec&&(C=C.filter($e=>$e===t.codec));const se=Dr(t.quality,t.bitrate)??new Me("high"),pe=await Gh(C,{width:t.process&&t.processedWidth?t.processedWidth:x,height:t.process&&t.processedHeight?t.processedHeight:T,quality:se});if(!pe){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec",trackOptions:t});return}const he={codec:pe,quality:se,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??"passThrough",alpha:_,hardwareAcceleration:t.hardwareAcceleration,transform:{}};w(he.transform);let Pe=x!==S||T!==A||c!==0&&(!h||t.process!==void 0)||u&&(!h||t.process!==void 0)||!!b||p!==await e.getCodedWidth()||m!==await e.getCodedHeight();if(!Pe){const $e={stack:[],error:void 0,hasError:!1};try{const ve=new _n({format:new $w,target:new rf}),Qe=new fl(he);ve.addVideoTrack(Qe),await ve.start();const Ge=new oo(e,{hardwareAcceleration:t.hardwareAcceleration}),_e=Jr($e,await Ge.getSample(await e.getFirstTimestamp()),!1);if(_e)try{await Qe.add(_e),_e.close(),await ve.finalize()}catch(Xe){K._warn("An error occurred when probing encoder support. Falling back to rerender path.",Xe),ve.cancel(),Pe=!0,he.transform.force=!0}else await ve.cancel()}catch(ve){$e.error=ve,$e.hasError=!0}finally{Xs($e)}}t.frameRate&&(he.transform.frameRate=t.frameRate),t.process&&(he.transform.process=t.process),Pe&&(l=0,d=!1,f=null,he.transform.width=x,he.transform.height=T,he.transform.fit=t.fit??"fill",he.transform.rotate=t.rotate,he.transform.flip=t.flip,he.transform.crop=b,he.transform.alpha=_);let We=null;he.onEncodedSample=$e=>{We=$e.timestamp};const tt=new fl(he);n=tt,this._registerTrackPump(async $e=>{const ve=new oo(e,{hardwareAcceleration:t.hardwareAcceleration});for await(const Qe of ve.samples(this._startTimestamp,this._endTimestamp)){const Ge={stack:[],error:void 0,hasError:!1};try{const _e=Jr(Ge,Qe,!1);if(this._state==="canceled")break;const Xe=Math.max(this._startTimestamp,_e.timestamp),St=Math.min(this._endTimestamp,_e.timestamp+_e.duration);if(Xe>St||Xe===St&&_e.duration>0)continue;_e.setTimestamp(Xe+this._timestampOffset),_e.setDuration(St-Xe),this._updateProgress(r,_e.timestamp+_e.duration),await tt.add(_e),_e.close(),We!==null&&(this._synchronizer.shouldWait(r,We)&&await this._synchronizer.wait(We),await this._checkpoint($e,We))}catch(_e){Ge.error=_e,Ge.hasError=!0}finally{Xs(Ge)}}tt.close(),this._closeTrack(r)})}else{const Y=new uo(s);n=Y,this._registerTrackPump(async se=>{const pe=new Ri(e),Pe={decoderConfig:await e.getDecoderConfig()??void 0},We=new ho;let tt=!1,$e=!1;if(v)for await(const ve of pe.packets(v,void 0,{verifyKeyPackets:!0})){if(this._state==="canceled")break;if(ve.timestamp>=this._endTimestamp){if(this._copyBoundaryPolicy==="shrink")break;{let St=ve,xi=!1;const Li=6;for(let Pi=0;Pi<Li;Pi++){const ii=await pe.getNextPacket(St,{metadataOnly:!0});if(!ii)break;if(ii.timestamp<this._endTimestamp){xi=!0;break}St=ii}if(!xi)break}}let Qe=ve.timestamp,Ge=ve.timestamp+ve.duration;if(this._copyBoundaryPolicy==="shrink"&&(Qe=Math.max(Qe,this._startTimestamp),Ge=Math.min(Ge,this._endTimestamp),Ge=Math.max(Ge,Qe)),Qe+=this._timestampOffset,Ge+=this._timestampOffset,ve.type==="key"&&(tt=!1),tt)continue;let _e=ve.type;if(_e==="key"&&!We.check(Qe,"key")&&(_e="delta"),!We.digest(Qe,_e)){tt=ve.type==="key",$e||(K._warn("Some video packets had to be dropped in order to produce correct output timestamps."),$e=!0);continue}const Xe=ve.clone({timestamp:Qe,duration:Ge-Qe,sideData:_==="discard"?{}:ve.sideData,type:_e});this._updateProgress(r,Xe.timestamp+Xe.duration),await Y.add(Xe,Pe),this._synchronizer.shouldWait(r,Xe.timestamp)&&await this._synchronizer.wait(Xe.timestamp),await this._checkpoint(se,Xe.timestamp)}Y.close(),this._closeTrack(r)})}let R=null;!t.group&&!this._composable&&(R=new Wt);const F=await e.getLanguageCode(),H=await e.getName(),O=await e.getDisposition(),U=I?null:await e.getBitrate(),L=I?null:await e.getAverageBitrate(),Q=_==="keep"&&await e.canBeTransparent();let re=t.maximumPacketCount;if(this.output.format.requiresMaximumPacketCount&&re===void 0){const Y=I?this._startTimestamp:(v==null?void 0:v.timestamp)??this._startTimestamp;re=await this._estimateMaximumPacketCount(e,Y,t.frameRate??null)}this.output.addVideoTrack(n,{frameRate:t.frameRate,languageCode:us(F)?F:void 0,name:H??void 0,disposition:O,rotation:l,flip:d,transformationMatrix:f??void 0,canBeTransparent:Q,group:R??t.group,bitrate:U??void 0,averageBitrate:L??void 0,maximumPacketCount:re}),this.utilizedTracks.push(e),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(R)}async _processAudioTrack(e,t,r){const s=await e.getCodec();if(!s){this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});return}if(this.output.format.requiresMaximumPacketCount&&t.maximumPacketCount===void 0&&this._endTimestamp===1/0&&await e.isLive()){this.discardedTracks.push({track:e,reason:"unknown_maximum_packet_count",trackOptions:t});return}let n;const a=await e.getNumberOfChannels(),o=await e.getSampleRate();let c=t.numberOfChannels??a,u=t.sampleRate??o,l=null,d=this.output.format.getSupportedAudioCodecs(),f=!this._copyMode||!!t.forceTranscode||!!t.quality||!!t.bitrate||c!==a||u!==o||!d.includes(s)||!!t.codec&&t.codec!==s||t.process!==void 0||t.sampleFormat!==void 0,h=null;if(!f){const x=new Ri(e);let T=await x.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await x.getFirstKeyPacket({verifyKeyPackets:!0});T&&(this._copyBoundaryPolicy==="shrink"&&T.timestamp<this._startTimestamp||this._copyBoundaryPolicy==="expand"&&T.timestamp+T.duration<=this._startTimestamp&&await e.hasOnlyKeyPackets())&&(T=await x.getNextKeyPacket(T,{verifyKeyPackets:!0}));const P=await e.getPreRollDuration();if(w(P!==null),T&&this._copyBoundaryPolicy==="expand"&&P>0&&(T=await x.getKeyPacket(T.timestamp-P,{verifyKeyPackets:!0})??await x.getFirstKeyPacket({verifyKeyPackets:!0})),h=T,T)if((this._copyBoundaryPolicy==="shrink"?Math.max(T.timestamp-this._startTimestamp,0):Math.max(this._startTimestamp-T.timestamp,0))>this._copyBoundaryTolerance)f=!0;else if(this.output.format.supportsTimestampedMediaData){if(this.output.format.negativeTimestampSupport!=="full"&&T.timestamp<this._startTimestamp){const _=Math.min(this._startTimestamp-T.timestamp,this._copyTimestampShiftTolerance);T.timestamp+_>=this._startTimestamp||this.output.format.negativeTimestampSupport==="prefer-non-negative"&&this._copyMode==="forced"?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+_):f=!0}}else if(this._timestampOffsetAdjusted)T.timestamp+this._timestampOffset===0||(f=!0);else{const _=Be(this._startTimestamp-T.timestamp,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);T.timestamp+_===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+_,this._timestampOffsetAdjusted=!0):f=!0}}if(f&&this._copyMode==="forced"){this.discardedTracks.push({track:e,reason:"cannot_copy",trackOptions:t});return}if(f){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});return}t.codec&&(d=d.filter(v=>v===t.codec));const T=Dr(t.quality,t.bitrate)??new Me("high"),P=await $a(d,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:c,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:u,quality:T});if(!P.some(v=>Ji.includes(v))&&d.some(v=>Ji.includes(v))&&(c!==Pa||u!==Ca)){const R=(await $a(d,{numberOfChannels:Pa,sampleRate:Ca,quality:T})).find(F=>Ji.includes(F));R?(l=R,c=Pa,u=Ca):l=P[0]??null}else l=P[0]??null;if(l===null){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec",trackOptions:t});return}const C={codec:l,quality:T,transform:{sampleFormat:t.sampleFormat,process:t.process}};w(C.transform),c!==a&&(C.transform.numberOfChannels=c),u!==o&&(C.transform.sampleRate=u);let _=null;C.onEncodedSample=v=>{_=v.timestamp};const I=new Lp(C);n=I,this._registerTrackPump(async v=>{let R=null;const F=new Id(e);for await(const H of F.samples(this._startTimestamp,this._endTimestamp)){const O={stack:[],error:void 0,hasError:!1};try{const U=Jr(O,H,!1);if(this._state==="canceled")break;let L=0,Q=U.numberOfFrames;if(U.timestamp<this._startTimestamp&&(L=Math.round((this._startTimestamp-U.timestamp)*U.sampleRate)),U.timestamp+U.duration>this._endTimestamp&&(Q=Math.round((this._endTimestamp-U.timestamp)*U.sampleRate)),L>=Q){U.close();continue}let re;if(L>0||Q<U.numberOfFrames){const se=U.trim(L,Q);if(U.close(),re=se,se.numberOfFrames===0){se.close();continue}}else re=U;const Y=Jr(O,re,!1);if(Y.setTimestamp(Y.timestamp+this._timestampOffset),R===null&&(R=this.output.format.supportsTimestampedMediaData?0:Math.round(Y.timestamp*Y.sampleRate)),R>0){const se=Mt(U.format)*Y.numberOfChannels,pe=new Uint8Array(se*Math.min(R,Y.sampleRate));(U.format==="u8"||U.format==="u8-planar")&&pe.fill(2**7);for(let he=0;he<R;he+=Y.sampleRate){const Pe={stack:[],error:void 0,hasError:!1};try{const We=Math.min(R-he,Y.sampleRate),tt=Jr(Pe,new qe({data:pe.subarray(0,se*We),_doNotCopy:!0,format:U.format,numberOfChannels:Y.numberOfChannels,sampleRate:Y.sampleRate,timestamp:he/Y.sampleRate}),!1);await this._registerAudioSample(v,tt,I,r,()=>_)}catch(We){Pe.error=We,Pe.hasError=!0}finally{Xs(Pe)}}R=0}await this._registerAudioSample(v,Y,I,r,()=>_)}catch(U){O.error=U,O.hasError=!0}finally{Xs(O)}}I.close(),this._closeTrack(r)})}else{const x=new fo(s);n=x,this._registerTrackPump(async T=>{const P=new Ri(e),_={decoderConfig:await e.getDecoderConfig()??void 0},I=new ho;let v=!1,R=!1;if(h)for await(const F of P.packets(h)){if(this._state==="canceled"||F.timestamp>=this._endTimestamp||this._copyBoundaryPolicy==="shrink"&&F.timestamp+F.duration>this._endTimestamp)break;const H=F.timestamp+this._timestampOffset;if(F.type==="key"&&(v=!1),v)continue;if(!I.digest(H,F.type)){v=F.type==="key",R||(K._warn("Some audio packets had to be dropped in order to produce correct output timestamps."),R=!0);continue}const O=F.clone({timestamp:H,duration:F.duration});this._updateProgress(r,O.timestamp+O.duration),await x.add(O,_),this._synchronizer.shouldWait(r,O.timestamp)&&await this._synchronizer.wait(O.timestamp),await this._checkpoint(T,O.timestamp)}x.close(),this._closeTrack(r)})}let p=null;!t.group&&!this._composable&&(p=new Wt);const m=await e.getLanguageCode(),g=await e.getName(),y=await e.getDisposition(),b=f?null:await e.getBitrate(),S=f?null:await e.getAverageBitrate();let A=t.maximumPacketCount;if(this.output.format.requiresMaximumPacketCount&&A===void 0){let x=null;f&&(w(l),x=u/Yp(l,u));const T=f?this._startTimestamp:(h==null?void 0:h.timestamp)??this._startTimestamp;A=await this._estimateMaximumPacketCount(e,T,x)}this.output.addAudioTrack(n,{languageCode:us(m)?m:void 0,name:g??void 0,disposition:y,group:p??t.group,bitrate:b??void 0,averageBitrate:S??void 0,maximumPacketCount:A}),this.utilizedTracks.push(e),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(p)}async _estimateMaximumPacketCount(e,t,r){if(r===null){const a=await e.computePacketStats(Yw);if(a.averagePacketRate===1/0)return a.packetCount;r=a.averagePacketRate}const s=Math.min(await this._getTrackDuration(e),this._endTimestamp),n=Math.max(s-t,0);return Math.ceil(1.5*r*n)+64}_getTrackDuration(e){let t=this._trackDurations.get(e);return t||(t=(async()=>await e.isLive()?1/0:await e.getDurationFromMetadata()??await e.computeDuration())(),this._trackDurations.set(e,t)),t}async _registerAudioSample(e,t,r,s,n){this._updateProgress(s,t.timestamp+t.duration),await r.add(t),t.close();const a=n();a!==null&&(this._synchronizer.shouldWait(s,a)&&await this._synchronizer.wait(a),await this._checkpoint(e,a))}_registerTrackPump(e){const t={done:!1,resolvers:Ae(),wake:null,start:()=>{e(t).then(()=>{t.done=!0,t.resolvers.resolve()},r=>{t.resolvers.reject(r)})}};this._trackPumps.push(t)}async _checkpoint(e,t){for(;this._state!=="canceled"&&(t>=this._executionUntil||this._pauseRequested);){e.resolvers.resolve();const{promise:r,resolve:s}=Ae();e.wake=s,await r}}_closeTrack(e){this._synchronizer.closeTrack(e),this._maxTimestamps.delete(e),this._reportProgress()}_updateProgress(e,t){this._computeProgress&&(this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e))),this._reportProgress())}_reportProgress(){var r;if(!this._computeProgress||this._maxTimestamps.size===0)return;w(this._totalDuration!==null);const e=Math.min(...this._maxTimestamps.values()),t=this._totalDuration>0?Be(e/this._totalDuration,0,1):0;this._lastProcessedTime=e,t!==this._lastProgress&&(this._lastProgress=t,(r=this.onProgress)==null||r.call(this,t,e))}}class _a extends Error{constructor(e="Conversion has been canceled."){super(e),this.name="ConversionCanceledError"}}const Rl=1;class Zw{constructor(e){this.maxTimestamps=new Map,this.resolvers=[],this.conversion=e}declareTrack(e){this.maxTimestamps.set(e,-1/0)}shouldWait(e,t){const r=this.maxTimestamps.get(e);w(r!==void 0),this.maxTimestamps.set(e,Math.max(t,r));const s=this.computeMinAndMaybeResolve();return this.conversion._state==="canceled"||this.conversion._pauseRequested||t>=this.conversion._executionUntil?!1:t-s>Rl}wait(e){const{promise:t,resolve:r}=Ae();return this.resolvers.push({timestamp:e,resolve:r}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}resolveAll(){for(const e of this.resolvers)e.resolve();this.resolvers.length=0}computeMinAndMaybeResolve(){let e=1/0;for(const[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){const r=this.resolvers[t];r.timestamp-e<Rl&&(r.resolve(),this.resolvers.splice(t,1),t--)}return e}}/*!
|
|
463
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
464
|
+
*
|
|
465
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
466
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
467
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
468
|
+
*/const uf=Symbol.for("mediabunny loaded");globalThis[uf]&&K._error(`[WARNING]
|
|
469
|
+
Mediabunny was loaded twice. This will likely cause Mediabunny not to work correctly. Check if multiple dependencies are importing different versions of Mediabunny, or if something is being bundled incorrectly.`);globalThis[uf]=!0;export{xd as ADTS,k0 as ALL_FORMATS,Fl as ALL_TRACK_TYPES,Ke as AUDIO_CODECS,hp as AdtsInputFormat,M0 as AdtsOutputFormat,v0 as AppendOnlyStreamTarget,bo as AttachedFile,A0 as AudioBufferSink,_0 as AudioBufferSource,qe as AudioSample,$r as AudioSampleResource,Id as AudioSampleSink,Lp as AudioSampleSource,Ms as AudioSource,_d as BaseMediaSampleSink,y0 as BlobSource,w0 as BufferSource,Aa as BufferTarget,S0 as CanvasSink,P0 as CanvasSource,vl as CmafOutputFormat,i0 as ConcurrentRunner,lf as Conversion,_a as ConversionCanceledError,Yh as CustomAudioDecoder,Jh as CustomAudioEncoder,Gm as CustomPathedSource,hd as CustomSource,Xh as CustomVideoDecoder,Zh as CustomVideoEncoder,fo as EncodedAudioPacketSource,Ce as EncodedPacket,Ri as EncodedPacketSink,uo as EncodedVideoPacketSource,Ps as EventEmitter,bp as FLAC,fd as FilePathSource,B0 as FilePathTarget,fp as FlacInputFormat,D0 as FlacOutputFormat,Cd as HLS,T0 as HLS_FORMATS,kd as HlsInputFormat,O0 as HlsOutputFormat,qn as Input,Hn as InputAudioTrack,He as InputDisposedError,ei as InputFormat,Fs as InputTrack,Ln as InputVideoTrack,yd as IsobmffInputFormat,Jo as IsobmffOutputFormat,jt as LogLevel,K as Logging,pp as MATROSKA,Ad as MP3,Td as MP4,Pd as MPEG_TS,bd as MatroskaInputFormat,$o as MediaSource,E0 as MediaStreamAudioTrackSource,C0 as MediaStreamVideoTrackSource,Bl as MkvOutputFormat,of as MovOutputFormat,lp as Mp3InputFormat,cf as Mp3OutputFormat,ap as Mp4InputFormat,Kw as Mp4OutputFormat,mp as MpegTsInputFormat,z0 as MpegTsOutputFormat,Ji as NON_PCM_AUDIO_CODECS,rf as NullTarget,yp as OGG,dp as OggInputFormat,R0 as OggOutputFormat,_n as Output,Gw as OutputAudioTrack,kt as OutputFormat,Xw as OutputSubtitleTrack,zs as OutputTrack,Wt as OutputTrackGroup,Qw as OutputVideoTrack,je as PCM_AUDIO_CODECS,ar as PathedSource,vi as PathedTarget,Sd as QTFF,l0 as QUALITY_HIGH,o0 as QUALITY_LOW,c0 as QUALITY_MEDIUM,u0 as QUALITY_VERY_HIGH,a0 as QUALITY_VERY_LOW,Me as Quality,op as QuickTimeInputFormat,ep as RangedSource,xw as RangedTarget,md as ReadableStreamSource,xr as RichImageData,vt as SUBTITLE_CODECS,It as Source,Ho as SourceRef,b0 as StreamSource,tf as StreamTarget,Dd as SubtitleSource,ht as Target,I0 as TextSubtitleSource,ul as UnsupportedInputFormatError,dd as UrlSource,Oe as VIDEO_CODECS,Ha as VIDEO_SAMPLE_PIXEL_FORMATS,Je as VideoSample,ia as VideoSampleColorSpace,Hi as VideoSampleResource,oo as VideoSampleSink,fl as VideoSampleSource,Rs as VideoSource,wp as WAVE,gp as WEBM,F0 as WavOutputFormat,up as WaveInputFormat,cp as WebMInputFormat,mr as WebMOutputFormat,x0 as asc,r0 as canDecode,yu as canDecodeAudio,wu as canDecodeVideo,d0 as canEncode,Mo as canEncodeAudio,Do as canEncodeSubtitles,Ro as canEncodeVideo,cl as desc,Mh as getDecodableAudioCodecs,s0 as getDecodableCodecs,Rh as getDecodableVideoCodecs,$a as getEncodableAudioCodecs,f0 as getEncodableCodecs,Qh as getEncodableSubtitleCodecs,$h as getEncodableVideoCodecs,h0 as getFirstEncodableAudioCodec,m0 as getFirstEncodableSubtitleCodec,Gh as getFirstEncodableVideoCodec,Gr as prefer,p0 as registerDecoder,g0 as registerEncoder,n0 as registerVideoSampleTransformer};
|