@kenzuya/mediabunny 1.28.5 → 1.28.6

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.
@@ -5,13 +5,13 @@
5
5
  * License, v. 2.0. If a copy of the MPL was not distributed with this
6
6
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
7
  */
8
- var K7=Object.defineProperty;var Q7=($,J)=>{for(var Y in J)K7($,Y,{get:J[Y],enumerable:!0,configurable:!0,set:(j)=>J[Y]=()=>j})};var q7=($,J)=>()=>($&&(J=$($=0)),J);var S8={};Q7(S8,{splitSrtIntoCues:()=>$$,splitAssIntoCues:()=>J$,parseSubtitleTimestamp:()=>I8,parseSrtTimestamp:()=>p6,parseAssTimestamp:()=>m6,inlineTimestampRegex:()=>u1,formatSubtitleTimestamp:()=>k1,formatSrtTimestamp:()=>l6,formatCuesToWebVTT:()=>o6,formatCuesToSrt:()=>n6,formatCuesToAss:()=>r6,formatAssTimestamp:()=>d6,convertDialogueLineToMkvFormat:()=>Y$,SubtitleParser:()=>c6});class c6{options;preambleText=null;preambleEmitted=!1;constructor($){this.options=$}parse($){if(this.options.codec==="srt")this.parseSrt($);else if(this.options.codec==="ass"||this.options.codec==="ssa")this.parseAss($);else if(this.options.codec==="tx3g")this.parseTx3g($);else if(this.options.codec==="ttml")this.parseTtml($);else this.parseWebVTT($)}parseSrt($){let J=$$($);for(let Y=0;Y<J.length;Y++){let j={};if(Y===0)j.config={description:""};this.options.output(J[Y],j)}}parseAss($){let{header:J,cues:Y}=J$($);for(let j=0;j<Y.length;j++){let X={};if(j===0&&J)X.config={description:J};this.options.output(Y[j],X)}}parseWebVTT($){$=$.replaceAll(`\r
8
+ var G7=Object.defineProperty;var K7=($,J)=>{for(var Y in J)G7($,Y,{get:J[Y],enumerable:!0,configurable:!0,set:(j)=>J[Y]=()=>j})};var Q7=($,J)=>()=>($&&(J=$($=0)),J);var S8={};K7(S8,{splitSrtIntoCues:()=>$$,splitAssIntoCues:()=>J$,parseSubtitleTimestamp:()=>I8,parseSrtTimestamp:()=>p6,parseAssTimestamp:()=>m6,inlineTimestampRegex:()=>u1,formatSubtitleTimestamp:()=>k1,formatSrtTimestamp:()=>l6,formatCuesToWebVTT:()=>o6,formatCuesToSrt:()=>n6,formatCuesToAss:()=>r6,formatAssTimestamp:()=>d6,convertDialogueLineToMkvFormat:()=>Y$,SubtitleParser:()=>c6});class c6{options;preambleText=null;preambleEmitted=!1;constructor($){this.options=$}parse($){if(this.options.codec==="srt")this.parseSrt($);else if(this.options.codec==="ass"||this.options.codec==="ssa")this.parseAss($);else if(this.options.codec==="tx3g")this.parseTx3g($);else if(this.options.codec==="ttml")this.parseTtml($);else this.parseWebVTT($)}parseSrt($){let J=$$($);for(let Y=0;Y<J.length;Y++){let j={};if(Y===0)j.config={description:""};this.options.output(J[Y],j)}}parseAss($){let{header:J,cues:Y}=J$($);for(let j=0;j<Y.length;j++){let X={};if(j===0&&J)X.config={description:J};this.options.output(Y[j],X)}}parseWebVTT($){$=$.replaceAll(`\r
9
9
  `,`
10
10
  `).replaceAll("\r",`
11
- `),x8.lastIndex=0;let J;if(!this.preambleText){if(!l7.test($))throw Error("WebVTT preamble incorrect.");J=x8.exec($);let Y=$.slice(0,J?.index??$.length).trimEnd();if(!Y)throw Error("No WebVTT preamble provided.");if(this.preambleText=Y,J)$=$.slice(J.index),x8.lastIndex=0}while(J=x8.exec($)){let Y=$.slice(0,J.index),j=J[1],X=J.index+J[0].length,Z=$.indexOf(`
11
+ `),x8.lastIndex=0;let J;if(!this.preambleText){if(!p7.test($))throw Error("WebVTT preamble incorrect.");J=x8.exec($);let Y=$.slice(0,J?.index??$.length).trimEnd();if(!Y)throw Error("No WebVTT preamble provided.");if(this.preambleText=Y,J)$=$.slice(J.index),x8.lastIndex=0}while(J=x8.exec($)){let Y=$.slice(0,J.index),j=J[1],X=J.index+J[0].length,Z=$.indexOf(`
12
12
  `,X)+1,G=$.slice(X,Z).trim(),K=$.indexOf(`
13
13
 
14
- `,X);if(K===-1)K=$.length;let Q=I8(J[2]),U=I8(J[3])-Q,W=$.slice(Z,K).trim();$=$.slice(K).trimStart(),x8.lastIndex=0;let V={timestamp:Q/1000,duration:U/1000,text:W,identifier:j,settings:G,notes:Y},N={};if(!this.preambleEmitted)N.config={description:this.preambleText},this.preambleEmitted=!0;this.options.output(V,N)}}parseTx3g($){let J={config:{description:""}},Y={timestamp:0,duration:0,text:$.trim()};this.options.output(Y,J)}parseTtml($){let J=/<p[^>]*>(.*?)<\/p>/gs,Y=[...$.matchAll(J)];for(let j=0;j<Y.length;j++){let Z=Y[j][1]?.replace(/<[^>]+>/g,"")||"",G={};if(j===0)G.config={description:""};let K={timestamp:0,duration:0,text:Z.trim()};this.options.output(K,G)}}}var x8,l7,u1,m7,I8=($)=>{let J=m7.exec($);if(!J)throw Error("Expected match.");return 3600000*Number(J[1]||"0")+60000*Number(J[2])+1000*Number(J[3])+Number(J[4])},k1=($)=>{let J=Math.floor($/3600000),Y=Math.floor($%3600000/60000),j=Math.floor($%60000/1000),X=$%1000;return J.toString().padStart(2,"0")+":"+Y.toString().padStart(2,"0")+":"+j.toString().padStart(2,"0")+"."+X.toString().padStart(3,"0")},d7,p6=($)=>{let J=d7.exec($);if(!J)throw Error("Invalid SRT timestamp format");let Y=Number(J[1]),j=Number(J[2]),X=Number(J[3]),Z=Number(J[4]);return Y*3600+j*60+X+Z/1000},l6=($)=>{let J=Math.floor($/3600),Y=Math.floor($%3600/60),j=Math.floor($%60),X=Math.round($%1*1000);return J.toString().padStart(2,"0")+":"+Y.toString().padStart(2,"0")+":"+j.toString().padStart(2,"0")+","+X.toString().padStart(3,"0")},$$=($)=>{$=$.replaceAll(`\r
14
+ `,X);if(K===-1)K=$.length;let Q=I8(J[2]),U=I8(J[3])-Q,W=$.slice(Z,K).trim();$=$.slice(K).trimStart(),x8.lastIndex=0;let V={timestamp:Q/1000,duration:U/1000,text:W,identifier:j,settings:G,notes:Y},N={};if(!this.preambleEmitted)N.config={description:this.preambleText},this.preambleEmitted=!0;this.options.output(V,N)}}parseTx3g($){let J={config:{description:""}},Y={timestamp:0,duration:0,text:$.trim()};this.options.output(Y,J)}parseTtml($){let J=/<p[^>]*>(.*?)<\/p>/gs,Y=[...$.matchAll(J)];for(let j=0;j<Y.length;j++){let Z=Y[j][1]?.replace(/<[^>]+>/g,"")||"",G={};if(j===0)G.config={description:""};let K={timestamp:0,duration:0,text:Z.trim()};this.options.output(K,G)}}}var x8,p7,u1,l7,I8=($)=>{let J=l7.exec($);if(!J)throw Error("Expected match.");return 3600000*Number(J[1]||"0")+60000*Number(J[2])+1000*Number(J[3])+Number(J[4])},k1=($)=>{let J=Math.floor($/3600000),Y=Math.floor($%3600000/60000),j=Math.floor($%60000/1000),X=$%1000;return J.toString().padStart(2,"0")+":"+Y.toString().padStart(2,"0")+":"+j.toString().padStart(2,"0")+"."+X.toString().padStart(3,"0")},m7,p6=($)=>{let J=m7.exec($);if(!J)throw Error("Invalid SRT timestamp format");let Y=Number(J[1]),j=Number(J[2]),X=Number(J[3]),Z=Number(J[4]);return Y*3600+j*60+X+Z/1000},l6=($)=>{let J=Math.floor($/3600),Y=Math.floor($%3600/60),j=Math.floor($%60),X=Math.round($%1*1000);return J.toString().padStart(2,"0")+":"+Y.toString().padStart(2,"0")+":"+j.toString().padStart(2,"0")+","+X.toString().padStart(3,"0")},$$=($)=>{$=$.replaceAll(`\r
15
15
  `,`
16
16
  `).replaceAll("\r",`
17
17
  `);let J=[],Y=/(\d+)\n(\d{2}:\d{2}:\d{2},\d{3})\s+-->\s+(\d{2}:\d{2}:\d{2},\d{3})\n([\s\S]*?)(?=\n\n\d+\n|\n*$)/g,j;while(j=Y.exec($)){let X=p6(j[2]),Z=p6(j[3]),G=j[4].trim();J.push({timestamp:X,duration:Z-X,text:G,identifier:j[1]})}return J},q5=($)=>{if($.startsWith("Dialogue:")||$.startsWith("Comment:")){let Y=$.indexOf(":");if(Y===-1)return $;let X=$.substring(Y+1).split(",");if(X.length>=10)return X.slice(9).join(",")}let J=$.split(",");if(J.length>=8){let Y=J[0]?.trim(),j=J[1]?.trim();if(Y&&!Number.isNaN(Number.parseInt(Y,10))){if(j&&!Number.isNaN(Number.parseInt(j,10))&&J.length>=9)return J.slice(8).join(",");if(J.length>=8)return J.slice(7).join(",")}}return $},n6=($)=>{return $.map((J,Y)=>{let j=Y+1,X=l6(J.timestamp),Z=l6(J.timestamp+J.duration),G=q5(J.text);return`${j}
@@ -25,12 +25,12 @@ ${G}
25
25
  `;let j=$.map((X)=>{let Z=k1(X.timestamp*1000),G=k1((X.timestamp+X.duration)*1000),K=q5(X.text);return`${Z} --> ${G}
26
26
  ${K}`});return Y+j.join(`
27
27
 
28
- `)},c7,m6=($)=>{let J=c7.exec($);if(!J)throw Error("Invalid ASS timestamp format");let Y=Number(J[1]),j=Number(J[2]),X=Number(J[3]),Z=Number(J[4]);return Y*3600+j*60+X+Z/100},d6=($)=>{let J=Math.floor($/3600),Y=Math.floor($%3600/60),j=Math.floor($%60),X=Math.floor($%1*100);return J.toString()+":"+Y.toString().padStart(2,"0")+":"+j.toString().padStart(2,"0")+"."+X.toString().padStart(2,"0")},J$=($)=>{$=$.replaceAll(`\r
28
+ `)},d7,m6=($)=>{let J=d7.exec($);if(!J)throw Error("Invalid ASS timestamp format");let Y=Number(J[1]),j=Number(J[2]),X=Number(J[3]),Z=Number(J[4]);return Y*3600+j*60+X+Z/100},d6=($)=>{let J=Math.floor($/3600),Y=Math.floor($%3600/60),j=Math.floor($%60),X=Math.floor($%1*100);return J.toString()+":"+Y.toString().padStart(2,"0")+":"+j.toString().padStart(2,"0")+"."+X.toString().padStart(2,"0")},J$=($)=>{$=$.replaceAll(`\r
29
29
  `,`
30
30
  `).replaceAll("\r",`
31
31
  `);let J=$.split(`
32
32
  `);if(J.findIndex((W)=>W.trim()==="[Events]")===-1)return{header:$,cues:[]};let j=[],X=[],Z=[],G=[],K=j,Q=!1;for(let W=0;W<J.length;W++){let V=J[W];if(V?.startsWith("[")&&V.endsWith("]")){if(V.trim()==="[Events]"){Q=!0,X.push(V);continue}if(Q)K=G,Q=!1;K.push(V);continue}if(Q){if(!V)continue;if(V.startsWith("Format:"))X.push(V);else if(V.startsWith("Dialogue:"))Z.push(V);else if(V.startsWith("Comment:"))X.push(V)}else if(V!==void 0)K.push(V)}let q=[...j,...X,...G].join(`
33
- `),U=[];for(let W of Z){let V=W.indexOf(":");if(V===-1)continue;let N=W.substring(V+1).split(",");if(N.length<10)continue;try{let A=m6(N[1].trim()),R=m6(N[2].trim());U.push({timestamp:A,duration:R-A,text:W})}catch{}}return{header:q,cues:U}},n7=($)=>{let J=$.substring($.indexOf(":")+1).split(",").map((j)=>j.trim()),Y=new Map;return J.forEach((j,X)=>{Y.set(j,X)}),Y},Y$=($)=>{let J=/^(Dialogue|Comment):\s*(\d+),\d+:\d{2}:\d{2}\.\d{2},\d+:\d{2}:\d{2}\.\d{2},(.*)$/.exec($);if(J){let Y=J[2],j=J[3];return`${Y},${j}`}if($.startsWith("Dialogue:")||$.startsWith("Comment:"))return $.substring($.indexOf(":")+1).trim();return $},r6=($,J)=>{if(!J||J.trim()==="")J=`[Script Info]
33
+ `),U=[];for(let W of Z){let V=W.indexOf(":");if(V===-1)continue;let N=W.substring(V+1).split(",");if(N.length<10)continue;try{let A=m6(N[1].trim()),R=m6(N[2].trim());U.push({timestamp:A,duration:R-A,text:W})}catch{}}return{header:q,cues:U}},c7=($)=>{let J=$.substring($.indexOf(":")+1).split(",").map((j)=>j.trim()),Y=new Map;return J.forEach((j,X)=>{Y.set(j,X)}),Y},Y$=($)=>{let J=/^(Dialogue|Comment):\s*(\d+),\d+:\d{2}:\d{2}\.\d{2},\d+:\d{2}:\d{2}\.\d{2},(.*)$/.exec($);if(J){let Y=J[2],j=J[3];return`${Y},${j}`}if($.startsWith("Dialogue:")||$.startsWith("Comment:"))return $.substring($.indexOf(":")+1).trim();return $},r6=($,J)=>{if(!J||J.trim()==="")J=`[Script Info]
34
34
  Title: Default
35
35
  ScriptType: v4.00+
36
36
 
@@ -45,46 +45,46 @@ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text`
45
45
  [Events]
46
46
  Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
47
47
  `+$.map((V)=>V.text).join(`
48
- `);let X=-1,Z="";for(let V=j+1;V<Y.length;V++){let N=Y[V];if(N?.trim().startsWith("Format:")){X=V,Z=N;break}if(N?.startsWith("[")&&N.endsWith("]"))break}let G=Z?n7(Z):null,K=$.map((V)=>{if(V.text.startsWith("Dialogue:")||V.text.startsWith("Comment:")){if(/^(Dialogue|Comment):\s*\d+,\d+:\d{2}:\d{2}\.\d{2},\d+:\d{2}:\d{2}\.\d{2},/.test(V.text))return V.text}let N=V.text,R=N.startsWith("Comment:")?"Comment:":"Dialogue:";if(N.startsWith("Dialogue:")||N.startsWith("Comment:"))N=N.substring(N.indexOf(":")+1).trim();let z=N.split(","),_=d6(V.timestamp),L=d6(V.timestamp+V.duration),M,B,F=z.length>=9&&!Number.isNaN(Number.parseInt(z[0],10))&&!Number.isNaN(Number.parseInt(z[1],10)),C=z.length>=8&&!Number.isNaN(Number.parseInt(z[0],10));if(F)M=z[1]||"0",B=z.slice(2);else if(C)M=z[0]||"0",B=z.slice(1);else return`${R} 0,${_},${L},Default,,0,0,0,,${V.text}`;return`${R} ${M},${_},${L},${B.join(",")}`});if(X===-1)return`${J}
48
+ `);let X=-1,Z="";for(let V=j+1;V<Y.length;V++){let N=Y[V];if(N?.trim().startsWith("Format:")){X=V,Z=N;break}if(N?.startsWith("[")&&N.endsWith("]"))break}let G=Z?c7(Z):null,K=$.map((V)=>{if(V.text.startsWith("Dialogue:")||V.text.startsWith("Comment:")){if(/^(Dialogue|Comment):\s*\d+,\d+:\d{2}:\d{2}\.\d{2},\d+:\d{2}:\d{2}\.\d{2},/.test(V.text))return V.text}let N=V.text,R=N.startsWith("Comment:")?"Comment:":"Dialogue:";if(N.startsWith("Dialogue:")||N.startsWith("Comment:"))N=N.substring(N.indexOf(":")+1).trim();let z=N.split(","),_=d6(V.timestamp),L=d6(V.timestamp+V.duration),M,B,F=z.length>=9&&!Number.isNaN(Number.parseInt(z[0],10))&&!Number.isNaN(Number.parseInt(z[1],10)),C=z.length>=8&&!Number.isNaN(Number.parseInt(z[0],10));if(F)M=z[1]||"0",B=z.slice(2);else if(C)M=z[0]||"0",B=z.slice(1);else return`${R} 0,${_},${L},Default,,0,0,0,,${V.text}`;return`${R} ${M},${_},${L},${B.join(",")}`});if(X===-1)return`${J}
49
49
  ${K.join(`
50
50
  `)}`;let Q=[],q=Y.length;for(let V=X+1;V<Y.length;V++){let N=Y[V];if(N?.startsWith("Comment:"))Q.push(N);if(N?.startsWith("[")&&N.endsWith("]")){q=V;break}}let U=Y.slice(0,X+1),W=Y.slice(q);return[...U,...K,...Q,...W].join(`
51
- `)};var x0=q7(()=>{/*!
51
+ `)};var x0=Q7(()=>{/*!
52
52
  * Copyright (c) 2025-present, Vanilagy and contributors
53
53
  *
54
54
  * This Source Code Form is subject to the terms of the Mozilla Public
55
55
  * License, v. 2.0. If a copy of the MPL was not distributed with this
56
56
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
57
- */x8=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,l7=/^WEBVTT(.|\n)*?\n{2}/,u1=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;m7=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,d7=/(\d{2}):(\d{2}):(\d{2}),(\d{3})/,c7=/(\d+):(\d{2}):(\d{2})\.(\d{2})/});/*!
57
+ */x8=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,p7=/^WEBVTT(.|\n)*?\n{2}/,u1=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;l7=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,m7=/(\d{2}):(\d{2}):(\d{2}),(\d{3})/,d7=/(\d+):(\d{2}):(\d{2})\.(\d{2})/});/*!
58
58
  * Copyright (c) 2025-present, Vanilagy and contributors
59
59
  *
60
60
  * This Source Code Form is subject to the terms of the Mozilla Public
61
61
  * License, v. 2.0. If a copy of the MPL was not distributed with this
62
62
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
63
- */function H($){if(!$)throw Error("Assertion failed.")}var N1=($)=>{let J=($%360+360)%360;if(J===0||J===90||J===180||J===270)return J;throw Error(`Invalid rotation ${$}.`)},n=($)=>{return $&&$[$.length-1]},E1=($)=>{return $>=0&&$<4294967296};class f{bytes;pos=0;constructor($){this.bytes=$}seekToByte($){this.pos=8*$}readBit(){let $=Math.floor(this.pos/8),J=this.bytes[$]??0,Y=7-(this.pos&7),j=(J&1<<Y)>>Y;return this.pos++,j}readBits($){if($===1)return this.readBit();let J=0;for(let Y=0;Y<$;Y++)J<<=1,J|=this.readBit();return J}writeBits($,J){let Y=this.pos+$;for(let j=this.pos;j<Y;j++){let X=Math.floor(j/8),Z=this.bytes[X],G=7-(j&7);Z&=~(1<<G),Z|=(J&1<<Y-j-1)>>Y-j-1<<G,this.bytes[X]=Z}this.pos=Y}readAlignedByte(){if(this.pos%8!==0)throw Error("Bitstream is not byte-aligned.");let $=this.pos/8,J=this.bytes[$]??0;return this.pos+=8,J}skipBits($){this.pos+=$}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let $=new f(this.bytes);return $.pos=this.pos,$}}var E=($)=>{let J=0;while($.readBits(1)===0&&J<32)J++;if(J>=32)throw Error("Invalid exponential-Golomb code.");return(1<<J)-1+$.readBits(J)},m0=($)=>{let J=E($);return(J&1)===0?-(J>>1):J+1>>1},WJ=($,J,Y,j)=>{for(let X=J;X<Y;X++){let Z=Math.floor(X/8),G=$[Z],K=7-(X&7);G&=~(1<<K),G|=(j&1<<Y-X-1)>>Y-X-1<<K,$[Z]=G}},l=($)=>{if($.constructor===Uint8Array)return $;if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);if(typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer)return new Uint8Array($);return new Uint8Array($)},h=($)=>{if($.constructor===DataView)return $;if(ArrayBuffer.isView($))return new DataView($.buffer,$.byteOffset,$.byteLength);if(typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer)return new DataView($);return new DataView($)},Y0=new TextDecoder,m=new TextEncoder,A1=($)=>{for(let J=0;J<$.length;J++)if($.charCodeAt(J)>255)return!1;return!0},I2=($)=>{return Object.fromEntries(Object.entries($).map(([J,Y])=>[Y,J]))},e0={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},X6=I2(e0),$1={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Z6=I2($1),J1={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},G6=I2(J1),K6=($)=>{return!!$&&!!$.primaries&&!!$.transfer&&!!$.matrix&&$.fullRange!==void 0},i1=($)=>{return $ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer||ArrayBuffer.isView($)};class w0{currentPromise=Promise.resolve();async acquire(){let $,J=new Promise((j)=>{$=j}),Y=this.currentPromise;return this.currentPromise=J,await Y,$}}var S2=($)=>{return[...$].map((J)=>J.toString(16).padStart(2,"0")).join("")},h2=($)=>{return $=$>>1&1431655765|($&1431655765)<<1,$=$>>2&858993459|($&858993459)<<2,$=$>>4&252645135|($&252645135)<<4,$=$>>8&16711935|($&16711935)<<8,$=$>>16&65535|($&65535)<<16,$>>>0},Y1=($,J,Y)=>{let j=0,X=$.length-1,Z=-1;while(j<=X){let G=j+X>>1,K=Y($[G]);if(K===J)Z=G,X=G-1;else if(K<J)j=G+1;else X=G-1}return Z},u=($,J,Y)=>{let j=0,X=$.length-1,Z=-1;while(j<=X){let G=j+(X-j+1)/2|0;if(Y($[G])<=J)Z=G,j=G+1;else X=G-1}return Z},f2=($,J,Y)=>{let j=u($,Y(J),Y);$.splice(j+1,0,J)},c=()=>{let $,J;return{promise:new Promise((j,X)=>{$=j,J=X}),resolve:$,reject:J}};var g2=($,J)=>{for(let Y=$.length-1;Y>=0;Y--)if(J($[Y]))return $[Y];return},Q6=($,J)=>{for(let Y=$.length-1;Y>=0;Y--)if(J($[Y]))return Y;return-1},VJ=async function*($){if(Symbol.iterator in $)yield*$[Symbol.iterator]();else yield*$[Symbol.asyncIterator]()},HJ=($)=>{if(!(Symbol.iterator in $)&&!(Symbol.asyncIterator in $))throw TypeError("Argument must be an iterable or async iterable.")},i=($)=>{throw Error(`Unexpected value: ${$}`)},T1=($,J,Y)=>{let j=$.getUint8(J),X=$.getUint8(J+1),Z=$.getUint8(J+2);if(Y)return j|X<<8|Z<<16;return j<<16|X<<8|Z},NJ=($,J,Y)=>{return T1($,J,Y)<<8>>8},L8=($,J,Y,j)=>{if(Y=Y>>>0,Y=Y&16777215,j)$.setUint8(J,Y&255),$.setUint8(J+1,Y>>>8&255),$.setUint8(J+2,Y>>>16&255);else $.setUint8(J,Y>>>16&255),$.setUint8(J+1,Y>>>8&255),$.setUint8(J+2,Y&255)},AJ=($,J,Y,j)=>{if(Y=$0(Y,-8388608,8388607),Y<0)Y=Y+16777216&16777215;L8($,J,Y,j)},RJ=($,J,Y,j)=>{if(j)$.setUint32(J+0,Y,!0),$.setInt32(J+4,Math.floor(Y/4294967296),!0);else $.setInt32(J+0,Math.floor(Y/4294967296),!0),$.setUint32(J+4,Y,!0)},M8=($,J)=>{return{async next(){let Y=await $.next();if(Y.done)return{value:void 0,done:!0};return{value:J(Y.value),done:!1}},return(){return $.return()},throw(Y){return $.throw(Y)},[Symbol.asyncIterator](){return this},async[Symbol.asyncDispose](){await $.return()}}},$0=($,J,Y)=>{return Math.max(J,Math.min(Y,$))},a="und",y1=($)=>{let J=Math.round($);if(Math.abs($/J-1)<10*Number.EPSILON)return J;return $},F8=($,J)=>{return Math.round($/J)*J},zJ=($)=>{let J=0;while($)J++,$>>=1;return J},U7=/^[a-z]{3}$/,d0=($)=>{return U7.test($)},c0=1e6*(1+Number.EPSILON),k2=($,J)=>{let Y={...$,...J};if($.headers||J.headers){let j=$.headers?UJ($.headers):{},X=J.headers?UJ(J.headers):{},Z={...j};Object.entries(X).forEach(([G,K])=>{let Q=Object.keys(Z).find((q)=>q.toLowerCase()===G.toLowerCase());if(Q)delete Z[Q];Z[G]=K}),Y.headers=Z}return Y},UJ=($)=>{if($ instanceof Headers){let J={};return $.forEach((Y,j)=>{J[j]=Y}),J}if(Array.isArray($)){let J={};return $.forEach(([Y,j])=>{J[Y]=j}),J}return $},u2=async($,J,Y,j,X)=>{let Z=0;while(!0)try{return await $(J,Y)}catch(G){if(X())throw G;Z++;let K=j(Z,G,J);if(K===null)throw G;if(console.error("Retrying failed fetch. Error:",G),!Number.isFinite(K)||K<0)throw TypeError("Retry delay must be a non-negative finite number.");if(K>0)await new Promise((Q)=>setTimeout(Q,1000*K));if(X())throw G}},_J=($,J)=>{let Y=$<0?-1:1;$=Math.abs($);let j=0,X=1,Z=1,G=0,K=$;while(!0){let Q=Math.floor(K),q=Q*Z+j,U=Q*G+X;if(U>J)return{numerator:Y*Z,denominator:G};if(j=Z,X=G,Z=q,G=U,K=1/(K-Q),!isFinite(K))break}return{numerator:Y*Z,denominator:G}};class v1{currentPromise=Promise.resolve();call($){return this.currentPromise=this.currentPromise.then($)}}var y2=null,s1=()=>{if(y2!==null)return y2;return y2=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)))},v2=null,n0=()=>{if(v2!==null)return v2;return v2=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox")},b2=null,B8=()=>{if(b2!==null)return b2;return b2=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent)))},x2=null,LJ=()=>{if(x2!==null)return x2;if(typeof navigator>"u")return null;let $=/\bChrome\/(\d+)/.exec(navigator.userAgent);if(!$)return null;return x2=Number($[1])},b1=($,J)=>{return $!==-1?$:J},q6=($,J,Y,j)=>{return $<=j&&Y<=J},v0=function*($){for(let J in $){let Y=$[J];if(Y===void 0)continue;yield{key:J,value:Y}}},MJ=($)=>{switch($.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}},FJ=($)=>{let J=atob($),Y=new Uint8Array(J.length);for(let j=0;j<J.length;j++)Y[j]=J.charCodeAt(j);return Y},BJ=($)=>{let J="";for(let Y=0;Y<$.length;Y++)J+=String.fromCharCode($[Y]);return btoa(J)},wJ=($,J)=>{if($.length!==J.length)return!1;for(let Y=0;Y<$.length;Y++)if($[Y]!==J[Y])return!1;return!0},U6=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},R1=($)=>{return typeof $==="number"&&!Number.isNaN($)};/*!
63
+ */function H($){if(!$)throw Error("Assertion failed.")}var N1=($)=>{let J=($%360+360)%360;if(J===0||J===90||J===180||J===270)return J;throw Error(`Invalid rotation ${$}.`)},n=($)=>{return $&&$[$.length-1]},E1=($)=>{return $>=0&&$<4294967296};class f{bytes;pos=0;constructor($){this.bytes=$}seekToByte($){this.pos=8*$}readBit(){let $=Math.floor(this.pos/8),J=this.bytes[$]??0,Y=7-(this.pos&7),j=(J&1<<Y)>>Y;return this.pos++,j}readBits($){if($===1)return this.readBit();let J=0;for(let Y=0;Y<$;Y++)J<<=1,J|=this.readBit();return J}writeBits($,J){let Y=this.pos+$;for(let j=this.pos;j<Y;j++){let X=Math.floor(j/8),Z=this.bytes[X],G=7-(j&7);Z&=~(1<<G),Z|=(J&1<<Y-j-1)>>Y-j-1<<G,this.bytes[X]=Z}this.pos=Y}readAlignedByte(){if(this.pos%8!==0)throw Error("Bitstream is not byte-aligned.");let $=this.pos/8,J=this.bytes[$]??0;return this.pos+=8,J}skipBits($){this.pos+=$}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let $=new f(this.bytes);return $.pos=this.pos,$}}var E=($)=>{let J=0;while($.readBits(1)===0&&J<32)J++;if(J>=32)throw Error("Invalid exponential-Golomb code.");return(1<<J)-1+$.readBits(J)},m0=($)=>{let J=E($);return(J&1)===0?-(J>>1):J+1>>1},WJ=($,J,Y,j)=>{for(let X=J;X<Y;X++){let Z=Math.floor(X/8),G=$[Z],K=7-(X&7);G&=~(1<<K),G|=(j&1<<Y-X-1)>>Y-X-1<<K,$[Z]=G}},l=($)=>{if($.constructor===Uint8Array)return $;if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);if(typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer)return new Uint8Array($);return new Uint8Array($)},h=($)=>{if($.constructor===DataView)return $;if(ArrayBuffer.isView($))return new DataView($.buffer,$.byteOffset,$.byteLength);if(typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer)return new DataView($);return new DataView($)},Y0=new TextDecoder,m=new TextEncoder,A1=($)=>{for(let J=0;J<$.length;J++)if($.charCodeAt(J)>255)return!1;return!0},I2=($)=>{return Object.fromEntries(Object.entries($).map(([J,Y])=>[Y,J]))},e0={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},X6=I2(e0),$1={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Z6=I2($1),J1={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},G6=I2(J1),K6=($)=>{return!!$&&!!$.primaries&&!!$.transfer&&!!$.matrix&&$.fullRange!==void 0},i1=($)=>{return $ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer||ArrayBuffer.isView($)};class w0{currentPromise=Promise.resolve();async acquire(){let $,J=new Promise((j)=>{$=j}),Y=this.currentPromise;return this.currentPromise=J,await Y,$}}var S2=($)=>{return[...$].map((J)=>J.toString(16).padStart(2,"0")).join("")},h2=($)=>{return $=$>>1&1431655765|($&1431655765)<<1,$=$>>2&858993459|($&858993459)<<2,$=$>>4&252645135|($&252645135)<<4,$=$>>8&16711935|($&16711935)<<8,$=$>>16&65535|($&65535)<<16,$>>>0},Y1=($,J,Y)=>{let j=0,X=$.length-1,Z=-1;while(j<=X){let G=j+X>>1,K=Y($[G]);if(K===J)Z=G,X=G-1;else if(K<J)j=G+1;else X=G-1}return Z},u=($,J,Y)=>{let j=0,X=$.length-1,Z=-1;while(j<=X){let G=j+(X-j+1)/2|0;if(Y($[G])<=J)Z=G,j=G+1;else X=G-1}return Z},f2=($,J,Y)=>{let j=u($,Y(J),Y);$.splice(j+1,0,J)},c=()=>{let $,J;return{promise:new Promise((j,X)=>{$=j,J=X}),resolve:$,reject:J}};var g2=($,J)=>{for(let Y=$.length-1;Y>=0;Y--)if(J($[Y]))return $[Y];return},Q6=($,J)=>{for(let Y=$.length-1;Y>=0;Y--)if(J($[Y]))return Y;return-1},VJ=async function*($){if(Symbol.iterator in $)yield*$[Symbol.iterator]();else yield*$[Symbol.asyncIterator]()},HJ=($)=>{if(!(Symbol.iterator in $)&&!(Symbol.asyncIterator in $))throw TypeError("Argument must be an iterable or async iterable.")},i=($)=>{throw Error(`Unexpected value: ${$}`)},T1=($,J,Y)=>{let j=$.getUint8(J),X=$.getUint8(J+1),Z=$.getUint8(J+2);if(Y)return j|X<<8|Z<<16;return j<<16|X<<8|Z},NJ=($,J,Y)=>{return T1($,J,Y)<<8>>8},L8=($,J,Y,j)=>{if(Y=Y>>>0,Y=Y&16777215,j)$.setUint8(J,Y&255),$.setUint8(J+1,Y>>>8&255),$.setUint8(J+2,Y>>>16&255);else $.setUint8(J,Y>>>16&255),$.setUint8(J+1,Y>>>8&255),$.setUint8(J+2,Y&255)},AJ=($,J,Y,j)=>{if(Y=$0(Y,-8388608,8388607),Y<0)Y=Y+16777216&16777215;L8($,J,Y,j)},RJ=($,J,Y,j)=>{if(j)$.setUint32(J+0,Y,!0),$.setInt32(J+4,Math.floor(Y/4294967296),!0);else $.setInt32(J+0,Math.floor(Y/4294967296),!0),$.setUint32(J+4,Y,!0)},M8=($,J)=>{return{async next(){let Y=await $.next();if(Y.done)return{value:void 0,done:!0};return{value:J(Y.value),done:!1}},return(){return $.return()},throw(Y){return $.throw(Y)},[Symbol.asyncIterator](){return this},async[Symbol.asyncDispose](){await $.return()}}},$0=($,J,Y)=>{return Math.max(J,Math.min(Y,$))},a="und",y1=($)=>{let J=Math.round($);if(Math.abs($/J-1)<10*Number.EPSILON)return J;return $},F8=($,J)=>{return Math.round($/J)*J},zJ=($)=>{let J=0;while($)J++,$>>=1;return J},q7=/^[a-z]{3}$/,d0=($)=>{return q7.test($)},c0=1e6*(1+Number.EPSILON),k2=($,J)=>{let Y={...$,...J};if($.headers||J.headers){let j=$.headers?UJ($.headers):{},X=J.headers?UJ(J.headers):{},Z={...j};Object.entries(X).forEach(([G,K])=>{let Q=Object.keys(Z).find((q)=>q.toLowerCase()===G.toLowerCase());if(Q)delete Z[Q];Z[G]=K}),Y.headers=Z}return Y},UJ=($)=>{if($ instanceof Headers){let J={};return $.forEach((Y,j)=>{J[j]=Y}),J}if(Array.isArray($)){let J={};return $.forEach(([Y,j])=>{J[Y]=j}),J}return $},u2=async($,J,Y,j,X)=>{let Z=0;while(!0)try{return await $(J,Y)}catch(G){if(X())throw G;Z++;let K=j(Z,G,J);if(K===null)throw G;if(console.error("Retrying failed fetch. Error:",G),!Number.isFinite(K)||K<0)throw TypeError("Retry delay must be a non-negative finite number.");if(K>0)await new Promise((Q)=>setTimeout(Q,1000*K));if(X())throw G}},_J=($,J)=>{let Y=$<0?-1:1;$=Math.abs($);let j=0,X=1,Z=1,G=0,K=$;while(!0){let Q=Math.floor(K),q=Q*Z+j,U=Q*G+X;if(U>J)return{numerator:Y*Z,denominator:G};if(j=Z,X=G,Z=q,G=U,K=1/(K-Q),!isFinite(K))break}return{numerator:Y*Z,denominator:G}};class v1{currentPromise=Promise.resolve();call($){return this.currentPromise=this.currentPromise.then($)}}var y2=null,s1=()=>{if(y2!==null)return y2;return y2=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)))},v2=null,n0=()=>{if(v2!==null)return v2;return v2=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox")},b2=null,B8=()=>{if(b2!==null)return b2;return b2=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent)))},x2=null,LJ=()=>{if(x2!==null)return x2;if(typeof navigator>"u")return null;let $=/\bChrome\/(\d+)/.exec(navigator.userAgent);if(!$)return null;return x2=Number($[1])},b1=($,J)=>{return $!==-1?$:J},q6=($,J,Y,j)=>{return $<=j&&Y<=J},v0=function*($){for(let J in $){let Y=$[J];if(Y===void 0)continue;yield{key:J,value:Y}}},MJ=($)=>{switch($.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}},FJ=($)=>{let J=atob($),Y=new Uint8Array(J.length);for(let j=0;j<J.length;j++)Y[j]=J.charCodeAt(j);return Y},BJ=($)=>{let J="";for(let Y=0;Y<$.length;Y++)J+=String.fromCharCode($[Y]);return btoa(J)},wJ=($,J)=>{if($.length!==J.length)return!1;for(let Y=0;Y<$.length;Y++)if($[Y]!==J[Y])return!1;return!0},U6=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},R1=($)=>{return typeof $==="number"&&!Number.isNaN($)};/*!
64
64
  * Copyright (c) 2025-present, Vanilagy and contributors
65
65
  *
66
66
  * This Source Code Form is subject to the terms of the Mozilla Public
67
67
  * License, v. 2.0. If a copy of the MPL was not distributed with this
68
68
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
69
- */var j0=["avc","hevc","vp9","av1","vp8","mpeg4"],o=["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"],X1=["aac","opus","mp3","vorbis","flac","ac3","eac3"],Z0=[...X1,...o],z0=["webvtt","tx3g","ttml","srt","ass","ssa"],OJ=[{maxMacroblocks:99,maxBitrate:64000,level:10},{maxMacroblocks:396,maxBitrate:192000,level:11},{maxMacroblocks:396,maxBitrate:384000,level:12},{maxMacroblocks:396,maxBitrate:768000,level:13},{maxMacroblocks:396,maxBitrate:2000000,level:20},{maxMacroblocks:792,maxBitrate:4000000,level:21},{maxMacroblocks:1620,maxBitrate:4000000,level:22},{maxMacroblocks:1620,maxBitrate:1e7,level:30},{maxMacroblocks:3600,maxBitrate:14000000,level:31},{maxMacroblocks:5120,maxBitrate:20000000,level:32},{maxMacroblocks:8192,maxBitrate:20000000,level:40},{maxMacroblocks:8192,maxBitrate:50000000,level:41},{maxMacroblocks:8704,maxBitrate:50000000,level:42},{maxMacroblocks:22080,maxBitrate:135000000,level:50},{maxMacroblocks:36864,maxBitrate:240000000,level:51},{maxMacroblocks:36864,maxBitrate:240000000,level:52},{maxMacroblocks:139264,maxBitrate:240000000,level:60},{maxMacroblocks:139264,maxBitrate:480000000,level:61},{maxMacroblocks:139264,maxBitrate:800000000,level:62}],PJ=[{maxPictureSize:36864,maxBitrate:128000,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:1500000,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3000000,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6000000,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12000000,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:30000000,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:20000000,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:50000000,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25000000,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:40000000,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:160000000,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:60000000,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:240000000,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:60000000,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:240000000,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:120000000,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:480000000,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:240000000,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:800000000,tier:"H",level:186}],j1=[{maxPictureSize:36864,maxBitrate:200000,level:10},{maxPictureSize:73728,maxBitrate:800000,level:11},{maxPictureSize:122880,maxBitrate:1800000,level:20},{maxPictureSize:245760,maxBitrate:3600000,level:21},{maxPictureSize:552960,maxBitrate:7200000,level:30},{maxPictureSize:983040,maxBitrate:12000000,level:31},{maxPictureSize:2228224,maxBitrate:18000000,level:40},{maxPictureSize:2228224,maxBitrate:30000000,level:41},{maxPictureSize:8912896,maxBitrate:60000000,level:50},{maxPictureSize:8912896,maxBitrate:120000000,level:51},{maxPictureSize:8912896,maxBitrate:180000000,level:52},{maxPictureSize:35651584,maxBitrate:180000000,level:60},{maxPictureSize:35651584,maxBitrate:240000000,level:61},{maxPictureSize:35651584,maxBitrate:480000000,level:62}],CJ=[{maxPictureSize:147456,maxBitrate:1500000,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3000000,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6000000,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12000000,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:30000000,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:20000000,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:50000000,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:30000000,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:40000000,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:160000000,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:60000000,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:240000000,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:60000000,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:240000000,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:60000000,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:240000000,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:480000000,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:160000000,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:800000000,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:160000000,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:800000000,tier:"H",level:19}],DJ=".01.01.01.01.00",EJ=".0.110.01.01.01.0",TJ=($,J,Y,j)=>{if($==="avc"){let Z=Math.ceil(J/16)*Math.ceil(Y/16),G=OJ.find((W)=>Z<=W.maxMacroblocks&&j<=W.maxBitrate)??n(OJ),K=G?G.level:0,Q=100 .toString(16).padStart(2,"0"),q="00",U=K.toString(16).padStart(2,"0");return`avc1.${Q}00${U}`}if($==="hevc"){let K=J*Y,Q=PJ.find((U)=>K<=U.maxPictureSize&&j<=U.maxBitrate)??n(PJ),q="B0";return`hev1.1.6.${Q.tier}${Q.level}.B0`}if($==="vp8")return"vp8";if($==="vp9"){let Z=J*Y,G=j1.find((Q)=>Z<=Q.maxPictureSize&&j<=Q.maxBitrate)??n(j1),K="08";return`vp09.00.${G.level.toString().padStart(2,"0")}.08`}if($==="av1"){let Z=J*Y,G=CJ.find((q)=>Z<=q.maxPictureSize&&j<=q.maxBitrate)??n(CJ),K=G.level.toString().padStart(2,"0"),Q="08";return`av01.0.${K}${G.tier}.08`}if($==="mpeg4")return"mp4v.20.9";throw TypeError(`Unhandled codec '${$}'.`)},yJ=($)=>{let J=$.split("."),Y=Number(J[1]),j=Number(J[2]),X=Number(J[3]),Z=J[4]?Number(J[4]):1;return[1,1,Y,2,1,j,3,1,X,4,1,Z]},W6=($)=>{let J=$.split("."),Y=1,j=1,X=129,Z=Number(J[1]),G=J[2],K=Number(G.slice(0,-1)),Q=(Z<<5)+K,q=G.slice(-1)==="H"?1:0,W=Number(J[3])===8?0:1,V=0,N=J[4]?Number(J[4]):0,A=J[5]?Number(J[5][0]):1,R=J[5]?Number(J[5][1]):1,z=J[5]?Number(J[5][2]):0,_=(q<<7)+(W<<6)+0+(N<<4)+(A<<3)+(R<<2)+z,L=0,M=0;return[129,Q,_,0]},V6=($)=>{let{codec:J,codecDescription:Y,colorSpace:j,avcCodecInfo:X,hevcCodecInfo:Z,vp9CodecInfo:G,av1CodecInfo:K}=$;if(J==="avc"){if(H($.avcType!==null),X){let Q=new Uint8Array([X.avcProfileIndication,X.profileCompatibility,X.avcLevelIndication]);return`avc${$.avcType}.${S2(Q)}`}if(!Y||Y.byteLength<4)throw TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${$.avcType}.${S2(Y.subarray(1,4))}`}if(J==="hevc"){let Q,q,U,W,V,N;if(Z)Q=Z.generalProfileSpace,q=Z.generalProfileIdc,U=h2(Z.generalProfileCompatibilityFlags),W=Z.generalTierFlag,V=Z.generalLevelIdc,N=[...Z.generalConstraintIndicatorFlags];else{if(!Y||Y.byteLength<23)throw TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let R=h(Y),z=R.getUint8(1);Q=z>>6&3,q=z&31,U=h2(R.getUint32(2)),W=z>>5&1,V=R.getUint8(12),N=[];for(let _=0;_<6;_++)N.push(R.getUint8(6+_))}let A="hev1.";A+=["","A","B","C"][Q]+q,A+=".",A+=U.toString(16).toUpperCase(),A+=".",A+=W===0?"L":"H",A+=V;while(N.length>0&&N[N.length-1]===0)N.pop();if(N.length>0)A+=".",A+=N.map((R)=>R.toString(16).toUpperCase()).join(".");return A}if(J==="vp8")return"vp8";if(J==="vp9"){if(!G){let _=$.width*$.height,L=n(j1).level;for(let M of j1)if(_<=M.maxPictureSize){L=M.level;break}return`vp09.00.${L.toString().padStart(2,"0")}.08`}let Q=G.profile.toString().padStart(2,"0"),q=G.level.toString().padStart(2,"0"),U=G.bitDepth.toString().padStart(2,"0"),W=G.chromaSubsampling.toString().padStart(2,"0"),V=G.colourPrimaries.toString().padStart(2,"0"),N=G.transferCharacteristics.toString().padStart(2,"0"),A=G.matrixCoefficients.toString().padStart(2,"0"),R=G.videoFullRangeFlag.toString().padStart(2,"0"),z=`vp09.${Q}.${q}.${U}.${W}`;if(z+=`.${V}.${N}.${A}.${R}`,z.endsWith(DJ))z=z.slice(0,-DJ.length);return z}if(J==="av1"){if(!K){let M=$.width*$.height,B=n(j1).level;for(let F of j1)if(M<=F.maxPictureSize){B=F.level;break}return`av01.0.${B.toString().padStart(2,"0")}M.08`}let Q=K.profile,q=K.level.toString().padStart(2,"0"),U=K.tier?"H":"M",W=K.bitDepth.toString().padStart(2,"0"),V=K.monochrome?"1":"0",N=100*K.chromaSubsamplingX+10*K.chromaSubsamplingY+1*(K.chromaSubsamplingX&&K.chromaSubsamplingY?K.chromaSamplePosition:0),A=j?.primaries?e0[j.primaries]:1,R=j?.transfer?$1[j.transfer]:1,z=j?.matrix?J1[j.matrix]:1,_=j?.fullRange?1:0,L=`av01.${Q}.${q}${U}.${W}`;if(L+=`.${V}.${N.toString().padStart(3,"0")}`,L+=`.${A.toString().padStart(2,"0")}`,L+=`.${R.toString().padStart(2,"0")}`,L+=`.${z.toString().padStart(2,"0")}`,L+=`.${_}`,L.endsWith(EJ))L=L.slice(0,-EJ.length);return L}if(J==="mpeg4")return"mp4v";throw TypeError(`Unhandled codec '${J}'.`)},vJ=($,J,Y)=>{if($==="aac"){if(J>=2&&Y<=24000)return"mp4a.40.29";if(Y<=24000)return"mp4a.40.5";return"mp4a.40.2"}if($==="mp3")return"mp3";if($==="opus")return"opus";if($==="vorbis")return"vorbis";if($==="flac")return"flac";if($==="ac3")return"ac-3";if($==="eac3")return"ec-3";if(o.includes($))return $;throw TypeError(`Unhandled codec '${$}'.`)},H6=($)=>{let{codec:J,codecDescription:Y,aacCodecInfo:j}=$;if(J==="aac"){if(!j)throw TypeError("AAC codec info must be provided.");if(j.isMpeg2)return"mp4a.67";return`mp4a.40.${x1(Y).objectType}`}if(J==="mp3")return"mp3";if(J==="opus")return"opus";if(J==="vorbis")return"vorbis";if(J==="flac")return"flac";if(J==="ac3")return"ac3";if(J==="eac3")return"ec-3";if(J&&o.includes(J))return J;throw TypeError(`Unhandled codec '${J}'.`)},a1=[96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350],N6=[-1,1,2,3,4,5,6,8],x1=($)=>{if(!$||$.byteLength<2)throw TypeError("AAC description must be at least 2 bytes long.");let J=new f($),Y=J.readBits(5);if(Y===31)Y=32+J.readBits(6);let j=J.readBits(4),X=null;if(j===15)X=J.readBits(24);else if(j<a1.length)X=a1[j];let Z=J.readBits(4),G=null;if(Z>=1&&Z<=7)G=N6[Z];return{objectType:Y,frequencyIndex:j,sampleRate:X,channelConfiguration:Z,numberOfChannels:G}},bJ=($)=>{let J=a1.indexOf($.sampleRate),Y=null;if(J===-1)J=15,Y=$.sampleRate;let j=N6.indexOf($.numberOfChannels);if(j===-1)throw TypeError(`Unsupported number of channels: ${$.numberOfChannels}`);let X=13;if($.objectType>=32)X+=6;if(J===15)X+=24;let Z=Math.ceil(X/8),G=new Uint8Array(Z),K=new f(G);if($.objectType<32)K.writeBits(5,$.objectType);else K.writeBits(5,31),K.writeBits(6,$.objectType-32);if(K.writeBits(4,J),J===15)K.writeBits(24,Y);return K.writeBits(4,j),G},b0=48000,xJ=/^pcm-([usf])(\d+)+(be)?$/,U0=($)=>{if(H(o.includes($)),$==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if($==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let J=xJ.exec($);H(J);let Y;if(J[1]==="u")Y="unsigned";else if(J[1]==="s")Y="signed";else Y="float";let j=Number(J[2])/8,X=J[3]!=="be";return{dataType:Y,sampleSize:j,littleEndian:X,silentValue:$==="pcm-u8"?128:0}},p2=($)=>{if($.startsWith("avc1")||$.startsWith("avc3"))return"avc";if($.startsWith("hev1")||$.startsWith("hvc1"))return"hevc";if($==="vp8")return"vp8";if($.startsWith("vp09"))return"vp9";if($.startsWith("av01"))return"av1";if($==="mp4v"||$.startsWith("mp4v."))return"mpeg4";if($.startsWith("mp4a.40")||$==="mp4a.67")return"aac";if($==="mp3"||$==="mp4a.69"||$==="mp4a.6B"||$==="mp4a.6b")return"mp3";if($==="opus")return"opus";if($==="vorbis")return"vorbis";if($==="flac")return"flac";if($==="ac-3"||$==="ac3")return"ac3";if($==="ec-3"||$==="eac3")return"eac3";if($==="ulaw")return"ulaw";if($==="alaw")return"alaw";if(xJ.test($))return $;if($==="webvtt")return"webvtt";if($==="srt")return"srt";if($==="ass")return"ass";if($==="ssa")return"ssa";return null},IJ=($)=>{if($==="avc")return{avc:{format:"avc"}};if($==="hevc")return{hevc:{format:"hevc"}};return{}},SJ=($)=>{if($==="aac")return{aac:{format:"aac"}};if($==="opus")return{opus:{format:"opus"}};return{}},W7=["avc1","avc3","hev1","hvc1","vp8","vp09","av01","mp4v"],V7=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,H7=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,N7=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,A7=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,t1=($)=>{if(!$)throw TypeError("Video chunk metadata must be provided.");if(typeof $!=="object")throw TypeError("Video chunk metadata must be an object.");if(!$.decoderConfig)throw TypeError("Video chunk metadata must include a decoder configuration.");if(typeof $.decoderConfig!=="object")throw TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof $.decoderConfig.codec!=="string")throw TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!W7.some((J)=>$.decoderConfig.codec.startsWith(J)))throw TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger($.decoderConfig.codedWidth)||$.decoderConfig.codedWidth<=0)throw TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger($.decoderConfig.codedHeight)||$.decoderConfig.codedHeight<=0)throw TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if($.decoderConfig.description!==void 0){if(!i1($.decoderConfig.description))throw TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.")}if($.decoderConfig.colorSpace!==void 0){let{colorSpace:J}=$.decoderConfig;if(typeof J!=="object")throw TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let Y=Object.keys(e0);if(J.primaries!=null&&!Y.includes(J.primaries))throw TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${Y.join(", ")}.`);let j=Object.keys($1);if(J.transfer!=null&&!j.includes(J.transfer))throw TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${j.join(", ")}.`);let X=Object.keys(J1);if(J.matrix!=null&&!X.includes(J.matrix))throw TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${X.join(", ")}.`);if(J.fullRange!=null&&typeof J.fullRange!=="boolean")throw TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if($.decoderConfig.codec.startsWith("avc1")||$.decoderConfig.codec.startsWith("avc3")){if(!V7.test($.decoderConfig.codec))throw TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if($.decoderConfig.codec.startsWith("hev1")||$.decoderConfig.codec.startsWith("hvc1")){if(!H7.test($.decoderConfig.codec))throw TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if($.decoderConfig.codec.startsWith("vp8")){if($.decoderConfig.codec!=="vp8")throw TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if($.decoderConfig.codec.startsWith("vp09")){if(!N7.test($.decoderConfig.codec))throw TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if($.decoderConfig.codec.startsWith("av01")){if(!A7.test($.decoderConfig.codec))throw TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')}else if($.decoderConfig.codec==="mp4v"||$.decoderConfig.codec.startsWith("mp4v.")){if($.decoderConfig.codec!=="mp4v")throw TypeError('Video chunk metadata decoder configuration codec string for MPEG-4 must be "mp4v".')}},R7=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],_0=($)=>{if(!$)throw TypeError("Audio chunk metadata must be provided.");if(typeof $!=="object")throw TypeError("Audio chunk metadata must be an object.");if(!$.decoderConfig)throw TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof $.decoderConfig!=="object")throw TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof $.decoderConfig.codec!=="string")throw TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!R7.some((J)=>$.decoderConfig.codec.startsWith(J)))throw TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger($.decoderConfig.sampleRate)||$.decoderConfig.sampleRate<=0)throw TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger($.decoderConfig.numberOfChannels)||$.decoderConfig.numberOfChannels<=0)throw TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if($.decoderConfig.description!==void 0){if(!i1($.decoderConfig.description))throw TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.")}if($.decoderConfig.codec.startsWith("mp4a")&&$.decoderConfig.codec!=="mp4a.69"&&$.decoderConfig.codec!=="mp4a.6B"&&$.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes($.decoderConfig.codec))throw TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.");if(!$.decoderConfig.description)throw TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}else if($.decoderConfig.codec.startsWith("mp3")||$.decoderConfig.codec.startsWith("mp4a")){if($.decoderConfig.codec!=="mp3"&&$.decoderConfig.codec!=="mp4a.69"&&$.decoderConfig.codec!=="mp4a.6B"&&$.decoderConfig.codec!=="mp4a.6b")throw TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if($.decoderConfig.codec.startsWith("opus")){if($.decoderConfig.codec!=="opus")throw TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if($.decoderConfig.description&&$.decoderConfig.description.byteLength<18)throw TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if($.decoderConfig.codec.startsWith("vorbis")){if($.decoderConfig.codec!=="vorbis")throw TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!$.decoderConfig.description)throw TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if($.decoderConfig.codec.startsWith("flac")){if($.decoderConfig.codec!=="flac")throw TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');let J=42;if(!$.decoderConfig.description||$.decoderConfig.description.byteLength<J)throw TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if($.decoderConfig.codec==="ac-3"||$.decoderConfig.codec==="ac3"){if($.decoderConfig.codec!=="ac-3")throw TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if($.decoderConfig.codec==="ec-3"||$.decoderConfig.codec==="eac3"){if($.decoderConfig.codec!=="ec-3")throw TypeError('Audio chunk metadata decoder configuration codec string for E-AC-3 must be "ec-3".')}else if($.decoderConfig.codec.startsWith("pcm")||$.decoderConfig.codec.startsWith("ulaw")||$.decoderConfig.codec.startsWith("alaw")){if(!o.includes($.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${o.join(", ")}).`)}},A6=($)=>{if(!$)throw TypeError("Subtitle metadata must be provided.");if(typeof $!=="object")throw TypeError("Subtitle metadata must be an object.");if(!$.config)throw TypeError("Subtitle metadata must include a config object.");if(typeof $.config!=="object")throw TypeError("Subtitle metadata config must be an object.");if(typeof $.config.description!=="string")throw TypeError("Subtitle metadata config description must be a string.")};/*!
69
+ */var j0=["avc","hevc","vp9","av1","vp8","mpeg4"],o=["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"],X1=["aac","opus","mp3","vorbis","flac","ac3","eac3"],Z0=[...X1,...o],z0=["webvtt","tx3g","ttml","srt","ass","ssa"],OJ=[{maxMacroblocks:99,maxBitrate:64000,level:10},{maxMacroblocks:396,maxBitrate:192000,level:11},{maxMacroblocks:396,maxBitrate:384000,level:12},{maxMacroblocks:396,maxBitrate:768000,level:13},{maxMacroblocks:396,maxBitrate:2000000,level:20},{maxMacroblocks:792,maxBitrate:4000000,level:21},{maxMacroblocks:1620,maxBitrate:4000000,level:22},{maxMacroblocks:1620,maxBitrate:1e7,level:30},{maxMacroblocks:3600,maxBitrate:14000000,level:31},{maxMacroblocks:5120,maxBitrate:20000000,level:32},{maxMacroblocks:8192,maxBitrate:20000000,level:40},{maxMacroblocks:8192,maxBitrate:50000000,level:41},{maxMacroblocks:8704,maxBitrate:50000000,level:42},{maxMacroblocks:22080,maxBitrate:135000000,level:50},{maxMacroblocks:36864,maxBitrate:240000000,level:51},{maxMacroblocks:36864,maxBitrate:240000000,level:52},{maxMacroblocks:139264,maxBitrate:240000000,level:60},{maxMacroblocks:139264,maxBitrate:480000000,level:61},{maxMacroblocks:139264,maxBitrate:800000000,level:62}],PJ=[{maxPictureSize:36864,maxBitrate:128000,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:1500000,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3000000,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6000000,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12000000,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:30000000,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:20000000,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:50000000,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25000000,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:40000000,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:160000000,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:60000000,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:240000000,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:60000000,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:240000000,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:120000000,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:480000000,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:240000000,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:800000000,tier:"H",level:186}],j1=[{maxPictureSize:36864,maxBitrate:200000,level:10},{maxPictureSize:73728,maxBitrate:800000,level:11},{maxPictureSize:122880,maxBitrate:1800000,level:20},{maxPictureSize:245760,maxBitrate:3600000,level:21},{maxPictureSize:552960,maxBitrate:7200000,level:30},{maxPictureSize:983040,maxBitrate:12000000,level:31},{maxPictureSize:2228224,maxBitrate:18000000,level:40},{maxPictureSize:2228224,maxBitrate:30000000,level:41},{maxPictureSize:8912896,maxBitrate:60000000,level:50},{maxPictureSize:8912896,maxBitrate:120000000,level:51},{maxPictureSize:8912896,maxBitrate:180000000,level:52},{maxPictureSize:35651584,maxBitrate:180000000,level:60},{maxPictureSize:35651584,maxBitrate:240000000,level:61},{maxPictureSize:35651584,maxBitrate:480000000,level:62}],CJ=[{maxPictureSize:147456,maxBitrate:1500000,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3000000,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6000000,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12000000,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:30000000,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:20000000,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:50000000,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:30000000,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:40000000,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:160000000,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:60000000,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:240000000,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:60000000,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:240000000,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:60000000,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:240000000,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:480000000,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:160000000,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:800000000,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:160000000,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:800000000,tier:"H",level:19}],DJ=".01.01.01.01.00",EJ=".0.110.01.01.01.0",TJ=($,J,Y,j)=>{if($==="avc"){let Z=Math.ceil(J/16)*Math.ceil(Y/16),G=OJ.find((W)=>Z<=W.maxMacroblocks&&j<=W.maxBitrate)??n(OJ),K=G?G.level:0,Q=100 .toString(16).padStart(2,"0"),q="00",U=K.toString(16).padStart(2,"0");return`avc1.${Q}00${U}`}if($==="hevc"){let K=J*Y,Q=PJ.find((U)=>K<=U.maxPictureSize&&j<=U.maxBitrate)??n(PJ),q="B0";return`hev1.1.6.${Q.tier}${Q.level}.B0`}if($==="vp8")return"vp8";if($==="vp9"){let Z=J*Y,G=j1.find((Q)=>Z<=Q.maxPictureSize&&j<=Q.maxBitrate)??n(j1),K="08";return`vp09.00.${G.level.toString().padStart(2,"0")}.08`}if($==="av1"){let Z=J*Y,G=CJ.find((q)=>Z<=q.maxPictureSize&&j<=q.maxBitrate)??n(CJ),K=G.level.toString().padStart(2,"0"),Q="08";return`av01.0.${K}${G.tier}.08`}if($==="mpeg4")return"mp4v.20.9";throw TypeError(`Unhandled codec '${$}'.`)},yJ=($)=>{let J=$.split("."),Y=Number(J[1]),j=Number(J[2]),X=Number(J[3]),Z=J[4]?Number(J[4]):1;return[1,1,Y,2,1,j,3,1,X,4,1,Z]},W6=($)=>{let J=$.split("."),Y=1,j=1,X=129,Z=Number(J[1]),G=J[2],K=Number(G.slice(0,-1)),Q=(Z<<5)+K,q=G.slice(-1)==="H"?1:0,W=Number(J[3])===8?0:1,V=0,N=J[4]?Number(J[4]):0,A=J[5]?Number(J[5][0]):1,R=J[5]?Number(J[5][1]):1,z=J[5]?Number(J[5][2]):0,_=(q<<7)+(W<<6)+0+(N<<4)+(A<<3)+(R<<2)+z,L=0,M=0;return[129,Q,_,0]},V6=($)=>{let{codec:J,codecDescription:Y,colorSpace:j,avcCodecInfo:X,hevcCodecInfo:Z,vp9CodecInfo:G,av1CodecInfo:K}=$;if(J==="avc"){if(H($.avcType!==null),X){let Q=new Uint8Array([X.avcProfileIndication,X.profileCompatibility,X.avcLevelIndication]);return`avc${$.avcType}.${S2(Q)}`}if(!Y||Y.byteLength<4)throw TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${$.avcType}.${S2(Y.subarray(1,4))}`}if(J==="hevc"){let Q,q,U,W,V,N;if(Z)Q=Z.generalProfileSpace,q=Z.generalProfileIdc,U=h2(Z.generalProfileCompatibilityFlags),W=Z.generalTierFlag,V=Z.generalLevelIdc,N=[...Z.generalConstraintIndicatorFlags];else{if(!Y||Y.byteLength<23)throw TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let R=h(Y),z=R.getUint8(1);Q=z>>6&3,q=z&31,U=h2(R.getUint32(2)),W=z>>5&1,V=R.getUint8(12),N=[];for(let _=0;_<6;_++)N.push(R.getUint8(6+_))}let A="hev1.";A+=["","A","B","C"][Q]+q,A+=".",A+=U.toString(16).toUpperCase(),A+=".",A+=W===0?"L":"H",A+=V;while(N.length>0&&N[N.length-1]===0)N.pop();if(N.length>0)A+=".",A+=N.map((R)=>R.toString(16).toUpperCase()).join(".");return A}if(J==="vp8")return"vp8";if(J==="vp9"){if(!G){let _=$.width*$.height,L=n(j1).level;for(let M of j1)if(_<=M.maxPictureSize){L=M.level;break}return`vp09.00.${L.toString().padStart(2,"0")}.08`}let Q=G.profile.toString().padStart(2,"0"),q=G.level.toString().padStart(2,"0"),U=G.bitDepth.toString().padStart(2,"0"),W=G.chromaSubsampling.toString().padStart(2,"0"),V=G.colourPrimaries.toString().padStart(2,"0"),N=G.transferCharacteristics.toString().padStart(2,"0"),A=G.matrixCoefficients.toString().padStart(2,"0"),R=G.videoFullRangeFlag.toString().padStart(2,"0"),z=`vp09.${Q}.${q}.${U}.${W}`;if(z+=`.${V}.${N}.${A}.${R}`,z.endsWith(DJ))z=z.slice(0,-DJ.length);return z}if(J==="av1"){if(!K){let M=$.width*$.height,B=n(j1).level;for(let F of j1)if(M<=F.maxPictureSize){B=F.level;break}return`av01.0.${B.toString().padStart(2,"0")}M.08`}let Q=K.profile,q=K.level.toString().padStart(2,"0"),U=K.tier?"H":"M",W=K.bitDepth.toString().padStart(2,"0"),V=K.monochrome?"1":"0",N=100*K.chromaSubsamplingX+10*K.chromaSubsamplingY+1*(K.chromaSubsamplingX&&K.chromaSubsamplingY?K.chromaSamplePosition:0),A=j?.primaries?e0[j.primaries]:1,R=j?.transfer?$1[j.transfer]:1,z=j?.matrix?J1[j.matrix]:1,_=j?.fullRange?1:0,L=`av01.${Q}.${q}${U}.${W}`;if(L+=`.${V}.${N.toString().padStart(3,"0")}`,L+=`.${A.toString().padStart(2,"0")}`,L+=`.${R.toString().padStart(2,"0")}`,L+=`.${z.toString().padStart(2,"0")}`,L+=`.${_}`,L.endsWith(EJ))L=L.slice(0,-EJ.length);return L}if(J==="mpeg4")return"mp4v";throw TypeError(`Unhandled codec '${J}'.`)},vJ=($,J,Y)=>{if($==="aac"){if(J>=2&&Y<=24000)return"mp4a.40.29";if(Y<=24000)return"mp4a.40.5";return"mp4a.40.2"}if($==="mp3")return"mp3";if($==="opus")return"opus";if($==="vorbis")return"vorbis";if($==="flac")return"flac";if($==="ac3")return"ac-3";if($==="eac3")return"ec-3";if(o.includes($))return $;throw TypeError(`Unhandled codec '${$}'.`)},H6=($)=>{let{codec:J,codecDescription:Y,aacCodecInfo:j}=$;if(J==="aac"){if(!j)throw TypeError("AAC codec info must be provided.");if(j.isMpeg2)return"mp4a.67";return`mp4a.40.${x1(Y).objectType}`}if(J==="mp3")return"mp3";if(J==="opus")return"opus";if(J==="vorbis")return"vorbis";if(J==="flac")return"flac";if(J==="ac3")return"ac3";if(J==="eac3")return"ec-3";if(J&&o.includes(J))return J;throw TypeError(`Unhandled codec '${J}'.`)},a1=[96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350],N6=[-1,1,2,3,4,5,6,8],x1=($)=>{if(!$||$.byteLength<2)throw TypeError("AAC description must be at least 2 bytes long.");let J=new f($),Y=J.readBits(5);if(Y===31)Y=32+J.readBits(6);let j=J.readBits(4),X=null;if(j===15)X=J.readBits(24);else if(j<a1.length)X=a1[j];let Z=J.readBits(4),G=null;if(Z>=1&&Z<=7)G=N6[Z];return{objectType:Y,frequencyIndex:j,sampleRate:X,channelConfiguration:Z,numberOfChannels:G}},bJ=($)=>{let J=a1.indexOf($.sampleRate),Y=null;if(J===-1)J=15,Y=$.sampleRate;let j=N6.indexOf($.numberOfChannels);if(j===-1)throw TypeError(`Unsupported number of channels: ${$.numberOfChannels}`);let X=13;if($.objectType>=32)X+=6;if(J===15)X+=24;let Z=Math.ceil(X/8),G=new Uint8Array(Z),K=new f(G);if($.objectType<32)K.writeBits(5,$.objectType);else K.writeBits(5,31),K.writeBits(6,$.objectType-32);if(K.writeBits(4,J),J===15)K.writeBits(24,Y);return K.writeBits(4,j),G},b0=48000,xJ=/^pcm-([usf])(\d+)+(be)?$/,U0=($)=>{if(H(o.includes($)),$==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if($==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let J=xJ.exec($);H(J);let Y;if(J[1]==="u")Y="unsigned";else if(J[1]==="s")Y="signed";else Y="float";let j=Number(J[2])/8,X=J[3]!=="be";return{dataType:Y,sampleSize:j,littleEndian:X,silentValue:$==="pcm-u8"?128:0}},p2=($)=>{if($.startsWith("avc1")||$.startsWith("avc3"))return"avc";if($.startsWith("hev1")||$.startsWith("hvc1"))return"hevc";if($==="vp8")return"vp8";if($.startsWith("vp09"))return"vp9";if($.startsWith("av01"))return"av1";if($==="mp4v"||$.startsWith("mp4v."))return"mpeg4";if($.startsWith("mp4a.40")||$==="mp4a.67")return"aac";if($==="mp3"||$==="mp4a.69"||$==="mp4a.6B"||$==="mp4a.6b")return"mp3";if($==="opus")return"opus";if($==="vorbis")return"vorbis";if($==="flac")return"flac";if($==="ac-3"||$==="ac3")return"ac3";if($==="ec-3"||$==="eac3")return"eac3";if($==="ulaw")return"ulaw";if($==="alaw")return"alaw";if(xJ.test($))return $;if($==="webvtt")return"webvtt";if($==="srt")return"srt";if($==="ass")return"ass";if($==="ssa")return"ssa";return null},IJ=($)=>{if($==="avc")return{avc:{format:"avc"}};if($==="hevc")return{hevc:{format:"hevc"}};return{}},SJ=($)=>{if($==="aac")return{aac:{format:"aac"}};if($==="opus")return{opus:{format:"opus"}};return{}},U7=["avc1","avc3","hev1","hvc1","vp8","vp09","av01","mp4v"],W7=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,V7=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,H7=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,N7=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,t1=($)=>{if(!$)throw TypeError("Video chunk metadata must be provided.");if(typeof $!=="object")throw TypeError("Video chunk metadata must be an object.");if(!$.decoderConfig)throw TypeError("Video chunk metadata must include a decoder configuration.");if(typeof $.decoderConfig!=="object")throw TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof $.decoderConfig.codec!=="string")throw TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!U7.some((J)=>$.decoderConfig.codec.startsWith(J)))throw TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger($.decoderConfig.codedWidth)||$.decoderConfig.codedWidth<=0)throw TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger($.decoderConfig.codedHeight)||$.decoderConfig.codedHeight<=0)throw TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if($.decoderConfig.description!==void 0){if(!i1($.decoderConfig.description))throw TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.")}if($.decoderConfig.colorSpace!==void 0){let{colorSpace:J}=$.decoderConfig;if(typeof J!=="object")throw TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let Y=Object.keys(e0);if(J.primaries!=null&&!Y.includes(J.primaries))throw TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${Y.join(", ")}.`);let j=Object.keys($1);if(J.transfer!=null&&!j.includes(J.transfer))throw TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${j.join(", ")}.`);let X=Object.keys(J1);if(J.matrix!=null&&!X.includes(J.matrix))throw TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${X.join(", ")}.`);if(J.fullRange!=null&&typeof J.fullRange!=="boolean")throw TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if($.decoderConfig.codec.startsWith("avc1")||$.decoderConfig.codec.startsWith("avc3")){if(!W7.test($.decoderConfig.codec))throw TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if($.decoderConfig.codec.startsWith("hev1")||$.decoderConfig.codec.startsWith("hvc1")){if(!V7.test($.decoderConfig.codec))throw TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if($.decoderConfig.codec.startsWith("vp8")){if($.decoderConfig.codec!=="vp8")throw TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if($.decoderConfig.codec.startsWith("vp09")){if(!H7.test($.decoderConfig.codec))throw TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if($.decoderConfig.codec.startsWith("av01")){if(!N7.test($.decoderConfig.codec))throw TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')}else if($.decoderConfig.codec==="mp4v"||$.decoderConfig.codec.startsWith("mp4v.")){if($.decoderConfig.codec!=="mp4v")throw TypeError('Video chunk metadata decoder configuration codec string for MPEG-4 must be "mp4v".')}},A7=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],_0=($)=>{if(!$)throw TypeError("Audio chunk metadata must be provided.");if(typeof $!=="object")throw TypeError("Audio chunk metadata must be an object.");if(!$.decoderConfig)throw TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof $.decoderConfig!=="object")throw TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof $.decoderConfig.codec!=="string")throw TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!A7.some((J)=>$.decoderConfig.codec.startsWith(J)))throw TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger($.decoderConfig.sampleRate)||$.decoderConfig.sampleRate<=0)throw TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger($.decoderConfig.numberOfChannels)||$.decoderConfig.numberOfChannels<=0)throw TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if($.decoderConfig.description!==void 0){if(!i1($.decoderConfig.description))throw TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.")}if($.decoderConfig.codec.startsWith("mp4a")&&$.decoderConfig.codec!=="mp4a.69"&&$.decoderConfig.codec!=="mp4a.6B"&&$.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes($.decoderConfig.codec))throw TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.");if(!$.decoderConfig.description)throw TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}else if($.decoderConfig.codec.startsWith("mp3")||$.decoderConfig.codec.startsWith("mp4a")){if($.decoderConfig.codec!=="mp3"&&$.decoderConfig.codec!=="mp4a.69"&&$.decoderConfig.codec!=="mp4a.6B"&&$.decoderConfig.codec!=="mp4a.6b")throw TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if($.decoderConfig.codec.startsWith("opus")){if($.decoderConfig.codec!=="opus")throw TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if($.decoderConfig.description&&$.decoderConfig.description.byteLength<18)throw TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if($.decoderConfig.codec.startsWith("vorbis")){if($.decoderConfig.codec!=="vorbis")throw TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!$.decoderConfig.description)throw TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if($.decoderConfig.codec.startsWith("flac")){if($.decoderConfig.codec!=="flac")throw TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');let J=42;if(!$.decoderConfig.description||$.decoderConfig.description.byteLength<J)throw TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if($.decoderConfig.codec==="ac-3"||$.decoderConfig.codec==="ac3"){if($.decoderConfig.codec!=="ac-3")throw TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if($.decoderConfig.codec==="ec-3"||$.decoderConfig.codec==="eac3"){if($.decoderConfig.codec!=="ec-3")throw TypeError('Audio chunk metadata decoder configuration codec string for E-AC-3 must be "ec-3".')}else if($.decoderConfig.codec.startsWith("pcm")||$.decoderConfig.codec.startsWith("ulaw")||$.decoderConfig.codec.startsWith("alaw")){if(!o.includes($.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${o.join(", ")}).`)}},A6=($)=>{if(!$)throw TypeError("Subtitle metadata must be provided.");if(typeof $!=="object")throw TypeError("Subtitle metadata must be an object.");if(!$.config)throw TypeError("Subtitle metadata must include a config object.");if(typeof $.config!=="object")throw TypeError("Subtitle metadata config must be an object.");if(typeof $.config.description!=="string")throw TypeError("Subtitle metadata config description must be a string.")};/*!
70
70
  * Copyright (c) 2025-present, Vanilagy and contributors
71
71
  *
72
72
  * This Source Code Form is subject to the terms of the Mozilla Public
73
73
  * License, v. 2.0. If a copy of the MPL was not distributed with this
74
74
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
75
- */class l2{codec;config;onSample;static supports($,J){return!1}}class m2{codec;config;onSample;static supports($,J){return!1}}class d2{codec;config;onPacket;static supports($,J){return!1}}class c2{codec;config;onPacket;static supports($,J){return!1}}var e1=[],$8=[],I1=[],S1=[],z7=($)=>{if($.prototype instanceof l2){let J=$;if(e1.includes(J)){console.warn("Video decoder already registered.");return}e1.push(J)}else if($.prototype instanceof m2){let J=$;if($8.includes(J)){console.warn("Audio decoder already registered.");return}$8.push(J)}else throw TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},_7=($)=>{if($.prototype instanceof d2){let J=$;if(I1.includes(J)){console.warn("Video encoder already registered.");return}I1.push(J)}else if($.prototype instanceof c2){let J=$;if(S1.includes(J)){console.warn("Audio encoder already registered.");return}S1.push(J)}else throw TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};/*!
75
+ */class l2{codec;config;onSample;static supports($,J){return!1}}class m2{codec;config;onSample;static supports($,J){return!1}}class d2{codec;config;onPacket;static supports($,J){return!1}}class c2{codec;config;onPacket;static supports($,J){return!1}}var e1=[],$8=[],I1=[],S1=[],R7=($)=>{if($.prototype instanceof l2){let J=$;if(e1.includes(J)){console.warn("Video decoder already registered.");return}e1.push(J)}else if($.prototype instanceof m2){let J=$;if($8.includes(J)){console.warn("Audio decoder already registered.");return}$8.push(J)}else throw TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},z7=($)=>{if($.prototype instanceof d2){let J=$;if(I1.includes(J)){console.warn("Video encoder already registered.");return}I1.push(J)}else if($.prototype instanceof c2){let J=$;if(S1.includes(J)){console.warn("Audio encoder already registered.");return}S1.push(J)}else throw TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};/*!
76
76
  * Copyright (c) 2025-present, Vanilagy and contributors
77
77
  *
78
78
  * This Source Code Form is subject to the terms of the Mozilla Public
79
79
  * License, v. 2.0. If a copy of the MPL was not distributed with this
80
80
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
81
- */var _6=($)=>{if(!$||typeof $!=="object")throw TypeError("Encoding config must be an object.");if(!j0.includes($.codec))throw TypeError(`Invalid video codec '${$.codec}'. Must be one of: ${j0.join(", ")}.`);if(!($.bitrate instanceof N0)&&(!Number.isInteger($.bitrate)||$.bitrate<=0))throw TypeError("config.bitrate must be a positive integer or a quality.");if($.keyFrameInterval!==void 0&&(!Number.isFinite($.keyFrameInterval)||$.keyFrameInterval<0))throw TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if($.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes($.sizeChangeBehavior))throw TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if($.onEncodedPacket!==void 0&&typeof $.onEncodedPacket!=="function")throw TypeError("config.onEncodedChunk, when provided, must be a function.");if($.onEncoderConfig!==void 0&&typeof $.onEncoderConfig!=="function")throw TypeError("config.onEncoderConfig, when provided, must be a function.");hJ($.codec,$)},hJ=($,J)=>{if(!J||typeof J!=="object")throw TypeError("Encoding options must be an object.");if(J.alpha!==void 0&&!["discard","keep"].includes(J.alpha))throw TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(J.bitrateMode!==void 0&&!["constant","variable"].includes(J.bitrateMode))throw TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(J.latencyMode!==void 0&&!["quality","realtime"].includes(J.latencyMode))throw TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(J.fullCodecString!==void 0&&typeof J.fullCodecString!=="string")throw TypeError("fullCodecString, when provided, must be a string.");if(J.fullCodecString!==void 0&&p2(J.fullCodecString)!==$)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${$}).`);if(J.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(J.hardwareAcceleration))throw TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(J.scalabilityMode!==void 0&&typeof J.scalabilityMode!=="string")throw TypeError("scalabilityMode, when provided, must be a string.");if(J.contentHint!==void 0&&typeof J.contentHint!=="string")throw TypeError("contentHint, when provided, must be a string.")},R6=($)=>{let J=$.bitrate instanceof N0?$.bitrate._toVideoBitrate($.codec,$.width,$.height):$.bitrate;return{codec:$.fullCodecString??TJ($.codec,$.width,$.height,J),width:$.width,height:$.height,bitrate:J,bitrateMode:$.bitrateMode,alpha:$.alpha??"discard",framerate:$.framerate,latencyMode:$.latencyMode,hardwareAcceleration:$.hardwareAcceleration,scalabilityMode:$.scalabilityMode,contentHint:$.contentHint,...IJ($.codec)}},L6=($)=>{if(!$||typeof $!=="object")throw TypeError("Encoding config must be an object.");if(!Z0.includes($.codec))throw TypeError(`Invalid audio codec '${$.codec}'. Must be one of: ${Z0.join(", ")}.`);if($.bitrate===void 0&&(!o.includes($.codec)||$.codec==="flac"))throw TypeError("config.bitrate must be provided for compressed audio codecs.");if($.bitrate!==void 0&&!($.bitrate instanceof N0)&&(!Number.isInteger($.bitrate)||$.bitrate<=0))throw TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if($.onEncodedPacket!==void 0&&typeof $.onEncodedPacket!=="function")throw TypeError("config.onEncodedChunk, when provided, must be a function.");if($.onEncoderConfig!==void 0&&typeof $.onEncoderConfig!=="function")throw TypeError("config.onEncoderConfig, when provided, must be a function.");fJ($.codec,$)},fJ=($,J)=>{if(!J||typeof J!=="object")throw TypeError("Encoding options must be an object.");if(J.bitrateMode!==void 0&&!["constant","variable"].includes(J.bitrateMode))throw TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(J.fullCodecString!==void 0&&typeof J.fullCodecString!=="string")throw TypeError("fullCodecString, when provided, must be a string.");if(J.fullCodecString!==void 0&&p2(J.fullCodecString)!==$)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${$}).`)},z6=($)=>{let J=$.bitrate instanceof N0?$.bitrate._toAudioBitrate($.codec):$.bitrate;return{codec:$.fullCodecString??vJ($.codec,$.numberOfChannels,$.sampleRate),numberOfChannels:$.numberOfChannels,sampleRate:$.sampleRate,bitrate:J,bitrateMode:$.bitrateMode,...SJ($.codec)}};class N0{_factor;constructor($){this._factor=$}_toVideoBitrate($,J,Y){let j=J*Y,X={avc:1,hevc:0.6,vp9:0.6,av1:0.4,vp8:1.2,mpeg4:1.5},Z=2073600,G=3000000,U=3000000*(j/2073600)**0.95*X[$]*this._factor;return Math.ceil(U/1000)*1000}_toAudioBitrate($){if(o.includes($)||$==="flac")return;let Y={aac:128000,opus:64000,mp3:160000,vorbis:64000,ac3:640000,eac3:256000}[$];if(!Y)throw Error(`Unhandled codec: ${$}`);let j=Y*this._factor;if($==="aac")j=[96000,128000,160000,192000].reduce((Z,G)=>Math.abs(G-j)<Math.abs(Z-j)?G:Z);else if($==="opus"||$==="vorbis")j=Math.max(6000,j);else if($==="mp3")j=[8000,16000,24000,32000,40000,48000,64000,80000,96000,112000,128000,160000,192000,224000,256000,320000].reduce((Z,G)=>Math.abs(G-j)<Math.abs(Z-j)?G:Z);return Math.round(j/1000)*1000}}var L7=new N0(0.3),M7=new N0(0.6),F7=new N0(1),M6=new N0(2),B7=new N0(4),w7=($)=>{if(j0.includes($))return F6($);if(Z0.includes($))return B6($);if(z0.includes($))return w6($);throw TypeError(`Unknown codec '${$}'.`)},F6=async($,J={})=>{let{width:Y=1280,height:j=720,bitrate:X=1e6,...Z}=J;if(!j0.includes($))return!1;if(!Number.isInteger(Y)||Y<=0)throw TypeError("width must be a positive integer.");if(!Number.isInteger(j)||j<=0)throw TypeError("height must be a positive integer.");if(!(X instanceof N0)&&(!Number.isInteger(X)||X<=0))throw TypeError("bitrate must be a positive integer or a quality.");hJ($,Z);let G=null;if(I1.length>0){if(G??=R6({codec:$,width:Y,height:j,bitrate:X,framerate:void 0,...Z}),I1.some((q)=>q.supports($,G)))return!0}if(typeof VideoEncoder>"u")return!1;if((Y%2===1||j%2===1)&&($==="avc"||$==="hevc"))return!1;if(G??=R6({codec:$,width:Y,height:j,bitrate:X,framerate:void 0,...Z,alpha:"discard"}),!(await VideoEncoder.isConfigSupported(G)).supported)return!1;if(n0())return new Promise(async(q)=>{try{let U=new VideoEncoder({output:()=>{},error:()=>q(!1)});U.configure(G);let W=new Uint8Array(Y*j*4),V=new VideoFrame(W,{format:"RGBA",codedWidth:Y,codedHeight:j,timestamp:0});U.encode(V),V.close(),await U.flush(),q(!0)}catch{q(!1)}});else return!0},B6=async($,J={})=>{let{numberOfChannels:Y=2,sampleRate:j=48000,bitrate:X=128000,...Z}=J;if(!Z0.includes($))return!1;if(!Number.isInteger(Y)||Y<=0)throw TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(j)||j<=0)throw TypeError("sampleRate must be a positive integer.");if(!(X instanceof N0)&&(!Number.isInteger(X)||X<=0))throw TypeError("bitrate must be a positive integer.");fJ($,Z);let G=null;if(S1.length>0){if(G??=z6({codec:$,numberOfChannels:Y,sampleRate:j,bitrate:X,...Z}),S1.some((Q)=>Q.supports($,G)))return!0}if(o.includes($))return!0;if(typeof AudioEncoder>"u")return!1;return G??=z6({codec:$,numberOfChannels:Y,sampleRate:j,bitrate:X,...Z}),(await AudioEncoder.isConfigSupported(G)).supported===!0},w6=async($)=>{if(!z0.includes($))return!1;return!0},O7=async()=>{let[$,J,Y]=await Promise.all([gJ(),w8(),kJ()]);return[...$,...J,...Y]},gJ=async($=j0,J)=>{let Y=await Promise.all($.map((j)=>F6(j,J)));return $.filter((j,X)=>Y[X])},w8=async($=Z0,J)=>{let Y=await Promise.all($.map((j)=>B6(j,J)));return $.filter((j,X)=>Y[X])},kJ=async($=z0)=>{let J=await Promise.all($.map(w6));return $.filter((Y,j)=>J[j])},n2=async($,J)=>{for(let Y of $)if(await F6(Y,J))return Y;return null},P7=async($,J)=>{for(let Y of $)if(await B6(Y,J))return Y;return null},C7=async($)=>{for(let J of $)if(await w6(J))return J;return null};/*!
81
+ */var _6=($)=>{if(!$||typeof $!=="object")throw TypeError("Encoding config must be an object.");if(!j0.includes($.codec))throw TypeError(`Invalid video codec '${$.codec}'. Must be one of: ${j0.join(", ")}.`);if(!($.bitrate instanceof N0)&&(!Number.isInteger($.bitrate)||$.bitrate<=0))throw TypeError("config.bitrate must be a positive integer or a quality.");if($.keyFrameInterval!==void 0&&(!Number.isFinite($.keyFrameInterval)||$.keyFrameInterval<0))throw TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if($.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes($.sizeChangeBehavior))throw TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if($.onEncodedPacket!==void 0&&typeof $.onEncodedPacket!=="function")throw TypeError("config.onEncodedChunk, when provided, must be a function.");if($.onEncoderConfig!==void 0&&typeof $.onEncoderConfig!=="function")throw TypeError("config.onEncoderConfig, when provided, must be a function.");hJ($.codec,$)},hJ=($,J)=>{if(!J||typeof J!=="object")throw TypeError("Encoding options must be an object.");if(J.alpha!==void 0&&!["discard","keep"].includes(J.alpha))throw TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(J.bitrateMode!==void 0&&!["constant","variable"].includes(J.bitrateMode))throw TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(J.latencyMode!==void 0&&!["quality","realtime"].includes(J.latencyMode))throw TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(J.fullCodecString!==void 0&&typeof J.fullCodecString!=="string")throw TypeError("fullCodecString, when provided, must be a string.");if(J.fullCodecString!==void 0&&p2(J.fullCodecString)!==$)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${$}).`);if(J.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(J.hardwareAcceleration))throw TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(J.scalabilityMode!==void 0&&typeof J.scalabilityMode!=="string")throw TypeError("scalabilityMode, when provided, must be a string.");if(J.contentHint!==void 0&&typeof J.contentHint!=="string")throw TypeError("contentHint, when provided, must be a string.")},R6=($)=>{let J=$.bitrate instanceof N0?$.bitrate._toVideoBitrate($.codec,$.width,$.height):$.bitrate;return{codec:$.fullCodecString??TJ($.codec,$.width,$.height,J),width:$.width,height:$.height,bitrate:J,bitrateMode:$.bitrateMode,alpha:$.alpha??"discard",framerate:$.framerate,latencyMode:$.latencyMode,hardwareAcceleration:$.hardwareAcceleration,scalabilityMode:$.scalabilityMode,contentHint:$.contentHint,...IJ($.codec)}},L6=($)=>{if(!$||typeof $!=="object")throw TypeError("Encoding config must be an object.");if(!Z0.includes($.codec))throw TypeError(`Invalid audio codec '${$.codec}'. Must be one of: ${Z0.join(", ")}.`);if($.bitrate===void 0&&(!o.includes($.codec)||$.codec==="flac"))throw TypeError("config.bitrate must be provided for compressed audio codecs.");if($.bitrate!==void 0&&!($.bitrate instanceof N0)&&(!Number.isInteger($.bitrate)||$.bitrate<=0))throw TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if($.onEncodedPacket!==void 0&&typeof $.onEncodedPacket!=="function")throw TypeError("config.onEncodedChunk, when provided, must be a function.");if($.onEncoderConfig!==void 0&&typeof $.onEncoderConfig!=="function")throw TypeError("config.onEncoderConfig, when provided, must be a function.");fJ($.codec,$)},fJ=($,J)=>{if(!J||typeof J!=="object")throw TypeError("Encoding options must be an object.");if(J.bitrateMode!==void 0&&!["constant","variable"].includes(J.bitrateMode))throw TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(J.fullCodecString!==void 0&&typeof J.fullCodecString!=="string")throw TypeError("fullCodecString, when provided, must be a string.");if(J.fullCodecString!==void 0&&p2(J.fullCodecString)!==$)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${$}).`)},z6=($)=>{let J=$.bitrate instanceof N0?$.bitrate._toAudioBitrate($.codec):$.bitrate;return{codec:$.fullCodecString??vJ($.codec,$.numberOfChannels,$.sampleRate),numberOfChannels:$.numberOfChannels,sampleRate:$.sampleRate,bitrate:J,bitrateMode:$.bitrateMode,...SJ($.codec)}};class N0{_factor;constructor($){this._factor=$}_toVideoBitrate($,J,Y){let j=J*Y,X={avc:1,hevc:0.6,vp9:0.6,av1:0.4,vp8:1.2,mpeg4:1.5},Z=2073600,G=3000000,U=3000000*(j/2073600)**0.95*X[$]*this._factor;return Math.ceil(U/1000)*1000}_toAudioBitrate($){if(o.includes($)||$==="flac")return;let Y={aac:128000,opus:64000,mp3:160000,vorbis:64000,ac3:640000,eac3:256000}[$];if(!Y)throw Error(`Unhandled codec: ${$}`);let j=Y*this._factor;if($==="aac")j=[96000,128000,160000,192000].reduce((Z,G)=>Math.abs(G-j)<Math.abs(Z-j)?G:Z);else if($==="opus"||$==="vorbis")j=Math.max(6000,j);else if($==="mp3")j=[8000,16000,24000,32000,40000,48000,64000,80000,96000,112000,128000,160000,192000,224000,256000,320000].reduce((Z,G)=>Math.abs(G-j)<Math.abs(Z-j)?G:Z);return Math.round(j/1000)*1000}}var _7=new N0(0.3),L7=new N0(0.6),M7=new N0(1),M6=new N0(2),F7=new N0(4),B7=($)=>{if(j0.includes($))return F6($);if(Z0.includes($))return B6($);if(z0.includes($))return w6($);throw TypeError(`Unknown codec '${$}'.`)},F6=async($,J={})=>{let{width:Y=1280,height:j=720,bitrate:X=1e6,...Z}=J;if(!j0.includes($))return!1;if(!Number.isInteger(Y)||Y<=0)throw TypeError("width must be a positive integer.");if(!Number.isInteger(j)||j<=0)throw TypeError("height must be a positive integer.");if(!(X instanceof N0)&&(!Number.isInteger(X)||X<=0))throw TypeError("bitrate must be a positive integer or a quality.");hJ($,Z);let G=null;if(I1.length>0){if(G??=R6({codec:$,width:Y,height:j,bitrate:X,framerate:void 0,...Z}),I1.some((q)=>q.supports($,G)))return!0}if(typeof VideoEncoder>"u")return!1;if((Y%2===1||j%2===1)&&($==="avc"||$==="hevc"))return!1;if(G??=R6({codec:$,width:Y,height:j,bitrate:X,framerate:void 0,...Z,alpha:"discard"}),!(await VideoEncoder.isConfigSupported(G)).supported)return!1;if(n0())return new Promise(async(q)=>{try{let U=new VideoEncoder({output:()=>{},error:()=>q(!1)});U.configure(G);let W=new Uint8Array(Y*j*4),V=new VideoFrame(W,{format:"RGBA",codedWidth:Y,codedHeight:j,timestamp:0});U.encode(V),V.close(),await U.flush(),q(!0)}catch{q(!1)}});else return!0},B6=async($,J={})=>{let{numberOfChannels:Y=2,sampleRate:j=48000,bitrate:X=128000,...Z}=J;if(!Z0.includes($))return!1;if(!Number.isInteger(Y)||Y<=0)throw TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(j)||j<=0)throw TypeError("sampleRate must be a positive integer.");if(!(X instanceof N0)&&(!Number.isInteger(X)||X<=0))throw TypeError("bitrate must be a positive integer.");fJ($,Z);let G=null;if(S1.length>0){if(G??=z6({codec:$,numberOfChannels:Y,sampleRate:j,bitrate:X,...Z}),S1.some((Q)=>Q.supports($,G)))return!0}if(o.includes($))return!0;if(typeof AudioEncoder>"u")return!1;return G??=z6({codec:$,numberOfChannels:Y,sampleRate:j,bitrate:X,...Z}),(await AudioEncoder.isConfigSupported(G)).supported===!0},w6=async($)=>{if(!z0.includes($))return!1;return!0},w7=async()=>{let[$,J,Y]=await Promise.all([gJ(),w8(),kJ()]);return[...$,...J,...Y]},gJ=async($=j0,J)=>{let Y=await Promise.all($.map((j)=>F6(j,J)));return $.filter((j,X)=>Y[X])},w8=async($=Z0,J)=>{let Y=await Promise.all($.map((j)=>B6(j,J)));return $.filter((j,X)=>Y[X])},kJ=async($=z0)=>{let J=await Promise.all($.map(w6));return $.filter((Y,j)=>J[j])},n2=async($,J)=>{for(let Y of $)if(await F6(Y,J))return Y;return null},O7=async($,J)=>{for(let Y of $)if(await B6(Y,J))return Y;return null},P7=async($)=>{for(let J of $)if(await w6(J))return J;return null};/*!
82
82
  * Copyright (c) 2025-present, Vanilagy and contributors
83
83
  *
84
84
  * This Source Code Form is subject to the terms of the Mozilla Public
85
85
  * License, v. 2.0. If a copy of the MPL was not distributed with this
86
86
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
87
- */var O6=4,D7=[44100,48000,32000],P6=[-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],J8=1483304551,C6=1231971951,D6=($,J,Y,j,X)=>{if(J===0)return 0;if(J===1)return Math.floor(144*Y/(j<<$))+X;if(J===2)return Math.floor(144*Y/j)+X;return(Math.floor(12*Y/j)+X)*4},Y8=($,J)=>{return $===3?J===3?21:36:J===3?13:21},E6=($,J)=>{let Y=$>>>24,j=$>>>16&255,X=$>>>8&255,Z=$&255;if(Y!==255&&j!==255&&X!==255&&Z!==255)return{header:null,bytesAdvanced:4};if(Y!==255)return{header:null,bytesAdvanced:1};if((j&224)!==224)return{header:null,bytesAdvanced:1};let G=0,K=0;if(j&16)G=j&8?0:1;else G=1,K=1;let Q=j>>3&3,q=j>>1&3,U=X>>4&15,W=(X>>2&3)%3,V=X>>1&1,N=Z>>6&3,A=Z>>4&3,R=Z>>3&1,z=Z>>2&1,_=Z&3,L=P6[G*16*4+q*16+U];if(L===-1)return{header:null,bytesAdvanced:1};let M=L*1000,B=D7[W]>>G+K,F=D6(G,q,M,B,V);if(J!==null&&J<F)return{header:null,bytesAdvanced:1};let C;if(Q===3)C=q===3?384:1152;else if(q===3)C=384;else if(q===2)C=1152;else C=576;return{header:{totalSize:F,mpegVersionId:Q,layer:q,bitrate:M,frequencyIndex:W,sampleRate:B,channel:N,modeExtension:A,copyright:R,original:z,emphasis:_,audioSamplesInFrame:C},bytesAdvanced:1}},uJ=($)=>{let J=127,Y=0,j=$;while((J^2147483647)!==0)Y=j&~J,Y<<=1,Y|=j&J,J=(J+1<<8)-1,j=Y;return Y},T6=($)=>{let J=2130706432,Y=0;while(J!==0)Y>>=1,Y|=$&J,J>>=8;return Y};/*!
87
+ */var O6=4,C7=[44100,48000,32000],P6=[-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],J8=1483304551,C6=1231971951,D6=($,J,Y,j,X)=>{if(J===0)return 0;if(J===1)return Math.floor(144*Y/(j<<$))+X;if(J===2)return Math.floor(144*Y/j)+X;return(Math.floor(12*Y/j)+X)*4},Y8=($,J)=>{return $===3?J===3?21:36:J===3?13:21},E6=($,J)=>{let Y=$>>>24,j=$>>>16&255,X=$>>>8&255,Z=$&255;if(Y!==255&&j!==255&&X!==255&&Z!==255)return{header:null,bytesAdvanced:4};if(Y!==255)return{header:null,bytesAdvanced:1};if((j&224)!==224)return{header:null,bytesAdvanced:1};let G=0,K=0;if(j&16)G=j&8?0:1;else G=1,K=1;let Q=j>>3&3,q=j>>1&3,U=X>>4&15,W=(X>>2&3)%3,V=X>>1&1,N=Z>>6&3,A=Z>>4&3,R=Z>>3&1,z=Z>>2&1,_=Z&3,L=P6[G*16*4+q*16+U];if(L===-1)return{header:null,bytesAdvanced:1};let M=L*1000,B=C7[W]>>G+K,F=D6(G,q,M,B,V);if(J!==null&&J<F)return{header:null,bytesAdvanced:1};let C;if(Q===3)C=q===3?384:1152;else if(q===3)C=384;else if(q===2)C=1152;else C=576;return{header:{totalSize:F,mpegVersionId:Q,layer:q,bitrate:M,frequencyIndex:W,sampleRate:B,channel:N,modeExtension:A,copyright:R,original:z,emphasis:_,audioSamplesInFrame:C},bytesAdvanced:1}},uJ=($)=>{let J=127,Y=0,j=$;while((J^2147483647)!==0)Y=j&~J,Y<<=1,Y|=j&J,J=(J+1<<8)-1,j=Y;return Y},T6=($)=>{let J=2130706432,Y=0;while(J!==0)Y>>=1,Y|=$&J,J>>=8;return Y};/*!
88
88
  * Copyright (c) 2025-present, Vanilagy and contributors
89
89
  *
90
90
  * This Source Code Form is subject to the terms of the Mozilla Public
@@ -96,7 +96,7 @@ ${K.join(`
96
96
  * This Source Code Form is subject to the terms of the Mozilla Public
97
97
  * License, v. 2.0. If a copy of the MPL was not distributed with this
98
98
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
99
- */var O8=($)=>{let J=[],Y=0;while(Y<$.length){let j=-1,X=0;for(let Z=Y;Z<$.length-3;Z++){if($[Z]===0&&$[Z+1]===0&&$[Z+2]===1){j=Z,X=3;break}if(Z<$.length-4&&$[Z]===0&&$[Z+1]===0&&$[Z+2]===0&&$[Z+3]===1){j=Z,X=4;break}}if(j===-1)break;if(Y>0&&j>Y){let Z=$.subarray(Y,j);if(Z.length>0)J.push(Z)}Y=j+X}if(Y<$.length){let j=$.subarray(Y);if(j.length>0)J.push(j)}return J},lJ=($,J)=>{let Y=[],j=0,X=new DataView($.buffer,$.byteOffset,$.byteLength);while(j+J<=$.length){let Z;if(J===1)Z=X.getUint8(j);else if(J===2)Z=X.getUint16(j,!1);else if(J===3)Z=T1(X,j,!1);else if(J===4)Z=X.getUint32(j,!1);else i(J),H(!1);j+=J;let G=$.subarray(j,j+Z);Y.push(G),j+=Z}return Y},y6=($)=>{let J=[],Y=$.length;for(let j=0;j<Y;j++)if(j+2<Y&&$[j]===0&&$[j+1]===0&&$[j+2]===3)J.push(0,0),j+=2;else J.push($[j]);return new Uint8Array(J)},o2=new Uint8Array([0,0,0,1]),E7=($)=>{let J=$.reduce((X,Z)=>X+o2.byteLength+Z.byteLength,0),Y=new Uint8Array(J),j=0;for(let X of $)Y.set(o2,j),j+=o2.byteLength,Y.set(X,j),j+=X.byteLength;return Y},mJ=($,J)=>{let Y=$.reduce((Z,G)=>Z+J+G.byteLength,0),j=new Uint8Array(Y),X=0;for(let Z of $){let G=new DataView(j.buffer,j.byteOffset,j.byteLength);switch(J){case 1:G.setUint8(X,Z.byteLength);break;case 2:G.setUint16(X,Z.byteLength,!1);break;case 3:L8(G,X,Z.byteLength,!1);break;case 4:G.setUint32(X,Z.byteLength,!1);break}X+=J,j.set(Z,X),X+=Z.byteLength}return j},dJ=($)=>{let J=O8($);if(J.length===0)return null;return mJ(J,4)},r2=($,J)=>{if(J.description){let X=(l(J.description)[4]&3)+1;return lJ($,X)}return O8($)},cJ=($,J)=>{if(J.description){let X=(l(J.description)[4]&3)+1;return mJ($,X)}else return E7($)},h1=($)=>{return $[0]&31},v6=($)=>{try{let J=O8($),Y=J.filter((Q)=>h1(Q)===7),j=J.filter((Q)=>h1(Q)===8),X=J.filter((Q)=>h1(Q)===13);if(Y.length===0)return null;if(j.length===0)return null;let Z=Y[0],G=i2(Z);H(G!==null);let K=G.profileIdc===100||G.profileIdc===110||G.profileIdc===122||G.profileIdc===144;return{configurationVersion:1,avcProfileIndication:G.profileIdc,profileCompatibility:G.constraintFlags,avcLevelIndication:G.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:Y,pictureParameterSets:j,chromaFormat:K?G.chromaFormatIdc:null,bitDepthLumaMinus8:K?G.bitDepthLumaMinus8:null,bitDepthChromaMinus8:K?G.bitDepthChromaMinus8:null,sequenceParameterSetExt:K?X:null}}catch(J){return console.error("Error building AVC Decoder Configuration Record:",J),null}},nJ=($)=>{let J=[];J.push($.configurationVersion),J.push($.avcProfileIndication),J.push($.profileCompatibility),J.push($.avcLevelIndication),J.push(252|$.lengthSizeMinusOne&3),J.push(224|$.sequenceParameterSets.length&31);for(let Y of $.sequenceParameterSets){let j=Y.byteLength;J.push(j>>8),J.push(j&255);for(let X=0;X<j;X++)J.push(Y[X])}J.push($.pictureParameterSets.length);for(let Y of $.pictureParameterSets){let j=Y.byteLength;J.push(j>>8),J.push(j&255);for(let X=0;X<j;X++)J.push(Y[X])}if($.avcProfileIndication===100||$.avcProfileIndication===110||$.avcProfileIndication===122||$.avcProfileIndication===144){H($.chromaFormat!==null),H($.bitDepthLumaMinus8!==null),H($.bitDepthChromaMinus8!==null),H($.sequenceParameterSetExt!==null),J.push(252|$.chromaFormat&3),J.push(248|$.bitDepthLumaMinus8&7),J.push(248|$.bitDepthChromaMinus8&7),J.push($.sequenceParameterSetExt.length);for(let Y of $.sequenceParameterSetExt){let j=Y.byteLength;J.push(j>>8),J.push(j&255);for(let X=0;X<j;X++)J.push(Y[X])}}return new Uint8Array(J)},oJ=($)=>{try{let J=h($),Y=0,j=J.getUint8(Y++),X=J.getUint8(Y++),Z=J.getUint8(Y++),G=J.getUint8(Y++),K=J.getUint8(Y++)&3,Q=J.getUint8(Y++)&31,q=[];for(let N=0;N<Q;N++){let A=J.getUint16(Y,!1);Y+=2,q.push($.subarray(Y,Y+A)),Y+=A}let U=J.getUint8(Y++),W=[];for(let N=0;N<U;N++){let A=J.getUint16(Y,!1);Y+=2,W.push($.subarray(Y,Y+A)),Y+=A}let V={configurationVersion:j,avcProfileIndication:X,profileCompatibility:Z,avcLevelIndication:G,lengthSizeMinusOne:K,sequenceParameterSets:q,pictureParameterSets:W,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((X===100||X===110||X===122||X===144)&&Y+4<=$.length){let N=J.getUint8(Y++)&3,A=J.getUint8(Y++)&7,R=J.getUint8(Y++)&7,z=J.getUint8(Y++);V.chromaFormat=N,V.bitDepthLumaMinus8=A,V.bitDepthChromaMinus8=R;let _=[];for(let L=0;L<z;L++){let M=J.getUint16(Y,!1);Y+=2,_.push($.subarray(Y,Y+M)),Y+=M}V.sequenceParameterSetExt=_}return V}catch(J){return console.error("Error deserializing AVC Decoder Configuration Record:",J),null}},i2=($)=>{try{let J=new f(y6($));if(J.skipBits(1),J.skipBits(2),J.readBits(5)!==7)return null;let j=J.readAlignedByte(),X=J.readAlignedByte(),Z=J.readAlignedByte();E(J);let G=null,K=null,Q=null;if(j===100||j===110||j===122||j===244||j===44||j===83||j===86||j===118||j===128){if(G=E(J),G===3)J.skipBits(1);if(K=E(J),Q=E(J),J.skipBits(1),J.readBits(1)){for(let V=0;V<(G!==3?8:12);V++)if(J.readBits(1)){let A=V<6?16:64,R=8,z=8;for(let _=0;_<A;_++){if(z!==0){let L=m0(J);z=(R+L+256)%256}R=z===0?R:z}}}}E(J);let q=E(J);if(q===0)E(J);else if(q===1){J.skipBits(1),m0(J),m0(J);let W=E(J);for(let V=0;V<W;V++)m0(J)}E(J),J.skipBits(1),E(J),E(J);let U=J.readBits(1);return{profileIdc:j,constraintFlags:X,levelIdc:Z,frameMbsOnlyFlag:U,chromaFormatIdc:G,bitDepthLumaMinus8:K,bitDepthChromaMinus8:Q}}catch(J){return console.error("Error parsing AVC SPS:",J),null}},s2=($,J)=>{if(J.description){let X=(l(J.description)[21]&3)+1;return lJ($,X)}return O8($)},Z1=($)=>{return $[0]>>1&63},b6=($)=>{try{let J=O8($),Y=J.filter((S)=>Z1(S)===32),j=J.filter((S)=>Z1(S)===33),X=J.filter((S)=>Z1(S)===34),Z=J.filter((S)=>Z1(S)===39||Z1(S)===40);if(j.length===0||X.length===0)return null;let G=j[0],K=new f(y6(G));K.skipBits(16),K.readBits(4);let Q=K.readBits(3),q=K.readBits(1),{general_profile_space:U,general_tier_flag:W,general_profile_idc:V,general_profile_compatibility_flags:N,general_constraint_indicator_flags:A,general_level_idc:R}=T7(K,Q);E(K);let z=E(K);if(z===3)K.skipBits(1);if(E(K),E(K),K.readBits(1))E(K),E(K),E(K),E(K);let _=E(K),L=E(K);E(K);let B=K.readBits(1)?0:Q;for(let S=B;S<=Q;S++)E(K),E(K),E(K);if(E(K),E(K),E(K),E(K),E(K),E(K),K.readBits(1)){if(K.readBits(1))y7(K)}if(K.skipBits(1),K.skipBits(1),K.readBits(1))K.skipBits(4),K.skipBits(4),E(K),E(K),K.skipBits(1);let F=E(K);if(v7(K,F),K.readBits(1)){let S=E(K);for(let T=0;T<S;T++)E(K),K.skipBits(1)}K.skipBits(1),K.skipBits(1);let C=0;if(K.readBits(1))C=x7(K,Q);let w=0;if(X.length>0){let S=X[0],T=new f(y6(S));if(T.skipBits(16),E(T),E(T),T.skipBits(1),T.skipBits(1),T.skipBits(3),T.skipBits(1),T.skipBits(1),E(T),E(T),m0(T),T.skipBits(1),T.skipBits(1),T.readBits(1))E(T);m0(T),m0(T),T.skipBits(1),T.skipBits(1),T.skipBits(1),T.skipBits(1);let r=T.readBits(1),H0=T.readBits(1);if(!r&&!H0)w=0;else if(r&&!H0)w=2;else if(!r&&H0)w=3;else w=0}let v=[...Y.length?[{arrayCompleteness:1,nalUnitType:32,nalUnits:Y}]:[],...j.length?[{arrayCompleteness:1,nalUnitType:33,nalUnits:j}]:[],...X.length?[{arrayCompleteness:1,nalUnitType:34,nalUnits:X}]:[],...Z.length?[{arrayCompleteness:1,nalUnitType:Z1(Z[0]),nalUnits:Z}]:[]];return{configurationVersion:1,generalProfileSpace:U,generalTierFlag:W,generalProfileIdc:V,generalProfileCompatibilityFlags:N,generalConstraintIndicatorFlags:A,generalLevelIdc:R,minSpatialSegmentationIdc:C,parallelismType:w,chromaFormatIdc:z,bitDepthLumaMinus8:_,bitDepthChromaMinus8:L,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:Q+1,temporalIdNested:q,lengthSizeMinusOne:3,arrays:v}}catch(J){return console.error("Error building HEVC Decoder Configuration Record:",J),null}},T7=($,J)=>{let Y=$.readBits(2),j=$.readBits(1),X=$.readBits(5),Z=0;for(let U=0;U<32;U++)Z=Z<<1|$.readBits(1);let G=new Uint8Array(6);for(let U=0;U<6;U++)G[U]=$.readBits(8);let K=$.readBits(8),Q=[],q=[];for(let U=0;U<J;U++)Q.push($.readBits(1)),q.push($.readBits(1));if(J>0)for(let U=J;U<8;U++)$.skipBits(2);for(let U=0;U<J;U++){if(Q[U])$.skipBits(88);if(q[U])$.skipBits(8)}return{general_profile_space:Y,general_tier_flag:j,general_profile_idc:X,general_profile_compatibility_flags:Z,general_constraint_indicator_flags:G,general_level_idc:K}},y7=($)=>{for(let J=0;J<4;J++)for(let Y=0;Y<(J===3?2:6);Y++)if(!$.readBits(1))E($);else{let X=Math.min(64,1<<4+(J<<1));if(J>1)m0($);for(let Z=0;Z<X;Z++)m0($)}},v7=($,J)=>{let Y=[];for(let j=0;j<J;j++)Y[j]=b7($,j,J,Y)},b7=($,J,Y,j)=>{let X=0,Z=0,G=0;if(J!==0)Z=$.readBits(1);if(Z){if(J===Y){let Q=E($);G=J-(Q+1)}else G=J-1;$.readBits(1),E($);let K=j[G]??0;for(let Q=0;Q<=K;Q++)if(!$.readBits(1))$.readBits(1);X=j[G]}else{let K=E($),Q=E($);for(let q=0;q<K;q++)E($),$.readBits(1);for(let q=0;q<Q;q++)E($),$.readBits(1);X=K+Q}return X},x7=($,J)=>{if($.readBits(1)){if($.readBits(8)===255)$.readBits(16),$.readBits(16)}if($.readBits(1))$.readBits(1);if($.readBits(1)){if($.readBits(3),$.readBits(1),$.readBits(1))$.readBits(8),$.readBits(8),$.readBits(8)}if($.readBits(1))E($),E($);if($.readBits(1),$.readBits(1),$.readBits(1),$.readBits(1))E($),E($),E($),E($);if($.readBits(1)){if($.readBits(32),$.readBits(32),$.readBits(1))E($);if($.readBits(1))I7($,!0,J)}if($.readBits(1)){$.readBits(1),$.readBits(1),$.readBits(1);let Y=E($);return E($),E($),E($),E($),Y}return 0},I7=($,J,Y)=>{let j=!1,X=!1,Z=!1;if(J){if(j=$.readBits(1)===1,X=$.readBits(1)===1,j||X){if(Z=$.readBits(1)===1,Z)$.readBits(8),$.readBits(5),$.readBits(1),$.readBits(5);if($.readBits(4),$.readBits(4),Z)$.readBits(4);$.readBits(5),$.readBits(5),$.readBits(5)}}for(let G=0;G<=Y;G++){let K=$.readBits(1)===1,Q=!0;if(!K)Q=$.readBits(1)===1;let q=!1;if(Q)E($);else q=$.readBits(1)===1;let U=1;if(!q)U=E($)+1;if(j)pJ($,U,Z);if(X)pJ($,U,Z)}},pJ=($,J,Y)=>{for(let j=0;j<J;j++){if(E($),E($),Y)E($),E($);$.readBits(1)}},rJ=($)=>{let J=[];J.push($.configurationVersion),J.push(($.generalProfileSpace&3)<<6|($.generalTierFlag&1)<<5|$.generalProfileIdc&31),J.push($.generalProfileCompatibilityFlags>>>24&255),J.push($.generalProfileCompatibilityFlags>>>16&255),J.push($.generalProfileCompatibilityFlags>>>8&255),J.push($.generalProfileCompatibilityFlags&255),J.push(...$.generalConstraintIndicatorFlags),J.push($.generalLevelIdc&255),J.push(240|$.minSpatialSegmentationIdc>>8&15),J.push($.minSpatialSegmentationIdc&255),J.push(252|$.parallelismType&3),J.push(252|$.chromaFormatIdc&3),J.push(248|$.bitDepthLumaMinus8&7),J.push(248|$.bitDepthChromaMinus8&7),J.push($.avgFrameRate>>8&255),J.push($.avgFrameRate&255),J.push(($.constantFrameRate&3)<<6|($.numTemporalLayers&7)<<3|($.temporalIdNested&1)<<2|$.lengthSizeMinusOne&3),J.push($.arrays.length&255);for(let Y of $.arrays){J.push((Y.arrayCompleteness&1)<<7|0|Y.nalUnitType&63),J.push(Y.nalUnits.length>>8&255),J.push(Y.nalUnits.length&255);for(let j of Y.nalUnits){J.push(j.length>>8&255),J.push(j.length&255);for(let X=0;X<j.length;X++)J.push(j[X])}}return new Uint8Array(J)},x6=($)=>{let J=new f($);if(J.readBits(2)!==2)return null;let j=J.readBits(1),Z=(J.readBits(1)<<1)+j;if(Z===3)J.skipBits(1);if(J.readBits(1)===1)return null;if(J.readBits(1)!==0)return null;if(J.skipBits(2),J.readBits(24)!==4817730)return null;let q=8;if(Z>=2)q=J.readBits(1)?12:10;let U=J.readBits(3),W=0,V=0;if(U!==7)if(V=J.readBits(1),Z===1||Z===3){let w=J.readBits(1),v=J.readBits(1);W=!w&&!v?3:w&&!v?2:1,J.skipBits(1)}else W=1;else W=3,V=1;let N=J.readBits(16),A=J.readBits(16),R=N+1,z=A+1,_=R*z,L=n(j1).level;for(let C of j1)if(_<=C.maxPictureSize){L=C.level;break}return{profile:Z,level:L,bitDepth:q,chromaSubsampling:W,videoFullRangeFlag:V,colourPrimaries:U===2?1:U===1?6:2,transferCharacteristics:U===2?1:U===1?6:2,matrixCoefficients:U===7?0:U===2?1:U===1?6:2}},iJ=function*($){let J=new f($),Y=()=>{let j=0;for(let X=0;X<8;X++){let Z=J.readAlignedByte();if(j|=(Z&127)<<X*7,!(Z&128))break;if(X===7&&Z&128)return null}if(j>=4294967295)return null;return j};while(J.getBitsLeft()>=8){J.skipBits(1);let j=J.readBits(4),X=J.readBits(1),Z=J.readBits(1);if(J.skipBits(1),X)J.skipBits(8);let G;if(Z){let K=Y();if(K===null)return;G=K}else G=Math.floor(J.getBitsLeft()/8);H(J.pos%8===0),yield{type:j,data:$.subarray(J.pos/8,J.pos/8+G)},J.skipBits(G*8)}},I6=($)=>{for(let{type:J,data:Y}of iJ($)){if(J!==1)continue;let j=new f(Y),X=j.readBits(3),Z=j.readBits(1),G=j.readBits(1),K=0,Q=0,q=0;if(G)K=j.readBits(5);else{if(j.readBits(1)){if(j.skipBits(32),j.skipBits(32),j.readBits(1))return null}let C=j.readBits(1);if(C)q=j.readBits(5),j.skipBits(32),j.skipBits(5),j.skipBits(5);let w=j.readBits(5);for(let v=0;v<=w;v++){j.skipBits(12);let k=j.readBits(5);if(v===0)K=k;if(k>7){let T=j.readBits(1);if(v===0)Q=T}if(C){if(j.readBits(1)){let r=q+1;j.skipBits(r),j.skipBits(r),j.skipBits(1)}}if(j.readBits(1))j.skipBits(4)}}let U=j.readBits(4),W=j.readBits(4),V=U+1;j.skipBits(V);let N=W+1;j.skipBits(N);let A=0;if(G)A=0;else A=j.readBits(1);if(A)j.skipBits(4),j.skipBits(3);if(j.skipBits(1),j.skipBits(1),j.skipBits(1),!G){j.skipBits(1),j.skipBits(1),j.skipBits(1),j.skipBits(1);let F=j.readBits(1);if(F)j.skipBits(1),j.skipBits(1);let C=j.readBits(1),w=0;if(C)w=2;else w=j.readBits(1);if(w>0){if(!j.readBits(1))j.skipBits(1)}if(F)j.skipBits(3)}j.skipBits(1),j.skipBits(1),j.skipBits(1);let R=j.readBits(1),z=8;if(X===2&&R)z=j.readBits(1)?12:10;else if(X<=2)z=R?10:8;let _=0;if(X!==1)_=j.readBits(1);let L=1,M=1,B=0;if(!_){if(X===0)L=1,M=1;else if(X===1)L=0,M=0;else if(z===12){if(L=j.readBits(1),L)M=j.readBits(1)}if(L&&M)B=j.readBits(2)}return{profile:X,level:K,tier:Q,bitDepth:z,monochrome:_,chromaSubsamplingX:L,chromaSubsamplingY:M,chromaSamplePosition:B}}return null},z1=($)=>{let J=h($),Y=J.getUint8(9),j=J.getUint16(10,!0),X=J.getUint32(12,!0),Z=J.getInt16(16,!0),G=J.getUint8(18),K=null;if(G)K=$.subarray(19,21+Y);return{outputChannelCount:Y,preSkip:j,inputSampleRate:X,outputGain:Z,channelMappingFamily:G,channelMappingTable:K}},S7=[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],sJ=($)=>{let J=$[0]>>3;return{durationInSamples:S7[J]}},S6=($)=>{if($.length<7)throw Error("Setup header is too short.");if($[0]!==5)throw Error("Wrong packet type in Setup header.");if(String.fromCharCode(...$.slice(1,7))!=="vorbis")throw Error("Invalid packet signature in Setup header.");let Y=$.length,j=new Uint8Array(Y);for(let W=0;W<Y;W++)j[W]=$[Y-1-W];let X=new f(j),Z=0;while(X.getBitsLeft()>97)if(X.readBits(1)===1){Z=X.pos;break}if(Z===0)throw Error("Invalid Setup header: framing bit not found.");let G=0,K=!1,Q=0;while(X.getBitsLeft()>=97){let W=X.pos,V=X.readBits(8),N=X.readBits(16),A=X.readBits(16);if(V>63||N!==0||A!==0){X.pos=W;break}if(X.skipBits(1),G++,G>64)break;if(X.clone().readBits(6)+1===G)K=!0,Q=G}if(!K)throw Error("Invalid Setup header: mode header not found.");if(Q>63)throw Error(`Unsupported mode count: ${Q}.`);let q=Q;X.pos=0,X.skipBits(Z);let U=Array(q).fill(0);for(let W=q-1;W>=0;W--)X.skipBits(40),U[W]=X.readBits(1);return{modeBlockflags:U}},h6=($,J,Y)=>{switch($){case"avc":{let j=r2(Y,J),X=j.some((Z)=>h1(Z)===5);if(!X&&(!B8()||LJ()>=144))for(let Z of j){if(h1(Z)!==6)continue;let K=y6(Z),Q=1;do{let q=0;while(!0){let V=K[Q++];if(V===void 0)break;if(q+=V,V<255)break}let U=0;while(!0){let V=K[Q++];if(V===void 0)break;if(U+=V,V<255)break}if(q===6){let V=new f(K);V.pos=8*Q;let N=E(V),A=V.readBits(1);if(N===0&&A===1){X=!0;break}}Q+=U}while(Q<K.length-1)}return X?"key":"delta"}case"hevc":return s2(Y,J).some((Z)=>{let G=Z1(Z);return 16<=G&&G<=23})?"key":"delta";case"vp8":return(Y[0]&1)===0?"key":"delta";case"vp9":{let j=new f(Y);if(j.readBits(2)!==2)return null;let X=j.readBits(1);if((j.readBits(1)<<1)+X===3)j.skipBits(1);if(j.readBits(1))return null;return j.readBits(1)===0?"key":"delta"}case"av1":{let j=!1;for(let{type:X,data:Z}of iJ(Y))if(X===1){let G=new f(Z);G.skipBits(4),j=!!G.readBits(1)}else if(X===3||X===6||X===7){if(j)return"key";let G=new f(Z);if(G.readBits(1))return null;return G.readBits(2)===0?"key":"delta"}return null}case"mpeg4":{for(let j=0;j<Y.length-4;j++)if(Y[j]===0&&Y[j+1]===0&&Y[j+2]===1&&Y[j+3]===182)return(Y[j+4]>>6&3)===0?"key":"delta";return null}default:i($),H(!1)}};var P8=($,J)=>{let Y=h($),j=0,X=Y.getUint32(j,!0);j+=4;let Z=Y0.decode($.subarray(j,j+X));if(j+=X,X>0)J.raw??={},J.raw.vendor??=Z;let G=Y.getUint32(j,!0);j+=4;for(let K=0;K<G;K++){let Q=Y.getUint32(j,!0);j+=4;let q=Y0.decode($.subarray(j,j+Q));j+=Q;let U=q.indexOf("=");if(U===-1)continue;let W=q.slice(0,U).toUpperCase(),V=q.slice(U+1);switch(J.raw??={},J.raw[W]??=V,W){case"TITLE":J.title??=V;break;case"DESCRIPTION":J.description??=V;break;case"ARTIST":J.artist??=V;break;case"ALBUM":J.album??=V;break;case"ALBUMARTIST":J.albumArtist??=V;break;case"COMMENT":J.comment??=V;break;case"LYRICS":J.lyrics??=V;break;case"TRACKNUMBER":{let N=V.split("/"),A=Number.parseInt(N[0],10),R=N[1]&&Number.parseInt(N[1],10);if(Number.isInteger(A)&&A>0)J.trackNumber??=A;if(R&&Number.isInteger(R)&&R>0)J.tracksTotal??=R}break;case"TRACKTOTAL":{let N=Number.parseInt(V,10);if(Number.isInteger(N)&&N>0)J.tracksTotal??=N}break;case"DISCNUMBER":{let N=V.split("/"),A=Number.parseInt(N[0],10),R=N[1]&&Number.parseInt(N[1],10);if(Number.isInteger(A)&&A>0)J.discNumber??=A;if(R&&Number.isInteger(R)&&R>0)J.discsTotal??=R}break;case"DISCTOTAL":{let N=Number.parseInt(V,10);if(Number.isInteger(N)&&N>0)J.discsTotal??=N}break;case"DATE":{let N=new Date(V);if(!Number.isNaN(N.getTime()))J.date??=N}break;case"GENRE":J.genre??=V;break;case"METADATA_BLOCK_PICTURE":{let N=FJ(V),A=h(N),R=A.getUint32(0,!1),z=A.getUint32(4,!1),_=String.fromCharCode(...N.subarray(8,8+z)),L=A.getUint32(8+z,!1),M=Y0.decode(N.subarray(12+z,12+z+L)),B=A.getUint32(z+L+28),F=N.subarray(z+L+32,z+L+32+B);J.images??=[],J.images.push({data:F,mimeType:_,kind:R===3?"coverFront":R===4?"coverBack":"unknown",name:void 0,description:M||void 0})}break}}},C8=($,J,Y)=>{let j=[$],X="Mediabunny",Z=m.encode("Mediabunny"),G=new Uint8Array(4+Z.length),K=new DataView(G.buffer);K.setUint32(0,Z.length,!0),G.set(Z,4),j.push(G);let Q=new Set,q=(A,R)=>{let z=`${A}=${R}`,_=m.encode(z);G=new Uint8Array(4+_.length),K=new DataView(G.buffer),K.setUint32(0,_.length,!0),G.set(_,4),j.push(G),Q.add(A)};for(let{key:A,value:R}of v0(J))switch(A){case"title":q("TITLE",R);break;case"description":q("DESCRIPTION",R);break;case"artist":q("ARTIST",R);break;case"album":q("ALBUM",R);break;case"albumArtist":q("ALBUMARTIST",R);break;case"genre":q("GENRE",R);break;case"date":{let z=J.raw?.DATE??J.raw?.date;if(z&&typeof z==="string")q("DATE",z);else q("DATE",R.toISOString().slice(0,10))}break;case"comment":q("COMMENT",R);break;case"lyrics":q("LYRICS",R);break;case"trackNumber":q("TRACKNUMBER",R.toString());break;case"tracksTotal":q("TRACKTOTAL",R.toString());break;case"discNumber":q("DISCNUMBER",R.toString());break;case"discsTotal":q("DISCTOTAL",R.toString());break;case"images":{if(!Y)break;for(let z of R){let _=z.kind==="coverFront"?3:z.kind==="coverBack"?4:0,L=new Uint8Array(z.mimeType.length);for(let w=0;w<z.mimeType.length;w++)L[w]=z.mimeType.charCodeAt(w);let M=m.encode(z.description??""),B=new Uint8Array(8+L.length+4+M.length+16+4+z.data.length),F=h(B);F.setUint32(0,_,!1),F.setUint32(4,L.length,!1),B.set(L,8),F.setUint32(8+L.length,M.length,!1),B.set(M,12+L.length),F.setUint32(28+L.length+M.length,z.data.length,!1),B.set(z.data,32+L.length+M.length);let C=BJ(B);q("METADATA_BLOCK_PICTURE",C)}}break;case"raw":break;default:i(A)}if(J.raw)for(let A in J.raw){let R=J.raw[A]??J.raw[A.toLowerCase()];if(A==="vendor"||R==null||Q.has(A))continue;if(typeof R==="string")q(A,R)}let U=new Uint8Array(4);h(U).setUint32(0,Q.size,!0),j.splice(2,0,U);let W=j.reduce((A,R)=>A+R.length,0),V=new Uint8Array(W),N=0;for(let A of j)V.set(A,N),N+=A.length;return V};/*!
99
+ */var O8=($)=>{let J=[],Y=0;while(Y<$.length){let j=-1,X=0;for(let Z=Y;Z<$.length-3;Z++){if($[Z]===0&&$[Z+1]===0&&$[Z+2]===1){j=Z,X=3;break}if(Z<$.length-4&&$[Z]===0&&$[Z+1]===0&&$[Z+2]===0&&$[Z+3]===1){j=Z,X=4;break}}if(j===-1)break;if(Y>0&&j>Y){let Z=$.subarray(Y,j);if(Z.length>0)J.push(Z)}Y=j+X}if(Y<$.length){let j=$.subarray(Y);if(j.length>0)J.push(j)}return J},lJ=($,J)=>{let Y=[],j=0,X=new DataView($.buffer,$.byteOffset,$.byteLength);while(j+J<=$.length){let Z;if(J===1)Z=X.getUint8(j);else if(J===2)Z=X.getUint16(j,!1);else if(J===3)Z=T1(X,j,!1);else if(J===4)Z=X.getUint32(j,!1);else i(J),H(!1);j+=J;let G=$.subarray(j,j+Z);Y.push(G),j+=Z}return Y},y6=($)=>{let J=[],Y=$.length;for(let j=0;j<Y;j++)if(j+2<Y&&$[j]===0&&$[j+1]===0&&$[j+2]===3)J.push(0,0),j+=2;else J.push($[j]);return new Uint8Array(J)},o2=new Uint8Array([0,0,0,1]),D7=($)=>{let J=$.reduce((X,Z)=>X+o2.byteLength+Z.byteLength,0),Y=new Uint8Array(J),j=0;for(let X of $)Y.set(o2,j),j+=o2.byteLength,Y.set(X,j),j+=X.byteLength;return Y},mJ=($,J)=>{let Y=$.reduce((Z,G)=>Z+J+G.byteLength,0),j=new Uint8Array(Y),X=0;for(let Z of $){let G=new DataView(j.buffer,j.byteOffset,j.byteLength);switch(J){case 1:G.setUint8(X,Z.byteLength);break;case 2:G.setUint16(X,Z.byteLength,!1);break;case 3:L8(G,X,Z.byteLength,!1);break;case 4:G.setUint32(X,Z.byteLength,!1);break}X+=J,j.set(Z,X),X+=Z.byteLength}return j},dJ=($)=>{let J=O8($);if(J.length===0)return null;return mJ(J,4)},r2=($,J)=>{if(J.description){let X=(l(J.description)[4]&3)+1;return lJ($,X)}return O8($)},cJ=($,J)=>{if(J.description){let X=(l(J.description)[4]&3)+1;return mJ($,X)}else return D7($)},h1=($)=>{return $[0]&31},v6=($)=>{try{let J=O8($),Y=J.filter((Q)=>h1(Q)===7),j=J.filter((Q)=>h1(Q)===8),X=J.filter((Q)=>h1(Q)===13);if(Y.length===0)return null;if(j.length===0)return null;let Z=Y[0],G=i2(Z);H(G!==null);let K=G.profileIdc===100||G.profileIdc===110||G.profileIdc===122||G.profileIdc===144;return{configurationVersion:1,avcProfileIndication:G.profileIdc,profileCompatibility:G.constraintFlags,avcLevelIndication:G.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:Y,pictureParameterSets:j,chromaFormat:K?G.chromaFormatIdc:null,bitDepthLumaMinus8:K?G.bitDepthLumaMinus8:null,bitDepthChromaMinus8:K?G.bitDepthChromaMinus8:null,sequenceParameterSetExt:K?X:null}}catch(J){return console.error("Error building AVC Decoder Configuration Record:",J),null}},nJ=($)=>{let J=[];J.push($.configurationVersion),J.push($.avcProfileIndication),J.push($.profileCompatibility),J.push($.avcLevelIndication),J.push(252|$.lengthSizeMinusOne&3),J.push(224|$.sequenceParameterSets.length&31);for(let Y of $.sequenceParameterSets){let j=Y.byteLength;J.push(j>>8),J.push(j&255);for(let X=0;X<j;X++)J.push(Y[X])}J.push($.pictureParameterSets.length);for(let Y of $.pictureParameterSets){let j=Y.byteLength;J.push(j>>8),J.push(j&255);for(let X=0;X<j;X++)J.push(Y[X])}if($.avcProfileIndication===100||$.avcProfileIndication===110||$.avcProfileIndication===122||$.avcProfileIndication===144){H($.chromaFormat!==null),H($.bitDepthLumaMinus8!==null),H($.bitDepthChromaMinus8!==null),H($.sequenceParameterSetExt!==null),J.push(252|$.chromaFormat&3),J.push(248|$.bitDepthLumaMinus8&7),J.push(248|$.bitDepthChromaMinus8&7),J.push($.sequenceParameterSetExt.length);for(let Y of $.sequenceParameterSetExt){let j=Y.byteLength;J.push(j>>8),J.push(j&255);for(let X=0;X<j;X++)J.push(Y[X])}}return new Uint8Array(J)},oJ=($)=>{try{let J=h($),Y=0,j=J.getUint8(Y++),X=J.getUint8(Y++),Z=J.getUint8(Y++),G=J.getUint8(Y++),K=J.getUint8(Y++)&3,Q=J.getUint8(Y++)&31,q=[];for(let N=0;N<Q;N++){let A=J.getUint16(Y,!1);Y+=2,q.push($.subarray(Y,Y+A)),Y+=A}let U=J.getUint8(Y++),W=[];for(let N=0;N<U;N++){let A=J.getUint16(Y,!1);Y+=2,W.push($.subarray(Y,Y+A)),Y+=A}let V={configurationVersion:j,avcProfileIndication:X,profileCompatibility:Z,avcLevelIndication:G,lengthSizeMinusOne:K,sequenceParameterSets:q,pictureParameterSets:W,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((X===100||X===110||X===122||X===144)&&Y+4<=$.length){let N=J.getUint8(Y++)&3,A=J.getUint8(Y++)&7,R=J.getUint8(Y++)&7,z=J.getUint8(Y++);V.chromaFormat=N,V.bitDepthLumaMinus8=A,V.bitDepthChromaMinus8=R;let _=[];for(let L=0;L<z;L++){let M=J.getUint16(Y,!1);Y+=2,_.push($.subarray(Y,Y+M)),Y+=M}V.sequenceParameterSetExt=_}return V}catch(J){return console.error("Error deserializing AVC Decoder Configuration Record:",J),null}},i2=($)=>{try{let J=new f(y6($));if(J.skipBits(1),J.skipBits(2),J.readBits(5)!==7)return null;let j=J.readAlignedByte(),X=J.readAlignedByte(),Z=J.readAlignedByte();E(J);let G=null,K=null,Q=null;if(j===100||j===110||j===122||j===244||j===44||j===83||j===86||j===118||j===128){if(G=E(J),G===3)J.skipBits(1);if(K=E(J),Q=E(J),J.skipBits(1),J.readBits(1)){for(let V=0;V<(G!==3?8:12);V++)if(J.readBits(1)){let A=V<6?16:64,R=8,z=8;for(let _=0;_<A;_++){if(z!==0){let L=m0(J);z=(R+L+256)%256}R=z===0?R:z}}}}E(J);let q=E(J);if(q===0)E(J);else if(q===1){J.skipBits(1),m0(J),m0(J);let W=E(J);for(let V=0;V<W;V++)m0(J)}E(J),J.skipBits(1),E(J),E(J);let U=J.readBits(1);return{profileIdc:j,constraintFlags:X,levelIdc:Z,frameMbsOnlyFlag:U,chromaFormatIdc:G,bitDepthLumaMinus8:K,bitDepthChromaMinus8:Q}}catch(J){return console.error("Error parsing AVC SPS:",J),null}},s2=($,J)=>{if(J.description){let X=(l(J.description)[21]&3)+1;return lJ($,X)}return O8($)},Z1=($)=>{return $[0]>>1&63},b6=($)=>{try{let J=O8($),Y=J.filter((S)=>Z1(S)===32),j=J.filter((S)=>Z1(S)===33),X=J.filter((S)=>Z1(S)===34),Z=J.filter((S)=>Z1(S)===39||Z1(S)===40);if(j.length===0||X.length===0)return null;let G=j[0],K=new f(y6(G));K.skipBits(16),K.readBits(4);let Q=K.readBits(3),q=K.readBits(1),{general_profile_space:U,general_tier_flag:W,general_profile_idc:V,general_profile_compatibility_flags:N,general_constraint_indicator_flags:A,general_level_idc:R}=E7(K,Q);E(K);let z=E(K);if(z===3)K.skipBits(1);if(E(K),E(K),K.readBits(1))E(K),E(K),E(K),E(K);let _=E(K),L=E(K);E(K);let B=K.readBits(1)?0:Q;for(let S=B;S<=Q;S++)E(K),E(K),E(K);if(E(K),E(K),E(K),E(K),E(K),E(K),K.readBits(1)){if(K.readBits(1))T7(K)}if(K.skipBits(1),K.skipBits(1),K.readBits(1))K.skipBits(4),K.skipBits(4),E(K),E(K),K.skipBits(1);let F=E(K);if(y7(K,F),K.readBits(1)){let S=E(K);for(let T=0;T<S;T++)E(K),K.skipBits(1)}K.skipBits(1),K.skipBits(1);let C=0;if(K.readBits(1))C=b7(K,Q);let w=0;if(X.length>0){let S=X[0],T=new f(y6(S));if(T.skipBits(16),E(T),E(T),T.skipBits(1),T.skipBits(1),T.skipBits(3),T.skipBits(1),T.skipBits(1),E(T),E(T),m0(T),T.skipBits(1),T.skipBits(1),T.readBits(1))E(T);m0(T),m0(T),T.skipBits(1),T.skipBits(1),T.skipBits(1),T.skipBits(1);let r=T.readBits(1),H0=T.readBits(1);if(!r&&!H0)w=0;else if(r&&!H0)w=2;else if(!r&&H0)w=3;else w=0}let v=[...Y.length?[{arrayCompleteness:1,nalUnitType:32,nalUnits:Y}]:[],...j.length?[{arrayCompleteness:1,nalUnitType:33,nalUnits:j}]:[],...X.length?[{arrayCompleteness:1,nalUnitType:34,nalUnits:X}]:[],...Z.length?[{arrayCompleteness:1,nalUnitType:Z1(Z[0]),nalUnits:Z}]:[]];return{configurationVersion:1,generalProfileSpace:U,generalTierFlag:W,generalProfileIdc:V,generalProfileCompatibilityFlags:N,generalConstraintIndicatorFlags:A,generalLevelIdc:R,minSpatialSegmentationIdc:C,parallelismType:w,chromaFormatIdc:z,bitDepthLumaMinus8:_,bitDepthChromaMinus8:L,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:Q+1,temporalIdNested:q,lengthSizeMinusOne:3,arrays:v}}catch(J){return console.error("Error building HEVC Decoder Configuration Record:",J),null}},E7=($,J)=>{let Y=$.readBits(2),j=$.readBits(1),X=$.readBits(5),Z=0;for(let U=0;U<32;U++)Z=Z<<1|$.readBits(1);let G=new Uint8Array(6);for(let U=0;U<6;U++)G[U]=$.readBits(8);let K=$.readBits(8),Q=[],q=[];for(let U=0;U<J;U++)Q.push($.readBits(1)),q.push($.readBits(1));if(J>0)for(let U=J;U<8;U++)$.skipBits(2);for(let U=0;U<J;U++){if(Q[U])$.skipBits(88);if(q[U])$.skipBits(8)}return{general_profile_space:Y,general_tier_flag:j,general_profile_idc:X,general_profile_compatibility_flags:Z,general_constraint_indicator_flags:G,general_level_idc:K}},T7=($)=>{for(let J=0;J<4;J++)for(let Y=0;Y<(J===3?2:6);Y++)if(!$.readBits(1))E($);else{let X=Math.min(64,1<<4+(J<<1));if(J>1)m0($);for(let Z=0;Z<X;Z++)m0($)}},y7=($,J)=>{let Y=[];for(let j=0;j<J;j++)Y[j]=v7($,j,J,Y)},v7=($,J,Y,j)=>{let X=0,Z=0,G=0;if(J!==0)Z=$.readBits(1);if(Z){if(J===Y){let Q=E($);G=J-(Q+1)}else G=J-1;$.readBits(1),E($);let K=j[G]??0;for(let Q=0;Q<=K;Q++)if(!$.readBits(1))$.readBits(1);X=j[G]}else{let K=E($),Q=E($);for(let q=0;q<K;q++)E($),$.readBits(1);for(let q=0;q<Q;q++)E($),$.readBits(1);X=K+Q}return X},b7=($,J)=>{if($.readBits(1)){if($.readBits(8)===255)$.readBits(16),$.readBits(16)}if($.readBits(1))$.readBits(1);if($.readBits(1)){if($.readBits(3),$.readBits(1),$.readBits(1))$.readBits(8),$.readBits(8),$.readBits(8)}if($.readBits(1))E($),E($);if($.readBits(1),$.readBits(1),$.readBits(1),$.readBits(1))E($),E($),E($),E($);if($.readBits(1)){if($.readBits(32),$.readBits(32),$.readBits(1))E($);if($.readBits(1))x7($,!0,J)}if($.readBits(1)){$.readBits(1),$.readBits(1),$.readBits(1);let Y=E($);return E($),E($),E($),E($),Y}return 0},x7=($,J,Y)=>{let j=!1,X=!1,Z=!1;if(J){if(j=$.readBits(1)===1,X=$.readBits(1)===1,j||X){if(Z=$.readBits(1)===1,Z)$.readBits(8),$.readBits(5),$.readBits(1),$.readBits(5);if($.readBits(4),$.readBits(4),Z)$.readBits(4);$.readBits(5),$.readBits(5),$.readBits(5)}}for(let G=0;G<=Y;G++){let K=$.readBits(1)===1,Q=!0;if(!K)Q=$.readBits(1)===1;let q=!1;if(Q)E($);else q=$.readBits(1)===1;let U=1;if(!q)U=E($)+1;if(j)pJ($,U,Z);if(X)pJ($,U,Z)}},pJ=($,J,Y)=>{for(let j=0;j<J;j++){if(E($),E($),Y)E($),E($);$.readBits(1)}},rJ=($)=>{let J=[];J.push($.configurationVersion),J.push(($.generalProfileSpace&3)<<6|($.generalTierFlag&1)<<5|$.generalProfileIdc&31),J.push($.generalProfileCompatibilityFlags>>>24&255),J.push($.generalProfileCompatibilityFlags>>>16&255),J.push($.generalProfileCompatibilityFlags>>>8&255),J.push($.generalProfileCompatibilityFlags&255),J.push(...$.generalConstraintIndicatorFlags),J.push($.generalLevelIdc&255),J.push(240|$.minSpatialSegmentationIdc>>8&15),J.push($.minSpatialSegmentationIdc&255),J.push(252|$.parallelismType&3),J.push(252|$.chromaFormatIdc&3),J.push(248|$.bitDepthLumaMinus8&7),J.push(248|$.bitDepthChromaMinus8&7),J.push($.avgFrameRate>>8&255),J.push($.avgFrameRate&255),J.push(($.constantFrameRate&3)<<6|($.numTemporalLayers&7)<<3|($.temporalIdNested&1)<<2|$.lengthSizeMinusOne&3),J.push($.arrays.length&255);for(let Y of $.arrays){J.push((Y.arrayCompleteness&1)<<7|0|Y.nalUnitType&63),J.push(Y.nalUnits.length>>8&255),J.push(Y.nalUnits.length&255);for(let j of Y.nalUnits){J.push(j.length>>8&255),J.push(j.length&255);for(let X=0;X<j.length;X++)J.push(j[X])}}return new Uint8Array(J)},x6=($)=>{let J=new f($);if(J.readBits(2)!==2)return null;let j=J.readBits(1),Z=(J.readBits(1)<<1)+j;if(Z===3)J.skipBits(1);if(J.readBits(1)===1)return null;if(J.readBits(1)!==0)return null;if(J.skipBits(2),J.readBits(24)!==4817730)return null;let q=8;if(Z>=2)q=J.readBits(1)?12:10;let U=J.readBits(3),W=0,V=0;if(U!==7)if(V=J.readBits(1),Z===1||Z===3){let w=J.readBits(1),v=J.readBits(1);W=!w&&!v?3:w&&!v?2:1,J.skipBits(1)}else W=1;else W=3,V=1;let N=J.readBits(16),A=J.readBits(16),R=N+1,z=A+1,_=R*z,L=n(j1).level;for(let C of j1)if(_<=C.maxPictureSize){L=C.level;break}return{profile:Z,level:L,bitDepth:q,chromaSubsampling:W,videoFullRangeFlag:V,colourPrimaries:U===2?1:U===1?6:2,transferCharacteristics:U===2?1:U===1?6:2,matrixCoefficients:U===7?0:U===2?1:U===1?6:2}},iJ=function*($){let J=new f($),Y=()=>{let j=0;for(let X=0;X<8;X++){let Z=J.readAlignedByte();if(j|=(Z&127)<<X*7,!(Z&128))break;if(X===7&&Z&128)return null}if(j>=4294967295)return null;return j};while(J.getBitsLeft()>=8){J.skipBits(1);let j=J.readBits(4),X=J.readBits(1),Z=J.readBits(1);if(J.skipBits(1),X)J.skipBits(8);let G;if(Z){let K=Y();if(K===null)return;G=K}else G=Math.floor(J.getBitsLeft()/8);H(J.pos%8===0),yield{type:j,data:$.subarray(J.pos/8,J.pos/8+G)},J.skipBits(G*8)}},I6=($)=>{for(let{type:J,data:Y}of iJ($)){if(J!==1)continue;let j=new f(Y),X=j.readBits(3),Z=j.readBits(1),G=j.readBits(1),K=0,Q=0,q=0;if(G)K=j.readBits(5);else{if(j.readBits(1)){if(j.skipBits(32),j.skipBits(32),j.readBits(1))return null}let C=j.readBits(1);if(C)q=j.readBits(5),j.skipBits(32),j.skipBits(5),j.skipBits(5);let w=j.readBits(5);for(let v=0;v<=w;v++){j.skipBits(12);let k=j.readBits(5);if(v===0)K=k;if(k>7){let T=j.readBits(1);if(v===0)Q=T}if(C){if(j.readBits(1)){let r=q+1;j.skipBits(r),j.skipBits(r),j.skipBits(1)}}if(j.readBits(1))j.skipBits(4)}}let U=j.readBits(4),W=j.readBits(4),V=U+1;j.skipBits(V);let N=W+1;j.skipBits(N);let A=0;if(G)A=0;else A=j.readBits(1);if(A)j.skipBits(4),j.skipBits(3);if(j.skipBits(1),j.skipBits(1),j.skipBits(1),!G){j.skipBits(1),j.skipBits(1),j.skipBits(1),j.skipBits(1);let F=j.readBits(1);if(F)j.skipBits(1),j.skipBits(1);let C=j.readBits(1),w=0;if(C)w=2;else w=j.readBits(1);if(w>0){if(!j.readBits(1))j.skipBits(1)}if(F)j.skipBits(3)}j.skipBits(1),j.skipBits(1),j.skipBits(1);let R=j.readBits(1),z=8;if(X===2&&R)z=j.readBits(1)?12:10;else if(X<=2)z=R?10:8;let _=0;if(X!==1)_=j.readBits(1);let L=1,M=1,B=0;if(!_){if(X===0)L=1,M=1;else if(X===1)L=0,M=0;else if(z===12){if(L=j.readBits(1),L)M=j.readBits(1)}if(L&&M)B=j.readBits(2)}return{profile:X,level:K,tier:Q,bitDepth:z,monochrome:_,chromaSubsamplingX:L,chromaSubsamplingY:M,chromaSamplePosition:B}}return null},z1=($)=>{let J=h($),Y=J.getUint8(9),j=J.getUint16(10,!0),X=J.getUint32(12,!0),Z=J.getInt16(16,!0),G=J.getUint8(18),K=null;if(G)K=$.subarray(19,21+Y);return{outputChannelCount:Y,preSkip:j,inputSampleRate:X,outputGain:Z,channelMappingFamily:G,channelMappingTable:K}},I7=[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],sJ=($)=>{let J=$[0]>>3;return{durationInSamples:I7[J]}},S6=($)=>{if($.length<7)throw Error("Setup header is too short.");if($[0]!==5)throw Error("Wrong packet type in Setup header.");if(String.fromCharCode(...$.slice(1,7))!=="vorbis")throw Error("Invalid packet signature in Setup header.");let Y=$.length,j=new Uint8Array(Y);for(let W=0;W<Y;W++)j[W]=$[Y-1-W];let X=new f(j),Z=0;while(X.getBitsLeft()>97)if(X.readBits(1)===1){Z=X.pos;break}if(Z===0)throw Error("Invalid Setup header: framing bit not found.");let G=0,K=!1,Q=0;while(X.getBitsLeft()>=97){let W=X.pos,V=X.readBits(8),N=X.readBits(16),A=X.readBits(16);if(V>63||N!==0||A!==0){X.pos=W;break}if(X.skipBits(1),G++,G>64)break;if(X.clone().readBits(6)+1===G)K=!0,Q=G}if(!K)throw Error("Invalid Setup header: mode header not found.");if(Q>63)throw Error(`Unsupported mode count: ${Q}.`);let q=Q;X.pos=0,X.skipBits(Z);let U=Array(q).fill(0);for(let W=q-1;W>=0;W--)X.skipBits(40),U[W]=X.readBits(1);return{modeBlockflags:U}},h6=($,J,Y)=>{switch($){case"avc":{let j=r2(Y,J),X=j.some((Z)=>h1(Z)===5);if(!X&&(!B8()||LJ()>=144))for(let Z of j){if(h1(Z)!==6)continue;let K=y6(Z),Q=1;do{let q=0;while(!0){let V=K[Q++];if(V===void 0)break;if(q+=V,V<255)break}let U=0;while(!0){let V=K[Q++];if(V===void 0)break;if(U+=V,V<255)break}if(q===6){let V=new f(K);V.pos=8*Q;let N=E(V),A=V.readBits(1);if(N===0&&A===1){X=!0;break}}Q+=U}while(Q<K.length-1)}return X?"key":"delta"}case"hevc":return s2(Y,J).some((Z)=>{let G=Z1(Z);return 16<=G&&G<=23})?"key":"delta";case"vp8":return(Y[0]&1)===0?"key":"delta";case"vp9":{let j=new f(Y);if(j.readBits(2)!==2)return null;let X=j.readBits(1);if((j.readBits(1)<<1)+X===3)j.skipBits(1);if(j.readBits(1))return null;return j.readBits(1)===0?"key":"delta"}case"av1":{let j=!1;for(let{type:X,data:Z}of iJ(Y))if(X===1){let G=new f(Z);G.skipBits(4),j=!!G.readBits(1)}else if(X===3||X===6||X===7){if(j)return"key";let G=new f(Z);if(G.readBits(1))return null;return G.readBits(2)===0?"key":"delta"}return null}case"mpeg4":{for(let j=0;j<Y.length-4;j++)if(Y[j]===0&&Y[j+1]===0&&Y[j+2]===1&&Y[j+3]===182)return(Y[j+4]>>6&3)===0?"key":"delta";return null}default:i($),H(!1)}};var P8=($,J)=>{let Y=h($),j=0,X=Y.getUint32(j,!0);j+=4;let Z=Y0.decode($.subarray(j,j+X));if(j+=X,X>0)J.raw??={},J.raw.vendor??=Z;let G=Y.getUint32(j,!0);j+=4;for(let K=0;K<G;K++){let Q=Y.getUint32(j,!0);j+=4;let q=Y0.decode($.subarray(j,j+Q));j+=Q;let U=q.indexOf("=");if(U===-1)continue;let W=q.slice(0,U).toUpperCase(),V=q.slice(U+1);switch(J.raw??={},J.raw[W]??=V,W){case"TITLE":J.title??=V;break;case"DESCRIPTION":J.description??=V;break;case"ARTIST":J.artist??=V;break;case"ALBUM":J.album??=V;break;case"ALBUMARTIST":J.albumArtist??=V;break;case"COMMENT":J.comment??=V;break;case"LYRICS":J.lyrics??=V;break;case"TRACKNUMBER":{let N=V.split("/"),A=Number.parseInt(N[0],10),R=N[1]&&Number.parseInt(N[1],10);if(Number.isInteger(A)&&A>0)J.trackNumber??=A;if(R&&Number.isInteger(R)&&R>0)J.tracksTotal??=R}break;case"TRACKTOTAL":{let N=Number.parseInt(V,10);if(Number.isInteger(N)&&N>0)J.tracksTotal??=N}break;case"DISCNUMBER":{let N=V.split("/"),A=Number.parseInt(N[0],10),R=N[1]&&Number.parseInt(N[1],10);if(Number.isInteger(A)&&A>0)J.discNumber??=A;if(R&&Number.isInteger(R)&&R>0)J.discsTotal??=R}break;case"DISCTOTAL":{let N=Number.parseInt(V,10);if(Number.isInteger(N)&&N>0)J.discsTotal??=N}break;case"DATE":{let N=new Date(V);if(!Number.isNaN(N.getTime()))J.date??=N}break;case"GENRE":J.genre??=V;break;case"METADATA_BLOCK_PICTURE":{let N=FJ(V),A=h(N),R=A.getUint32(0,!1),z=A.getUint32(4,!1),_=String.fromCharCode(...N.subarray(8,8+z)),L=A.getUint32(8+z,!1),M=Y0.decode(N.subarray(12+z,12+z+L)),B=A.getUint32(z+L+28),F=N.subarray(z+L+32,z+L+32+B);J.images??=[],J.images.push({data:F,mimeType:_,kind:R===3?"coverFront":R===4?"coverBack":"unknown",name:void 0,description:M||void 0})}break}}},C8=($,J,Y)=>{let j=[$],X="Mediabunny",Z=m.encode("Mediabunny"),G=new Uint8Array(4+Z.length),K=new DataView(G.buffer);K.setUint32(0,Z.length,!0),G.set(Z,4),j.push(G);let Q=new Set,q=(A,R)=>{let z=`${A}=${R}`,_=m.encode(z);G=new Uint8Array(4+_.length),K=new DataView(G.buffer),K.setUint32(0,_.length,!0),G.set(_,4),j.push(G),Q.add(A)};for(let{key:A,value:R}of v0(J))switch(A){case"title":q("TITLE",R);break;case"description":q("DESCRIPTION",R);break;case"artist":q("ARTIST",R);break;case"album":q("ALBUM",R);break;case"albumArtist":q("ALBUMARTIST",R);break;case"genre":q("GENRE",R);break;case"date":{let z=J.raw?.DATE??J.raw?.date;if(z&&typeof z==="string")q("DATE",z);else q("DATE",R.toISOString().slice(0,10))}break;case"comment":q("COMMENT",R);break;case"lyrics":q("LYRICS",R);break;case"trackNumber":q("TRACKNUMBER",R.toString());break;case"tracksTotal":q("TRACKTOTAL",R.toString());break;case"discNumber":q("DISCNUMBER",R.toString());break;case"discsTotal":q("DISCTOTAL",R.toString());break;case"images":{if(!Y)break;for(let z of R){let _=z.kind==="coverFront"?3:z.kind==="coverBack"?4:0,L=new Uint8Array(z.mimeType.length);for(let w=0;w<z.mimeType.length;w++)L[w]=z.mimeType.charCodeAt(w);let M=m.encode(z.description??""),B=new Uint8Array(8+L.length+4+M.length+16+4+z.data.length),F=h(B);F.setUint32(0,_,!1),F.setUint32(4,L.length,!1),B.set(L,8),F.setUint32(8+L.length,M.length,!1),B.set(M,12+L.length),F.setUint32(28+L.length+M.length,z.data.length,!1),B.set(z.data,32+L.length+M.length);let C=BJ(B);q("METADATA_BLOCK_PICTURE",C)}}break;case"raw":break;default:i(A)}if(J.raw)for(let A in J.raw){let R=J.raw[A]??J.raw[A.toLowerCase()];if(A==="vendor"||R==null||Q.has(A))continue;if(typeof R==="string")q(A,R)}let U=new Uint8Array(4);h(U).setUint32(0,Q.size,!0),j.splice(2,0,U);let W=j.reduce((A,R)=>A+R.length,0),V=new Uint8Array(W),N=0;for(let A of j)V.set(A,N),N+=A.length;return V};/*!
100
100
  * Copyright (c) 2025-present, Vanilagy and contributors
101
101
  *
102
102
  * This Source Code Form is subject to the terms of the Mozilla Public
@@ -114,7 +114,7 @@ ${K.join(`
114
114
  * This Source Code Form is subject to the terms of the Mozilla Public
115
115
  * License, v. 2.0. If a copy of the MPL was not distributed with this
116
116
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
117
- */U6();var J5=-1/0,Y5=-1/0,y8=null;if(typeof FinalizationRegistry<"u")y8=new FinalizationRegistry(($)=>{let J=Date.now();if($.type==="video"){if(J-J5>=1000)console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),J5=J;if(typeof VideoFrame<"u"&&$.data instanceof VideoFrame)$.data.close()}else{if(J-Y5>=1000)console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Y5=J;if(typeof AudioData<"u"&&$.data instanceof AudioData)$.data.close()}});var t2=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],h7=new Set(t2);class J0{_data;_layout;_closed=!1;format;codedWidth;codedHeight;rotation;timestamp;duration;colorSpace;get displayWidth(){return this.rotation%180===0?this.codedWidth:this.codedHeight}get displayHeight(){return this.rotation%180===0?this.codedHeight:this.codedWidth}get microsecondTimestamp(){return Math.trunc(c0*this.timestamp)}get microsecondDuration(){return Math.trunc(c0*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor($,J){if($ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer||ArrayBuffer.isView($)){if(!J||typeof J!=="object")throw TypeError("init must be an object.");if(J.format===void 0||!h7.has(J.format))throw TypeError("init.format must be one of: "+t2.join(", "));if(!Number.isInteger(J.codedWidth)||J.codedWidth<=0)throw TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(J.codedHeight)||J.codedHeight<=0)throw TypeError("init.codedHeight must be a positive integer.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(J.timestamp))throw TypeError("init.timestamp must be a number.");if(J.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");this._data=l($).slice(),this._layout=J.layout??g7(J.format,J.codedWidth,J.codedHeight),this.format=J.format,this.codedWidth=J.codedWidth,this.codedHeight=J.codedHeight,this.rotation=J.rotation??0,this.timestamp=J.timestamp,this.duration=J.duration??0,this.colorSpace=new T8(J.colorSpace)}else if(typeof VideoFrame<"u"&&$ instanceof VideoFrame){if(J?.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(J?.timestamp!==void 0&&!Number.isFinite(J?.timestamp))throw TypeError("init.timestamp, when provided, must be a number.");if(J?.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");this._data=$,this._layout=null,this.format=$.format,this.codedWidth=$.displayWidth,this.codedHeight=$.displayHeight,this.rotation=J?.rotation??0,this.timestamp=J?.timestamp??$.timestamp/1e6,this.duration=J?.duration??($.duration??0)/1e6,this.colorSpace=new T8($.colorSpace)}else if(typeof HTMLImageElement<"u"&&$ instanceof HTMLImageElement||typeof SVGImageElement<"u"&&$ instanceof SVGImageElement||typeof ImageBitmap<"u"&&$ instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&$ instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&$ instanceof OffscreenCanvas){if(!J||typeof J!=="object")throw TypeError("init must be an object.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(J.timestamp))throw TypeError("init.timestamp must be a number.");if(J.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new J0(new VideoFrame($,{timestamp:Math.trunc(J.timestamp*c0),duration:Math.trunc((J.duration??0)*c0)||void 0}),J);let Y=0,j=0;if("naturalWidth"in $)Y=$.naturalWidth,j=$.naturalHeight;else if("videoWidth"in $)Y=$.videoWidth,j=$.videoHeight;else if("width"in $)Y=Number($.width),j=Number($.height);if(!Y||!j)throw TypeError("Could not determine dimensions.");let X=new OffscreenCanvas(Y,j),Z=X.getContext("2d",{alpha:n0(),willReadFrequently:!0});H(Z),Z.drawImage($,0,0),this._data=X,this._layout=null,this.format="RGBX",this.codedWidth=Y,this.codedHeight=j,this.rotation=J.rotation??0,this.timestamp=J.timestamp,this.duration=J.duration??0,this.colorSpace=new T8({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");y8?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw Error("VideoSample is closed.");if(H(this._data!==null),f1(this._data))return new J0(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation});if(this._data instanceof Uint8Array)return H(this._layout),new J0(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});return new J0(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){if(this._closed)return;if(y8?.unregister(this),f1(this._data))this._data.close();else this._data=null;this._closed=!0}allocationSize($={}){if(f7($),this._closed)throw Error("VideoSample is closed.");if(($.format??this.format)===null)throw Error("Cannot get allocation size when format is null. Please manually provide an RGB pixel format in the options instead.");if(H(this._data!==null),!f1(this._data)){if($.colorSpace||$.format&&$.format!==this.format||$.layout||$.rect){let J=this.toVideoFrame(),Y=J.allocationSize($);return J.close(),Y}}if(f1(this._data))return this._data.allocationSize($);if(this._data instanceof Uint8Array)return this._data.byteLength;return this.codedWidth*this.codedHeight*4}async copyTo($,J={}){if(!i1($))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(this._closed)throw Error("VideoSample is closed.");if((J.format??this.format)===null)throw Error("Cannot copy video sample data when format is null. Please manually provide an RGB pixel format in the options instead.");if(H(this._data!==null),!f1(this._data)){if(J.colorSpace||J.format&&J.format!==this.format||J.layout||J.rect){let Y=this.toVideoFrame(),j=await Y.copyTo($,J);return Y.close(),j}}if(f1(this._data))return this._data.copyTo($,J);else if(this._data instanceof Uint8Array)return H(this._layout),l($).set(this._data),this._layout;else{let j=this._data.getContext("2d");H(j);let X=j.getImageData(0,0,this.codedWidth,this.codedHeight);return l($).set(X.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw Error("VideoSample is closed.");if(H(this._data!==null),f1(this._data))return new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0});if(this._data instanceof Uint8Array)return new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace});return new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw($,J,Y,j,X,Z,G,K,Q){let q=0,U=0,W=this.displayWidth,V=this.displayHeight,N=0,A=0,R=this.displayWidth,z=this.displayHeight;if(Z!==void 0)if(q=J,U=Y,W=j,V=X,N=Z,A=G,K!==void 0)R=K,z=Q;else R=W,z=V;else if(N=J,A=Y,j!==void 0)R=j,z=X;if(!(typeof CanvasRenderingContext2D<"u"&&$ instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&$ instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(q))throw TypeError("sx must be a number.");if(!Number.isFinite(U))throw TypeError("sy must be a number.");if(!Number.isFinite(W)||W<0)throw TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(V)||V<0)throw TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(N))throw TypeError("dx must be a number.");if(!Number.isFinite(A))throw TypeError("dy must be a number.");if(!Number.isFinite(R)||R<0)throw TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(z)||z<0)throw TypeError("dHeight must be a non-negative number.");if(this._closed)throw Error("VideoSample is closed.");({sx:q,sy:U,sWidth:W,sHeight:V}=this._rotateSourceRegion(q,U,W,V,this.rotation));let _=this.toCanvasImageSource();$.save();let L=N+R/2,M=A+z/2;$.translate(L,M),$.rotate(this.rotation*Math.PI/180);let B=this.rotation%180===0?1:R/z;$.scale(1/B,B),$.drawImage(_,q,U,W,V,-R/2,-z/2,R,z),$.restore()}drawWithFit($,J){if(!(typeof CanvasRenderingContext2D<"u"&&$ instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&$ instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(!["fill","contain","cover"].includes(J.fit))throw TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");if(J.crop!==void 0)b8(J.crop,"options.");let Y=$.canvas.width,j=$.canvas.height,X=J.rotation??this.rotation,[Z,G]=X%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];if(J.crop)v8(J.crop,Z,G);let K,Q,q,U,{sx:W,sy:V,sWidth:N,sHeight:A}=this._rotateSourceRegion(J.crop?.left??0,J.crop?.top??0,J.crop?.width??Z,J.crop?.height??G,X);if(J.fit==="fill")K=0,Q=0,q=Y,U=j;else{let[z,_]=J.crop?[J.crop.width,J.crop.height]:[Z,G],L=J.fit==="contain"?Math.min(Y/z,j/_):Math.max(Y/z,j/_);q=z*L,U=_*L,K=(Y-q)/2,Q=(j-U)/2}$.save();let R=X%180===0?1:q/U;$.translate(Y/2,j/2),$.rotate(X*Math.PI/180),$.scale(1/R,R),$.translate(-Y/2,-j/2),$.drawImage(this.toCanvasImageSource(),W,V,N,A,K,Q,q,U),$.restore()}_rotateSourceRegion($,J,Y,j,X){if(X===90)[$,J,Y,j]=[J,this.codedHeight-$-Y,j,Y];else if(X===180)[$,J]=[this.codedWidth-$-Y,this.codedHeight-J-j];else if(X===270)[$,J,Y,j]=[this.codedWidth-J-j,$,j,Y];return{sx:$,sy:J,sWidth:Y,sHeight:j}}toCanvasImageSource(){if(this._closed)throw Error("VideoSample is closed.");if(H(this._data!==null),this._data instanceof Uint8Array){let $=this.toVideoFrame();return queueMicrotask(()=>$.close()),$}return this._data}setRotation($){if(![0,90,180,270].includes($))throw TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=$}setTimestamp($){if(!Number.isFinite($))throw TypeError("newTimestamp must be a number.");this.timestamp=$}setDuration($){if(!Number.isFinite($)||$<0)throw TypeError("newDuration must be a non-negative number.");this.duration=$}[Symbol.dispose](){this.close()}}class T8{primaries;transfer;matrix;fullRange;constructor($){this.primaries=$?.primaries??null,this.transfer=$?.transfer??null,this.matrix=$?.matrix??null,this.fullRange=$?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}var f1=($)=>{return typeof VideoFrame<"u"&&$ instanceof VideoFrame},v8=($,J,Y)=>{$.left=Math.min($.left,J),$.top=Math.min($.top,Y),$.width=Math.min($.width,J-$.left),$.height=Math.min($.height,Y-$.top),H($.width>=0),H($.height>=0)},b8=($,J)=>{if(!$||typeof $!=="object")throw TypeError(J+"crop, when provided, must be an object.");if(!Number.isInteger($.left)||$.left<0)throw TypeError(J+"crop.left must be a non-negative integer.");if(!Number.isInteger($.top)||$.top<0)throw TypeError(J+"crop.top must be a non-negative integer.");if(!Number.isInteger($.width)||$.width<0)throw TypeError(J+"crop.width must be a non-negative integer.");if(!Number.isInteger($.height)||$.height<0)throw TypeError(J+"crop.height must be a non-negative integer.")},f7=($)=>{if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.colorSpace!==void 0&&!["display-p3","srgb"].includes($.colorSpace))throw TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if($.format!==void 0&&typeof $.format!=="string")throw TypeError("options.format, when provided, must be a string.");if($.layout!==void 0){if(!Array.isArray($.layout))throw TypeError("options.layout, when provided, must be an array.");for(let J of $.layout){if(!J||typeof J!=="object")throw TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(J.offset)||J.offset<0)throw TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(J.stride)||J.stride<0)throw TypeError("plane.stride must be a non-negative integer.")}}if($.rect!==void 0){if(!$.rect||typeof $.rect!=="object")throw TypeError("options.rect, when provided, must be an object.");if($.rect.x!==void 0&&(!Number.isInteger($.rect.x)||$.rect.x<0))throw TypeError("options.rect.x, when provided, must be a non-negative integer.");if($.rect.y!==void 0&&(!Number.isInteger($.rect.y)||$.rect.y<0))throw TypeError("options.rect.y, when provided, must be a non-negative integer.");if($.rect.width!==void 0&&(!Number.isInteger($.rect.width)||$.rect.width<0))throw TypeError("options.rect.width, when provided, must be a non-negative integer.");if($.rect.height!==void 0&&(!Number.isInteger($.rect.height)||$.rect.height<0))throw TypeError("options.rect.height, when provided, must be a non-negative integer.")}},g7=($,J,Y)=>{let j=k7($),X=[],Z=0;for(let G of j){let K=Math.ceil(J/G.widthDivisor),Q=Math.ceil(Y/G.heightDivisor),q=K*G.sampleBytes,U=q*Q;X.push({offset:Z,stride:q}),Z+=U}return X},k7=($)=>{let J=(Y,j,X,Z,G)=>{let K=[{sampleBytes:Y,widthDivisor:1,heightDivisor:1},{sampleBytes:j,widthDivisor:X,heightDivisor:Z},{sampleBytes:j,widthDivisor:X,heightDivisor:Z}];if(G)K.push({sampleBytes:Y,widthDivisor:1,heightDivisor:1});return K};switch($){case"I420":return J(1,1,2,2,!1);case"I420P10":case"I420P12":return J(2,2,2,2,!1);case"I420A":return J(1,1,2,2,!0);case"I420AP10":case"I420AP12":return J(2,2,2,2,!0);case"I422":return J(1,1,2,1,!1);case"I422P10":case"I422P12":return J(2,2,2,1,!1);case"I422A":return J(1,1,2,1,!0);case"I422AP10":case"I422AP12":return J(2,2,2,1,!0);case"I444":return J(1,1,1,1,!1);case"I444P10":case"I444P12":return J(2,2,1,1,!1);case"I444A":return J(1,1,1,1,!0);case"I444AP10":case"I444AP12":return J(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:i($),H(!1)}},a2=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class K0{_data;_closed=!1;format;sampleRate;numberOfFrames;numberOfChannels;duration;timestamp;get microsecondTimestamp(){return Math.trunc(c0*this.timestamp)}get microsecondDuration(){return Math.trunc(c0*this.duration)}constructor($){if(E8($)){if($.format===null)throw TypeError("AudioData with null format is not supported.");this._data=$,this.format=$.format,this.sampleRate=$.sampleRate,this.numberOfFrames=$.numberOfFrames,this.numberOfChannels=$.numberOfChannels,this.timestamp=$.timestamp/1e6,this.duration=$.numberOfFrames/$.sampleRate}else{if(!$||typeof $!=="object")throw TypeError("Invalid AudioDataInit: must be an object.");if(!a2.has($.format))throw TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite($.sampleRate)||$.sampleRate<=0)throw TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger($.numberOfChannels)||$.numberOfChannels===0)throw TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite($?.timestamp))throw TypeError("init.timestamp must be a number.");let J=$.data.byteLength/(D8($.format)*$.numberOfChannels);if(!Number.isInteger(J))throw TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=$.format,this.sampleRate=$.sampleRate,this.numberOfFrames=J,this.numberOfChannels=$.numberOfChannels,this.timestamp=$.timestamp,this.duration=J/$.sampleRate;let Y;if($.data instanceof ArrayBuffer)Y=new Uint8Array($.data);else if(ArrayBuffer.isView($.data))Y=new Uint8Array($.data.buffer,$.data.byteOffset,$.data.byteLength);else throw TypeError("Invalid AudioDataInit: data is not a BufferSource.");let j=this.numberOfFrames*this.numberOfChannels*D8(this.format);if(Y.byteLength<j)throw TypeError("Invalid AudioDataInit: insufficient data size.");this._data=Y}y8?.register(this,{type:"audio",data:this._data},this)}allocationSize($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if(!Number.isInteger($.planeIndex)||$.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if($.format!==void 0&&!a2.has($.format))throw TypeError("Invalid format.");if($.frameOffset!==void 0&&(!Number.isInteger($.frameOffset)||$.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if($.frameCount!==void 0&&(!Number.isInteger($.frameCount)||$.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let J=$.format??this.format,Y=$.frameOffset??0;if(Y>=this.numberOfFrames)throw RangeError("frameOffset out of range");let j=$.frameCount!==void 0?$.frameCount:this.numberOfFrames-Y;if(j>this.numberOfFrames-Y)throw RangeError("frameCount out of range");let X=D8(J),Z=f6(J);if(Z&&$.planeIndex>=this.numberOfChannels)throw RangeError("planeIndex out of range");if(!Z&&$.planeIndex!==0)throw RangeError("planeIndex out of range");return(Z?j:j*this.numberOfChannels)*X}copyTo($,J){if(!i1($))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(!Number.isInteger(J.planeIndex)||J.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if(J.format!==void 0&&!a2.has(J.format))throw TypeError("Invalid format.");if(J.frameOffset!==void 0&&(!Number.isInteger(J.frameOffset)||J.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if(J.frameCount!==void 0&&(!Number.isInteger(J.frameCount)||J.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let{planeIndex:Y,format:j,frameCount:X,frameOffset:Z}=J,G=j??this.format;if(!G)throw Error("Destination format not determined");let K=this.numberOfFrames,Q=this.numberOfChannels,q=Z??0;if(q>=K)throw RangeError("frameOffset out of range");let U=X!==void 0?X:K-q;if(U>K-q)throw RangeError("frameCount out of range");let W=D8(G),V=f6(G);if(V&&Y>=Q)throw RangeError("planeIndex out of range");if(!V&&Y!==0)throw RangeError("planeIndex out of range");let A=(V?U:U*Q)*W;if($.byteLength<A)throw RangeError("Destination buffer is too small");let R=h($),z=p7(G);if(E8(this._data))if(V)if(G==="f32-planar")this._data.copyTo($,{planeIndex:Y,frameOffset:q,frameCount:U,format:"f32-planar"});else{let _=new ArrayBuffer(U*4),L=new Float32Array(_);this._data.copyTo(L,{planeIndex:Y,frameOffset:q,frameCount:U,format:"f32-planar"});let M=new DataView(_);for(let B=0;B<U;B++){let F=B*W,C=M.getFloat32(B*4,!0);z(R,F,C)}}else{let _=Q,L=new Float32Array(U);for(let M=0;M<_;M++){this._data.copyTo(L,{planeIndex:M,frameOffset:q,frameCount:U,format:"f32-planar"});for(let B=0;B<U;B++){let C=(B*_+M)*W;z(R,C,L[B])}}}else{let _=this._data,L=h(_),M=this.format,B=u7(M),F=D8(M),C=f6(M);for(let w=0;w<U;w++)if(V){let v=w*W,k;if(C)k=(Y*K+(w+q))*F;else k=((w+q)*Q+Y)*F;let S=B(L,k);z(R,v,S)}else for(let v=0;v<Q;v++){let S=(w*Q+v)*W,T;if(C)T=(v*K+(w+q))*F;else T=((w+q)*Q+v)*F;let r=B(L,T);z(R,S,r)}}}clone(){if(this._closed)throw Error("AudioSample is closed.");if(E8(this._data)){let $=new K0(this._data.clone());return $.setTimestamp(this.timestamp),$}return new K0({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){if(this._closed)return;if(y8?.unregister(this),E8(this._data))this._data.close();else this._data=new Uint8Array(0);this._closed=!0}toAudioData(){if(this._closed)throw Error("AudioSample is closed.");if(E8(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(f6(this.format)){let J=this.allocationSize({planeIndex:0,format:this.format}),Y=new ArrayBuffer(J*this.numberOfChannels);for(let j=0;j<this.numberOfChannels;j++)this.copyTo(new Uint8Array(Y,j*J,J),{planeIndex:j,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:Y})}let $=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo($,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:$})}return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw Error("AudioSample is closed.");let $=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),J=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let Y=0;Y<this.numberOfChannels;Y++)this.copyTo(J,{planeIndex:Y,format:"f32-planar"}),$.copyToChannel(J,Y);return $}setTimestamp($){if(!Number.isFinite($))throw TypeError("newTimestamp must be a number.");this.timestamp=$}[Symbol.dispose](){this.close()}static*_fromAudioBuffer($,J){if(!($ instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let Y=240000,j=$.numberOfChannels,X=$.sampleRate,Z=$.length,G=Math.floor(Y/j),K=0,Q=Z;while(Q>0){let q=Math.min(G,Q),U=new Float32Array(j*q);for(let W=0;W<j;W++)$.copyFromChannel(U.subarray(W*q,(W+1)*q),W,K);yield new K0({format:"f32-planar",sampleRate:X,numberOfFrames:q,numberOfChannels:j,timestamp:J+K/X,data:U}),K+=q,Q-=q}}static fromAudioBuffer($,J){if(!($ instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let Y=240000,j=$.numberOfChannels,X=$.sampleRate,Z=$.length,G=Math.floor(Y/j),K=0,Q=Z,q=[];while(Q>0){let U=Math.min(G,Q),W=new Float32Array(j*U);for(let N=0;N<j;N++)$.copyFromChannel(W.subarray(N*U,(N+1)*U),N,K);let V=new K0({format:"f32-planar",sampleRate:X,numberOfFrames:U,numberOfChannels:j,timestamp:J+K/X,data:W});q.push(V),K+=U,Q-=U}return q}}var D8=($)=>{switch($){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw Error("Unknown AudioSampleFormat")}},f6=($)=>{switch($){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},u7=($)=>{switch($){case"u8":case"u8-planar":return(J,Y)=>(J.getUint8(Y)-128)/128;case"s16":case"s16-planar":return(J,Y)=>J.getInt16(Y,!0)/32768;case"s32":case"s32-planar":return(J,Y)=>J.getInt32(Y,!0)/2147483648;case"f32":case"f32-planar":return(J,Y)=>J.getFloat32(Y,!0)}},p7=($)=>{switch($){case"u8":case"u8-planar":return(J,Y,j)=>J.setUint8(Y,$0((j+1)*127.5,0,255));case"s16":case"s16-planar":return(J,Y,j)=>J.setInt16(Y,$0(Math.round(j*32767),-32768,32767),!0);case"s32":case"s32-planar":return(J,Y,j)=>J.setInt32(Y,$0(Math.round(j*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(J,Y,j)=>J.setFloat32(Y,j,!0)}},E8=($)=>{return typeof AudioData<"u"&&$ instanceof AudioData};/*!
117
+ */U6();var J5=-1/0,Y5=-1/0,y8=null;if(typeof FinalizationRegistry<"u")y8=new FinalizationRegistry(($)=>{let J=Date.now();if($.type==="video"){if(J-J5>=1000)console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),J5=J;if(typeof VideoFrame<"u"&&$.data instanceof VideoFrame)$.data.close()}else{if(J-Y5>=1000)console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Y5=J;if(typeof AudioData<"u"&&$.data instanceof AudioData)$.data.close()}});var t2=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],S7=new Set(t2);class J0{_data;_layout;_closed=!1;format;codedWidth;codedHeight;rotation;timestamp;duration;colorSpace;get displayWidth(){return this.rotation%180===0?this.codedWidth:this.codedHeight}get displayHeight(){return this.rotation%180===0?this.codedHeight:this.codedWidth}get microsecondTimestamp(){return Math.trunc(c0*this.timestamp)}get microsecondDuration(){return Math.trunc(c0*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor($,J){if($ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer||ArrayBuffer.isView($)){if(!J||typeof J!=="object")throw TypeError("init must be an object.");if(J.format===void 0||!S7.has(J.format))throw TypeError("init.format must be one of: "+t2.join(", "));if(!Number.isInteger(J.codedWidth)||J.codedWidth<=0)throw TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(J.codedHeight)||J.codedHeight<=0)throw TypeError("init.codedHeight must be a positive integer.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(J.timestamp))throw TypeError("init.timestamp must be a number.");if(J.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");this._data=l($).slice(),this._layout=J.layout??f7(J.format,J.codedWidth,J.codedHeight),this.format=J.format,this.codedWidth=J.codedWidth,this.codedHeight=J.codedHeight,this.rotation=J.rotation??0,this.timestamp=J.timestamp,this.duration=J.duration??0,this.colorSpace=new T8(J.colorSpace)}else if(typeof VideoFrame<"u"&&$ instanceof VideoFrame){if(J?.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(J?.timestamp!==void 0&&!Number.isFinite(J?.timestamp))throw TypeError("init.timestamp, when provided, must be a number.");if(J?.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");this._data=$,this._layout=null,this.format=$.format,this.codedWidth=$.displayWidth,this.codedHeight=$.displayHeight,this.rotation=J?.rotation??0,this.timestamp=J?.timestamp??$.timestamp/1e6,this.duration=J?.duration??($.duration??0)/1e6,this.colorSpace=new T8($.colorSpace)}else if(typeof HTMLImageElement<"u"&&$ instanceof HTMLImageElement||typeof SVGImageElement<"u"&&$ instanceof SVGImageElement||typeof ImageBitmap<"u"&&$ instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&$ instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&$ instanceof OffscreenCanvas){if(!J||typeof J!=="object")throw TypeError("init must be an object.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(J.timestamp))throw TypeError("init.timestamp must be a number.");if(J.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new J0(new VideoFrame($,{timestamp:Math.trunc(J.timestamp*c0),duration:Math.trunc((J.duration??0)*c0)||void 0}),J);let Y=0,j=0;if("naturalWidth"in $)Y=$.naturalWidth,j=$.naturalHeight;else if("videoWidth"in $)Y=$.videoWidth,j=$.videoHeight;else if("width"in $)Y=Number($.width),j=Number($.height);if(!Y||!j)throw TypeError("Could not determine dimensions.");let X=new OffscreenCanvas(Y,j),Z=X.getContext("2d",{alpha:n0(),willReadFrequently:!0});H(Z),Z.drawImage($,0,0),this._data=X,this._layout=null,this.format="RGBX",this.codedWidth=Y,this.codedHeight=j,this.rotation=J.rotation??0,this.timestamp=J.timestamp,this.duration=J.duration??0,this.colorSpace=new T8({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");y8?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw Error("VideoSample is closed.");if(H(this._data!==null),f1(this._data))return new J0(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation});if(this._data instanceof Uint8Array)return H(this._layout),new J0(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});return new J0(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){if(this._closed)return;if(y8?.unregister(this),f1(this._data))this._data.close();else this._data=null;this._closed=!0}allocationSize($={}){if(h7($),this._closed)throw Error("VideoSample is closed.");if(($.format??this.format)===null)throw Error("Cannot get allocation size when format is null. Please manually provide an RGB pixel format in the options instead.");if(H(this._data!==null),!f1(this._data)){if($.colorSpace||$.format&&$.format!==this.format||$.layout||$.rect){let J=this.toVideoFrame(),Y=J.allocationSize($);return J.close(),Y}}if(f1(this._data))return this._data.allocationSize($);if(this._data instanceof Uint8Array)return this._data.byteLength;return this.codedWidth*this.codedHeight*4}async copyTo($,J={}){if(!i1($))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(this._closed)throw Error("VideoSample is closed.");if((J.format??this.format)===null)throw Error("Cannot copy video sample data when format is null. Please manually provide an RGB pixel format in the options instead.");if(H(this._data!==null),!f1(this._data)){if(J.colorSpace||J.format&&J.format!==this.format||J.layout||J.rect){let Y=this.toVideoFrame(),j=await Y.copyTo($,J);return Y.close(),j}}if(f1(this._data))return this._data.copyTo($,J);else if(this._data instanceof Uint8Array)return H(this._layout),l($).set(this._data),this._layout;else{let j=this._data.getContext("2d");H(j);let X=j.getImageData(0,0,this.codedWidth,this.codedHeight);return l($).set(X.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw Error("VideoSample is closed.");if(H(this._data!==null),f1(this._data))return new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0});if(this._data instanceof Uint8Array)return new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace});return new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw($,J,Y,j,X,Z,G,K,Q){let q=0,U=0,W=this.displayWidth,V=this.displayHeight,N=0,A=0,R=this.displayWidth,z=this.displayHeight;if(Z!==void 0)if(q=J,U=Y,W=j,V=X,N=Z,A=G,K!==void 0)R=K,z=Q;else R=W,z=V;else if(N=J,A=Y,j!==void 0)R=j,z=X;if(!(typeof CanvasRenderingContext2D<"u"&&$ instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&$ instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(q))throw TypeError("sx must be a number.");if(!Number.isFinite(U))throw TypeError("sy must be a number.");if(!Number.isFinite(W)||W<0)throw TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(V)||V<0)throw TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(N))throw TypeError("dx must be a number.");if(!Number.isFinite(A))throw TypeError("dy must be a number.");if(!Number.isFinite(R)||R<0)throw TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(z)||z<0)throw TypeError("dHeight must be a non-negative number.");if(this._closed)throw Error("VideoSample is closed.");({sx:q,sy:U,sWidth:W,sHeight:V}=this._rotateSourceRegion(q,U,W,V,this.rotation));let _=this.toCanvasImageSource();$.save();let L=N+R/2,M=A+z/2;$.translate(L,M),$.rotate(this.rotation*Math.PI/180);let B=this.rotation%180===0?1:R/z;$.scale(1/B,B),$.drawImage(_,q,U,W,V,-R/2,-z/2,R,z),$.restore()}drawWithFit($,J){if(!(typeof CanvasRenderingContext2D<"u"&&$ instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&$ instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(!["fill","contain","cover"].includes(J.fit))throw TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");if(J.crop!==void 0)b8(J.crop,"options.");let Y=$.canvas.width,j=$.canvas.height,X=J.rotation??this.rotation,[Z,G]=X%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];if(J.crop)v8(J.crop,Z,G);let K,Q,q,U,{sx:W,sy:V,sWidth:N,sHeight:A}=this._rotateSourceRegion(J.crop?.left??0,J.crop?.top??0,J.crop?.width??Z,J.crop?.height??G,X);if(J.fit==="fill")K=0,Q=0,q=Y,U=j;else{let[z,_]=J.crop?[J.crop.width,J.crop.height]:[Z,G],L=J.fit==="contain"?Math.min(Y/z,j/_):Math.max(Y/z,j/_);q=z*L,U=_*L,K=(Y-q)/2,Q=(j-U)/2}$.save();let R=X%180===0?1:q/U;$.translate(Y/2,j/2),$.rotate(X*Math.PI/180),$.scale(1/R,R),$.translate(-Y/2,-j/2),$.drawImage(this.toCanvasImageSource(),W,V,N,A,K,Q,q,U),$.restore()}_rotateSourceRegion($,J,Y,j,X){if(X===90)[$,J,Y,j]=[J,this.codedHeight-$-Y,j,Y];else if(X===180)[$,J]=[this.codedWidth-$-Y,this.codedHeight-J-j];else if(X===270)[$,J,Y,j]=[this.codedWidth-J-j,$,j,Y];return{sx:$,sy:J,sWidth:Y,sHeight:j}}toCanvasImageSource(){if(this._closed)throw Error("VideoSample is closed.");if(H(this._data!==null),this._data instanceof Uint8Array){let $=this.toVideoFrame();return queueMicrotask(()=>$.close()),$}return this._data}setRotation($){if(![0,90,180,270].includes($))throw TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=$}setTimestamp($){if(!Number.isFinite($))throw TypeError("newTimestamp must be a number.");this.timestamp=$}setDuration($){if(!Number.isFinite($)||$<0)throw TypeError("newDuration must be a non-negative number.");this.duration=$}[Symbol.dispose](){this.close()}}class T8{primaries;transfer;matrix;fullRange;constructor($){this.primaries=$?.primaries??null,this.transfer=$?.transfer??null,this.matrix=$?.matrix??null,this.fullRange=$?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}var f1=($)=>{return typeof VideoFrame<"u"&&$ instanceof VideoFrame},v8=($,J,Y)=>{$.left=Math.min($.left,J),$.top=Math.min($.top,Y),$.width=Math.min($.width,J-$.left),$.height=Math.min($.height,Y-$.top),H($.width>=0),H($.height>=0)},b8=($,J)=>{if(!$||typeof $!=="object")throw TypeError(J+"crop, when provided, must be an object.");if(!Number.isInteger($.left)||$.left<0)throw TypeError(J+"crop.left must be a non-negative integer.");if(!Number.isInteger($.top)||$.top<0)throw TypeError(J+"crop.top must be a non-negative integer.");if(!Number.isInteger($.width)||$.width<0)throw TypeError(J+"crop.width must be a non-negative integer.");if(!Number.isInteger($.height)||$.height<0)throw TypeError(J+"crop.height must be a non-negative integer.")},h7=($)=>{if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.colorSpace!==void 0&&!["display-p3","srgb"].includes($.colorSpace))throw TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if($.format!==void 0&&typeof $.format!=="string")throw TypeError("options.format, when provided, must be a string.");if($.layout!==void 0){if(!Array.isArray($.layout))throw TypeError("options.layout, when provided, must be an array.");for(let J of $.layout){if(!J||typeof J!=="object")throw TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(J.offset)||J.offset<0)throw TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(J.stride)||J.stride<0)throw TypeError("plane.stride must be a non-negative integer.")}}if($.rect!==void 0){if(!$.rect||typeof $.rect!=="object")throw TypeError("options.rect, when provided, must be an object.");if($.rect.x!==void 0&&(!Number.isInteger($.rect.x)||$.rect.x<0))throw TypeError("options.rect.x, when provided, must be a non-negative integer.");if($.rect.y!==void 0&&(!Number.isInteger($.rect.y)||$.rect.y<0))throw TypeError("options.rect.y, when provided, must be a non-negative integer.");if($.rect.width!==void 0&&(!Number.isInteger($.rect.width)||$.rect.width<0))throw TypeError("options.rect.width, when provided, must be a non-negative integer.");if($.rect.height!==void 0&&(!Number.isInteger($.rect.height)||$.rect.height<0))throw TypeError("options.rect.height, when provided, must be a non-negative integer.")}},f7=($,J,Y)=>{let j=g7($),X=[],Z=0;for(let G of j){let K=Math.ceil(J/G.widthDivisor),Q=Math.ceil(Y/G.heightDivisor),q=K*G.sampleBytes,U=q*Q;X.push({offset:Z,stride:q}),Z+=U}return X},g7=($)=>{let J=(Y,j,X,Z,G)=>{let K=[{sampleBytes:Y,widthDivisor:1,heightDivisor:1},{sampleBytes:j,widthDivisor:X,heightDivisor:Z},{sampleBytes:j,widthDivisor:X,heightDivisor:Z}];if(G)K.push({sampleBytes:Y,widthDivisor:1,heightDivisor:1});return K};switch($){case"I420":return J(1,1,2,2,!1);case"I420P10":case"I420P12":return J(2,2,2,2,!1);case"I420A":return J(1,1,2,2,!0);case"I420AP10":case"I420AP12":return J(2,2,2,2,!0);case"I422":return J(1,1,2,1,!1);case"I422P10":case"I422P12":return J(2,2,2,1,!1);case"I422A":return J(1,1,2,1,!0);case"I422AP10":case"I422AP12":return J(2,2,2,1,!0);case"I444":return J(1,1,1,1,!1);case"I444P10":case"I444P12":return J(2,2,1,1,!1);case"I444A":return J(1,1,1,1,!0);case"I444AP10":case"I444AP12":return J(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:i($),H(!1)}},a2=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class K0{_data;_closed=!1;format;sampleRate;numberOfFrames;numberOfChannels;duration;timestamp;get microsecondTimestamp(){return Math.trunc(c0*this.timestamp)}get microsecondDuration(){return Math.trunc(c0*this.duration)}constructor($){if(E8($)){if($.format===null)throw TypeError("AudioData with null format is not supported.");this._data=$,this.format=$.format,this.sampleRate=$.sampleRate,this.numberOfFrames=$.numberOfFrames,this.numberOfChannels=$.numberOfChannels,this.timestamp=$.timestamp/1e6,this.duration=$.numberOfFrames/$.sampleRate}else{if(!$||typeof $!=="object")throw TypeError("Invalid AudioDataInit: must be an object.");if(!a2.has($.format))throw TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite($.sampleRate)||$.sampleRate<=0)throw TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger($.numberOfChannels)||$.numberOfChannels===0)throw TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite($?.timestamp))throw TypeError("init.timestamp must be a number.");let J=$.data.byteLength/(D8($.format)*$.numberOfChannels);if(!Number.isInteger(J))throw TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=$.format,this.sampleRate=$.sampleRate,this.numberOfFrames=J,this.numberOfChannels=$.numberOfChannels,this.timestamp=$.timestamp,this.duration=J/$.sampleRate;let Y;if($.data instanceof ArrayBuffer)Y=new Uint8Array($.data);else if(ArrayBuffer.isView($.data))Y=new Uint8Array($.data.buffer,$.data.byteOffset,$.data.byteLength);else throw TypeError("Invalid AudioDataInit: data is not a BufferSource.");let j=this.numberOfFrames*this.numberOfChannels*D8(this.format);if(Y.byteLength<j)throw TypeError("Invalid AudioDataInit: insufficient data size.");this._data=Y}y8?.register(this,{type:"audio",data:this._data},this)}allocationSize($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if(!Number.isInteger($.planeIndex)||$.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if($.format!==void 0&&!a2.has($.format))throw TypeError("Invalid format.");if($.frameOffset!==void 0&&(!Number.isInteger($.frameOffset)||$.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if($.frameCount!==void 0&&(!Number.isInteger($.frameCount)||$.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let J=$.format??this.format,Y=$.frameOffset??0;if(Y>=this.numberOfFrames)throw RangeError("frameOffset out of range");let j=$.frameCount!==void 0?$.frameCount:this.numberOfFrames-Y;if(j>this.numberOfFrames-Y)throw RangeError("frameCount out of range");let X=D8(J),Z=f6(J);if(Z&&$.planeIndex>=this.numberOfChannels)throw RangeError("planeIndex out of range");if(!Z&&$.planeIndex!==0)throw RangeError("planeIndex out of range");return(Z?j:j*this.numberOfChannels)*X}copyTo($,J){if(!i1($))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(!Number.isInteger(J.planeIndex)||J.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if(J.format!==void 0&&!a2.has(J.format))throw TypeError("Invalid format.");if(J.frameOffset!==void 0&&(!Number.isInteger(J.frameOffset)||J.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if(J.frameCount!==void 0&&(!Number.isInteger(J.frameCount)||J.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let{planeIndex:Y,format:j,frameCount:X,frameOffset:Z}=J,G=j??this.format;if(!G)throw Error("Destination format not determined");let K=this.numberOfFrames,Q=this.numberOfChannels,q=Z??0;if(q>=K)throw RangeError("frameOffset out of range");let U=X!==void 0?X:K-q;if(U>K-q)throw RangeError("frameCount out of range");let W=D8(G),V=f6(G);if(V&&Y>=Q)throw RangeError("planeIndex out of range");if(!V&&Y!==0)throw RangeError("planeIndex out of range");let A=(V?U:U*Q)*W;if($.byteLength<A)throw RangeError("Destination buffer is too small");let R=h($),z=u7(G);if(E8(this._data))if(V)if(G==="f32-planar")this._data.copyTo($,{planeIndex:Y,frameOffset:q,frameCount:U,format:"f32-planar"});else{let _=new ArrayBuffer(U*4),L=new Float32Array(_);this._data.copyTo(L,{planeIndex:Y,frameOffset:q,frameCount:U,format:"f32-planar"});let M=new DataView(_);for(let B=0;B<U;B++){let F=B*W,C=M.getFloat32(B*4,!0);z(R,F,C)}}else{let _=Q,L=new Float32Array(U);for(let M=0;M<_;M++){this._data.copyTo(L,{planeIndex:M,frameOffset:q,frameCount:U,format:"f32-planar"});for(let B=0;B<U;B++){let C=(B*_+M)*W;z(R,C,L[B])}}}else{let _=this._data,L=h(_),M=this.format,B=k7(M),F=D8(M),C=f6(M);for(let w=0;w<U;w++)if(V){let v=w*W,k;if(C)k=(Y*K+(w+q))*F;else k=((w+q)*Q+Y)*F;let S=B(L,k);z(R,v,S)}else for(let v=0;v<Q;v++){let S=(w*Q+v)*W,T;if(C)T=(v*K+(w+q))*F;else T=((w+q)*Q+v)*F;let r=B(L,T);z(R,S,r)}}}clone(){if(this._closed)throw Error("AudioSample is closed.");if(E8(this._data)){let $=new K0(this._data.clone());return $.setTimestamp(this.timestamp),$}return new K0({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){if(this._closed)return;if(y8?.unregister(this),E8(this._data))this._data.close();else this._data=new Uint8Array(0);this._closed=!0}toAudioData(){if(this._closed)throw Error("AudioSample is closed.");if(E8(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(f6(this.format)){let J=this.allocationSize({planeIndex:0,format:this.format}),Y=new ArrayBuffer(J*this.numberOfChannels);for(let j=0;j<this.numberOfChannels;j++)this.copyTo(new Uint8Array(Y,j*J,J),{planeIndex:j,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:Y})}let $=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo($,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:$})}return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw Error("AudioSample is closed.");let $=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),J=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let Y=0;Y<this.numberOfChannels;Y++)this.copyTo(J,{planeIndex:Y,format:"f32-planar"}),$.copyToChannel(J,Y);return $}setTimestamp($){if(!Number.isFinite($))throw TypeError("newTimestamp must be a number.");this.timestamp=$}[Symbol.dispose](){this.close()}static*_fromAudioBuffer($,J){if(!($ instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let Y=240000,j=$.numberOfChannels,X=$.sampleRate,Z=$.length,G=Math.floor(Y/j),K=0,Q=Z;while(Q>0){let q=Math.min(G,Q),U=new Float32Array(j*q);for(let W=0;W<j;W++)$.copyFromChannel(U.subarray(W*q,(W+1)*q),W,K);yield new K0({format:"f32-planar",sampleRate:X,numberOfFrames:q,numberOfChannels:j,timestamp:J+K/X,data:U}),K+=q,Q-=q}}static fromAudioBuffer($,J){if(!($ instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let Y=240000,j=$.numberOfChannels,X=$.sampleRate,Z=$.length,G=Math.floor(Y/j),K=0,Q=Z,q=[];while(Q>0){let U=Math.min(G,Q),W=new Float32Array(j*U);for(let N=0;N<j;N++)$.copyFromChannel(W.subarray(N*U,(N+1)*U),N,K);let V=new K0({format:"f32-planar",sampleRate:X,numberOfFrames:U,numberOfChannels:j,timestamp:J+K/X,data:W});q.push(V),K+=U,Q-=U}return q}}var D8=($)=>{switch($){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw Error("Unknown AudioSampleFormat")}},f6=($)=>{switch($){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},k7=($)=>{switch($){case"u8":case"u8-planar":return(J,Y)=>(J.getUint8(Y)-128)/128;case"s16":case"s16-planar":return(J,Y)=>J.getInt16(Y,!0)/32768;case"s32":case"s32-planar":return(J,Y)=>J.getInt32(Y,!0)/2147483648;case"f32":case"f32-planar":return(J,Y)=>J.getFloat32(Y,!0)}},u7=($)=>{switch($){case"u8":case"u8-planar":return(J,Y,j)=>J.setUint8(Y,$0((j+1)*127.5,0,255));case"s16":case"s16-planar":return(J,Y,j)=>J.setInt16(Y,$0(Math.round(j*32767),-32768,32767),!0);case"s32":case"s32-planar":return(J,Y,j)=>J.setInt32(Y,$0(Math.round(j*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(J,Y,j)=>J.setFloat32(Y,j,!0)}},E8=($)=>{return typeof AudioData<"u"&&$ instanceof AudioData};/*!
118
118
  * Copyright (c) 2025-present, Vanilagy and contributors
119
119
  *
120
120
  * This Source Code Form is subject to the terms of the Mozilla Public
@@ -160,7 +160,7 @@ ${K.join(`
160
160
  * This Source Code Form is subject to the terms of the Mozilla Public
161
161
  * License, v. 2.0. If a copy of the MPL was not distributed with this
162
162
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
163
- */class j${source;fileSize;constructor($){this.source=$}requestSlice($,J){if(this.source._disposed)throw new q0;if(this.fileSize!==null&&$+J>this.fileSize)return null;let Y=$+J,j=this.source._read($,Y);if(j instanceof Promise)return j.then((X)=>{if(!X)return null;return new S0(X.bytes,X.view,X.offset,$,Y)});if(!j)return null;return new S0(j.bytes,j.view,j.offset,$,Y)}requestSliceRange($,J,Y){if(this.source._disposed)throw new q0;if(this.fileSize!==null)return this.requestSlice($,$0(this.fileSize-$,J,Y));let j=this.requestSlice($,Y),X=(Z)=>{if(Z)return Z;let G=(Q)=>{return H(Q!==null),this.requestSlice($,$0(Q-$,J,Y))},K=this.source._retrieveSize();if(K instanceof Promise)return K.then(G);return G(K)};if(j instanceof Promise)return j.then(X);return X(j)}}class S0{bytes;view;offset;start;end;bufferPos;constructor($,J,Y,j,X){this.bytes=$;this.view=J;this.offset=Y;this.start=j;this.end=X;this.bufferPos=j-Y}static tempFromBytes($){return new S0($,h($),0,0,$.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos($){this.bufferPos=$-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip($){this.bufferPos+=$}slice($,J=this.end-$){if($<this.start||$+J>this.end)throw RangeError("Slicing outside of original slice.");return new S0(this.bytes,this.view,this.offset,$,$+J)}}var M0=($,J)=>{if($.filePos<$.start||$.filePos+J>$.end)throw RangeError(`Tried reading [${$.filePos}, ${$.filePos+J}), but slice is [${$.start}, ${$.end}). This is likely an internal error, please report it alongside the file that caused it.`)},D=($,J)=>{M0($,J);let Y=$.bytes.subarray($.bufferPos,$.bufferPos+J);return $.bufferPos+=J,Y},y=($)=>{return M0($,1),$.view.getUint8($.bufferPos++)},G8=($,J)=>{M0($,2);let Y=$.view.getUint16($.bufferPos,J);return $.bufferPos+=2,Y},X0=($)=>{M0($,2);let J=$.view.getUint16($.bufferPos,!1);return $.bufferPos+=2,J},_1=($)=>{M0($,3);let J=T1($.view,$.bufferPos,!1);return $.bufferPos+=3,J},f8=($)=>{M0($,2);let J=$.view.getInt16($.bufferPos,!1);return $.bufferPos+=2,J},Q1=($,J)=>{M0($,4);let Y=$.view.getUint32($.bufferPos,J);return $.bufferPos+=4,Y},P=($)=>{M0($,4);let J=$.view.getUint32($.bufferPos,!1);return $.bufferPos+=4,J},h0=($)=>{M0($,4);let J=$.view.getUint32($.bufferPos,!0);return $.bufferPos+=4,J},q1=($)=>{M0($,4);let J=$.view.getInt32($.bufferPos,!1);return $.bufferPos+=4,J},o7=($)=>{M0($,4);let J=$.view.getInt32($.bufferPos,!0);return $.bufferPos+=4,J},X$=($,J)=>{let Y,j;if(J)Y=Q1($,!0),j=Q1($,!0);else j=Q1($,!1),Y=Q1($,!1);return j*4294967296+Y},O0=($)=>{let J=P($),Y=P($);return J*4294967296+Y},W5=($)=>{let J=q1($),Y=P($);return J*4294967296+Y},V5=($)=>{let J=h0($);return o7($)*4294967296+J},H5=($)=>{M0($,4);let J=$.view.getFloat32($.bufferPos,!1);return $.bufferPos+=4,J},i6=($)=>{M0($,8);let J=$.view.getFloat64($.bufferPos,!1);return $.bufferPos+=8,J},s=($,J)=>{M0($,J);let Y="";for(let j=0;j<J;j++)Y+=String.fromCharCode($.bytes[$.bufferPos++]);return Y};/*!
163
+ */class j${source;fileSize;constructor($){this.source=$}requestSlice($,J){if(this.source._disposed)throw new q0;if(this.fileSize!==null&&$+J>this.fileSize)return null;let Y=$+J,j=this.source._read($,Y);if(j instanceof Promise)return j.then((X)=>{if(!X)return null;return new S0(X.bytes,X.view,X.offset,$,Y)});if(!j)return null;return new S0(j.bytes,j.view,j.offset,$,Y)}requestSliceRange($,J,Y){if(this.source._disposed)throw new q0;if(this.fileSize!==null)return this.requestSlice($,$0(this.fileSize-$,J,Y));let j=this.requestSlice($,Y),X=(Z)=>{if(Z)return Z;let G=(Q)=>{return H(Q!==null),this.requestSlice($,$0(Q-$,J,Y))},K=this.source._retrieveSize();if(K instanceof Promise)return K.then(G);return G(K)};if(j instanceof Promise)return j.then(X);return X(j)}}class S0{bytes;view;offset;start;end;bufferPos;constructor($,J,Y,j,X){this.bytes=$;this.view=J;this.offset=Y;this.start=j;this.end=X;this.bufferPos=j-Y}static tempFromBytes($){return new S0($,h($),0,0,$.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos($){this.bufferPos=$-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip($){this.bufferPos+=$}slice($,J=this.end-$){if($<this.start||$+J>this.end)throw RangeError("Slicing outside of original slice.");return new S0(this.bytes,this.view,this.offset,$,$+J)}}var M0=($,J)=>{if($.filePos<$.start||$.filePos+J>$.end)throw RangeError(`Tried reading [${$.filePos}, ${$.filePos+J}), but slice is [${$.start}, ${$.end}). This is likely an internal error, please report it alongside the file that caused it.`)},D=($,J)=>{M0($,J);let Y=$.bytes.subarray($.bufferPos,$.bufferPos+J);return $.bufferPos+=J,Y},y=($)=>{return M0($,1),$.view.getUint8($.bufferPos++)},G8=($,J)=>{M0($,2);let Y=$.view.getUint16($.bufferPos,J);return $.bufferPos+=2,Y},X0=($)=>{M0($,2);let J=$.view.getUint16($.bufferPos,!1);return $.bufferPos+=2,J},_1=($)=>{M0($,3);let J=T1($.view,$.bufferPos,!1);return $.bufferPos+=3,J},f8=($)=>{M0($,2);let J=$.view.getInt16($.bufferPos,!1);return $.bufferPos+=2,J},Q1=($,J)=>{M0($,4);let Y=$.view.getUint32($.bufferPos,J);return $.bufferPos+=4,Y},P=($)=>{M0($,4);let J=$.view.getUint32($.bufferPos,!1);return $.bufferPos+=4,J},h0=($)=>{M0($,4);let J=$.view.getUint32($.bufferPos,!0);return $.bufferPos+=4,J},q1=($)=>{M0($,4);let J=$.view.getInt32($.bufferPos,!1);return $.bufferPos+=4,J},n7=($)=>{M0($,4);let J=$.view.getInt32($.bufferPos,!0);return $.bufferPos+=4,J},X$=($,J)=>{let Y,j;if(J)Y=Q1($,!0),j=Q1($,!0);else j=Q1($,!1),Y=Q1($,!1);return j*4294967296+Y},O0=($)=>{let J=P($),Y=P($);return J*4294967296+Y},W5=($)=>{let J=q1($),Y=P($);return J*4294967296+Y},V5=($)=>{let J=h0($);return n7($)*4294967296+J},H5=($)=>{M0($,4);let J=$.view.getFloat32($.bufferPos,!1);return $.bufferPos+=4,J},i6=($)=>{M0($,8);let J=$.view.getFloat64($.bufferPos,!1);return $.bufferPos+=8,J},s=($,J)=>{M0($,J);let Y="";for(let j=0;j<J;j++)Y+=String.fromCharCode($.bytes[$.bufferPos++]);return Y};/*!
164
164
  * Copyright (c) 2025-present, Vanilagy and contributors
165
165
  *
166
166
  * This Source Code Form is subject to the terms of the Mozilla Public
@@ -178,7 +178,7 @@ ${K.join(`
178
178
  * This Source Code Form is subject to the terms of the Mozilla Public
179
179
  * License, v. 2.0. If a copy of the MPL was not distributed with this
180
180
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
181
- */var L1=16;var A5={H264:"avc",h264:"avc",AVC1:"avc",avc1:"avc",H265:"hevc",h265:"hevc",HEVC:"hevc",hevc:"hevc",hev1:"hevc",hvc1:"hevc",VP80:"vp8","VP8 ":"vp8",VP90:"vp9","VP9 ":"vp9",AV01:"av1",av01:"av1",XVID:"mpeg4",xvid:"mpeg4",DIVX:"mpeg4",DX50:"mpeg4",FMP4:"mpeg4",MP4V:"mpeg4"},R5={1:"pcm-s16",3:"pcm-f32",6:"alaw",7:"ulaw",85:"mp3",146:"ac3",255:"aac",8192:"aac",22127:"vorbis",26447:"vorbis",61868:"flac"};function k8($){return A5[$]||null}function K$($){return R5[$]||null}var r7={avc:"H264",hevc:"H265",vp8:"VP80",vp9:"VP90",av1:"AV01",mpeg4:"XVID"};function z5($){let J=r7[$];if(J)return J;for(let[Y,j]of Object.entries(A5))if(j===$)return Y;return null}function _5($){for(let[J,Y]of Object.entries(R5))if(Y===$)return Number(J);return null}function L5($){return{microSecPerFrame:$.getUint32(0,!0),maxBytesPerSec:$.getUint32(4,!0),paddingGranularity:$.getUint32(8,!0),flags:$.getUint32(12,!0),totalFrames:$.getUint32(16,!0),initialFrames:$.getUint32(20,!0),streams:$.getUint32(24,!0),suggestedBufferSize:$.getUint32(28,!0),width:$.getUint32(32,!0),height:$.getUint32(36,!0)}}function M5($){let J=new TextDecoder("latin1");return{fccType:J.decode(new Uint8Array($.buffer,$.byteOffset,4)),fccHandler:J.decode(new Uint8Array($.buffer,$.byteOffset+4,4)),flags:$.getUint32(8,!0),priority:$.getUint16(12,!0),language:$.getUint16(14,!0),initialFrames:$.getUint32(16,!0),scale:$.getUint32(20,!0),rate:$.getUint32(24,!0),start:$.getUint32(28,!0),length:$.getUint32(32,!0),suggestedBufferSize:$.getUint32(36,!0),quality:$.getUint32(40,!0),sampleSize:$.getUint32(44,!0),frame:{left:$.getUint16(48,!0),top:$.getUint16(50,!0),right:$.getUint16(52,!0),bottom:$.getUint16(54,!0)}}}function F5($){let J=new TextDecoder("latin1");return{size:$.getUint32(0,!0),width:$.getInt32(4,!0),height:$.getInt32(8,!0),planes:$.getUint16(12,!0),bitCount:$.getUint16(14,!0),compression:J.decode(new Uint8Array($.buffer,$.byteOffset+16,4)),sizeImage:$.getUint32(20,!0),xPelsPerMeter:$.getInt32(24,!0),yPelsPerMeter:$.getInt32(28,!0),clrUsed:$.getUint32(32,!0),clrImportant:$.getUint32(36,!0)}}function B5($){let J=$.getUint16(0,!0),Y=$.getUint16(2,!0),j=$.getUint32(4,!0),X=$.getUint32(8,!0),Z=$.getUint16(12,!0),G=$.getUint16(14,!0),K=0,Q;if($.byteLength>=18){if(K=$.getUint16(16,!0),K>0&&$.byteLength>=18+K)Q=new Uint8Array($.buffer,$.byteOffset+18,K)}return{formatTag:J,channels:Y,samplesPerSec:j,avgBytesPerSec:X,blockAlign:Z,bitsPerSample:G,cbSize:K,extraData:Q}}function w5($,J){return{ckid:new TextDecoder("latin1").decode(new Uint8Array($.buffer,$.byteOffset+J,4)),flags:$.getUint32(J+4,!0),offset:$.getUint32(J+8,!0),size:$.getUint32(J+12,!0)}}function Q$($,J){return $.toString().padStart(2,"0")+J}function O5($){if($.length!==4)return null;let J=$.substring(0,2),Y=$.substring(2),j=Number.parseInt(J,10);if(isNaN(j))return null;return{streamNumber:j,type:Y}}/*!
181
+ */var L1=16;var A5={H264:"avc",h264:"avc",AVC1:"avc",avc1:"avc",H265:"hevc",h265:"hevc",HEVC:"hevc",hevc:"hevc",hev1:"hevc",hvc1:"hevc",VP80:"vp8","VP8 ":"vp8",VP90:"vp9","VP9 ":"vp9",AV01:"av1",av01:"av1",XVID:"mpeg4",xvid:"mpeg4",DIVX:"mpeg4",DX50:"mpeg4",FMP4:"mpeg4",MP4V:"mpeg4"},R5={1:"pcm-s16",3:"pcm-f32",6:"alaw",7:"ulaw",85:"mp3",146:"ac3",255:"aac",8192:"aac",22127:"vorbis",26447:"vorbis",61868:"flac"};function k8($){return A5[$]||null}function K$($){return R5[$]||null}var o7={avc:"H264",hevc:"H265",vp8:"VP80",vp9:"VP90",av1:"AV01",mpeg4:"XVID"};function z5($){let J=o7[$];if(J)return J;for(let[Y,j]of Object.entries(A5))if(j===$)return Y;return null}function _5($){for(let[J,Y]of Object.entries(R5))if(Y===$)return Number(J);return null}function L5($){return{microSecPerFrame:$.getUint32(0,!0),maxBytesPerSec:$.getUint32(4,!0),paddingGranularity:$.getUint32(8,!0),flags:$.getUint32(12,!0),totalFrames:$.getUint32(16,!0),initialFrames:$.getUint32(20,!0),streams:$.getUint32(24,!0),suggestedBufferSize:$.getUint32(28,!0),width:$.getUint32(32,!0),height:$.getUint32(36,!0)}}function M5($){let J=new TextDecoder("latin1");return{fccType:J.decode(new Uint8Array($.buffer,$.byteOffset,4)),fccHandler:J.decode(new Uint8Array($.buffer,$.byteOffset+4,4)),flags:$.getUint32(8,!0),priority:$.getUint16(12,!0),language:$.getUint16(14,!0),initialFrames:$.getUint32(16,!0),scale:$.getUint32(20,!0),rate:$.getUint32(24,!0),start:$.getUint32(28,!0),length:$.getUint32(32,!0),suggestedBufferSize:$.getUint32(36,!0),quality:$.getUint32(40,!0),sampleSize:$.getUint32(44,!0),frame:{left:$.getUint16(48,!0),top:$.getUint16(50,!0),right:$.getUint16(52,!0),bottom:$.getUint16(54,!0)}}}function F5($){let J=new TextDecoder("latin1");return{size:$.getUint32(0,!0),width:$.getInt32(4,!0),height:$.getInt32(8,!0),planes:$.getUint16(12,!0),bitCount:$.getUint16(14,!0),compression:J.decode(new Uint8Array($.buffer,$.byteOffset+16,4)),sizeImage:$.getUint32(20,!0),xPelsPerMeter:$.getInt32(24,!0),yPelsPerMeter:$.getInt32(28,!0),clrUsed:$.getUint32(32,!0),clrImportant:$.getUint32(36,!0)}}function B5($){let J=$.getUint16(0,!0),Y=$.getUint16(2,!0),j=$.getUint32(4,!0),X=$.getUint32(8,!0),Z=$.getUint16(12,!0),G=$.getUint16(14,!0),K=0,Q;if($.byteLength>=18){if(K=$.getUint16(16,!0),K>0&&$.byteLength>=18+K)Q=new Uint8Array($.buffer,$.byteOffset+18,K)}return{formatTag:J,channels:Y,samplesPerSec:j,avgBytesPerSec:X,blockAlign:Z,bitsPerSample:G,cbSize:K,extraData:Q}}function w5($,J){return{ckid:new TextDecoder("latin1").decode(new Uint8Array($.buffer,$.byteOffset+J,4)),flags:$.getUint32(J+4,!0),offset:$.getUint32(J+8,!0),size:$.getUint32(J+12,!0)}}function Q$($,J){return $.toString().padStart(2,"0")+J}function O5($){if($.length!==4)return null;let J=$.substring(0,2),Y=$.substring(2),j=Number.parseInt(J,10);if(isNaN(j))return null;return{streamNumber:j,type:Y}}/*!
182
182
  * Copyright (c) 2025-present, Vanilagy and contributors
183
183
  *
184
184
  * This Source Code Form is subject to the terms of the Mozilla Public
@@ -220,13 +220,13 @@ ${K.join(`
220
220
  * This Source Code Form is subject to the terms of the Mozilla Public
221
221
  * License, v. 2.0. If a copy of the MPL was not distributed with this
222
222
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
223
- */class H$ extends W0{reader;moovSlice=null;currentTrack=null;tracks=[];metadataPromise=null;movieTimescale=-1;movieDurationInTimescale=-1;isQuickTime=!1;metadataTags={};currentMetadataKeys=null;isFragmented=!1;fragmentTrackDefaults=[];currentFragment=null;lastReadFragment=null;constructor($){super($);this.reader=$._reader}async computeDuration(){let $=await this.getTracks(),J=await Promise.all($.map((Y)=>Y.computeDuration()));return Math.max(0,...J)}async getTracks(){return await this.readMetadata(),this.tracks.map(($)=>$.inputTrack)}async getMimeType(){await this.readMetadata();let $=await Promise.all(this.tracks.map((J)=>J.inputTrack.getCodecParameterString()));return $2({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some((J)=>J.info?.type==="video"),hasAudio:this.tracks.some((J)=>J.info?.type==="audio"),codecStrings:$.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let $=0;while(!0){let J=this.reader.requestSliceRange($,f0,U1);if(J instanceof Promise)J=await J;if(!J)break;let Y=$,j=g0(J);if(!j)break;if(j.name==="ftyp"){let X=s(J,4);this.isQuickTime=X==="qt "}else if(j.name==="moov"){let X=this.reader.requestSlice(J.filePos,j.contentSize);if(X instanceof Promise)X=await X;if(!X)break;this.moovSlice=X,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((Z,G)=>Number(G.disposition.default)-Number(Z.disposition.default));for(let Z of this.tracks){let G=Z.editListPreviousSegmentDurations/this.movieTimescale;Z.editListOffset-=Math.round(G*Z.timescale)}break}$=Y+j.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let J=this.reader.requestSlice(this.reader.fileSize-4,4);if(J instanceof Promise)J=await J;H(J);let Y=P(J),j=this.reader.fileSize-Y;if(j>=0&&j<=this.reader.fileSize-U1){let X=this.reader.requestSliceRange(j,f0,U1);if(X instanceof Promise)X=await X;if(X){let Z=g0(X);if(Z&&Z.name==="mfra"){let G=this.reader.requestSlice(X.filePos,Z.contentSize);if(G instanceof Promise)G=await G;if(G)this.readContiguousBoxes(G)}}}}})()}getSampleTableForTrack($){if($.sampleTable)return $.sampleTable;let J={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};$.sampleTable=J,H(this.moovSlice);let Y=this.moovSlice.slice($.sampleTableByteOffset);if(this.currentTrack=$,this.traverseBox(Y),this.currentTrack=null,$.info?.type==="audio"&&$.info.codec&&o.includes($.info.codec)&&J.sampleCompositionTimeOffsets.length===0){H($.info?.type==="audio");let X=U0($.info.codec),Z=[],G=[];for(let K=0;K<J.sampleToChunk.length;K++){let Q=J.sampleToChunk[K],q=J.sampleToChunk[K+1],U=(q?q.startChunkIndex:J.chunkOffsets.length)-Q.startChunkIndex;for(let W=0;W<U;W++){let V=Q.startSampleIndex+W*Q.samplesPerChunk,N=V+Q.samplesPerChunk,A=u(J.sampleTimingEntries,V,(w)=>w.startIndex),R=J.sampleTimingEntries[A],z=u(J.sampleTimingEntries,N,(w)=>w.startIndex),_=J.sampleTimingEntries[z],L=R.startDecodeTimestamp+(V-R.startIndex)*R.delta,B=_.startDecodeTimestamp+(N-_.startIndex)*_.delta-L,F=n(Z);if(F&&F.delta===B)F.count++;else Z.push({startIndex:Q.startChunkIndex+W,startDecodeTimestamp:L,count:1,delta:B});let C=Q.samplesPerChunk*X.sampleSize*$.info.numberOfChannels;G.push(C)}Q.startSampleIndex=Q.startChunkIndex,Q.samplesPerChunk=1}J.sampleTimingEntries=Z,J.sampleSizes=G}if(J.sampleCompositionTimeOffsets.length>0){J.presentationTimestamps=[];for(let X of J.sampleTimingEntries)for(let Z=0;Z<X.count;Z++)J.presentationTimestamps.push({presentationTimestamp:X.startDecodeTimestamp+Z*X.delta,sampleIndex:X.startIndex+Z});for(let X of J.sampleCompositionTimeOffsets)for(let Z=0;Z<X.count;Z++){let G=X.startIndex+Z,K=J.presentationTimestamps[G];if(!K)continue;K.presentationTimestamp+=X.offset}J.presentationTimestamps.sort((X,Z)=>X.presentationTimestamp-Z.presentationTimestamp),J.presentationTimestampIndexMap=Array(J.presentationTimestamps.length).fill(-1);for(let X=0;X<J.presentationTimestamps.length;X++)J.presentationTimestampIndexMap[J.presentationTimestamps[X].sampleIndex]=X}return J}async readFragment($){if(this.lastReadFragment?.moofOffset===$)return this.lastReadFragment;let J=this.reader.requestSliceRange($,f0,U1);if(J instanceof Promise)J=await J;H(J);let Y=g0(J);H(Y?.name==="moof");let j=this.reader.requestSlice($,Y.totalSize);if(j instanceof Promise)j=await j;H(j),this.traverseBox(j);let X=this.lastReadFragment;H(X&&X.moofOffset===$);for(let[,Z]of X.trackData){let G=Z.track,{fragmentPositionCache:K}=G;if(!Z.startTimestampIsFinal){let q=G.fragmentLookupTable.find((U)=>U.moofOffset===X.moofOffset);if(q)W$(Z,q.timestamp);else{let U=u(K,X.moofOffset-1,(W)=>W.moofOffset);if(U!==-1){let W=K[U];W$(Z,W.endTimestamp)}}Z.startTimestampIsFinal=!0}let Q=u(K,Z.startTimestamp,(q)=>q.startTimestamp);if(Q===-1||K[Q].moofOffset!==X.moofOffset)K.splice(Q+1,0,{moofOffset:X.moofOffset,startTimestamp:Z.startTimestamp,endTimestamp:Z.endTimestamp})}return X}readContiguousBoxes($){let J=$.filePos;while($.filePos-J<=$.length-f0)if(!this.traverseBox($))break}*iterateContiguousBoxes($){let J=$.filePos;while($.filePos-J<=$.length-f0){let Y=$.filePos,j=g0($);if(!j)break;yield{boxInfo:j,slice:$},$.filePos=Y+j.totalSize}}traverseBox($){let J=$.filePos,Y=g0($);if(!Y)return!1;let j=$.filePos,X=J+Y.totalSize;switch(Y.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes($.slice(j,Y.contentSize));break;case"mvhd":{let Z=y($);if($.skip(3),Z===1)$.skip(16),this.movieTimescale=P($),this.movieDurationInTimescale=O0($);else $.skip(8),this.movieTimescale=P($),this.movieDurationInTimescale=P($)}break;case"trak":{let Z={id:-1,demuxer:this,inputTrack:null,disposition:{...L0},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:a,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=Z,this.readContiguousBoxes($.slice(j,Y.contentSize)),Z.id!==-1&&Z.timescale!==-1&&Z.info!==null){if(Z.info.type==="video"&&Z.info.width!==-1){let G=Z;Z.inputTrack=new D0(this.input,new h5(G)),this.tracks.push(Z)}else if(Z.info.type==="audio"&&Z.info.numberOfChannels!==-1){let G=Z;Z.inputTrack=new t(this.input,new f5(G)),this.tracks.push(Z)}else if(Z.info.type==="subtitle"){let G=Z;Z.inputTrack=new p1(this.input,new g5(G)),this.tracks.push(Z)}}this.currentTrack=null}break;case"tkhd":{let Z=this.currentTrack;if(!Z)break;let G=y($),Q=!!(_1($)&1);if(Z.disposition.default=Q,G===0)$.skip(8),Z.id=P($),$.skip(4),Z.durationInMovieTimescale=P($);else if(G===1)$.skip(16),Z.id=P($),$.skip(4),Z.durationInMovieTimescale=O0($);else throw Error(`Incorrect track header version ${G}.`);$.skip(16);let q=[M1($),M1($),J2($),M1($),M1($),J2($),M1($),M1($),J2($)],U=N1(F8(t7(q),90));H(U===0||U===90||U===180||U===270),Z.rotation=U}break;case"elst":{let Z=this.currentTrack;if(!Z)break;let G=y($);$.skip(3);let K=!1,Q=0,q=P($);for(let U=0;U<q;U++){let W=G===1?O0($):P($),V=G===1?W5($):q1($),N=M1($);if(W===0)continue;if(K){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(V===-1){Q+=W;continue}if(N!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}Z.editListPreviousSegmentDurations=Q,Z.editListOffset=V,K=!0}}break;case"mdhd":{let Z=this.currentTrack;if(!Z)break;let G=y($);if($.skip(3),G===0)$.skip(8),Z.timescale=P($),Z.durationInMediaTimescale=P($);else if(G===1)$.skip(16),Z.timescale=P($),Z.durationInMediaTimescale=O0($);let K=X0($);if(K>0){Z.languageCode="";for(let Q=0;Q<3;Q++)Z.languageCode=String.fromCharCode(96+(K&31))+Z.languageCode,K>>=5;if(!d0(Z.languageCode))Z.languageCode=a}}break;case"hdlr":{let Z=this.currentTrack;if(!Z)break;$.skip(8);let G=s($,4);if(G==="vide")Z.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null};else if(G==="soun")Z.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null};else if(G==="text"||G==="subt"||G==="sbtl")Z.info={type:"subtitle",codec:null,codecPrivateText:null}}break;case"stbl":{let Z=this.currentTrack;if(!Z)break;Z.sampleTableByteOffset=J,this.readContiguousBoxes($.slice(j,Y.contentSize))}break;case"stsd":{let Z=this.currentTrack;if(!Z)break;if(Z.info===null||Z.sampleTable)break;let G=y($);$.skip(3);let K=P($);for(let Q=0;Q<K;Q++){let q=$.filePos,U=g0($);if(!U)break;Z.internalCodecId=U.name;let W=U.name.toLowerCase();if(Z.info.type==="video"){if(W==="avc1"||W==="avc3")Z.info.codec="avc",Z.info.avcType=W==="avc1"?1:3;else if(W==="hvc1"||W==="hev1")Z.info.codec="hevc";else if(W==="vp08")Z.info.codec="vp8";else if(W==="vp09")Z.info.codec="vp9";else if(W==="av01")Z.info.codec="av1";else if(W==="mp4v")Z.info.codec="mpeg4";else console.warn(`Unsupported video codec (sample entry type '${U.name}').`);$.skip(24),Z.info.width=X0($),Z.info.height=X0($),$.skip(50),this.readContiguousBoxes($.slice($.filePos,q+U.totalSize-$.filePos))}else if(Z.info.type==="subtitle"){$.skip(6);let V=X0($);if(W==="wvtt")Z.info.codec="webvtt";else if(W==="tx3g"||W==="text")Z.info.codec="tx3g";else if(W==="stpp")Z.info.codec="ttml";this.readContiguousBoxes($.slice($.filePos,q+U.totalSize-$.filePos))}else{if(W==="mp4a");else if(W==="opus")Z.info.codec="opus";else if(W==="flac")Z.info.codec="flac";else if(W==="twos"||W==="sowt"||W==="raw "||W==="in24"||W==="in32"||W==="fl32"||W==="fl64"||W==="lpcm"||W==="ipcm"||W==="fpcm");else if(W==="ulaw")Z.info.codec="ulaw";else if(W==="alaw")Z.info.codec="alaw";else if(W==="ac-3")Z.info.codec="ac3";else if(W==="ec-3")Z.info.codec="eac3";else console.warn(`Unsupported audio codec (sample entry type '${U.name}').`);$.skip(8);let V=X0($);$.skip(6);let N=X0($),A=X0($);$.skip(4);let R=P($)/65536;if(G===0&&V>0){if(V===1)$.skip(4),A=8*P($),$.skip(8);else if(V===2){$.skip(4),R=i6($),N=P($),$.skip(4),A=P($);let z=P($);if($.skip(8),W==="lpcm"){let _=A+7>>3,L=Boolean(z&1),M=Boolean(z&2),B=z&4?-1:0;if(A>0&&A<=64){if(L){if(A===32)Z.info.codec=M?"pcm-f32be":"pcm-f32"}else if(B&1<<_-1){if(_===1)Z.info.codec="pcm-s8";else if(_===2)Z.info.codec=M?"pcm-s16be":"pcm-s16";else if(_===3)Z.info.codec=M?"pcm-s24be":"pcm-s24";else if(_===4)Z.info.codec=M?"pcm-s32be":"pcm-s32"}else if(_===1)Z.info.codec="pcm-u8"}if(Z.info.codec===null)console.warn("Unsupported PCM format.")}}}if(Z.info.codec==="opus")R=b0;if(Z.info.numberOfChannels=N,Z.info.sampleRate=R,W==="twos")if(A===8)Z.info.codec="pcm-s8";else if(A===16)Z.info.codec="pcm-s16be";else console.warn(`Unsupported sample size ${A} for codec 'twos'.`),Z.info.codec=null;else if(W==="sowt")if(A===8)Z.info.codec="pcm-s8";else if(A===16)Z.info.codec="pcm-s16";else console.warn(`Unsupported sample size ${A} for codec 'sowt'.`),Z.info.codec=null;else if(W==="raw ")Z.info.codec="pcm-u8";else if(W==="in24")Z.info.codec="pcm-s24be";else if(W==="in32")Z.info.codec="pcm-s32be";else if(W==="fl32")Z.info.codec="pcm-f32be";else if(W==="fl64")Z.info.codec="pcm-f64be";else if(W==="ipcm")Z.info.codec="pcm-s16be";else if(W==="fpcm")Z.info.codec="pcm-f32be";this.readContiguousBoxes($.slice($.filePos,q+U.totalSize-$.filePos))}}}break;case"avcC":{let Z=this.currentTrack;if(!Z)break;if(H(Z.info),Z.info.type==="video")Z.info.codecDescription=D($,Y.contentSize)}break;case"hvcC":{let Z=this.currentTrack;if(!Z)break;if(H(Z.info),Z.info.type==="video")Z.info.codecDescription=D($,Y.contentSize)}break;case"vpcC":{let Z=this.currentTrack;if(!Z)break;H(Z.info?.type==="video"),$.skip(4);let G=y($),K=y($),Q=y($),q=Q>>4,U=Q>>1&7,W=Q&1,V=y($),N=y($),A=y($);Z.info.vp9CodecInfo={profile:G,level:K,bitDepth:q,chromaSubsampling:U,videoFullRangeFlag:W,colourPrimaries:V,transferCharacteristics:N,matrixCoefficients:A}}break;case"av1C":{let Z=this.currentTrack;if(!Z)break;H(Z.info?.type==="video"),$.skip(1);let G=y($),K=G>>5,Q=G&31,q=y($),U=q>>7,W=q>>6&1,V=q>>5&1,N=q>>4&1,A=q>>3&1,R=q>>2&1,z=q&3,_=K===2&&W?V?12:10:W?10:8;Z.info.av1CodecInfo={profile:K,level:Q,tier:U,bitDepth:_,monochrome:N,chromaSubsamplingX:A,chromaSubsamplingY:R,chromaSamplePosition:z}}break;case"colr":{let Z=this.currentTrack;if(!Z)break;if(H(Z.info?.type==="video"),s($,4)!=="nclx")break;let K=X0($),Q=X0($),q=X0($),U=Boolean(y($)&128);Z.info.colorSpace={primaries:X6[K],transfer:Z6[Q],matrix:G6[q],fullRange:U}}break;case"wave":this.readContiguousBoxes($.slice(j,Y.contentSize));break;case"esds":{let Z=this.currentTrack;if(!Z)break;if(Z.info?.type!=="audio"&&Z.info?.type!=="video")break;$.skip(4);let G=y($);H(G===3),Y2($),$.skip(2);let K=y($),Q=(K&128)!==0,q=(K&64)!==0,U=(K&32)!==0;if(Q)$.skip(2);if(q){let R=y($);$.skip(R)}if(U)$.skip(2);let W=y($);H(W===4);let V=Y2($),N=$.filePos,A=y($);if(Z.info.type==="audio")if(A===64||A===103)Z.info.codec="aac",Z.info.aacCodecInfo={isMpeg2:A===103};else if(A===105||A===107)Z.info.codec="mp3";else if(A===221)Z.info.codec="vorbis";else console.warn(`Unsupported audio codec (objectTypeIndication ${A}) - discarding track.`);else if(Z.info.type==="video"){if(A===32)Z.info.codec="mpeg4"}if($.skip(12),V>$.filePos-N){let R=y($);H(R===5);let z=Y2($);if(Z.info.codecDescription=D($,z),Z.info.type==="audio"&&Z.info.codec==="aac"){let _=x1(Z.info.codecDescription);if(_.numberOfChannels!==null)Z.info.numberOfChannels=_.numberOfChannels;if(_.sampleRate!==null)Z.info.sampleRate=_.sampleRate}}}break;case"enda":{let Z=this.currentTrack;if(!Z)break;if(H(Z.info?.type==="audio"),X0($)&255){if(Z.info.codec==="pcm-s16be")Z.info.codec="pcm-s16";else if(Z.info.codec==="pcm-s24be")Z.info.codec="pcm-s24";else if(Z.info.codec==="pcm-s32be")Z.info.codec="pcm-s32";else if(Z.info.codec==="pcm-f32be")Z.info.codec="pcm-f32";else if(Z.info.codec==="pcm-f64be")Z.info.codec="pcm-f64"}}break;case"pcmC":{let Z=this.currentTrack;if(!Z)break;H(Z.info?.type==="audio"),$.skip(4);let G=y($),K=Boolean(G&1),Q=y($);if(Z.info.codec==="pcm-s16be")if(K)if(Q===16)Z.info.codec="pcm-s16";else if(Q===24)Z.info.codec="pcm-s24";else if(Q===32)Z.info.codec="pcm-s32";else console.warn(`Invalid ipcm sample size ${Q}.`),Z.info.codec=null;else if(Q===16)Z.info.codec="pcm-s16be";else if(Q===24)Z.info.codec="pcm-s24be";else if(Q===32)Z.info.codec="pcm-s32be";else console.warn(`Invalid ipcm sample size ${Q}.`),Z.info.codec=null;else if(Z.info.codec==="pcm-f32be")if(K)if(Q===32)Z.info.codec="pcm-f32";else if(Q===64)Z.info.codec="pcm-f64";else console.warn(`Invalid fpcm sample size ${Q}.`),Z.info.codec=null;else if(Q===32)Z.info.codec="pcm-f32be";else if(Q===64)Z.info.codec="pcm-f64be";else console.warn(`Invalid fpcm sample size ${Q}.`),Z.info.codec=null;break}case"dOps":{let Z=this.currentTrack;if(!Z)break;H(Z.info?.type==="audio"),$.skip(1);let G=y($),K=X0($),Q=P($),q=f8($),U=y($),W;if(U!==0)W=D($,2+G);else W=new Uint8Array(0);let V=new Uint8Array(19+W.byteLength),N=new DataView(V.buffer);N.setUint32(0,1332770163,!1),N.setUint32(4,1214603620,!1),N.setUint8(8,1),N.setUint8(9,G),N.setUint16(10,K,!0),N.setUint32(12,Q,!0),N.setInt16(16,q,!0),N.setUint8(18,U),V.set(W,19),Z.info.codecDescription=V,Z.info.numberOfChannels=G}break;case"dfLa":{let Z=this.currentTrack;if(!Z)break;H(Z.info?.type==="audio"),$.skip(4);let G=127,K=128,Q=$.filePos;while($.filePos<X){let N=y($),A=_1($);if((N&G)===0){$.skip(10);let z=P($),_=z>>>12,L=(z>>9&7)+1;Z.info.sampleRate=_,Z.info.numberOfChannels=L,$.skip(20)}else $.skip(A);if(N&K)break}let q=$.filePos;$.filePos=Q;let U=D($,q-Q),W=new Uint8Array(4+U.byteLength);new DataView(W.buffer).setUint32(0,1716281667,!1),W.set(U,4),Z.info.codecDescription=W}break;case"stts":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let G=P($),K=0,Q=0;for(let q=0;q<G;q++){let U=P($),W=P($);Z.sampleTable.sampleTimingEntries.push({startIndex:K,startDecodeTimestamp:Q,count:U,delta:W}),K+=U,Q+=U*W}}break;case"ctts":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let G=P($),K=0;for(let Q=0;Q<G;Q++){let q=P($),U=q1($);Z.sampleTable.sampleCompositionTimeOffsets.push({startIndex:K,count:q,offset:U}),K+=q}}break;case"stsz":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let G=P($),K=P($);if(G===0)for(let Q=0;Q<K;Q++){let q=P($);Z.sampleTable.sampleSizes.push(q)}else Z.sampleTable.sampleSizes.push(G)}break;case"stz2":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4),$.skip(3);let G=y($),K=P($),Q=D($,Math.ceil(K*G/8)),q=new f(Q);for(let U=0;U<K;U++){let W=q.readBits(G);Z.sampleTable.sampleSizes.push(W)}}break;case"stss":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4),Z.sampleTable.keySampleIndices=[];let G=P($);for(let K=0;K<G;K++){let Q=P($)-1;Z.sampleTable.keySampleIndices.push(Q)}if(Z.sampleTable.keySampleIndices[0]!==0)Z.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let G=P($);for(let Q=0;Q<G;Q++){let q=P($)-1,U=P($),W=P($);Z.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:q,samplesPerChunk:U,sampleDescriptionIndex:W})}let K=0;for(let Q=0;Q<Z.sampleTable.sampleToChunk.length;Q++)if(Z.sampleTable.sampleToChunk[Q].startSampleIndex=K,Q<Z.sampleTable.sampleToChunk.length-1){let U=Z.sampleTable.sampleToChunk[Q+1].startChunkIndex-Z.sampleTable.sampleToChunk[Q].startChunkIndex;K+=U*Z.sampleTable.sampleToChunk[Q].samplesPerChunk}}break;case"stco":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let G=P($);for(let K=0;K<G;K++){let Q=P($);Z.sampleTable.chunkOffsets.push(Q)}}break;case"co64":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let G=P($);for(let K=0;K<G;K++){let Q=O0($);Z.sampleTable.chunkOffsets.push(Q)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes($.slice(j,Y.contentSize));break;case"mehd":{let Z=y($);$.skip(3);let G=Z===1?O0($):P($);this.movieDurationInTimescale=G}break;case"trex":{$.skip(4);let Z=P($),G=P($),K=P($),Q=P($),q=P($);this.fragmentTrackDefaults.push({trackId:Z,defaultSampleDescriptionIndex:G,defaultSampleDuration:K,defaultSampleSize:Q,defaultSampleFlags:q})}break;case"tfra":{let Z=y($);$.skip(3);let G=P($),K=this.tracks.find((_)=>_.id===G);if(!K)break;let Q=P($),q=(Q&48)>>4,U=(Q&12)>>2,W=Q&3,V=[y,X0,_1,P],N=V[q],A=V[U],R=V[W],z=P($);for(let _=0;_<z;_++){let L=Z===1?O0($):P($),M=Z===1?O0($):P($);N($),A($),R($),K.fragmentLookupTable.push({timestamp:L,moofOffset:M})}K.fragmentLookupTable.sort((_,L)=>_.timestamp-L.timestamp);for(let _=0;_<K.fragmentLookupTable.length-1;_++){let L=K.fragmentLookupTable[_],M=K.fragmentLookupTable[_+1];if(L.timestamp===M.timestamp)K.fragmentLookupTable.splice(_+1,1),_--}}break;case"moof":this.currentFragment={moofOffset:J,moofSize:Y.totalSize,implicitBaseDataOffset:J,trackData:new Map},this.readContiguousBoxes($.slice(j,Y.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(H(this.currentFragment),this.readContiguousBoxes($.slice(j,Y.contentSize)),this.currentTrack){let Z=this.currentFragment.trackData.get(this.currentTrack.id);if(Z){let{currentFragmentState:G}=this.currentTrack;if(H(G),G.startTimestamp!==null)W$(Z,G.startTimestamp),Z.startTimestampIsFinal=!0}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{H(this.currentFragment),$.skip(1);let Z=_1($),G=Boolean(Z&1),K=Boolean(Z&2),Q=Boolean(Z&8),q=Boolean(Z&16),U=Boolean(Z&32),W=Boolean(Z&65536),V=Boolean(Z&131072),N=P($),A=this.tracks.find((z)=>z.id===N);if(!A)break;let R=this.fragmentTrackDefaults.find((z)=>z.trackId===N);if(this.currentTrack=A,A.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:R?.defaultSampleDescriptionIndex??null,defaultSampleDuration:R?.defaultSampleDuration??null,defaultSampleSize:R?.defaultSampleSize??null,defaultSampleFlags:R?.defaultSampleFlags??null,startTimestamp:null},G)A.currentFragmentState.baseDataOffset=O0($);else if(V)A.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset;if(K)A.currentFragmentState.sampleDescriptionIndex=P($);if(Q)A.currentFragmentState.defaultSampleDuration=P($);if(q)A.currentFragmentState.defaultSampleSize=P($);if(U)A.currentFragmentState.defaultSampleFlags=P($);if(W)A.currentFragmentState.defaultSampleDuration=0}break;case"tfdt":{let Z=this.currentTrack;if(!Z)break;H(Z.currentFragmentState);let G=y($);$.skip(3);let K=G===0?P($):O0($);Z.currentFragmentState.startTimestamp=K}break;case"trun":{let Z=this.currentTrack;if(!Z)break;if(H(this.currentFragment),H(Z.currentFragmentState),this.currentFragment.trackData.has(Z.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}let G=y($),K=_1($),Q=Boolean(K&1),q=Boolean(K&4),U=Boolean(K&256),W=Boolean(K&512),V=Boolean(K&1024),N=Boolean(K&2048),A=P($),R=Z.currentFragmentState.baseDataOffset;if(Q)R+=q1($);let z=null;if(q)z=P($);let _=R;if(A===0){this.currentFragment.implicitBaseDataOffset=_;break}let L=0,M={track:Z,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(Z.id,M);for(let C=0;C<A;C++){let w;if(U)w=P($);else H(Z.currentFragmentState.defaultSampleDuration!==null),w=Z.currentFragmentState.defaultSampleDuration;let v;if(W)v=P($);else H(Z.currentFragmentState.defaultSampleSize!==null),v=Z.currentFragmentState.defaultSampleSize;let k;if(V)k=P($);else H(Z.currentFragmentState.defaultSampleFlags!==null),k=Z.currentFragmentState.defaultSampleFlags;if(C===0&&z!==null)k=z;let S=0;if(N)if(G===0)S=P($);else S=q1($);let T=!(k&65536);M.samples.push({presentationTimestamp:L+S,duration:w,byteOffset:_,byteSize:v,isKeyFrame:T}),_+=v,L+=w}M.presentationTimestamps=M.samples.map((C,w)=>({presentationTimestamp:C.presentationTimestamp,sampleIndex:w})).sort((C,w)=>C.presentationTimestamp-w.presentationTimestamp);for(let C=0;C<M.presentationTimestamps.length;C++){let w=M.presentationTimestamps[C],v=M.samples[w.sampleIndex];if(M.firstKeyFrameTimestamp===null&&v.isKeyFrame)M.firstKeyFrameTimestamp=v.presentationTimestamp;if(C<M.presentationTimestamps.length-1){let k=M.presentationTimestamps[C+1];v.duration=k.presentationTimestamp-w.presentationTimestamp}}let B=M.samples[M.presentationTimestamps[0].sampleIndex],F=M.samples[n(M.presentationTimestamps).sampleIndex];M.startTimestamp=B.presentationTimestamp,M.endTimestamp=F.presentationTimestamp+F.duration,this.currentFragment.implicitBaseDataOffset=_}break;case"udta":{let Z=this.iterateContiguousBoxes($.slice(j,Y.contentSize));for(let{boxInfo:G,slice:K}of Z){if(G.name!=="meta"&&!this.currentTrack){let Q=K.filePos;if(this.metadataTags.raw??={},G.name[0]==="©")this.metadataTags.raw[G.name]??=k0(K);else this.metadataTags.raw[G.name]??=D(K,G.contentSize);K.filePos=Q}switch(G.name){case"meta":K.skip(-G.headerSize),this.traverseBox(K);break;case"©nam":case"name":if(this.currentTrack)this.currentTrack.name=Y0.decode(D(K,G.contentSize));else this.metadataTags.title??=k0(K);break;case"©des":if(!this.currentTrack)this.metadataTags.description??=k0(K);break;case"©ART":if(!this.currentTrack)this.metadataTags.artist??=k0(K);break;case"©alb":if(!this.currentTrack)this.metadataTags.album??=k0(K);break;case"albr":if(!this.currentTrack)this.metadataTags.albumArtist??=k0(K);break;case"©gen":if(!this.currentTrack)this.metadataTags.genre??=k0(K);break;case"©day":if(!this.currentTrack){let Q=new Date(k0(K));if(!Number.isNaN(Q.getTime()))this.metadataTags.date??=Q}break;case"©cmt":if(!this.currentTrack)this.metadataTags.comment??=k0(K);break;case"©lyr":if(!this.currentTrack)this.metadataTags.lyrics??=k0(K);break}}}break;case"meta":{if(this.currentTrack)break;let G=P($)!==0;if(this.currentMetadataKeys=new Map,G)this.readContiguousBoxes($.slice(j,Y.contentSize));else this.readContiguousBoxes($.slice(j+4,Y.contentSize-4));this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;$.skip(4);let Z=P($);for(let G=0;G<Z;G++){let K=P($);$.skip(4);let Q=Y0.decode(D($,K-8));this.currentMetadataKeys.set(G+1,Q)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let Z=this.iterateContiguousBoxes($.slice(j,Y.contentSize));for(let{boxInfo:G,slice:K}of Z){let Q=G.name,q=(Q.charCodeAt(0)<<24)+(Q.charCodeAt(1)<<16)+(Q.charCodeAt(2)<<8)+Q.charCodeAt(3);if(this.currentMetadataKeys.has(q))Q=this.currentMetadataKeys.get(q);let U=I5(K);switch(this.metadataTags.raw??={},this.metadataTags.raw[Q]??=U,Q){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":if(typeof U==="string")this.metadataTags.title??=U;break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":if(typeof U==="string")this.metadataTags.description??=U;break;case"©ART":case"com.apple.quicktime.artist":case"artist":if(typeof U==="string")this.metadataTags.artist??=U;break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":if(typeof U==="string")this.metadataTags.album??=U;break;case"aART":case"album_artist":if(typeof U==="string")this.metadataTags.albumArtist??=U;break;case"©cmt":case"com.apple.quicktime.comment":case"comment":if(typeof U==="string")this.metadataTags.comment??=U;break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":if(typeof U==="string")this.metadataTags.genre??=U;break;case"©lyr":case"lyrics":if(typeof U==="string")this.metadataTags.lyrics??=U;break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof U==="string"){let W=new Date(U);if(!Number.isNaN(W.getTime()))this.metadataTags.date??=W}break;case"covr":case"com.apple.quicktime.artwork":if(U instanceof I0)this.metadataTags.images??=[],this.metadataTags.images.push({data:U.data,kind:"coverFront",mimeType:U.mimeType});else if(U instanceof Uint8Array)this.metadataTags.images??=[],this.metadataTags.images.push({data:U,kind:"coverFront",mimeType:"image/*"});break;case"track":if(typeof U==="string"){let W=U.split("/"),V=Number.parseInt(W[0],10),N=W[1]&&Number.parseInt(W[1],10);if(Number.isInteger(V)&&V>0)this.metadataTags.trackNumber??=V;if(N&&Number.isInteger(N)&&N>0)this.metadataTags.tracksTotal??=N}break;case"trkn":if(U instanceof Uint8Array&&U.length>=6){let W=h(U),V=W.getUint16(2,!1),N=W.getUint16(4,!1);if(V>0)this.metadataTags.trackNumber??=V;if(N>0)this.metadataTags.tracksTotal??=N}break;case"disc":case"disk":if(U instanceof Uint8Array&&U.length>=6){let W=h(U),V=W.getUint16(2,!1),N=W.getUint16(4,!1);if(V>0)this.metadataTags.discNumber??=V;if(N>0)this.metadataTags.discsTotal??=N}break}}}break}return $.filePos=X,!0}}class j2{internalTrack;packetToSampleIndex=new WeakMap;packetToFragmentLocation=new WeakMap;constructor($){this.internalTrack=$}getId(){return this.internalTrack.id}getCodec(){throw Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){let $=await this.getPacket(Number.POSITIVE_INFINITY,{metadataOnly:!0});return($?.timestamp??0)+($?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket($){let J=await this.fetchPacketForSampleIndex(0,$);if(J||!this.internalTrack.demuxer.isFragmented)return J;return this.performFragmentedLookup(null,(Y)=>{if(Y.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,$)}mapTimestampIntoTimescale($){return y1($*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket($,J){let Y=this.mapTimestampIntoTimescale($),j=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),X=V$(j,Y),Z=await this.fetchPacketForSampleIndex(X,J);if(!S5(j)||!this.internalTrack.demuxer.isFragmented)return Z;return this.performFragmentedLookup(null,(G)=>{let K=G.trackData.get(this.internalTrack.id);if(!K)return{sampleIndex:-1,correctSampleFound:!1};let Q=u(K.presentationTimestamps,Y,(W)=>W.presentationTimestamp),q=Q!==-1?K.presentationTimestamps[Q].sampleIndex:-1,U=Q!==-1&&Y<K.endTimestamp;return{sampleIndex:q,correctSampleFound:U}},Y,Y,J)}async getNextPacket($,J){let Y=this.packetToSampleIndex.get($);if(Y!==void 0)return this.fetchPacketForSampleIndex(Y+1,J);let j=this.packetToFragmentLocation.get($);if(j===void 0)throw Error("Packet was not created from this track.");return this.performFragmentedLookup(j.fragment,(X)=>{if(X===j.fragment){let Z=X.trackData.get(this.internalTrack.id);if(j.sampleIndex+1<Z.samples.length)return{sampleIndex:j.sampleIndex+1,correctSampleFound:!0}}else if(X.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,J)}async getKeyPacket($,J){let Y=this.mapTimestampIntoTimescale($),j=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),X=i7(j,Y),Z=await this.fetchPacketForSampleIndex(X,J);if(!S5(j)||!this.internalTrack.demuxer.isFragmented)return Z;return this.performFragmentedLookup(null,(G)=>{let K=G.trackData.get(this.internalTrack.id);if(!K)return{sampleIndex:-1,correctSampleFound:!1};let Q=Q6(K.presentationTimestamps,(W)=>{return K.samples[W.sampleIndex].isKeyFrame&&W.presentationTimestamp<=Y}),q=Q!==-1?K.presentationTimestamps[Q].sampleIndex:-1,U=Q!==-1&&Y<K.endTimestamp;return{sampleIndex:q,correctSampleFound:U}},Y,Y,J)}async getNextKeyPacket($,J){let Y=this.packetToSampleIndex.get($);if(Y!==void 0){let X=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),Z=a7(X,Y);return this.fetchPacketForSampleIndex(Z,J)}let j=this.packetToFragmentLocation.get($);if(j===void 0)throw Error("Packet was not created from this track.");return this.performFragmentedLookup(j.fragment,(X)=>{if(X===j.fragment){let G=X.trackData.get(this.internalTrack.id).samples.findIndex((K,Q)=>K.isKeyFrame&&Q>j.sampleIndex);if(G!==-1)return{sampleIndex:G,correctSampleFound:!0}}else{let Z=X.trackData.get(this.internalTrack.id);if(Z&&Z.firstKeyFrameTimestamp!==null){let G=Z.samples.findIndex((K)=>K.isKeyFrame);return H(G!==-1),{sampleIndex:G,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY,J)}async fetchPacketForSampleIndex($,J){if($===-1)return null;let Y=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),j=s7(Y,$);if(!j)return null;let X;if(J.metadataOnly)X=G0;else{let Q=this.internalTrack.demuxer.reader.requestSlice(j.sampleOffset,j.sampleSize);if(Q instanceof Promise)Q=await Q;H(Q),X=D(Q,j.sampleSize)}let Z=(j.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,G=j.duration/this.internalTrack.timescale,K=new I(X,j.isKeyFrame?"key":"delta",Z,G,$,j.sampleSize);return this.packetToSampleIndex.set(K,$),K}async fetchPacketInFragment($,J,Y){if(J===-1)return null;let X=$.trackData.get(this.internalTrack.id).samples[J];H(X);let Z;if(Y.metadataOnly)Z=G0;else{let q=this.internalTrack.demuxer.reader.requestSlice(X.byteOffset,X.byteSize);if(q instanceof Promise)q=await q;H(q),Z=D(q,X.byteSize)}let G=(X.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,K=X.duration/this.internalTrack.timescale,Q=new I(Z,X.isKeyFrame?"key":"delta",G,K,$.moofOffset+J,X.byteSize);return this.packetToFragmentLocation.set(Q,{fragment:$,sampleIndex:J}),Q}async performFragmentedLookup($,J,Y,j,X){let Z=this.internalTrack.demuxer,G=null,K=null,Q=-1;if($){let{sampleIndex:R,correctSampleFound:z}=J($);if(z)return this.fetchPacketInFragment($,R,X);if(R!==-1)K=$,Q=R}let q=u(this.internalTrack.fragmentLookupTable,Y,(R)=>R.timestamp),U=q!==-1?this.internalTrack.fragmentLookupTable[q]:null,W=u(this.internalTrack.fragmentPositionCache,Y,(R)=>R.startTimestamp),V=W!==-1?this.internalTrack.fragmentPositionCache[W]:null,N=Math.max(U?.moofOffset??0,V?.moofOffset??0)||null,A;if(!$)A=N??0;else if(N===null||$.moofOffset>=N)A=$.moofOffset+$.moofSize,G=$;else A=N;while(!0){if(G){let L=G.trackData.get(this.internalTrack.id);if(L&&L.startTimestamp>j)break}let R=Z.reader.requestSliceRange(A,f0,U1);if(R instanceof Promise)R=await R;if(!R)break;let z=A,_=g0(R);if(!_)break;if(_.name==="moof"){G=await Z.readFragment(z);let{sampleIndex:L,correctSampleFound:M}=J(G);if(M)return this.fetchPacketInFragment(G,L,X);if(L!==-1)K=G,Q=L}A=z+_.totalSize}if(U&&(!K||K.moofOffset<U.moofOffset)){let R=this.internalTrack.fragmentLookupTable[q-1];H(!R||R.timestamp<U.timestamp);let z=R?.timestamp??Number.NEGATIVE_INFINITY;return this.performFragmentedLookup(null,J,z,j,X)}if(K)return this.fetchPacketInFragment(K,Q,X);return null}}class h5 extends j2{internalTrack;decoderConfigPromise=null;constructor($){super($);this.internalTrack=$}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let $=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=$&&x6($.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let $=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=$&&I6($.data)}return{codec:V6(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??void 0}})()}}class f5 extends j2{internalTrack;decoderConfig=null;constructor($){super($);this.internalTrack=$}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfig??={codec:H6(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}}}class g5 extends j2{internalTrack;constructor($){super($);this.internalTrack=$}getCodec(){return this.internalTrack.info.codec}getCodecPrivate(){return this.internalTrack.info.codecPrivateText}async*getCues(){let $=await this.getFirstPacket({});while($){let J="";if(this.internalTrack.info.codec==="webvtt"){let Y=new Uint8Array($.data),j=new S0(Y,new DataView(Y.buffer,Y.byteOffset,Y.byteLength),0,0,Y.length);while(j.remainingLength>0){let X=g0(j);if(!X)break;if(X.name==="vttc"){let Z=j.filePos+X.contentSize;while(j.filePos<Z&&j.remainingLength>0){let G=g0(j);if(!G)break;if(G.name==="payl"){let K=D(j,G.contentSize),Q=new TextDecoder("utf-8");J+=Q.decode(K)}else j.skip(G.contentSize)}}else if(X.name==="vtte")j.skip(X.contentSize);else j.skip(X.contentSize)}}else J=new TextDecoder("utf-8").decode($.data);if(J)yield{timestamp:$.timestamp,duration:$.duration,text:J};$=await this.getNextPacket($,{})}}}var V$=($,J)=>{if($.presentationTimestamps){let X=u($.presentationTimestamps,J,(Z)=>Z.presentationTimestamp);if(X===-1)return-1;return $.presentationTimestamps[X].sampleIndex}let Y=u($.sampleTimingEntries,J,(X)=>X.startDecodeTimestamp);if(Y===-1)return-1;let j=$.sampleTimingEntries[Y];return j.startIndex+Math.min(Math.floor((J-j.startDecodeTimestamp)/j.delta),j.count-1)},i7=($,J)=>{if(!$.keySampleIndices)return V$($,J);if($.presentationTimestamps){let Y=u($.presentationTimestamps,J,(j)=>j.presentationTimestamp);if(Y===-1)return-1;for(let j=Y;j>=0;j--){let X=$.presentationTimestamps[j].sampleIndex;if(Y1($.keySampleIndices,X,(G)=>G)!==-1)return X}return-1}else{let Y=V$($,J),j=u($.keySampleIndices,Y,(X)=>X);return $.keySampleIndices[j]??-1}},s7=($,J)=>{let Y=u($.sampleTimingEntries,J,(_)=>_.startIndex),j=$.sampleTimingEntries[Y];if(!j||j.startIndex+j.count<=J)return null;let Z=j.startDecodeTimestamp+(J-j.startIndex)*j.delta,G=u($.sampleCompositionTimeOffsets,J,(_)=>_.startIndex),K=$.sampleCompositionTimeOffsets[G];if(K&&J-K.startIndex<K.count)Z+=K.offset;let Q=$.sampleSizes[Math.min(J,$.sampleSizes.length-1)],q=u($.sampleToChunk,J,(_)=>_.startSampleIndex),U=$.sampleToChunk[q];H(U);let W=U.startChunkIndex+Math.floor((J-U.startSampleIndex)/U.samplesPerChunk),V=$.chunkOffsets[W],N=U.startSampleIndex+(W-U.startChunkIndex)*U.samplesPerChunk,A=0,R=V;if($.sampleSizes.length===1)R+=Q*(J-N),A+=Q*U.samplesPerChunk;else for(let _=N;_<N+U.samplesPerChunk;_++){let L=$.sampleSizes[_];if(_<J)R+=L;A+=L}let z=j.delta;if($.presentationTimestamps){let _=$.presentationTimestampIndexMap[J];if(H(_!==void 0),_<$.presentationTimestamps.length-1)z=$.presentationTimestamps[_+1].presentationTimestamp-Z}return{presentationTimestamp:Z,duration:z,sampleOffset:R,sampleSize:Q,chunkOffset:V,chunkSize:A,isKeyFrame:$.keySampleIndices?Y1($.keySampleIndices,J,(_)=>_)!==-1:!0}},a7=($,J)=>{if(!$.keySampleIndices)return J+1;let Y=u($.keySampleIndices,J,(j)=>j);return $.keySampleIndices[Y+1]??-1},W$=($,J)=>{$.startTimestamp+=J,$.endTimestamp+=J;for(let Y of $.samples)Y.presentationTimestamp+=J;for(let Y of $.presentationTimestamps)Y.presentationTimestamp+=J},t7=($)=>{let[J,,,Y]=$,j=Math.hypot(J,Y),X=J/j,Z=Y/j,G=-Math.atan2(Z,X)*(180/Math.PI);if(!Number.isFinite(G))return 0;return G},S5=($)=>{return $.sampleSizes.length===0};/*!
223
+ */class H$ extends W0{reader;moovSlice=null;currentTrack=null;tracks=[];metadataPromise=null;movieTimescale=-1;movieDurationInTimescale=-1;isQuickTime=!1;metadataTags={};currentMetadataKeys=null;isFragmented=!1;fragmentTrackDefaults=[];currentFragment=null;lastReadFragment=null;constructor($){super($);this.reader=$._reader}async computeDuration(){let $=await this.getTracks(),J=await Promise.all($.map((Y)=>Y.computeDuration()));return Math.max(0,...J)}async getTracks(){return await this.readMetadata(),this.tracks.map(($)=>$.inputTrack)}async getMimeType(){await this.readMetadata();let $=await Promise.all(this.tracks.map((J)=>J.inputTrack.getCodecParameterString()));return $2({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some((J)=>J.info?.type==="video"),hasAudio:this.tracks.some((J)=>J.info?.type==="audio"),codecStrings:$.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let $=0;while(!0){let J=this.reader.requestSliceRange($,f0,U1);if(J instanceof Promise)J=await J;if(!J)break;let Y=$,j=g0(J);if(!j)break;if(j.name==="ftyp"){let X=s(J,4);this.isQuickTime=X==="qt "}else if(j.name==="moov"){let X=this.reader.requestSlice(J.filePos,j.contentSize);if(X instanceof Promise)X=await X;if(!X)break;this.moovSlice=X,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((Z,G)=>Number(G.disposition.default)-Number(Z.disposition.default));for(let Z of this.tracks){let G=Z.editListPreviousSegmentDurations/this.movieTimescale;Z.editListOffset-=Math.round(G*Z.timescale)}break}$=Y+j.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let J=this.reader.requestSlice(this.reader.fileSize-4,4);if(J instanceof Promise)J=await J;H(J);let Y=P(J),j=this.reader.fileSize-Y;if(j>=0&&j<=this.reader.fileSize-U1){let X=this.reader.requestSliceRange(j,f0,U1);if(X instanceof Promise)X=await X;if(X){let Z=g0(X);if(Z&&Z.name==="mfra"){let G=this.reader.requestSlice(X.filePos,Z.contentSize);if(G instanceof Promise)G=await G;if(G)this.readContiguousBoxes(G)}}}}})()}getSampleTableForTrack($){if($.sampleTable)return $.sampleTable;let J={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};$.sampleTable=J,H(this.moovSlice);let Y=this.moovSlice.slice($.sampleTableByteOffset);if(this.currentTrack=$,this.traverseBox(Y),this.currentTrack=null,$.info?.type==="audio"&&$.info.codec&&o.includes($.info.codec)&&J.sampleCompositionTimeOffsets.length===0){H($.info?.type==="audio");let X=U0($.info.codec),Z=[],G=[];for(let K=0;K<J.sampleToChunk.length;K++){let Q=J.sampleToChunk[K],q=J.sampleToChunk[K+1],U=(q?q.startChunkIndex:J.chunkOffsets.length)-Q.startChunkIndex;for(let W=0;W<U;W++){let V=Q.startSampleIndex+W*Q.samplesPerChunk,N=V+Q.samplesPerChunk,A=u(J.sampleTimingEntries,V,(w)=>w.startIndex),R=J.sampleTimingEntries[A],z=u(J.sampleTimingEntries,N,(w)=>w.startIndex),_=J.sampleTimingEntries[z],L=R.startDecodeTimestamp+(V-R.startIndex)*R.delta,B=_.startDecodeTimestamp+(N-_.startIndex)*_.delta-L,F=n(Z);if(F&&F.delta===B)F.count++;else Z.push({startIndex:Q.startChunkIndex+W,startDecodeTimestamp:L,count:1,delta:B});let C=Q.samplesPerChunk*X.sampleSize*$.info.numberOfChannels;G.push(C)}Q.startSampleIndex=Q.startChunkIndex,Q.samplesPerChunk=1}J.sampleTimingEntries=Z,J.sampleSizes=G}if(J.sampleCompositionTimeOffsets.length>0){J.presentationTimestamps=[];for(let X of J.sampleTimingEntries)for(let Z=0;Z<X.count;Z++)J.presentationTimestamps.push({presentationTimestamp:X.startDecodeTimestamp+Z*X.delta,sampleIndex:X.startIndex+Z});for(let X of J.sampleCompositionTimeOffsets)for(let Z=0;Z<X.count;Z++){let G=X.startIndex+Z,K=J.presentationTimestamps[G];if(!K)continue;K.presentationTimestamp+=X.offset}J.presentationTimestamps.sort((X,Z)=>X.presentationTimestamp-Z.presentationTimestamp),J.presentationTimestampIndexMap=Array(J.presentationTimestamps.length).fill(-1);for(let X=0;X<J.presentationTimestamps.length;X++)J.presentationTimestampIndexMap[J.presentationTimestamps[X].sampleIndex]=X}return J}async readFragment($){if(this.lastReadFragment?.moofOffset===$)return this.lastReadFragment;let J=this.reader.requestSliceRange($,f0,U1);if(J instanceof Promise)J=await J;H(J);let Y=g0(J);H(Y?.name==="moof");let j=this.reader.requestSlice($,Y.totalSize);if(j instanceof Promise)j=await j;H(j),this.traverseBox(j);let X=this.lastReadFragment;H(X&&X.moofOffset===$);for(let[,Z]of X.trackData){let G=Z.track,{fragmentPositionCache:K}=G;if(!Z.startTimestampIsFinal){let q=G.fragmentLookupTable.find((U)=>U.moofOffset===X.moofOffset);if(q)W$(Z,q.timestamp);else{let U=u(K,X.moofOffset-1,(W)=>W.moofOffset);if(U!==-1){let W=K[U];W$(Z,W.endTimestamp)}}Z.startTimestampIsFinal=!0}let Q=u(K,Z.startTimestamp,(q)=>q.startTimestamp);if(Q===-1||K[Q].moofOffset!==X.moofOffset)K.splice(Q+1,0,{moofOffset:X.moofOffset,startTimestamp:Z.startTimestamp,endTimestamp:Z.endTimestamp})}return X}readContiguousBoxes($){let J=$.filePos;while($.filePos-J<=$.length-f0)if(!this.traverseBox($))break}*iterateContiguousBoxes($){let J=$.filePos;while($.filePos-J<=$.length-f0){let Y=$.filePos,j=g0($);if(!j)break;yield{boxInfo:j,slice:$},$.filePos=Y+j.totalSize}}traverseBox($){let J=$.filePos,Y=g0($);if(!Y)return!1;let j=$.filePos,X=J+Y.totalSize;switch(Y.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes($.slice(j,Y.contentSize));break;case"mvhd":{let Z=y($);if($.skip(3),Z===1)$.skip(16),this.movieTimescale=P($),this.movieDurationInTimescale=O0($);else $.skip(8),this.movieTimescale=P($),this.movieDurationInTimescale=P($)}break;case"trak":{let Z={id:-1,demuxer:this,inputTrack:null,disposition:{...L0},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:a,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=Z,this.readContiguousBoxes($.slice(j,Y.contentSize)),Z.id!==-1&&Z.timescale!==-1&&Z.info!==null){if(Z.info.type==="video"&&Z.info.width!==-1){let G=Z;Z.inputTrack=new D0(this.input,new h5(G)),this.tracks.push(Z)}else if(Z.info.type==="audio"&&Z.info.numberOfChannels!==-1){let G=Z;Z.inputTrack=new t(this.input,new f5(G)),this.tracks.push(Z)}else if(Z.info.type==="subtitle"){let G=Z;Z.inputTrack=new p1(this.input,new g5(G)),this.tracks.push(Z)}}this.currentTrack=null}break;case"tkhd":{let Z=this.currentTrack;if(!Z)break;let G=y($),Q=!!(_1($)&1);if(Z.disposition.default=Q,G===0)$.skip(8),Z.id=P($),$.skip(4),Z.durationInMovieTimescale=P($);else if(G===1)$.skip(16),Z.id=P($),$.skip(4),Z.durationInMovieTimescale=O0($);else throw Error(`Incorrect track header version ${G}.`);$.skip(16);let q=[M1($),M1($),J2($),M1($),M1($),J2($),M1($),M1($),J2($)],U=N1(F8(a7(q),90));H(U===0||U===90||U===180||U===270),Z.rotation=U}break;case"elst":{let Z=this.currentTrack;if(!Z)break;let G=y($);$.skip(3);let K=!1,Q=0,q=P($);for(let U=0;U<q;U++){let W=G===1?O0($):P($),V=G===1?W5($):q1($),N=M1($);if(W===0)continue;if(K){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(V===-1){Q+=W;continue}if(N!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}Z.editListPreviousSegmentDurations=Q,Z.editListOffset=V,K=!0}}break;case"mdhd":{let Z=this.currentTrack;if(!Z)break;let G=y($);if($.skip(3),G===0)$.skip(8),Z.timescale=P($),Z.durationInMediaTimescale=P($);else if(G===1)$.skip(16),Z.timescale=P($),Z.durationInMediaTimescale=O0($);let K=X0($);if(K>0){Z.languageCode="";for(let Q=0;Q<3;Q++)Z.languageCode=String.fromCharCode(96+(K&31))+Z.languageCode,K>>=5;if(!d0(Z.languageCode))Z.languageCode=a}}break;case"hdlr":{let Z=this.currentTrack;if(!Z)break;$.skip(8);let G=s($,4);if(G==="vide")Z.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null};else if(G==="soun")Z.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null};else if(G==="text"||G==="subt"||G==="sbtl")Z.info={type:"subtitle",codec:null,codecPrivateText:null}}break;case"stbl":{let Z=this.currentTrack;if(!Z)break;Z.sampleTableByteOffset=J,this.readContiguousBoxes($.slice(j,Y.contentSize))}break;case"stsd":{let Z=this.currentTrack;if(!Z)break;if(Z.info===null||Z.sampleTable)break;let G=y($);$.skip(3);let K=P($);for(let Q=0;Q<K;Q++){let q=$.filePos,U=g0($);if(!U)break;Z.internalCodecId=U.name;let W=U.name.toLowerCase();if(Z.info.type==="video"){if(W==="avc1"||W==="avc3")Z.info.codec="avc",Z.info.avcType=W==="avc1"?1:3;else if(W==="hvc1"||W==="hev1")Z.info.codec="hevc";else if(W==="vp08")Z.info.codec="vp8";else if(W==="vp09")Z.info.codec="vp9";else if(W==="av01")Z.info.codec="av1";else if(W==="mp4v")Z.info.codec="mpeg4";else console.warn(`Unsupported video codec (sample entry type '${U.name}').`);$.skip(24),Z.info.width=X0($),Z.info.height=X0($),$.skip(50),this.readContiguousBoxes($.slice($.filePos,q+U.totalSize-$.filePos))}else if(Z.info.type==="subtitle"){$.skip(6);let V=X0($);if(W==="wvtt")Z.info.codec="webvtt";else if(W==="tx3g"||W==="text")Z.info.codec="tx3g";else if(W==="stpp")Z.info.codec="ttml";this.readContiguousBoxes($.slice($.filePos,q+U.totalSize-$.filePos))}else{if(W==="mp4a");else if(W==="opus")Z.info.codec="opus";else if(W==="flac")Z.info.codec="flac";else if(W==="twos"||W==="sowt"||W==="raw "||W==="in24"||W==="in32"||W==="fl32"||W==="fl64"||W==="lpcm"||W==="ipcm"||W==="fpcm");else if(W==="ulaw")Z.info.codec="ulaw";else if(W==="alaw")Z.info.codec="alaw";else if(W==="ac-3")Z.info.codec="ac3";else if(W==="ec-3")Z.info.codec="eac3";else console.warn(`Unsupported audio codec (sample entry type '${U.name}').`);$.skip(8);let V=X0($);$.skip(6);let N=X0($),A=X0($);$.skip(4);let R=P($)/65536;if(G===0&&V>0){if(V===1)$.skip(4),A=8*P($),$.skip(8);else if(V===2){$.skip(4),R=i6($),N=P($),$.skip(4),A=P($);let z=P($);if($.skip(8),W==="lpcm"){let _=A+7>>3,L=Boolean(z&1),M=Boolean(z&2),B=z&4?-1:0;if(A>0&&A<=64){if(L){if(A===32)Z.info.codec=M?"pcm-f32be":"pcm-f32"}else if(B&1<<_-1){if(_===1)Z.info.codec="pcm-s8";else if(_===2)Z.info.codec=M?"pcm-s16be":"pcm-s16";else if(_===3)Z.info.codec=M?"pcm-s24be":"pcm-s24";else if(_===4)Z.info.codec=M?"pcm-s32be":"pcm-s32"}else if(_===1)Z.info.codec="pcm-u8"}if(Z.info.codec===null)console.warn("Unsupported PCM format.")}}}if(Z.info.codec==="opus")R=b0;if(Z.info.numberOfChannels=N,Z.info.sampleRate=R,W==="twos")if(A===8)Z.info.codec="pcm-s8";else if(A===16)Z.info.codec="pcm-s16be";else console.warn(`Unsupported sample size ${A} for codec 'twos'.`),Z.info.codec=null;else if(W==="sowt")if(A===8)Z.info.codec="pcm-s8";else if(A===16)Z.info.codec="pcm-s16";else console.warn(`Unsupported sample size ${A} for codec 'sowt'.`),Z.info.codec=null;else if(W==="raw ")Z.info.codec="pcm-u8";else if(W==="in24")Z.info.codec="pcm-s24be";else if(W==="in32")Z.info.codec="pcm-s32be";else if(W==="fl32")Z.info.codec="pcm-f32be";else if(W==="fl64")Z.info.codec="pcm-f64be";else if(W==="ipcm")Z.info.codec="pcm-s16be";else if(W==="fpcm")Z.info.codec="pcm-f32be";this.readContiguousBoxes($.slice($.filePos,q+U.totalSize-$.filePos))}}}break;case"avcC":{let Z=this.currentTrack;if(!Z)break;if(H(Z.info),Z.info.type==="video")Z.info.codecDescription=D($,Y.contentSize)}break;case"hvcC":{let Z=this.currentTrack;if(!Z)break;if(H(Z.info),Z.info.type==="video")Z.info.codecDescription=D($,Y.contentSize)}break;case"vpcC":{let Z=this.currentTrack;if(!Z)break;H(Z.info?.type==="video"),$.skip(4);let G=y($),K=y($),Q=y($),q=Q>>4,U=Q>>1&7,W=Q&1,V=y($),N=y($),A=y($);Z.info.vp9CodecInfo={profile:G,level:K,bitDepth:q,chromaSubsampling:U,videoFullRangeFlag:W,colourPrimaries:V,transferCharacteristics:N,matrixCoefficients:A}}break;case"av1C":{let Z=this.currentTrack;if(!Z)break;H(Z.info?.type==="video"),$.skip(1);let G=y($),K=G>>5,Q=G&31,q=y($),U=q>>7,W=q>>6&1,V=q>>5&1,N=q>>4&1,A=q>>3&1,R=q>>2&1,z=q&3,_=K===2&&W?V?12:10:W?10:8;Z.info.av1CodecInfo={profile:K,level:Q,tier:U,bitDepth:_,monochrome:N,chromaSubsamplingX:A,chromaSubsamplingY:R,chromaSamplePosition:z}}break;case"colr":{let Z=this.currentTrack;if(!Z)break;if(H(Z.info?.type==="video"),s($,4)!=="nclx")break;let K=X0($),Q=X0($),q=X0($),U=Boolean(y($)&128);Z.info.colorSpace={primaries:X6[K],transfer:Z6[Q],matrix:G6[q],fullRange:U}}break;case"wave":this.readContiguousBoxes($.slice(j,Y.contentSize));break;case"esds":{let Z=this.currentTrack;if(!Z)break;if(Z.info?.type!=="audio"&&Z.info?.type!=="video")break;$.skip(4);let G=y($);H(G===3),Y2($),$.skip(2);let K=y($),Q=(K&128)!==0,q=(K&64)!==0,U=(K&32)!==0;if(Q)$.skip(2);if(q){let R=y($);$.skip(R)}if(U)$.skip(2);let W=y($);H(W===4);let V=Y2($),N=$.filePos,A=y($);if(Z.info.type==="audio")if(A===64||A===103)Z.info.codec="aac",Z.info.aacCodecInfo={isMpeg2:A===103};else if(A===105||A===107)Z.info.codec="mp3";else if(A===221)Z.info.codec="vorbis";else console.warn(`Unsupported audio codec (objectTypeIndication ${A}) - discarding track.`);else if(Z.info.type==="video"){if(A===32)Z.info.codec="mpeg4"}if($.skip(12),V>$.filePos-N){let R=y($);H(R===5);let z=Y2($);if(Z.info.codecDescription=D($,z),Z.info.type==="audio"&&Z.info.codec==="aac"){let _=x1(Z.info.codecDescription);if(_.numberOfChannels!==null)Z.info.numberOfChannels=_.numberOfChannels;if(_.sampleRate!==null)Z.info.sampleRate=_.sampleRate}}}break;case"enda":{let Z=this.currentTrack;if(!Z)break;if(H(Z.info?.type==="audio"),X0($)&255){if(Z.info.codec==="pcm-s16be")Z.info.codec="pcm-s16";else if(Z.info.codec==="pcm-s24be")Z.info.codec="pcm-s24";else if(Z.info.codec==="pcm-s32be")Z.info.codec="pcm-s32";else if(Z.info.codec==="pcm-f32be")Z.info.codec="pcm-f32";else if(Z.info.codec==="pcm-f64be")Z.info.codec="pcm-f64"}}break;case"pcmC":{let Z=this.currentTrack;if(!Z)break;H(Z.info?.type==="audio"),$.skip(4);let G=y($),K=Boolean(G&1),Q=y($);if(Z.info.codec==="pcm-s16be")if(K)if(Q===16)Z.info.codec="pcm-s16";else if(Q===24)Z.info.codec="pcm-s24";else if(Q===32)Z.info.codec="pcm-s32";else console.warn(`Invalid ipcm sample size ${Q}.`),Z.info.codec=null;else if(Q===16)Z.info.codec="pcm-s16be";else if(Q===24)Z.info.codec="pcm-s24be";else if(Q===32)Z.info.codec="pcm-s32be";else console.warn(`Invalid ipcm sample size ${Q}.`),Z.info.codec=null;else if(Z.info.codec==="pcm-f32be")if(K)if(Q===32)Z.info.codec="pcm-f32";else if(Q===64)Z.info.codec="pcm-f64";else console.warn(`Invalid fpcm sample size ${Q}.`),Z.info.codec=null;else if(Q===32)Z.info.codec="pcm-f32be";else if(Q===64)Z.info.codec="pcm-f64be";else console.warn(`Invalid fpcm sample size ${Q}.`),Z.info.codec=null;break}case"dOps":{let Z=this.currentTrack;if(!Z)break;H(Z.info?.type==="audio"),$.skip(1);let G=y($),K=X0($),Q=P($),q=f8($),U=y($),W;if(U!==0)W=D($,2+G);else W=new Uint8Array(0);let V=new Uint8Array(19+W.byteLength),N=new DataView(V.buffer);N.setUint32(0,1332770163,!1),N.setUint32(4,1214603620,!1),N.setUint8(8,1),N.setUint8(9,G),N.setUint16(10,K,!0),N.setUint32(12,Q,!0),N.setInt16(16,q,!0),N.setUint8(18,U),V.set(W,19),Z.info.codecDescription=V,Z.info.numberOfChannels=G}break;case"dfLa":{let Z=this.currentTrack;if(!Z)break;H(Z.info?.type==="audio"),$.skip(4);let G=127,K=128,Q=$.filePos;while($.filePos<X){let N=y($),A=_1($);if((N&G)===0){$.skip(10);let z=P($),_=z>>>12,L=(z>>9&7)+1;Z.info.sampleRate=_,Z.info.numberOfChannels=L,$.skip(20)}else $.skip(A);if(N&K)break}let q=$.filePos;$.filePos=Q;let U=D($,q-Q),W=new Uint8Array(4+U.byteLength);new DataView(W.buffer).setUint32(0,1716281667,!1),W.set(U,4),Z.info.codecDescription=W}break;case"stts":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let G=P($),K=0,Q=0;for(let q=0;q<G;q++){let U=P($),W=P($);Z.sampleTable.sampleTimingEntries.push({startIndex:K,startDecodeTimestamp:Q,count:U,delta:W}),K+=U,Q+=U*W}}break;case"ctts":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let G=P($),K=0;for(let Q=0;Q<G;Q++){let q=P($),U=q1($);Z.sampleTable.sampleCompositionTimeOffsets.push({startIndex:K,count:q,offset:U}),K+=q}}break;case"stsz":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let G=P($),K=P($);if(G===0)for(let Q=0;Q<K;Q++){let q=P($);Z.sampleTable.sampleSizes.push(q)}else Z.sampleTable.sampleSizes.push(G)}break;case"stz2":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4),$.skip(3);let G=y($),K=P($),Q=D($,Math.ceil(K*G/8)),q=new f(Q);for(let U=0;U<K;U++){let W=q.readBits(G);Z.sampleTable.sampleSizes.push(W)}}break;case"stss":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4),Z.sampleTable.keySampleIndices=[];let G=P($);for(let K=0;K<G;K++){let Q=P($)-1;Z.sampleTable.keySampleIndices.push(Q)}if(Z.sampleTable.keySampleIndices[0]!==0)Z.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let G=P($);for(let Q=0;Q<G;Q++){let q=P($)-1,U=P($),W=P($);Z.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:q,samplesPerChunk:U,sampleDescriptionIndex:W})}let K=0;for(let Q=0;Q<Z.sampleTable.sampleToChunk.length;Q++)if(Z.sampleTable.sampleToChunk[Q].startSampleIndex=K,Q<Z.sampleTable.sampleToChunk.length-1){let U=Z.sampleTable.sampleToChunk[Q+1].startChunkIndex-Z.sampleTable.sampleToChunk[Q].startChunkIndex;K+=U*Z.sampleTable.sampleToChunk[Q].samplesPerChunk}}break;case"stco":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let G=P($);for(let K=0;K<G;K++){let Q=P($);Z.sampleTable.chunkOffsets.push(Q)}}break;case"co64":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let G=P($);for(let K=0;K<G;K++){let Q=O0($);Z.sampleTable.chunkOffsets.push(Q)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes($.slice(j,Y.contentSize));break;case"mehd":{let Z=y($);$.skip(3);let G=Z===1?O0($):P($);this.movieDurationInTimescale=G}break;case"trex":{$.skip(4);let Z=P($),G=P($),K=P($),Q=P($),q=P($);this.fragmentTrackDefaults.push({trackId:Z,defaultSampleDescriptionIndex:G,defaultSampleDuration:K,defaultSampleSize:Q,defaultSampleFlags:q})}break;case"tfra":{let Z=y($);$.skip(3);let G=P($),K=this.tracks.find((_)=>_.id===G);if(!K)break;let Q=P($),q=(Q&48)>>4,U=(Q&12)>>2,W=Q&3,V=[y,X0,_1,P],N=V[q],A=V[U],R=V[W],z=P($);for(let _=0;_<z;_++){let L=Z===1?O0($):P($),M=Z===1?O0($):P($);N($),A($),R($),K.fragmentLookupTable.push({timestamp:L,moofOffset:M})}K.fragmentLookupTable.sort((_,L)=>_.timestamp-L.timestamp);for(let _=0;_<K.fragmentLookupTable.length-1;_++){let L=K.fragmentLookupTable[_],M=K.fragmentLookupTable[_+1];if(L.timestamp===M.timestamp)K.fragmentLookupTable.splice(_+1,1),_--}}break;case"moof":this.currentFragment={moofOffset:J,moofSize:Y.totalSize,implicitBaseDataOffset:J,trackData:new Map},this.readContiguousBoxes($.slice(j,Y.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(H(this.currentFragment),this.readContiguousBoxes($.slice(j,Y.contentSize)),this.currentTrack){let Z=this.currentFragment.trackData.get(this.currentTrack.id);if(Z){let{currentFragmentState:G}=this.currentTrack;if(H(G),G.startTimestamp!==null)W$(Z,G.startTimestamp),Z.startTimestampIsFinal=!0}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{H(this.currentFragment),$.skip(1);let Z=_1($),G=Boolean(Z&1),K=Boolean(Z&2),Q=Boolean(Z&8),q=Boolean(Z&16),U=Boolean(Z&32),W=Boolean(Z&65536),V=Boolean(Z&131072),N=P($),A=this.tracks.find((z)=>z.id===N);if(!A)break;let R=this.fragmentTrackDefaults.find((z)=>z.trackId===N);if(this.currentTrack=A,A.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:R?.defaultSampleDescriptionIndex??null,defaultSampleDuration:R?.defaultSampleDuration??null,defaultSampleSize:R?.defaultSampleSize??null,defaultSampleFlags:R?.defaultSampleFlags??null,startTimestamp:null},G)A.currentFragmentState.baseDataOffset=O0($);else if(V)A.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset;if(K)A.currentFragmentState.sampleDescriptionIndex=P($);if(Q)A.currentFragmentState.defaultSampleDuration=P($);if(q)A.currentFragmentState.defaultSampleSize=P($);if(U)A.currentFragmentState.defaultSampleFlags=P($);if(W)A.currentFragmentState.defaultSampleDuration=0}break;case"tfdt":{let Z=this.currentTrack;if(!Z)break;H(Z.currentFragmentState);let G=y($);$.skip(3);let K=G===0?P($):O0($);Z.currentFragmentState.startTimestamp=K}break;case"trun":{let Z=this.currentTrack;if(!Z)break;if(H(this.currentFragment),H(Z.currentFragmentState),this.currentFragment.trackData.has(Z.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}let G=y($),K=_1($),Q=Boolean(K&1),q=Boolean(K&4),U=Boolean(K&256),W=Boolean(K&512),V=Boolean(K&1024),N=Boolean(K&2048),A=P($),R=Z.currentFragmentState.baseDataOffset;if(Q)R+=q1($);let z=null;if(q)z=P($);let _=R;if(A===0){this.currentFragment.implicitBaseDataOffset=_;break}let L=0,M={track:Z,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(Z.id,M);for(let C=0;C<A;C++){let w;if(U)w=P($);else H(Z.currentFragmentState.defaultSampleDuration!==null),w=Z.currentFragmentState.defaultSampleDuration;let v;if(W)v=P($);else H(Z.currentFragmentState.defaultSampleSize!==null),v=Z.currentFragmentState.defaultSampleSize;let k;if(V)k=P($);else H(Z.currentFragmentState.defaultSampleFlags!==null),k=Z.currentFragmentState.defaultSampleFlags;if(C===0&&z!==null)k=z;let S=0;if(N)if(G===0)S=P($);else S=q1($);let T=!(k&65536);M.samples.push({presentationTimestamp:L+S,duration:w,byteOffset:_,byteSize:v,isKeyFrame:T}),_+=v,L+=w}M.presentationTimestamps=M.samples.map((C,w)=>({presentationTimestamp:C.presentationTimestamp,sampleIndex:w})).sort((C,w)=>C.presentationTimestamp-w.presentationTimestamp);for(let C=0;C<M.presentationTimestamps.length;C++){let w=M.presentationTimestamps[C],v=M.samples[w.sampleIndex];if(M.firstKeyFrameTimestamp===null&&v.isKeyFrame)M.firstKeyFrameTimestamp=v.presentationTimestamp;if(C<M.presentationTimestamps.length-1){let k=M.presentationTimestamps[C+1];v.duration=k.presentationTimestamp-w.presentationTimestamp}}let B=M.samples[M.presentationTimestamps[0].sampleIndex],F=M.samples[n(M.presentationTimestamps).sampleIndex];M.startTimestamp=B.presentationTimestamp,M.endTimestamp=F.presentationTimestamp+F.duration,this.currentFragment.implicitBaseDataOffset=_}break;case"udta":{let Z=this.iterateContiguousBoxes($.slice(j,Y.contentSize));for(let{boxInfo:G,slice:K}of Z){if(G.name!=="meta"&&!this.currentTrack){let Q=K.filePos;if(this.metadataTags.raw??={},G.name[0]==="©")this.metadataTags.raw[G.name]??=k0(K);else this.metadataTags.raw[G.name]??=D(K,G.contentSize);K.filePos=Q}switch(G.name){case"meta":K.skip(-G.headerSize),this.traverseBox(K);break;case"©nam":case"name":if(this.currentTrack)this.currentTrack.name=Y0.decode(D(K,G.contentSize));else this.metadataTags.title??=k0(K);break;case"©des":if(!this.currentTrack)this.metadataTags.description??=k0(K);break;case"©ART":if(!this.currentTrack)this.metadataTags.artist??=k0(K);break;case"©alb":if(!this.currentTrack)this.metadataTags.album??=k0(K);break;case"albr":if(!this.currentTrack)this.metadataTags.albumArtist??=k0(K);break;case"©gen":if(!this.currentTrack)this.metadataTags.genre??=k0(K);break;case"©day":if(!this.currentTrack){let Q=new Date(k0(K));if(!Number.isNaN(Q.getTime()))this.metadataTags.date??=Q}break;case"©cmt":if(!this.currentTrack)this.metadataTags.comment??=k0(K);break;case"©lyr":if(!this.currentTrack)this.metadataTags.lyrics??=k0(K);break}}}break;case"meta":{if(this.currentTrack)break;let G=P($)!==0;if(this.currentMetadataKeys=new Map,G)this.readContiguousBoxes($.slice(j,Y.contentSize));else this.readContiguousBoxes($.slice(j+4,Y.contentSize-4));this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;$.skip(4);let Z=P($);for(let G=0;G<Z;G++){let K=P($);$.skip(4);let Q=Y0.decode(D($,K-8));this.currentMetadataKeys.set(G+1,Q)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let Z=this.iterateContiguousBoxes($.slice(j,Y.contentSize));for(let{boxInfo:G,slice:K}of Z){let Q=G.name,q=(Q.charCodeAt(0)<<24)+(Q.charCodeAt(1)<<16)+(Q.charCodeAt(2)<<8)+Q.charCodeAt(3);if(this.currentMetadataKeys.has(q))Q=this.currentMetadataKeys.get(q);let U=I5(K);switch(this.metadataTags.raw??={},this.metadataTags.raw[Q]??=U,Q){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":if(typeof U==="string")this.metadataTags.title??=U;break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":if(typeof U==="string")this.metadataTags.description??=U;break;case"©ART":case"com.apple.quicktime.artist":case"artist":if(typeof U==="string")this.metadataTags.artist??=U;break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":if(typeof U==="string")this.metadataTags.album??=U;break;case"aART":case"album_artist":if(typeof U==="string")this.metadataTags.albumArtist??=U;break;case"©cmt":case"com.apple.quicktime.comment":case"comment":if(typeof U==="string")this.metadataTags.comment??=U;break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":if(typeof U==="string")this.metadataTags.genre??=U;break;case"©lyr":case"lyrics":if(typeof U==="string")this.metadataTags.lyrics??=U;break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof U==="string"){let W=new Date(U);if(!Number.isNaN(W.getTime()))this.metadataTags.date??=W}break;case"covr":case"com.apple.quicktime.artwork":if(U instanceof I0)this.metadataTags.images??=[],this.metadataTags.images.push({data:U.data,kind:"coverFront",mimeType:U.mimeType});else if(U instanceof Uint8Array)this.metadataTags.images??=[],this.metadataTags.images.push({data:U,kind:"coverFront",mimeType:"image/*"});break;case"track":if(typeof U==="string"){let W=U.split("/"),V=Number.parseInt(W[0],10),N=W[1]&&Number.parseInt(W[1],10);if(Number.isInteger(V)&&V>0)this.metadataTags.trackNumber??=V;if(N&&Number.isInteger(N)&&N>0)this.metadataTags.tracksTotal??=N}break;case"trkn":if(U instanceof Uint8Array&&U.length>=6){let W=h(U),V=W.getUint16(2,!1),N=W.getUint16(4,!1);if(V>0)this.metadataTags.trackNumber??=V;if(N>0)this.metadataTags.tracksTotal??=N}break;case"disc":case"disk":if(U instanceof Uint8Array&&U.length>=6){let W=h(U),V=W.getUint16(2,!1),N=W.getUint16(4,!1);if(V>0)this.metadataTags.discNumber??=V;if(N>0)this.metadataTags.discsTotal??=N}break}}}break}return $.filePos=X,!0}}class j2{internalTrack;packetToSampleIndex=new WeakMap;packetToFragmentLocation=new WeakMap;constructor($){this.internalTrack=$}getId(){return this.internalTrack.id}getCodec(){throw Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){let $=await this.getPacket(Number.POSITIVE_INFINITY,{metadataOnly:!0});return($?.timestamp??0)+($?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket($){let J=await this.fetchPacketForSampleIndex(0,$);if(J||!this.internalTrack.demuxer.isFragmented)return J;return this.performFragmentedLookup(null,(Y)=>{if(Y.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,$)}mapTimestampIntoTimescale($){return y1($*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket($,J){let Y=this.mapTimestampIntoTimescale($),j=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),X=V$(j,Y),Z=await this.fetchPacketForSampleIndex(X,J);if(!S5(j)||!this.internalTrack.demuxer.isFragmented)return Z;return this.performFragmentedLookup(null,(G)=>{let K=G.trackData.get(this.internalTrack.id);if(!K)return{sampleIndex:-1,correctSampleFound:!1};let Q=u(K.presentationTimestamps,Y,(W)=>W.presentationTimestamp),q=Q!==-1?K.presentationTimestamps[Q].sampleIndex:-1,U=Q!==-1&&Y<K.endTimestamp;return{sampleIndex:q,correctSampleFound:U}},Y,Y,J)}async getNextPacket($,J){let Y=this.packetToSampleIndex.get($);if(Y!==void 0)return this.fetchPacketForSampleIndex(Y+1,J);let j=this.packetToFragmentLocation.get($);if(j===void 0)throw Error("Packet was not created from this track.");return this.performFragmentedLookup(j.fragment,(X)=>{if(X===j.fragment){let Z=X.trackData.get(this.internalTrack.id);if(j.sampleIndex+1<Z.samples.length)return{sampleIndex:j.sampleIndex+1,correctSampleFound:!0}}else if(X.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,J)}async getKeyPacket($,J){let Y=this.mapTimestampIntoTimescale($),j=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),X=r7(j,Y),Z=await this.fetchPacketForSampleIndex(X,J);if(!S5(j)||!this.internalTrack.demuxer.isFragmented)return Z;return this.performFragmentedLookup(null,(G)=>{let K=G.trackData.get(this.internalTrack.id);if(!K)return{sampleIndex:-1,correctSampleFound:!1};let Q=Q6(K.presentationTimestamps,(W)=>{return K.samples[W.sampleIndex].isKeyFrame&&W.presentationTimestamp<=Y}),q=Q!==-1?K.presentationTimestamps[Q].sampleIndex:-1,U=Q!==-1&&Y<K.endTimestamp;return{sampleIndex:q,correctSampleFound:U}},Y,Y,J)}async getNextKeyPacket($,J){let Y=this.packetToSampleIndex.get($);if(Y!==void 0){let X=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),Z=s7(X,Y);return this.fetchPacketForSampleIndex(Z,J)}let j=this.packetToFragmentLocation.get($);if(j===void 0)throw Error("Packet was not created from this track.");return this.performFragmentedLookup(j.fragment,(X)=>{if(X===j.fragment){let G=X.trackData.get(this.internalTrack.id).samples.findIndex((K,Q)=>K.isKeyFrame&&Q>j.sampleIndex);if(G!==-1)return{sampleIndex:G,correctSampleFound:!0}}else{let Z=X.trackData.get(this.internalTrack.id);if(Z&&Z.firstKeyFrameTimestamp!==null){let G=Z.samples.findIndex((K)=>K.isKeyFrame);return H(G!==-1),{sampleIndex:G,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY,J)}async fetchPacketForSampleIndex($,J){if($===-1)return null;let Y=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),j=i7(Y,$);if(!j)return null;let X;if(J.metadataOnly)X=G0;else{let Q=this.internalTrack.demuxer.reader.requestSlice(j.sampleOffset,j.sampleSize);if(Q instanceof Promise)Q=await Q;H(Q),X=D(Q,j.sampleSize)}let Z=(j.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,G=j.duration/this.internalTrack.timescale,K=new I(X,j.isKeyFrame?"key":"delta",Z,G,$,j.sampleSize);return this.packetToSampleIndex.set(K,$),K}async fetchPacketInFragment($,J,Y){if(J===-1)return null;let X=$.trackData.get(this.internalTrack.id).samples[J];H(X);let Z;if(Y.metadataOnly)Z=G0;else{let q=this.internalTrack.demuxer.reader.requestSlice(X.byteOffset,X.byteSize);if(q instanceof Promise)q=await q;H(q),Z=D(q,X.byteSize)}let G=(X.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,K=X.duration/this.internalTrack.timescale,Q=new I(Z,X.isKeyFrame?"key":"delta",G,K,$.moofOffset+J,X.byteSize);return this.packetToFragmentLocation.set(Q,{fragment:$,sampleIndex:J}),Q}async performFragmentedLookup($,J,Y,j,X){let Z=this.internalTrack.demuxer,G=null,K=null,Q=-1;if($){let{sampleIndex:R,correctSampleFound:z}=J($);if(z)return this.fetchPacketInFragment($,R,X);if(R!==-1)K=$,Q=R}let q=u(this.internalTrack.fragmentLookupTable,Y,(R)=>R.timestamp),U=q!==-1?this.internalTrack.fragmentLookupTable[q]:null,W=u(this.internalTrack.fragmentPositionCache,Y,(R)=>R.startTimestamp),V=W!==-1?this.internalTrack.fragmentPositionCache[W]:null,N=Math.max(U?.moofOffset??0,V?.moofOffset??0)||null,A;if(!$)A=N??0;else if(N===null||$.moofOffset>=N)A=$.moofOffset+$.moofSize,G=$;else A=N;while(!0){if(G){let L=G.trackData.get(this.internalTrack.id);if(L&&L.startTimestamp>j)break}let R=Z.reader.requestSliceRange(A,f0,U1);if(R instanceof Promise)R=await R;if(!R)break;let z=A,_=g0(R);if(!_)break;if(_.name==="moof"){G=await Z.readFragment(z);let{sampleIndex:L,correctSampleFound:M}=J(G);if(M)return this.fetchPacketInFragment(G,L,X);if(L!==-1)K=G,Q=L}A=z+_.totalSize}if(U&&(!K||K.moofOffset<U.moofOffset)){let R=this.internalTrack.fragmentLookupTable[q-1];H(!R||R.timestamp<U.timestamp);let z=R?.timestamp??Number.NEGATIVE_INFINITY;return this.performFragmentedLookup(null,J,z,j,X)}if(K)return this.fetchPacketInFragment(K,Q,X);return null}}class h5 extends j2{internalTrack;decoderConfigPromise=null;constructor($){super($);this.internalTrack=$}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let $=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=$&&x6($.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let $=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=$&&I6($.data)}return{codec:V6(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??void 0}})()}}class f5 extends j2{internalTrack;decoderConfig=null;constructor($){super($);this.internalTrack=$}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfig??={codec:H6(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}}}class g5 extends j2{internalTrack;constructor($){super($);this.internalTrack=$}getCodec(){return this.internalTrack.info.codec}getCodecPrivate(){return this.internalTrack.info.codecPrivateText}async*getCues(){let $=await this.getFirstPacket({});while($){let J="";if(this.internalTrack.info.codec==="webvtt"){let Y=new Uint8Array($.data),j=new S0(Y,new DataView(Y.buffer,Y.byteOffset,Y.byteLength),0,0,Y.length);while(j.remainingLength>0){let X=g0(j);if(!X)break;if(X.name==="vttc"){let Z=j.filePos+X.contentSize;while(j.filePos<Z&&j.remainingLength>0){let G=g0(j);if(!G)break;if(G.name==="payl"){let K=D(j,G.contentSize),Q=new TextDecoder("utf-8");J+=Q.decode(K)}else j.skip(G.contentSize)}}else if(X.name==="vtte")j.skip(X.contentSize);else j.skip(X.contentSize)}}else J=new TextDecoder("utf-8").decode($.data);if(J)yield{timestamp:$.timestamp,duration:$.duration,text:J};$=await this.getNextPacket($,{})}}}var V$=($,J)=>{if($.presentationTimestamps){let X=u($.presentationTimestamps,J,(Z)=>Z.presentationTimestamp);if(X===-1)return-1;return $.presentationTimestamps[X].sampleIndex}let Y=u($.sampleTimingEntries,J,(X)=>X.startDecodeTimestamp);if(Y===-1)return-1;let j=$.sampleTimingEntries[Y];return j.startIndex+Math.min(Math.floor((J-j.startDecodeTimestamp)/j.delta),j.count-1)},r7=($,J)=>{if(!$.keySampleIndices)return V$($,J);if($.presentationTimestamps){let Y=u($.presentationTimestamps,J,(j)=>j.presentationTimestamp);if(Y===-1)return-1;for(let j=Y;j>=0;j--){let X=$.presentationTimestamps[j].sampleIndex;if(Y1($.keySampleIndices,X,(G)=>G)!==-1)return X}return-1}else{let Y=V$($,J),j=u($.keySampleIndices,Y,(X)=>X);return $.keySampleIndices[j]??-1}},i7=($,J)=>{let Y=u($.sampleTimingEntries,J,(_)=>_.startIndex),j=$.sampleTimingEntries[Y];if(!j||j.startIndex+j.count<=J)return null;let Z=j.startDecodeTimestamp+(J-j.startIndex)*j.delta,G=u($.sampleCompositionTimeOffsets,J,(_)=>_.startIndex),K=$.sampleCompositionTimeOffsets[G];if(K&&J-K.startIndex<K.count)Z+=K.offset;let Q=$.sampleSizes[Math.min(J,$.sampleSizes.length-1)],q=u($.sampleToChunk,J,(_)=>_.startSampleIndex),U=$.sampleToChunk[q];H(U);let W=U.startChunkIndex+Math.floor((J-U.startSampleIndex)/U.samplesPerChunk),V=$.chunkOffsets[W],N=U.startSampleIndex+(W-U.startChunkIndex)*U.samplesPerChunk,A=0,R=V;if($.sampleSizes.length===1)R+=Q*(J-N),A+=Q*U.samplesPerChunk;else for(let _=N;_<N+U.samplesPerChunk;_++){let L=$.sampleSizes[_];if(_<J)R+=L;A+=L}let z=j.delta;if($.presentationTimestamps){let _=$.presentationTimestampIndexMap[J];if(H(_!==void 0),_<$.presentationTimestamps.length-1)z=$.presentationTimestamps[_+1].presentationTimestamp-Z}return{presentationTimestamp:Z,duration:z,sampleOffset:R,sampleSize:Q,chunkOffset:V,chunkSize:A,isKeyFrame:$.keySampleIndices?Y1($.keySampleIndices,J,(_)=>_)!==-1:!0}},s7=($,J)=>{if(!$.keySampleIndices)return J+1;let Y=u($.keySampleIndices,J,(j)=>j);return $.keySampleIndices[Y+1]??-1},W$=($,J)=>{$.startTimestamp+=J,$.endTimestamp+=J;for(let Y of $.samples)Y.presentationTimestamp+=J;for(let Y of $.presentationTimestamps)Y.presentationTimestamp+=J},a7=($)=>{let[J,,,Y]=$,j=Math.hypot(J,Y),X=J/j,Z=Y/j,G=-Math.atan2(Z,X)*(180/Math.PI);if(!Number.isFinite(G))return 0;return G},S5=($)=>{return $.sampleSizes.length===0};/*!
224
224
  * Copyright (c) 2025-present, Vanilagy and contributors
225
225
  *
226
226
  * This Source Code Form is subject to the terms of the Mozilla Public
227
227
  * License, v. 2.0. If a copy of the MPL was not distributed with this
228
228
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
229
- */class l8{value;constructor($){this.value=$}}class m8{value;constructor($){this.value=$}}class X2{value;constructor($){this.value=$}}class r0{value;constructor($){this.value=$}}var e7=[440786851,408125543],V8=[290298740,357149030,524531317,374648427,475249515,423732329,272869232,307544935],d8=[...e7,...V8],k5=($)=>{if($<256)return 1;if($<65536)return 2;if($<16777216)return 3;if($<4294967296)return 4;if($<1099511627776)return 5;return 6},u5=($)=>{if($<1n<<8n)return 1;if($<1n<<16n)return 2;if($<1n<<24n)return 3;if($<1n<<32n)return 4;if($<1n<<40n)return 5;if($<1n<<48n)return 6;if($<1n<<56n)return 7;return 8},p5=($)=>{if($>=-64&&$<64)return 1;if($>=-8192&&$<8192)return 2;if($>=-1048576&&$<1048576)return 3;if($>=-134217728&&$<134217728)return 4;if($>=-17179869184&&$<17179869184)return 5;return 6},$j=($)=>{if($<127)return 1;if($<16383)return 2;if($<2097151)return 3;if($<268435455)return 4;if($<34359738367)return 5;if($<4398046511103)return 6;throw Error("EBML varint size not supported "+$)};class A${writer;helper=new Uint8Array(8);helperView=new DataView(this.helper.buffer);offsets=new WeakMap;dataOffsets=new WeakMap;constructor($){this.writer=$}writeByte($){this.helperView.setUint8(0,$),this.writer.write(this.helper.subarray(0,1))}writeFloat32($){this.helperView.setFloat32(0,$,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64($){this.helperView.setFloat64(0,$,!1),this.writer.write(this.helper)}writeUnsignedInt($,J=k5($)){let Y=0;switch(J){case 6:this.helperView.setUint8(Y++,$/1099511627776|0);case 5:this.helperView.setUint8(Y++,$/4294967296|0);case 4:this.helperView.setUint8(Y++,$>>24);case 3:this.helperView.setUint8(Y++,$>>16);case 2:this.helperView.setUint8(Y++,$>>8);case 1:this.helperView.setUint8(Y++,$);break;default:throw Error("Bad unsigned int size "+J)}this.writer.write(this.helper.subarray(0,Y))}writeUnsignedBigInt($,J=u5($)){let Y=0;for(let j=J-1;j>=0;j--)this.helperView.setUint8(Y++,Number($>>BigInt(j*8)&0xffn));this.writer.write(this.helper.subarray(0,Y))}writeSignedInt($,J=p5($)){if($<0)$+=2**(J*8);this.writeUnsignedInt($,J)}writeVarInt($,J=$j($)){let Y=0;switch(J){case 1:this.helperView.setUint8(Y++,128|$);break;case 2:this.helperView.setUint8(Y++,64|$>>8),this.helperView.setUint8(Y++,$);break;case 3:this.helperView.setUint8(Y++,32|$>>16),this.helperView.setUint8(Y++,$>>8),this.helperView.setUint8(Y++,$);break;case 4:this.helperView.setUint8(Y++,16|$>>24),this.helperView.setUint8(Y++,$>>16),this.helperView.setUint8(Y++,$>>8),this.helperView.setUint8(Y++,$);break;case 5:this.helperView.setUint8(Y++,8|$/4294967296&7),this.helperView.setUint8(Y++,$>>24),this.helperView.setUint8(Y++,$>>16),this.helperView.setUint8(Y++,$>>8),this.helperView.setUint8(Y++,$);break;case 6:this.helperView.setUint8(Y++,4|$/1099511627776&3),this.helperView.setUint8(Y++,$/4294967296|0),this.helperView.setUint8(Y++,$>>24),this.helperView.setUint8(Y++,$>>16),this.helperView.setUint8(Y++,$>>8),this.helperView.setUint8(Y++,$);break;default:throw Error("Bad EBML varint size "+J)}this.writer.write(this.helper.subarray(0,Y))}writeAsciiString($){this.writer.write(new Uint8Array($.split("").map((J)=>J.charCodeAt(0))))}writeEBML($){if($===null)return;if($ instanceof Uint8Array)this.writer.write($);else if(Array.isArray($))for(let J of $)this.writeEBML(J);else if(this.offsets.set($,this.writer.getPos()),this.writeUnsignedInt($.id),Array.isArray($.data)){let J=this.writer.getPos(),Y=$.size===-1?1:$.size??4;if($.size===-1)this.writeByte(255);else this.writer.seek(this.writer.getPos()+Y);let j=this.writer.getPos();if(this.dataOffsets.set($,j),this.writeEBML($.data),$.size!==-1){let X=this.writer.getPos()-j,Z=this.writer.getPos();this.writer.seek(J),this.writeVarInt(X,Y),this.writer.seek(Z)}}else if(typeof $.data==="number"){let J=$.size??k5($.data);this.writeVarInt(J),this.writeUnsignedInt($.data,J)}else if(typeof $.data==="bigint"){let J=$.size??u5($.data);this.writeVarInt(J),this.writeUnsignedBigInt($.data,J)}else if(typeof $.data==="string")this.writeVarInt($.data.length),this.writeAsciiString($.data);else if($.data instanceof Uint8Array)this.writeVarInt($.data.byteLength,$.size),this.writer.write($.data);else if($.data instanceof l8)this.writeVarInt(4),this.writeFloat32($.data.value);else if($.data instanceof m8)this.writeVarInt(8),this.writeFloat64($.data.value);else if($.data instanceof X2){let J=$.size??p5($.data.value);this.writeVarInt(J),this.writeSignedInt($.data.value,J)}else if($.data instanceof r0){let J=m.encode($.data.value);this.writeVarInt(J.length),this.writer.write(J)}else i($.data)}}var N$=8,P0=2,u0=2*N$,R$=($)=>{let J=y($);if($.skip(-1),J===0)return null;let Y=1,j=128;while((J&j)===0)Y++,j>>=1;return Y},H8=($)=>{let J=y($);if(J===0)return null;let Y=1,j=128;while((J&j)===0)Y++,j>>=1;let X=J&j-1;for(let Z=1;Z<Y;Z++)X*=256,X+=y($);return X},g=($,J)=>{if(J<1||J>8)throw Error("Bad unsigned int size "+J);let Y=0;for(let j=0;j<J;j++)Y*=256,Y+=y($);return Y},l5=($,J)=>{if(J<1)throw Error("Bad unsigned int size "+J);let Y=0n;for(let j=0;j<J;j++)Y<<=8n,Y+=BigInt(y($));return Y};var Z2=($)=>{let J=R$($);if(J===null)return null;return g($,J)},z$=($)=>{let J=y($);if(J===255)J=null;else if($.skip(-1),J=H8($),J===72057594037927940)J=null;return J},p0=($)=>{let J=Z2($);if(J===null)return null;let Y=z$($);return{id:J,size:Y}},F1=($,J)=>{let Y=D($,J),j=0;while(j<J&&Y[j]!==0)j+=1;return String.fromCharCode(...Y.subarray(0,j))},N8=($,J)=>{let Y=D($,J),j=0;while(j<J&&Y[j]!==0)j+=1;return Y0.decode(Y.subarray(0,j))},G2=($,J)=>{if(J===0)return 0;if(J!==4&&J!==8)throw Error("Bad float size "+J);return J===4?H5($):i6($)},K2=async($,J,Y,j)=>{let X=new Set(Y),Z=J;while(j===null||Z<j){let G=$.requestSliceRange(Z,P0,u0);if(G instanceof Promise)G=await G;if(!G)break;let K=p0(G);if(!K)break;if(X.has(K.id))return{pos:Z,found:!0};W1(K.size),Z=G.filePos+K.size}return{pos:j!==null&&j>Z?j:Z,found:!1}},_$=async($,J,Y,j)=>{let Z=new Set(Y),G=J;while(G<j){let K=$.requestSliceRange(G,0,Math.min(65536,j-G));if(K instanceof Promise)K=await K;if(!K)break;if(K.length<N$)break;for(let Q=0;Q<K.length-N$;Q++){K.filePos=G;let q=Z2(K);if(q!==null&&Z.has(q))return G;G++}}return null},A0={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",mpeg4:"V_MPEG4/ISO/ASP",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT",srt:"S_TEXT/UTF8",ass:"S_TEXT/ASS",ssa:"S_TEXT/SSA"};function W1($){if($===null)throw Error("Undefined element size is used in a place where it is not supported.")}/*!
229
+ */class l8{value;constructor($){this.value=$}}class m8{value;constructor($){this.value=$}}class X2{value;constructor($){this.value=$}}class r0{value;constructor($){this.value=$}}var t7=[440786851,408125543],V8=[290298740,357149030,524531317,374648427,475249515,423732329,272869232,307544935],d8=[...t7,...V8],k5=($)=>{if($<256)return 1;if($<65536)return 2;if($<16777216)return 3;if($<4294967296)return 4;if($<1099511627776)return 5;return 6},u5=($)=>{if($<1n<<8n)return 1;if($<1n<<16n)return 2;if($<1n<<24n)return 3;if($<1n<<32n)return 4;if($<1n<<40n)return 5;if($<1n<<48n)return 6;if($<1n<<56n)return 7;return 8},p5=($)=>{if($>=-64&&$<64)return 1;if($>=-8192&&$<8192)return 2;if($>=-1048576&&$<1048576)return 3;if($>=-134217728&&$<134217728)return 4;if($>=-17179869184&&$<17179869184)return 5;return 6},e7=($)=>{if($<127)return 1;if($<16383)return 2;if($<2097151)return 3;if($<268435455)return 4;if($<34359738367)return 5;if($<4398046511103)return 6;throw Error("EBML varint size not supported "+$)};class A${writer;helper=new Uint8Array(8);helperView=new DataView(this.helper.buffer);offsets=new WeakMap;dataOffsets=new WeakMap;constructor($){this.writer=$}writeByte($){this.helperView.setUint8(0,$),this.writer.write(this.helper.subarray(0,1))}writeFloat32($){this.helperView.setFloat32(0,$,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64($){this.helperView.setFloat64(0,$,!1),this.writer.write(this.helper)}writeUnsignedInt($,J=k5($)){let Y=0;switch(J){case 6:this.helperView.setUint8(Y++,$/1099511627776|0);case 5:this.helperView.setUint8(Y++,$/4294967296|0);case 4:this.helperView.setUint8(Y++,$>>24);case 3:this.helperView.setUint8(Y++,$>>16);case 2:this.helperView.setUint8(Y++,$>>8);case 1:this.helperView.setUint8(Y++,$);break;default:throw Error("Bad unsigned int size "+J)}this.writer.write(this.helper.subarray(0,Y))}writeUnsignedBigInt($,J=u5($)){let Y=0;for(let j=J-1;j>=0;j--)this.helperView.setUint8(Y++,Number($>>BigInt(j*8)&0xffn));this.writer.write(this.helper.subarray(0,Y))}writeSignedInt($,J=p5($)){if($<0)$+=2**(J*8);this.writeUnsignedInt($,J)}writeVarInt($,J=e7($)){let Y=0;switch(J){case 1:this.helperView.setUint8(Y++,128|$);break;case 2:this.helperView.setUint8(Y++,64|$>>8),this.helperView.setUint8(Y++,$);break;case 3:this.helperView.setUint8(Y++,32|$>>16),this.helperView.setUint8(Y++,$>>8),this.helperView.setUint8(Y++,$);break;case 4:this.helperView.setUint8(Y++,16|$>>24),this.helperView.setUint8(Y++,$>>16),this.helperView.setUint8(Y++,$>>8),this.helperView.setUint8(Y++,$);break;case 5:this.helperView.setUint8(Y++,8|$/4294967296&7),this.helperView.setUint8(Y++,$>>24),this.helperView.setUint8(Y++,$>>16),this.helperView.setUint8(Y++,$>>8),this.helperView.setUint8(Y++,$);break;case 6:this.helperView.setUint8(Y++,4|$/1099511627776&3),this.helperView.setUint8(Y++,$/4294967296|0),this.helperView.setUint8(Y++,$>>24),this.helperView.setUint8(Y++,$>>16),this.helperView.setUint8(Y++,$>>8),this.helperView.setUint8(Y++,$);break;default:throw Error("Bad EBML varint size "+J)}this.writer.write(this.helper.subarray(0,Y))}writeAsciiString($){this.writer.write(new Uint8Array($.split("").map((J)=>J.charCodeAt(0))))}writeEBML($){if($===null)return;if($ instanceof Uint8Array)this.writer.write($);else if(Array.isArray($))for(let J of $)this.writeEBML(J);else if(this.offsets.set($,this.writer.getPos()),this.writeUnsignedInt($.id),Array.isArray($.data)){let J=this.writer.getPos(),Y=$.size===-1?1:$.size??4;if($.size===-1)this.writeByte(255);else this.writer.seek(this.writer.getPos()+Y);let j=this.writer.getPos();if(this.dataOffsets.set($,j),this.writeEBML($.data),$.size!==-1){let X=this.writer.getPos()-j,Z=this.writer.getPos();this.writer.seek(J),this.writeVarInt(X,Y),this.writer.seek(Z)}}else if(typeof $.data==="number"){let J=$.size??k5($.data);this.writeVarInt(J),this.writeUnsignedInt($.data,J)}else if(typeof $.data==="bigint"){let J=$.size??u5($.data);this.writeVarInt(J),this.writeUnsignedBigInt($.data,J)}else if(typeof $.data==="string")this.writeVarInt($.data.length),this.writeAsciiString($.data);else if($.data instanceof Uint8Array)this.writeVarInt($.data.byteLength,$.size),this.writer.write($.data);else if($.data instanceof l8)this.writeVarInt(4),this.writeFloat32($.data.value);else if($.data instanceof m8)this.writeVarInt(8),this.writeFloat64($.data.value);else if($.data instanceof X2){let J=$.size??p5($.data.value);this.writeVarInt(J),this.writeSignedInt($.data.value,J)}else if($.data instanceof r0){let J=m.encode($.data.value);this.writeVarInt(J.length),this.writer.write(J)}else i($.data)}}var N$=8,P0=2,u0=2*N$,R$=($)=>{let J=y($);if($.skip(-1),J===0)return null;let Y=1,j=128;while((J&j)===0)Y++,j>>=1;return Y},H8=($)=>{let J=y($);if(J===0)return null;let Y=1,j=128;while((J&j)===0)Y++,j>>=1;let X=J&j-1;for(let Z=1;Z<Y;Z++)X*=256,X+=y($);return X},g=($,J)=>{if(J<1||J>8)throw Error("Bad unsigned int size "+J);let Y=0;for(let j=0;j<J;j++)Y*=256,Y+=y($);return Y},l5=($,J)=>{if(J<1)throw Error("Bad unsigned int size "+J);let Y=0n;for(let j=0;j<J;j++)Y<<=8n,Y+=BigInt(y($));return Y};var Z2=($)=>{let J=R$($);if(J===null)return null;return g($,J)},z$=($)=>{let J=y($);if(J===255)J=null;else if($.skip(-1),J=H8($),J===72057594037927940)J=null;return J},p0=($)=>{let J=Z2($);if(J===null)return null;let Y=z$($);return{id:J,size:Y}},F1=($,J)=>{let Y=D($,J),j=0;while(j<J&&Y[j]!==0)j+=1;return String.fromCharCode(...Y.subarray(0,j))},N8=($,J)=>{let Y=D($,J),j=0;while(j<J&&Y[j]!==0)j+=1;return Y0.decode(Y.subarray(0,j))},G2=($,J)=>{if(J===0)return 0;if(J!==4&&J!==8)throw Error("Bad float size "+J);return J===4?H5($):i6($)},K2=async($,J,Y,j)=>{let X=new Set(Y),Z=J;while(j===null||Z<j){let G=$.requestSliceRange(Z,P0,u0);if(G instanceof Promise)G=await G;if(!G)break;let K=p0(G);if(!K)break;if(X.has(K.id))return{pos:Z,found:!0};W1(K.size),Z=G.filePos+K.size}return{pos:j!==null&&j>Z?j:Z,found:!1}},_$=async($,J,Y,j)=>{let Z=new Set(Y),G=J;while(G<j){let K=$.requestSliceRange(G,0,Math.min(65536,j-G));if(K instanceof Promise)K=await K;if(!K)break;if(K.length<N$)break;for(let Q=0;Q<K.length-N$;Q++){K.filePos=G;let q=Z2(K);if(q!==null&&Z.has(q))return G;G++}}return null},A0={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",mpeg4:"V_MPEG4/ISO/ASP",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT",srt:"S_TEXT/UTF8",ass:"S_TEXT/ASS",ssa:"S_TEXT/SSA"};function W1($){if($===null)throw Error("Undefined element size is used in a place where it is not supported.")}/*!
230
230
  * Copyright (c) 2025-present, Vanilagy and contributors
231
231
  *
232
232
  * This Source Code Form is subject to the terms of the Mozilla Public
@@ -256,7 +256,7 @@ ${K.join(`
256
256
  * This Source Code Form is subject to the terms of the Mozilla Public
257
257
  * License, v. 2.0. If a copy of the MPL was not distributed with this
258
258
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
259
- */var n8=1399285583,Jj=79764919,i5=new Uint32Array(256);for(let $=0;$<256;$++){let J=$<<24;for(let Y=0;Y<8;Y++)J=J&2147483648?J<<1^Jj:J<<1;i5[$]=J>>>0&4294967295}var U2=($)=>{let J=h($),Y=J.getUint32(22,!0);J.setUint32(22,0,!0);let j=0;for(let X=0;X<$.length;X++){let Z=$[X];j=(j<<8^i5[j>>>24^Z])>>>0}return J.setUint32(22,Y,!0),j},W2=($,J,Y)=>{let j=0,X=null;if($.length>0){if(J.codec==="vorbis"){H(J.vorbisInfo);let Z=J.vorbisInfo.modeBlockflags.length,K=(1<<zJ(Z-1))-1<<1,Q=($[0]&K)>>1;if(Q>=J.vorbisInfo.modeBlockflags.length)throw Error("Invalid mode number.");let q=Y,U=J.vorbisInfo.modeBlockflags[Q];if(X=J.vorbisInfo.blocksizes[U],U===1){let W=(K|1)+1,V=$[0]&W?1:0;q=J.vorbisInfo.blocksizes[V]}j=q!==null?q+X>>2:0}else if(J.codec==="opus")j=sJ($).durationInSamples}return{durationInSamples:j,vorbisBlockSize:X}},V2=($)=>{let J="audio/ogg";if($.codecStrings){let Y=[...new Set($.codecStrings)];J+=`; codecs="${Y.join(", ")}"`}return J};/*!
259
+ */var n8=1399285583,$j=79764919,i5=new Uint32Array(256);for(let $=0;$<256;$++){let J=$<<24;for(let Y=0;Y<8;Y++)J=J&2147483648?J<<1^$j:J<<1;i5[$]=J>>>0&4294967295}var U2=($)=>{let J=h($),Y=J.getUint32(22,!0);J.setUint32(22,0,!0);let j=0;for(let X=0;X<$.length;X++){let Z=$[X];j=(j<<8^i5[j>>>24^Z])>>>0}return J.setUint32(22,Y,!0),j},W2=($,J,Y)=>{let j=0,X=null;if($.length>0){if(J.codec==="vorbis"){H(J.vorbisInfo);let Z=J.vorbisInfo.modeBlockflags.length,K=(1<<zJ(Z-1))-1<<1,Q=($[0]&K)>>1;if(Q>=J.vorbisInfo.modeBlockflags.length)throw Error("Invalid mode number.");let q=Y,U=J.vorbisInfo.modeBlockflags[Q];if(X=J.vorbisInfo.blocksizes[U],U===1){let W=(K|1)+1,V=$[0]&W?1:0;q=J.vorbisInfo.blocksizes[V]}j=q!==null?q+X>>2:0}else if(J.codec==="opus")j=sJ($).durationInSamples}return{durationInSamples:j,vorbisBlockSize:X}},V2=($)=>{let J="audio/ogg";if($.codecStrings){let Y=[...new Set($.codecStrings)];J+=`; codecs="${Y.join(", ")}"`}return J};/*!
260
260
  * Copyright (c) 2025-present, Vanilagy and contributors
261
261
  *
262
262
  * This Source Code Form is subject to the terms of the Mozilla Public
@@ -280,13 +280,13 @@ ${K.join(`
280
280
  * This Source Code Form is subject to the terms of the Mozilla Public
281
281
  * License, v. 2.0. If a copy of the MPL was not distributed with this
282
282
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
283
- */class E0{}class N2 extends E0{async _getMajorBrand($){let J=$._reader.requestSlice(0,12);if(J instanceof Promise)J=await J;if(!J)return null;if(J.skip(4),s(J,4)!=="ftyp")return null;return s(J,4)}_createDemuxer($){return new H$($)}}class O$ extends N2{async _canReadInput($){let J=await this._getMajorBrand($);return!!J&&J!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class P$ extends N2{async _canReadInput($){return await this._getMajorBrand($)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class A2 extends E0{async isSupportedEBMLOfDocType($,J){let Y=$._reader.requestSlice(0,u0);if(Y instanceof Promise)Y=await Y;if(!Y)return!1;let j=R$(Y);if(j===null)return!1;if(j<1||j>8)return!1;if(g(Y,j)!==440786851)return!1;let Z=z$(Y);if(Z===null)return!1;let G=$._reader.requestSlice(Y.filePos,Z);if(G instanceof Promise)G=await G;if(!G)return!1;let K=Y.filePos;while(G.filePos<=K+Z-P0){let Q=p0(G);if(!Q)break;let{id:q,size:U}=Q,W=G.filePos;if(U===null)return!1;switch(q){case 17030:if(g(G,U)!==1)return!1;break;case 17143:if(g(G,U)!==1)return!1;break;case 17026:if(F1(G,U)!==J)return!1;break;case 17031:if(g(G,U)>4)return!1;break}G.filePos=W+U}return!0}_canReadInput($){return this.isSupportedEBMLOfDocType($,"matroska")}_createDemuxer($){return new M$($)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class C$ extends A2{_canReadInput($){return this.isSupportedEBMLOfDocType($,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class D$ extends E0{async _canReadInput($){let J=$._reader.requestSlice(0,10);if(J instanceof Promise)J=await J;if(!J)return!1;let Y=0,j=!1;while(!0){let Q=$._reader.requestSlice(Y,W8);if(Q instanceof Promise)Q=await Q;if(!Q)break;let q=d1(Q);if(!q)break;j=!0,Y=Q.filePos+q.size}let X=await c8($._reader,Y,Y+4096);if(!X)return!1;if(j)return!0;Y=X.startPos+X.header.totalSize;let Z=await c8($._reader,Y,Y+O6);if(!Z)return!1;let G=X.header,K=Z.header;if(G.channel!==K.channel||G.sampleRate!==K.sampleRate)return!1;return!0}_createDemuxer($){return new F$($)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class E$ extends E0{async _canReadInput($){let J=$._reader.requestSlice(0,12);if(J instanceof Promise)J=await J;if(!J)return!1;let Y=s(J,4);if(Y!=="RIFF"&&Y!=="RIFX"&&Y!=="RF64")return!1;return J.skip(4),s(J,4)==="WAVE"}_createDemuxer($){return new w$($)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class T$ extends E0{async _canReadInput($){let J=$._reader.requestSlice(0,4);if(J instanceof Promise)J=await J;if(!J)return!1;return s(J,4)==="OggS"}_createDemuxer($){return new B$($)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class y$ extends E0{async _canReadInput($){let J=$._reader.requestSlice(0,4);if(J instanceof Promise)J=await J;if(!J)return!1;return s(J,4)==="fLaC"}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer($){return new U$($)}}class v$ extends E0{async _canReadInput($){let J=$._reader.requestSliceRange(0,K8,Q8);if(J instanceof Promise)J=await J;if(!J)return!1;let Y=g8(J);if(!Y)return!1;if(J=$._reader.requestSliceRange(Y.frameLength,K8,Q8),J instanceof Promise)J=await J;if(!J)return!1;let j=g8(J);if(!j)return!1;return Y.objectType===j.objectType&&Y.samplingFrequencyIndex===j.samplingFrequencyIndex&&Y.channelConfiguration===j.channelConfiguration}_createDemuxer($){return new G$($)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}var JY=new O$,YY=new P$,R2=new A2,jY=new C$,XY=new D$,ZY=new E$,GY=new T$,KY=new v$,QY=new y$;class b$ extends E0{async _canReadInput($){let J=$._reader.requestSlice(0,12);if(J instanceof Promise)J=await J;if(!J)return!1;let Y=s(J,4);if(Y!=="RIFF"&&Y!=="RIFX"&&Y!=="RF64")return!1;return J.skip(4),s(J,4)==="AVI "}_createDemuxer($){return new o0($)}get name(){return"AVI"}get mimeType(){return"video/x-msvideo"}}var qY=new b$,Yj=[JY,YY,R2,jY,ZY,GY,QY,XY,KY,qY];var UY=(()=>({}));/*!
283
+ */class E0{}class N2 extends E0{async _getMajorBrand($){let J=$._reader.requestSlice(0,12);if(J instanceof Promise)J=await J;if(!J)return null;if(J.skip(4),s(J,4)!=="ftyp")return null;return s(J,4)}_createDemuxer($){return new H$($)}}class O$ extends N2{async _canReadInput($){let J=await this._getMajorBrand($);return!!J&&J!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class P$ extends N2{async _canReadInput($){return await this._getMajorBrand($)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class A2 extends E0{async isSupportedEBMLOfDocType($,J){let Y=$._reader.requestSlice(0,u0);if(Y instanceof Promise)Y=await Y;if(!Y)return!1;let j=R$(Y);if(j===null)return!1;if(j<1||j>8)return!1;if(g(Y,j)!==440786851)return!1;let Z=z$(Y);if(Z===null)return!1;let G=$._reader.requestSlice(Y.filePos,Z);if(G instanceof Promise)G=await G;if(!G)return!1;let K=Y.filePos;while(G.filePos<=K+Z-P0){let Q=p0(G);if(!Q)break;let{id:q,size:U}=Q,W=G.filePos;if(U===null)return!1;switch(q){case 17030:if(g(G,U)!==1)return!1;break;case 17143:if(g(G,U)!==1)return!1;break;case 17026:if(F1(G,U)!==J)return!1;break;case 17031:if(g(G,U)>4)return!1;break}G.filePos=W+U}return!0}_canReadInput($){return this.isSupportedEBMLOfDocType($,"matroska")}_createDemuxer($){return new M$($)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class C$ extends A2{_canReadInput($){return this.isSupportedEBMLOfDocType($,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class D$ extends E0{async _canReadInput($){let J=$._reader.requestSlice(0,10);if(J instanceof Promise)J=await J;if(!J)return!1;let Y=0,j=!1;while(!0){let Q=$._reader.requestSlice(Y,W8);if(Q instanceof Promise)Q=await Q;if(!Q)break;let q=d1(Q);if(!q)break;j=!0,Y=Q.filePos+q.size}let X=await c8($._reader,Y,Y+4096);if(!X)return!1;if(j)return!0;Y=X.startPos+X.header.totalSize;let Z=await c8($._reader,Y,Y+O6);if(!Z)return!1;let G=X.header,K=Z.header;if(G.channel!==K.channel||G.sampleRate!==K.sampleRate)return!1;return!0}_createDemuxer($){return new F$($)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class E$ extends E0{async _canReadInput($){let J=$._reader.requestSlice(0,12);if(J instanceof Promise)J=await J;if(!J)return!1;let Y=s(J,4);if(Y!=="RIFF"&&Y!=="RIFX"&&Y!=="RF64")return!1;return J.skip(4),s(J,4)==="WAVE"}_createDemuxer($){return new w$($)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class T$ extends E0{async _canReadInput($){let J=$._reader.requestSlice(0,4);if(J instanceof Promise)J=await J;if(!J)return!1;return s(J,4)==="OggS"}_createDemuxer($){return new B$($)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class y$ extends E0{async _canReadInput($){let J=$._reader.requestSlice(0,4);if(J instanceof Promise)J=await J;if(!J)return!1;return s(J,4)==="fLaC"}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer($){return new U$($)}}class v$ extends E0{async _canReadInput($){let J=$._reader.requestSliceRange(0,K8,Q8);if(J instanceof Promise)J=await J;if(!J)return!1;let Y=g8(J);if(!Y)return!1;if(J=$._reader.requestSliceRange(Y.frameLength,K8,Q8),J instanceof Promise)J=await J;if(!J)return!1;let j=g8(J);if(!j)return!1;return Y.objectType===j.objectType&&Y.samplingFrequencyIndex===j.samplingFrequencyIndex&&Y.channelConfiguration===j.channelConfiguration}_createDemuxer($){return new G$($)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}var JY=new O$,YY=new P$,R2=new A2,jY=new C$,XY=new D$,ZY=new E$,GY=new T$,KY=new v$,QY=new y$;class b$ extends E0{async _canReadInput($){let J=$._reader.requestSlice(0,12);if(J instanceof Promise)J=await J;if(!J)return!1;let Y=s(J,4);if(Y!=="RIFF"&&Y!=="RIFX"&&Y!=="RF64")return!1;return J.skip(4),s(J,4)==="AVI "}_createDemuxer($){return new o0($)}get name(){return"AVI"}get mimeType(){return"video/x-msvideo"}}var qY=new b$,Jj=[JY,YY,R2,jY,ZY,GY,QY,XY,KY,qY];var UY=(()=>({}));/*!
284
284
  * Copyright (c) 2025-present, Vanilagy and contributors
285
285
  *
286
286
  * This Source Code Form is subject to the terms of the Mozilla Public
287
287
  * License, v. 2.0. If a copy of the MPL was not distributed with this
288
288
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
289
- */var jj=typeof UY<"u"?UY:void 0;class i0{_disposed=!1;_sizePromise=null;async getSizeOrNull(){if(this._disposed)throw new q0;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new q0;let $=await this.getSizeOrNull();if($===null)throw Error("Cannot determine the size of an unsized source.");return $}onread=null}class WY extends i0{_bytes;_view;_onreadCalled=!1;constructor($){if(!($ instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer)&&!ArrayBuffer.isView($))throw TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super();this._bytes=l($),this._view=h($)}_retrieveSize(){return this._bytes.byteLength}_read(){if(!this._onreadCalled)this.onread?.(0,this._bytes.byteLength),this._onreadCalled=!0;return{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}}class VY extends i0{_blob;_orchestrator;constructor($,J={}){if(!($ instanceof Blob))throw TypeError("blob must be a Blob.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.maxCacheSize!==void 0&&(!R1(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super();this._blob=$,this._orchestrator=new z2({maxCacheSize:J.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:I$.fileSystem})}_retrieveSize(){let $=this._blob.size;return this._orchestrator.fileSize=$,$}_read($,J){return this._orchestrator.read($,J)}_readers=new WeakMap;async _runWorker($){let J=this._readers.get($);if(J===void 0){if("stream"in this._blob&&!s1())J=this._blob.slice($.currentPos).stream().getReader();else J=null;this._readers.set($,J)}while($.currentPos<$.targetPos&&!$.aborted)if(J){let{done:Y,value:j}=await J.read();if(Y)throw this._orchestrator.forgetWorker($),Error("Blob reader stopped unexpectedly before all requested data was read.");if($.aborted)break;this.onread?.($.currentPos,$.currentPos+j.length),this._orchestrator.supplyWorkerData($,j)}else{let Y=await this._blob.slice($.currentPos,$.targetPos).arrayBuffer();if($.aborted)break;this.onread?.($.currentPos,$.currentPos+Y.byteLength),this._orchestrator.supplyWorkerData($,new Uint8Array(Y))}$.running=!1}_dispose(){this._orchestrator.dispose()}}var HY=524288,Xj=($,J,Y)=>{if(J instanceof Error&&(J.message.includes("Failed to fetch")||J.message.includes("Load failed")||J.message.includes("NetworkError when attempting to fetch resource"))){let X=null;try{if(typeof window<"u"&&typeof window.location<"u")X=new URL(Y instanceof Request?Y.url:Y,window.location.href).origin}catch{}if((typeof navigator<"u"&&typeof navigator.onLine==="boolean"?navigator.onLine:!0)&&X!==null&&X!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**($-2),16)};class NY extends i0{_url;_getRetryDelay;_options;_orchestrator;_existingResponses=new WeakMap;constructor($,J={}){if(typeof $!=="string"&&!($ instanceof URL)&&!(typeof Request<"u"&&$ instanceof Request))throw TypeError("url must be a string, URL or Request.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.requestInit!==void 0&&(!J.requestInit||typeof J.requestInit!=="object"))throw TypeError("options.requestInit, when provided, must be an object.");if(J.getRetryDelay!==void 0&&typeof J.getRetryDelay!=="function")throw TypeError("options.getRetryDelay, when provided, must be a function.");if(J.maxCacheSize!==void 0&&(!R1(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(J.fetchFn!==void 0&&typeof J.fetchFn!=="function")throw TypeError("options.fetchFn, when provided, must be a function.");super();this._url=$,this._options=J,this._getRetryDelay=J.getRetryDelay??Xj,this._orchestrator=new z2({maxCacheSize:J.maxCacheSize??67108864,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:I$.network})}async _retrieveSize(){let $=new AbortController,J=await u2(this._options.fetchFn??fetch,this._url,k2(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:$.signal}),this._getRetryDelay,()=>this._disposed);if(!J.ok)throw Error(`Error fetching ${String(this._url)}: ${J.status} ${J.statusText}`);let Y,j;if(J.status===206)j=this._getTotalLengthFromRangeResponse(J),Y=this._orchestrator.createWorker(0,Math.min(j,HY));else{let X=J.headers.get("Content-Length");if(X)j=Number(X),Y=this._orchestrator.createWorker(0,j),this._orchestrator.options.maxCacheSize=Number.POSITIVE_INFINITY,console.warn("HTTP server did not respond with 206 Partial Content, meaning the entire remote resource now has to be downloaded. For efficient media file streaming across a network, please make sure your server supports range requests.");else throw Error(`HTTP response (status ${J.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=j,this._existingResponses.set(Y,{response:J,abortController:$}),this._orchestrator.runWorker(Y),j}_read($,J){return this._orchestrator.read($,J)}async _runWorker($){while(!0){let J=this._existingResponses.get($);this._existingResponses.delete($);let Y=J?.abortController,j=J?.response;if(!Y)Y=new AbortController,j=await u2(this._options.fetchFn??fetch,this._url,k2(this._options.requestInit??{},{headers:{Range:`bytes=${$.currentPos}-`},signal:Y.signal}),this._getRetryDelay,()=>this._disposed);if(H(j),!j.ok)throw Error(`Error fetching ${String(this._url)}: ${j.status} ${j.statusText}`);if($.currentPos>0&&j.status!==206)throw Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!j.body)throw Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let X=j.body.getReader();while(!0){if($.currentPos>=$.targetPos||$.aborted){Y.abort(),$.running=!1;return}let Z;try{Z=await X.read()}catch(Q){let q=this._getRetryDelay(1,Q,this._url);if(q!==null){console.error("Error while reading response stream. Attempting to resume.",Q),await new Promise((U)=>setTimeout(U,1000*q));break}throw Q}if($.aborted)break;let{done:G,value:K}=Z;if(G){if(this._orchestrator.forgetWorker($),$.currentPos>=$.targetPos){this._orchestrator.forgetWorker($),$.running=!1;return}break}this.onread?.($.currentPos,$.currentPos+K.length),this._orchestrator.supplyWorkerData($,K)}if($.aborted)break}$.running=!1}_getTotalLengthFromRangeResponse($){let J=$.headers.get("Content-Range");if(J){let j=/\/(\d+)/.exec(J);if(j)return Number(j[1])}let Y=$.headers.get("Content-Length");if(Y)return Number(Y);throw Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}}class AY extends i0{_streamSource;_fileHandle=null;constructor($,J={}){if(typeof $!=="string")throw TypeError("filePath must be a string.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.maxCacheSize!==void 0&&(!R1(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super();this._streamSource=new x$({getSize:async()=>{return this._fileHandle=await jj.fs.open($,"r"),(await this._fileHandle.stat()).size},read:async(Y,j)=>{H(this._fileHandle);let X=new Uint8Array(j-Y);return await this._fileHandle.read(X,0,j-Y,Y),X},maxCacheSize:J.maxCacheSize,prefetchProfile:"fileSystem"})}_read($,J){return this._streamSource._read($,J)}_retrieveSize(){return this._streamSource._retrieveSize()}_dispose(){this._streamSource._dispose(),this._fileHandle?.close(),this._fileHandle=null}}class x$ extends i0{_options;_orchestrator;constructor($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if(typeof $.getSize!=="function")throw TypeError("options.getSize must be a function.");if(typeof $.read!=="function")throw TypeError("options.read must be a function.");if($.dispose!==void 0&&typeof $.dispose!=="function")throw TypeError("options.dispose, when provided, must be a function.");if($.maxCacheSize!==void 0&&(!R1($.maxCacheSize)||$.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if($.prefetchProfile&&!["none","fileSystem","network"].includes($.prefetchProfile))throw TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super();this._options=$,this._orchestrator=new z2({maxCacheSize:$.maxCacheSize??8388608,maxWorkerCount:2,prefetchProfile:I$[$.prefetchProfile??"none"],runWorker:this._runWorker.bind(this)})}_retrieveSize(){let $=this._options.getSize();if($ instanceof Promise)return $.then((J)=>{if(!Number.isInteger(J)||J<0)throw TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=J,J});if(!Number.isInteger($)||$<0)throw TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=$,$}_read($,J){return this._orchestrator.read($,J)}async _runWorker($){while($.currentPos<$.targetPos&&!$.aborted){let{currentPos:J,targetPos:Y}=$,j=this._options.read($.currentPos,Y);if(j instanceof Promise)j=await j;if($.aborted)break;if(j instanceof Uint8Array){if(j=l(j),j.length!==Y-$.currentPos)throw Error(`options.read returned a Uint8Array with unexpected length: Requested ${Y-$.currentPos} bytes, but got ${j.length}.`);this.onread?.($.currentPos,$.currentPos+j.length),this._orchestrator.supplyWorkerData($,j)}else if(j instanceof ReadableStream){let X=j.getReader();while($.currentPos<Y&&!$.aborted){let{done:Z,value:G}=await X.read();if(Z){if($.currentPos<Y)throw Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${Y-J} bytes, but got ${$.currentPos-J}`);break}if(!(G instanceof Uint8Array))throw TypeError("ReadableStream returned by options.read must yield Uint8Array chunks.");if($.aborted)break;let K=l(G);this.onread?.($.currentPos,$.currentPos+K.length),this._orchestrator.supplyWorkerData($,K)}}else throw TypeError("options.read must return or resolve to a Uint8Array or a ReadableStream.")}$.running=!1}_dispose(){this._orchestrator.dispose(),this._options.dispose?.()}}class RY extends i0{_stream;_reader=null;_cache=[];_maxCacheSize;_pendingSlices=[];_currentIndex=0;_targetIndex=0;_maxRequestedIndex=0;_endIndex=null;_pulling=!1;constructor($,J={}){if(!($ instanceof ReadableStream))throw TypeError("stream must be a ReadableStream.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.maxCacheSize!==void 0&&(!R1(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super();this._stream=$,this._maxCacheSize=J.maxCacheSize??16777216}_retrieveSize(){return this._endIndex}_read($,J){if(this._endIndex!==null&&J>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,J);let Y=u(this._cache,$,(q)=>q.start),j=Y!==-1?this._cache[Y]:null;if(j&&j.start<=$&&J<=j.end)return{bytes:j.bytes,view:j.view,offset:j.start};let X=$,Z=new Uint8Array(J-$);if(Y!==-1)for(let q=Y;q<this._cache.length;q++){let U=this._cache[q];if(U.start>=J)break;let W=Math.max($,U.start);if(W>X)this._throwDueToCacheMiss();let V=Math.min(J,U.end);if(W<V)Z.set(U.bytes.subarray(W-U.start,V-U.start),W-$),X=V}if(X===J)return{bytes:Z,view:h(Z),offset:$};if(this._currentIndex>X)this._throwDueToCacheMiss();let{promise:G,resolve:K,reject:Q}=c();if(this._pendingSlices.push({start:$,end:J,bytes:Z,resolve:K,reject:Q}),this._targetIndex=Math.max(this._targetIndex,J),!this._pulling)this._pulling=!0,this._pull().catch((q)=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach((U)=>U.reject(q)),this._pendingSlices.length=0;else throw q});return G}_throwDueToCacheMiss(){throw Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}async _pull(){this._reader??=this._stream.getReader();while(this._currentIndex<this._targetIndex&&!this._disposed){let{done:$,value:J}=await this._reader.read();if($){for(let X of this._pendingSlices)X.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let Y=this._currentIndex,j=this._currentIndex+J.byteLength;for(let X=0;X<this._pendingSlices.length;X++){let Z=this._pendingSlices[X],G=Math.max(Y,Z.start),K=Math.min(j,Z.end);if(G<K){if(Z.bytes.set(J.subarray(G-Y,K-Y),G-Z.start),K===Z.end)Z.resolve({bytes:Z.bytes,view:h(Z.bytes),offset:Z.start}),this._pendingSlices.splice(X,1),X--}}this._cache.push({start:Y,end:j,bytes:J,view:h(J),age:0});while(this._cache.length>0){let X=this._cache[0];if(this._maxRequestedIndex-X.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=J.byteLength}this._pulling=!1}_dispose(){this._pendingSlices.length=0,this._cache.length=0}}var I$={none:($,J)=>({start:$,end:J}),fileSystem:($,J)=>{return $=Math.floor(($-65536)/65536)*65536,J=Math.ceil((J+65536)/65536)*65536,{start:$,end:J}},network:($,J,Y)=>{$=Math.max(0,Math.floor(($-65536)/65536)*65536);for(let X of Y){let G=Math.max((X.startPos+X.targetPos)/2,X.targetPos-8388608);if(q6($,J,G,X.targetPos)){let K=X.targetPos-X.startPos,Q=Math.ceil((K+1)/8388608)*8388608,q=2**Math.ceil(Math.log2(K+1)),U=Math.min(q,Q);J=Math.max(J,X.startPos+U)}}return J=Math.max(J,$+HY),{start:$,end:J}}};class z2{options;fileSize=null;nextAge=0;workers=[];cache=[];currentCacheSize=0;disposed=!1;constructor($){this.options=$}read($,J){H(this.fileSize!==null);let Y=this.options.prefetchProfile($,J,this.workers),j=Math.max(Y.start,0),X=Math.min(Y.end,this.fileSize);H(j<=$&&J<=X);let Z=null,G=u(this.cache,$,(_)=>_.start),K=G!==-1?this.cache[G]:null;if(K&&K.start<=$&&J<=K.end)K.age=this.nextAge++,Z={bytes:K.bytes,view:K.view,offset:K.start};let Q=u(this.cache,j,(_)=>_.start),q=Z?null:new Uint8Array(J-$),U=0,W=j,V=[];if(Q!==-1){for(let _=Q;_<this.cache.length;_++){let L=this.cache[_];if(L.start>=X)break;if(L.end<=j)continue;let M=Math.max(j,L.start),B=Math.min(X,L.end);if(H(M<=B),W<M)V.push({start:W,end:M});if(W=B,q){let F=Math.max($,L.start),C=Math.min(J,L.end);if(F<C){let w=F-$;if(q.set(L.bytes.subarray(F-L.start,C-L.start),w),w===U)U=C-$}}L.age=this.nextAge++}if(W<X)V.push({start:W,end:X})}else V.push({start:j,end:X});if(q&&U>=q.length)Z={bytes:q,view:h(q),offset:$};if(V.length===0)return H(Z),Z;let{promise:N,resolve:A,reject:R}=c(),z=[];for(let _ of V){let L=Math.max($,_.start),M=Math.min(J,_.end);if(L===_.start&&M===_.end)z.push(_);else if(L<M)z.push({start:L,end:M})}for(let _ of V){let L=q&&{start:$,bytes:q,holes:z,resolve:A,reject:R},M=!1;for(let B of this.workers)if(q6(_.start-131072,_.start,B.currentPos,B.targetPos)){if(B.targetPos=Math.max(B.targetPos,_.end),M=!0,L&&!B.pendingSlices.includes(L))B.pendingSlices.push(L);if(!B.running)this.runWorker(B);break}if(!M){let B=this.createWorker(_.start,_.end);if(L)B.pendingSlices=[L];this.runWorker(B)}}if(!Z)H(q),Z=N.then((_)=>({bytes:_,view:h(_),offset:$}));return Z}createWorker($,J){let Y={startPos:$,currentPos:$,targetPos:J,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};this.workers.push(Y);while(this.workers.length>this.options.maxWorkerCount){let j=0,X=this.workers[0];for(let Z=1;Z<this.workers.length;Z++){let G=this.workers[Z];if(G.age<X.age)j=Z,X=G}if(X.running&&X.pendingSlices.length>0)break;X.aborted=!0,this.workers.splice(j,1)}return Y}runWorker($){H(!$.running),H($.currentPos<$.targetPos),$.running=!0,$.age=this.nextAge++,this.options.runWorker($).catch((J)=>{if($.running=!1,$.pendingSlices.length>0)$.pendingSlices.forEach((Y)=>Y.reject(J)),$.pendingSlices.length=0;else throw J})}supplyWorkerData($,J){H(!$.aborted);let Y=$.currentPos,j=Y+J.length;this.insertIntoCache({start:Y,end:j,bytes:J,view:h(J),age:this.nextAge++}),$.currentPos+=J.length,$.targetPos=Math.max($.targetPos,$.currentPos);for(let X=0;X<$.pendingSlices.length;X++){let Z=$.pendingSlices[X],G=Math.max(Y,Z.start),K=Math.min(j,Z.start+Z.bytes.length);if(G<K)Z.bytes.set(J.subarray(G-Y,K-Y),G-Z.start);for(let Q=0;Q<Z.holes.length;Q++){let q=Z.holes[Q];if(Y<=q.start&&j>q.start)q.start=j;if(q.end<=q.start)Z.holes.splice(Q,1),Q--}if(Z.holes.length===0)Z.resolve(Z.bytes),$.pendingSlices.splice(X,1),X--}for(let X=0;X<this.workers.length;X++){let Z=this.workers[X];if($===Z||Z.running)continue;if(q6(Y,j,Z.currentPos,Z.targetPos))this.workers.splice(X,1),X--}}forgetWorker($){let J=this.workers.indexOf($);H(J!==-1),this.workers.splice(J,1)}insertIntoCache($){if(this.options.maxCacheSize===0)return;let J=u(this.cache,$.start,(Y)=>Y.start)+1;if(J>0){let Y=this.cache[J-1];if(Y.end>=$.end)return;if(Y.end>$.start){let j=new Uint8Array($.end-Y.start);j.set(Y.bytes,0),j.set($.bytes,$.start-Y.start),this.currentCacheSize+=$.end-Y.end,Y.bytes=j,Y.view=h(j),Y.end=$.end,J--,$=Y}else this.cache.splice(J,0,$),this.currentCacheSize+=$.bytes.length}else this.cache.splice(J,0,$),this.currentCacheSize+=$.bytes.length;for(let Y=J+1;Y<this.cache.length;Y++){let j=this.cache[Y];if($.end<=j.start)break;if($.end>=j.end){this.cache.splice(Y,1),this.currentCacheSize-=j.bytes.length,Y--;continue}let X=new Uint8Array(j.end-$.start);X.set($.bytes,0),X.set(j.bytes,j.start-$.start),this.currentCacheSize-=$.end-j.start,$.bytes=X,$.view=h(X),$.end=j.end,this.cache.splice(Y,1);break}while(this.currentCacheSize>this.options.maxCacheSize){let Y=0,j=this.cache[0];for(let X=1;X<this.cache.length;X++){let Z=this.cache[X];if(Z.age<j.age)Y=X,j=Z}if(this.currentCacheSize-j.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(Y,1),this.currentCacheSize-=j.bytes.length}}dispose(){for(let $ of this.workers)$.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}/*!
289
+ */class i0{_disposed=!1;_sizePromise=null;async getSizeOrNull(){if(this._disposed)throw new q0;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new q0;let $=await this.getSizeOrNull();if($===null)throw Error("Cannot determine the size of an unsized source.");return $}onread=null}class WY extends i0{_bytes;_view;_onreadCalled=!1;constructor($){if(!($ instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer)&&!ArrayBuffer.isView($))throw TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super();this._bytes=l($),this._view=h($)}_retrieveSize(){return this._bytes.byteLength}_read(){if(!this._onreadCalled)this.onread?.(0,this._bytes.byteLength),this._onreadCalled=!0;return{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}}class VY extends i0{_blob;_orchestrator;constructor($,J={}){if(!($ instanceof Blob))throw TypeError("blob must be a Blob.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.maxCacheSize!==void 0&&(!R1(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super();this._blob=$,this._orchestrator=new z2({maxCacheSize:J.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:I$.fileSystem})}_retrieveSize(){let $=this._blob.size;return this._orchestrator.fileSize=$,$}_read($,J){return this._orchestrator.read($,J)}_readers=new WeakMap;async _runWorker($){let J=this._readers.get($);if(J===void 0){if("stream"in this._blob&&!s1())J=this._blob.slice($.currentPos).stream().getReader();else J=null;this._readers.set($,J)}while($.currentPos<$.targetPos&&!$.aborted)if(J){let{done:Y,value:j}=await J.read();if(Y)throw this._orchestrator.forgetWorker($),Error("Blob reader stopped unexpectedly before all requested data was read.");if($.aborted)break;this.onread?.($.currentPos,$.currentPos+j.length),this._orchestrator.supplyWorkerData($,j)}else{let Y=await this._blob.slice($.currentPos,$.targetPos).arrayBuffer();if($.aborted)break;this.onread?.($.currentPos,$.currentPos+Y.byteLength),this._orchestrator.supplyWorkerData($,new Uint8Array(Y))}$.running=!1}_dispose(){this._orchestrator.dispose()}}var HY=524288,Yj=($,J,Y)=>{if(J instanceof Error&&(J.message.includes("Failed to fetch")||J.message.includes("Load failed")||J.message.includes("NetworkError when attempting to fetch resource"))){let X=null;try{if(typeof window<"u"&&typeof window.location<"u")X=new URL(Y instanceof Request?Y.url:Y,window.location.href).origin}catch{}if((typeof navigator<"u"&&typeof navigator.onLine==="boolean"?navigator.onLine:!0)&&X!==null&&X!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**($-2),16)};class NY extends i0{_url;_getRetryDelay;_options;_orchestrator;_existingResponses=new WeakMap;constructor($,J={}){if(typeof $!=="string"&&!($ instanceof URL)&&!(typeof Request<"u"&&$ instanceof Request))throw TypeError("url must be a string, URL or Request.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.requestInit!==void 0&&(!J.requestInit||typeof J.requestInit!=="object"))throw TypeError("options.requestInit, when provided, must be an object.");if(J.getRetryDelay!==void 0&&typeof J.getRetryDelay!=="function")throw TypeError("options.getRetryDelay, when provided, must be a function.");if(J.maxCacheSize!==void 0&&(!R1(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(J.fetchFn!==void 0&&typeof J.fetchFn!=="function")throw TypeError("options.fetchFn, when provided, must be a function.");super();this._url=$,this._options=J,this._getRetryDelay=J.getRetryDelay??Yj,this._orchestrator=new z2({maxCacheSize:J.maxCacheSize??67108864,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:I$.network})}async _retrieveSize(){let $=new AbortController,J=await u2(this._options.fetchFn??fetch,this._url,k2(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:$.signal}),this._getRetryDelay,()=>this._disposed);if(!J.ok)throw Error(`Error fetching ${String(this._url)}: ${J.status} ${J.statusText}`);let Y,j;if(J.status===206)j=this._getTotalLengthFromRangeResponse(J),Y=this._orchestrator.createWorker(0,Math.min(j,HY));else{let X=J.headers.get("Content-Length");if(X)j=Number(X),Y=this._orchestrator.createWorker(0,j),this._orchestrator.options.maxCacheSize=Number.POSITIVE_INFINITY,console.warn("HTTP server did not respond with 206 Partial Content, meaning the entire remote resource now has to be downloaded. For efficient media file streaming across a network, please make sure your server supports range requests.");else throw Error(`HTTP response (status ${J.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=j,this._existingResponses.set(Y,{response:J,abortController:$}),this._orchestrator.runWorker(Y),j}_read($,J){return this._orchestrator.read($,J)}async _runWorker($){while(!0){let J=this._existingResponses.get($);this._existingResponses.delete($);let Y=J?.abortController,j=J?.response;if(!Y)Y=new AbortController,j=await u2(this._options.fetchFn??fetch,this._url,k2(this._options.requestInit??{},{headers:{Range:`bytes=${$.currentPos}-`},signal:Y.signal}),this._getRetryDelay,()=>this._disposed);if(H(j),!j.ok)throw Error(`Error fetching ${String(this._url)}: ${j.status} ${j.statusText}`);if($.currentPos>0&&j.status!==206)throw Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!j.body)throw Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let X=j.body.getReader();while(!0){if($.currentPos>=$.targetPos||$.aborted){Y.abort(),$.running=!1;return}let Z;try{Z=await X.read()}catch(Q){let q=this._getRetryDelay(1,Q,this._url);if(q!==null){console.error("Error while reading response stream. Attempting to resume.",Q),await new Promise((U)=>setTimeout(U,1000*q));break}throw Q}if($.aborted)break;let{done:G,value:K}=Z;if(G){if(this._orchestrator.forgetWorker($),$.currentPos>=$.targetPos){this._orchestrator.forgetWorker($),$.running=!1;return}break}this.onread?.($.currentPos,$.currentPos+K.length),this._orchestrator.supplyWorkerData($,K)}if($.aborted)break}$.running=!1}_getTotalLengthFromRangeResponse($){let J=$.headers.get("Content-Range");if(J){let j=/\/(\d+)/.exec(J);if(j)return Number(j[1])}let Y=$.headers.get("Content-Length");if(Y)return Number(Y);throw Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}}class AY extends i0{_streamSource;_fileHandle=null;constructor($,J={}){if(typeof $!=="string")throw TypeError("filePath must be a string.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.maxCacheSize!==void 0&&(!R1(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super();this._streamSource=new x$({getSize:async()=>{return this._fileHandle=await UY.open($,"r"),H(this._fileHandle),(await this._fileHandle.stat()).size},read:async(Y,j)=>{H(this._fileHandle);let X=new Uint8Array(j-Y);return await this._fileHandle.read(X,0,j-Y,Y),X},maxCacheSize:J.maxCacheSize,prefetchProfile:"fileSystem"})}_read($,J){return this._streamSource._read($,J)}_retrieveSize(){return this._streamSource._retrieveSize()}_dispose(){this._streamSource._dispose(),this._fileHandle?.close(),this._fileHandle=null}}class x$ extends i0{_options;_orchestrator;constructor($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if(typeof $.getSize!=="function")throw TypeError("options.getSize must be a function.");if(typeof $.read!=="function")throw TypeError("options.read must be a function.");if($.dispose!==void 0&&typeof $.dispose!=="function")throw TypeError("options.dispose, when provided, must be a function.");if($.maxCacheSize!==void 0&&(!R1($.maxCacheSize)||$.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if($.prefetchProfile&&!["none","fileSystem","network"].includes($.prefetchProfile))throw TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super();this._options=$,this._orchestrator=new z2({maxCacheSize:$.maxCacheSize??8388608,maxWorkerCount:2,prefetchProfile:I$[$.prefetchProfile??"none"],runWorker:this._runWorker.bind(this)})}_retrieveSize(){let $=this._options.getSize();if($ instanceof Promise)return $.then((J)=>{if(!Number.isInteger(J)||J<0)throw TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=J,J});if(!Number.isInteger($)||$<0)throw TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=$,$}_read($,J){return this._orchestrator.read($,J)}async _runWorker($){while($.currentPos<$.targetPos&&!$.aborted){let{currentPos:J,targetPos:Y}=$,j=this._options.read($.currentPos,Y);if(j instanceof Promise)j=await j;if($.aborted)break;if(j instanceof Uint8Array){if(j=l(j),j.length!==Y-$.currentPos)throw Error(`options.read returned a Uint8Array with unexpected length: Requested ${Y-$.currentPos} bytes, but got ${j.length}.`);this.onread?.($.currentPos,$.currentPos+j.length),this._orchestrator.supplyWorkerData($,j)}else if(j instanceof ReadableStream){let X=j.getReader();while($.currentPos<Y&&!$.aborted){let{done:Z,value:G}=await X.read();if(Z){if($.currentPos<Y)throw Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${Y-J} bytes, but got ${$.currentPos-J}`);break}if(!(G instanceof Uint8Array))throw TypeError("ReadableStream returned by options.read must yield Uint8Array chunks.");if($.aborted)break;let K=l(G);this.onread?.($.currentPos,$.currentPos+K.length),this._orchestrator.supplyWorkerData($,K)}}else throw TypeError("options.read must return or resolve to a Uint8Array or a ReadableStream.")}$.running=!1}_dispose(){this._orchestrator.dispose(),this._options.dispose?.()}}class RY extends i0{_stream;_reader=null;_cache=[];_maxCacheSize;_pendingSlices=[];_currentIndex=0;_targetIndex=0;_maxRequestedIndex=0;_endIndex=null;_pulling=!1;constructor($,J={}){if(!($ instanceof ReadableStream))throw TypeError("stream must be a ReadableStream.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.maxCacheSize!==void 0&&(!R1(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super();this._stream=$,this._maxCacheSize=J.maxCacheSize??16777216}_retrieveSize(){return this._endIndex}_read($,J){if(this._endIndex!==null&&J>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,J);let Y=u(this._cache,$,(q)=>q.start),j=Y!==-1?this._cache[Y]:null;if(j&&j.start<=$&&J<=j.end)return{bytes:j.bytes,view:j.view,offset:j.start};let X=$,Z=new Uint8Array(J-$);if(Y!==-1)for(let q=Y;q<this._cache.length;q++){let U=this._cache[q];if(U.start>=J)break;let W=Math.max($,U.start);if(W>X)this._throwDueToCacheMiss();let V=Math.min(J,U.end);if(W<V)Z.set(U.bytes.subarray(W-U.start,V-U.start),W-$),X=V}if(X===J)return{bytes:Z,view:h(Z),offset:$};if(this._currentIndex>X)this._throwDueToCacheMiss();let{promise:G,resolve:K,reject:Q}=c();if(this._pendingSlices.push({start:$,end:J,bytes:Z,resolve:K,reject:Q}),this._targetIndex=Math.max(this._targetIndex,J),!this._pulling)this._pulling=!0,this._pull().catch((q)=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach((U)=>U.reject(q)),this._pendingSlices.length=0;else throw q});return G}_throwDueToCacheMiss(){throw Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}async _pull(){this._reader??=this._stream.getReader();while(this._currentIndex<this._targetIndex&&!this._disposed){let{done:$,value:J}=await this._reader.read();if($){for(let X of this._pendingSlices)X.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let Y=this._currentIndex,j=this._currentIndex+J.byteLength;for(let X=0;X<this._pendingSlices.length;X++){let Z=this._pendingSlices[X],G=Math.max(Y,Z.start),K=Math.min(j,Z.end);if(G<K){if(Z.bytes.set(J.subarray(G-Y,K-Y),G-Z.start),K===Z.end)Z.resolve({bytes:Z.bytes,view:h(Z.bytes),offset:Z.start}),this._pendingSlices.splice(X,1),X--}}this._cache.push({start:Y,end:j,bytes:J,view:h(J),age:0});while(this._cache.length>0){let X=this._cache[0];if(this._maxRequestedIndex-X.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=J.byteLength}this._pulling=!1}_dispose(){this._pendingSlices.length=0,this._cache.length=0}}var I$={none:($,J)=>({start:$,end:J}),fileSystem:($,J)=>{return $=Math.floor(($-65536)/65536)*65536,J=Math.ceil((J+65536)/65536)*65536,{start:$,end:J}},network:($,J,Y)=>{$=Math.max(0,Math.floor(($-65536)/65536)*65536);for(let X of Y){let G=Math.max((X.startPos+X.targetPos)/2,X.targetPos-8388608);if(q6($,J,G,X.targetPos)){let K=X.targetPos-X.startPos,Q=Math.ceil((K+1)/8388608)*8388608,q=2**Math.ceil(Math.log2(K+1)),U=Math.min(q,Q);J=Math.max(J,X.startPos+U)}}return J=Math.max(J,$+HY),{start:$,end:J}}};class z2{options;fileSize=null;nextAge=0;workers=[];cache=[];currentCacheSize=0;disposed=!1;constructor($){this.options=$}read($,J){H(this.fileSize!==null);let Y=this.options.prefetchProfile($,J,this.workers),j=Math.max(Y.start,0),X=Math.min(Y.end,this.fileSize);H(j<=$&&J<=X);let Z=null,G=u(this.cache,$,(_)=>_.start),K=G!==-1?this.cache[G]:null;if(K&&K.start<=$&&J<=K.end)K.age=this.nextAge++,Z={bytes:K.bytes,view:K.view,offset:K.start};let Q=u(this.cache,j,(_)=>_.start),q=Z?null:new Uint8Array(J-$),U=0,W=j,V=[];if(Q!==-1){for(let _=Q;_<this.cache.length;_++){let L=this.cache[_];if(L.start>=X)break;if(L.end<=j)continue;let M=Math.max(j,L.start),B=Math.min(X,L.end);if(H(M<=B),W<M)V.push({start:W,end:M});if(W=B,q){let F=Math.max($,L.start),C=Math.min(J,L.end);if(F<C){let w=F-$;if(q.set(L.bytes.subarray(F-L.start,C-L.start),w),w===U)U=C-$}}L.age=this.nextAge++}if(W<X)V.push({start:W,end:X})}else V.push({start:j,end:X});if(q&&U>=q.length)Z={bytes:q,view:h(q),offset:$};if(V.length===0)return H(Z),Z;let{promise:N,resolve:A,reject:R}=c(),z=[];for(let _ of V){let L=Math.max($,_.start),M=Math.min(J,_.end);if(L===_.start&&M===_.end)z.push(_);else if(L<M)z.push({start:L,end:M})}for(let _ of V){let L=q&&{start:$,bytes:q,holes:z,resolve:A,reject:R},M=!1;for(let B of this.workers)if(q6(_.start-131072,_.start,B.currentPos,B.targetPos)){if(B.targetPos=Math.max(B.targetPos,_.end),M=!0,L&&!B.pendingSlices.includes(L))B.pendingSlices.push(L);if(!B.running)this.runWorker(B);break}if(!M){let B=this.createWorker(_.start,_.end);if(L)B.pendingSlices=[L];this.runWorker(B)}}if(!Z)H(q),Z=N.then((_)=>({bytes:_,view:h(_),offset:$}));return Z}createWorker($,J){let Y={startPos:$,currentPos:$,targetPos:J,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};this.workers.push(Y);while(this.workers.length>this.options.maxWorkerCount){let j=0,X=this.workers[0];for(let Z=1;Z<this.workers.length;Z++){let G=this.workers[Z];if(G.age<X.age)j=Z,X=G}if(X.running&&X.pendingSlices.length>0)break;X.aborted=!0,this.workers.splice(j,1)}return Y}runWorker($){H(!$.running),H($.currentPos<$.targetPos),$.running=!0,$.age=this.nextAge++,this.options.runWorker($).catch((J)=>{if($.running=!1,$.pendingSlices.length>0)$.pendingSlices.forEach((Y)=>Y.reject(J)),$.pendingSlices.length=0;else throw J})}supplyWorkerData($,J){H(!$.aborted);let Y=$.currentPos,j=Y+J.length;this.insertIntoCache({start:Y,end:j,bytes:J,view:h(J),age:this.nextAge++}),$.currentPos+=J.length,$.targetPos=Math.max($.targetPos,$.currentPos);for(let X=0;X<$.pendingSlices.length;X++){let Z=$.pendingSlices[X],G=Math.max(Y,Z.start),K=Math.min(j,Z.start+Z.bytes.length);if(G<K)Z.bytes.set(J.subarray(G-Y,K-Y),G-Z.start);for(let Q=0;Q<Z.holes.length;Q++){let q=Z.holes[Q];if(Y<=q.start&&j>q.start)q.start=j;if(q.end<=q.start)Z.holes.splice(Q,1),Q--}if(Z.holes.length===0)Z.resolve(Z.bytes),$.pendingSlices.splice(X,1),X--}for(let X=0;X<this.workers.length;X++){let Z=this.workers[X];if($===Z||Z.running)continue;if(q6(Y,j,Z.currentPos,Z.targetPos))this.workers.splice(X,1),X--}}forgetWorker($){let J=this.workers.indexOf($);H(J!==-1),this.workers.splice(J,1)}insertIntoCache($){if(this.options.maxCacheSize===0)return;let J=u(this.cache,$.start,(Y)=>Y.start)+1;if(J>0){let Y=this.cache[J-1];if(Y.end>=$.end)return;if(Y.end>$.start){let j=new Uint8Array($.end-Y.start);j.set(Y.bytes,0),j.set($.bytes,$.start-Y.start),this.currentCacheSize+=$.end-Y.end,Y.bytes=j,Y.view=h(j),Y.end=$.end,J--,$=Y}else this.cache.splice(J,0,$),this.currentCacheSize+=$.bytes.length}else this.cache.splice(J,0,$),this.currentCacheSize+=$.bytes.length;for(let Y=J+1;Y<this.cache.length;Y++){let j=this.cache[Y];if($.end<=j.start)break;if($.end>=j.end){this.cache.splice(Y,1),this.currentCacheSize-=j.bytes.length,Y--;continue}let X=new Uint8Array(j.end-$.start);X.set($.bytes,0),X.set(j.bytes,j.start-$.start),this.currentCacheSize-=$.end-j.start,$.bytes=X,$.view=h(X),$.end=j.end,this.cache.splice(Y,1);break}while(this.currentCacheSize>this.options.maxCacheSize){let Y=0,j=this.cache[0];for(let X=1;X<this.cache.length;X++){let Z=this.cache[X];if(Z.age<j.age)Y=X,j=Z}if(this.currentCacheSize-j.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(Y,1),this.currentCacheSize-=j.bytes.length}}dispose(){for(let $ of this.workers)$.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}/*!
290
290
  * Copyright (c) 2025-present, Vanilagy and contributors
291
291
  *
292
292
  * This Source Code Form is subject to the terms of the Mozilla Public
@@ -362,7 +362,7 @@ ${K.join(`
362
362
 
363
363
  fragColor = result;
364
364
  }
365
- `),Y=this.gl.createProgram();return this.gl.attachShader(Y,$),this.gl.attachShader(Y,J),this.gl.linkProgram(Y),Y}createShader($,J){let Y=this.gl.createShader($);if(this.gl.shaderSource(Y,J),this.gl.compileShader(Y),!this.gl.getShaderParameter(Y,this.gl.COMPILE_STATUS))console.error("Shader compile error:",this.gl.getShaderInfoLog(Y));return Y}createVAO(){let $=this.gl.createVertexArray();this.gl.bindVertexArray($);let J=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),Y=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,Y),this.gl.bufferData(this.gl.ARRAY_BUFFER,J,this.gl.STATIC_DRAW);let j=this.gl.getAttribLocation(this.colorProgram,"a_position"),X=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(j),this.gl.vertexAttribPointer(j,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(X),this.gl.vertexAttribPointer(X,2,this.gl.FLOAT,!1,16,8),$}createTexture(){let $=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,$),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),$}updateTexture($){if(this.lastFrame===$)return;if($.displayWidth!==this.canvas.width||$.displayHeight!==this.canvas.height)this.canvas.width=$.displayWidth,this.canvas.height=$.displayHeight;this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,$),this.lastFrame=$}extractColor($){return this.updateTexture($),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:$.timestamp,duration:$.duration??void 0,alpha:"discard"})}extractAlpha($){this.updateTexture($),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);let{width:J,height:Y}=this.canvas,j=Math.ceil(J/2)*Math.ceil(Y/2),X=J*Y+j*2,Z=Math.ceil(X/(J*4)),G=new Uint8Array(4*J*Z);this.gl.readPixels(0,0,J,Z,this.gl.RGBA,this.gl.UNSIGNED_BYTE,G),G=G.subarray(0,X),H(G[J*Y]===128),H(G[G.length-1]===128);let K={format:"I420",codedWidth:J,codedHeight:Y,timestamp:$.timestamp,duration:$.duration??void 0,transfer:[G.buffer]};return new VideoFrame(G,K)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class r8 extends w1{_encoder;constructor($){_6($);super($.codec);this._encoder=new L2(this,$)}add($,J){if(!($ instanceof J0))throw TypeError("videoSample must be a VideoSample.");return this._encoder.add($,!1,J)}_flushAndClose($){return this._encoder.flushAndClose($)}}class _Y extends w1{_encoder;_canvas;constructor($,J){if(!(typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&$ instanceof OffscreenCanvas))throw TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");_6(J);super(J.codec);this._encoder=new L2(this,J),this._canvas=$}add($,J=0,Y){if(!Number.isFinite($)||$<0)throw TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(J)||J<0)throw TypeError("duration must be a non-negative number.");let j=new J0(this._canvas,{timestamp:$,duration:J});return this._encoder.add(j,!0,Y)}_flushAndClose($){return this._encoder.flushAndClose($)}}class LY extends w1{_encoder;_abortController=null;_track;_workerTrackId=null;_workerListener=null;_promiseWithResolvers=c();_errorPromiseAccessed=!1;_paused=!1;_lastSampleTimestamp=null;_pauseOffset=0;get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor($,J){if(!($ instanceof MediaStreamTrack)||$.kind!=="video")throw TypeError("track must be a video MediaStreamTrack.");_6(J),J={...J,latencyMode:"realtime"};super(J.codec);this._encoder=new L2(this,J),this._track=$}async _start(){if(!this._errorPromiseAccessed)console.warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");this._abortController=new AbortController;let $=null,J=!1,Y=(j)=>{if(J){j.close();return}let X=j.timestamp/1e6;if(this._paused){if($!==null){if(this._lastSampleTimestamp!==null){let K=X-this._lastSampleTimestamp;this._pauseOffset-=K}this._lastSampleTimestamp=X}j.close();return}if($===null){$=X;let G=this._connectedTrack.output._muxer;if(G.firstMediaStreamTimestamp===null)G.firstMediaStreamTimestamp=performance.now()/1000,this._timestampOffset=-$;else this._timestampOffset=performance.now()/1000-G.firstMediaStreamTimestamp-$}if(this._lastSampleTimestamp=X,this._encoder.getQueueSize()>=4){j.close();return}let Z=new J0(j,{timestamp:X+this._pauseOffset});this._encoder.add(Z,!0).catch((G)=>{if(J=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(G),this._workerTrackId!==null)h$({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){let j=new MediaStreamTrackProcessor({track:this._track}),X=new WritableStream({write:Y});j.readable.pipeTo(X,{signal:this._abortController.signal}).catch((Z)=>{if(Z instanceof DOMException&&Z.name==="AbortError")return;this._promiseWithResolvers.reject(Z)})}else if(await Qj())this._workerTrackId=Gj++,h$({type:"videoTrack",trackId:this._workerTrackId,track:this._track}),this._workerListener=(X)=>{let Z=X.data;if(Z.type==="videoFrame"&&Z.trackId===this._workerTrackId)Y(Z.videoFrame);else if(Z.type==="error"&&Z.trackId===this._workerTrackId)this._promiseWithResolvers.reject(Z.error)},T0.addEventListener("message",this._workerListener);else throw Error("MediaStreamTrackProcessor is required but not supported by this browser.")}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose($){if(this._abortController)this._abortController.abort(),this._abortController=null;if(this._workerTrackId!==null)H(this._workerListener),h$({type:"stopTrack",trackId:this._workerTrackId}),await new Promise((J)=>{let Y=(j)=>{let X=j.data;if(X.type==="trackStopped"&&X.trackId===this._workerTrackId)H(this._workerListener),T0.removeEventListener("message",this._workerListener),T0.removeEventListener("message",Y),J()};T0.addEventListener("message",Y)});await this._encoder.flushAndClose($)}}class O1 extends o8{_connectedTrack=null;_codec;constructor($){super();if(!Z0.includes($))throw TypeError(`Invalid audio codec '${$}'. Must be one of: ${Z0.join(", ")}.`);this._codec=$}}class M2 extends O1{constructor($){super($)}add($,J){if(!($ instanceof I))throw TypeError("packet must be an EncodedPacket.");if($.isMetadataOnly)throw TypeError("Metadata-only packets cannot be added.");if(J!==void 0&&(!J||typeof J!=="object"))throw TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,$,J)}}class F2{source;encodingConfig;ensureEncoderPromise=null;encoderInitialized=!1;encoder=null;muxer=null;lastNumberOfChannels=null;lastSampleRate=null;isPcmEncoder=!1;outputSampleSize=null;writeOutputValue=null;customEncoder=null;customEncoderCallSerializer=new v1;customEncoderQueueSize=0;lastEndSampleIndex=null;error=null;errorNeedsNewStack=!0;constructor($,J){this.source=$;this.encodingConfig=J}async add($,J){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if($.numberOfChannels!==this.lastNumberOfChannels||$.sampleRate!==this.lastSampleRate)throw Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${$.numberOfChannels} channels at ${$.sampleRate} Hz.`)}else this.lastNumberOfChannels=$.numberOfChannels,this.lastSampleRate=$.sampleRate;if(!this.encoderInitialized){if(!this.ensureEncoderPromise)this.ensureEncoder($);if(!this.encoderInitialized)await this.ensureEncoderPromise}H(this.encoderInitialized);{let Y=Math.round($.timestamp*$.sampleRate),j=Math.round(($.timestamp+$.duration)*$.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=j;else{let X=Y-this.lastEndSampleIndex;if(X>=64){let Z=new K0({data:new Float32Array(X*$.numberOfChannels),format:"f32-planar",sampleRate:$.sampleRate,numberOfChannels:$.numberOfChannels,numberOfFrames:X,timestamp:this.lastEndSampleIndex/$.sampleRate});await this.add(Z,!0),this.lastEndSampleIndex+=$.numberOfFrames}}this.lastEndSampleIndex=j}if(this.customEncoder){this.customEncoderQueueSize++;let Y=$.clone(),j=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(Y)).then(()=>this.customEncoderQueueSize--).catch((X)=>this.error??=X).finally(()=>{Y.close()});if(this.customEncoderQueueSize>=4)await j;await this.muxer.mutex.currentPromise}else if(this.isPcmEncoder)await this.doPcmEncoding($,J);else{H(this.encoder);let Y=$.toAudioData();if(this.encoder.encode(Y),Y.close(),J)$.close();if(this.encoder.encodeQueueSize>=4)await new Promise((j)=>this.encoder.addEventListener("dequeue",j,{once:!0}));await this.muxer.mutex.currentPromise}}finally{if(J)$.close()}}async doPcmEncoding($,J){H(this.outputSampleSize),H(this.writeOutputValue);let{numberOfChannels:Y,numberOfFrames:j,sampleRate:X,timestamp:Z}=$,G=2048,K=[];for(let W=0;W<j;W+=G){let V=Math.min(G,$.numberOfFrames-W),N=V*Y*this.outputSampleSize,A=new ArrayBuffer(N),R=new DataView(A);K.push({frameCount:V,view:R})}let Q=$.allocationSize({planeIndex:0,format:"f32-planar"}),q=new Float32Array(Q/Float32Array.BYTES_PER_ELEMENT);for(let W=0;W<Y;W++){$.copyTo(q,{planeIndex:W,format:"f32-planar"});for(let V=0;V<K.length;V++){let{frameCount:N,view:A}=K[V];for(let R=0;R<N;R++)this.writeOutputValue(A,(R*Y+W)*this.outputSampleSize,q[V*G+R])}}if(J)$.close();let U={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:Y,sampleRate:X}};for(let W=0;W<K.length;W++){let{frameCount:V,view:N}=K[W],A=N.buffer,R=W*G,z=new I(new Uint8Array(A),"key",Z+R/X,V/X);this.encodingConfig.onEncodedPacket?.(z,U),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,z,U)}}ensureEncoder($){let J=Error();this.ensureEncoderPromise=(async()=>{let{numberOfChannels:Y,sampleRate:j}=$,X=z6({numberOfChannels:Y,sampleRate:j,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(X);let Z=S1.find((G)=>G.supports(this.encodingConfig.codec,X));if(Z)this.customEncoder=new Z,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=X,this.customEncoder.onPacket=(G,K)=>{if(!(G instanceof I))throw TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(K!==void 0&&(!K||typeof K!=="object"))throw TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(G,K),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,G,K).catch((Q)=>{this.error??=Q,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else if(o.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(X)).supported)throw Error(`This specific encoder configuration (${X.codec}, ${X.bitrate} bps, ${X.numberOfChannels} channels, ${X.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);this.encoder=new AudioEncoder({output:(K,Q)=>{if(this.encodingConfig.codec==="aac"&&Q?.decoderConfig){let U=!1;if(!Q.decoderConfig.description||Q.decoderConfig.description.byteLength<2)U=!0;else U=x1(l(Q.decoderConfig.description)).objectType===0;if(U){let W=Number(n(X.codec.split(".")));Q.decoderConfig.description=bJ({objectType:W,numberOfChannels:Q.decoderConfig.numberOfChannels,sampleRate:Q.decoderConfig.sampleRate})}}let q=I.fromEncodedChunk(K);this.encodingConfig.onEncodedPacket?.(q,Q),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,q,Q).catch((U)=>{this.error??=U,this.errorNeedsNewStack=!1})},error:(K)=>{K.stack=J.stack,this.error??=K}}),this.encoder.configure(X)}H(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let $=this.encodingConfig.codec,{dataType:J,sampleSize:Y,littleEndian:j}=U0($);switch(this.outputSampleSize=Y,Y){case 1:if(J==="unsigned")this.writeOutputValue=(X,Z,G)=>X.setUint8(Z,$0((G+1)*127.5,0,255));else if(J==="signed")this.writeOutputValue=(X,Z,G)=>{X.setInt8(Z,$0(Math.round(G*128),-128,127))};else if(J==="ulaw")this.writeOutputValue=(X,Z,G)=>{let K=$0(Math.floor(G*32767),-32768,32767);X.setUint8(Z,aJ(K))};else if(J==="alaw")this.writeOutputValue=(X,Z,G)=>{let K=$0(Math.floor(G*32767),-32768,32767);X.setUint8(Z,eJ(K))};else H(!1);break;case 2:if(J==="unsigned")this.writeOutputValue=(X,Z,G)=>X.setUint16(Z,$0((G+1)*32767.5,0,65535),j);else if(J==="signed")this.writeOutputValue=(X,Z,G)=>X.setInt16(Z,$0(Math.round(G*32767),-32768,32767),j);else H(!1);break;case 3:if(J==="unsigned")this.writeOutputValue=(X,Z,G)=>L8(X,Z,$0((G+1)*8388607.5,0,16777215),j);else if(J==="signed")this.writeOutputValue=(X,Z,G)=>AJ(X,Z,$0(Math.round(G*8388607),-8388608,8388607),j);else H(!1);break;case 4:if(J==="unsigned")this.writeOutputValue=(X,Z,G)=>X.setUint32(Z,$0((G+1)*2147483647.5,0,4294967295),j);else if(J==="signed")this.writeOutputValue=(X,Z,G)=>X.setInt32(Z,$0(Math.round(G*2147483647),-2147483648,2147483647),j);else if(J==="float")this.writeOutputValue=(X,Z,G)=>X.setFloat32(Z,G,j);else H(!1);break;case 8:if(J==="float")this.writeOutputValue=(X,Z,G)=>X.setFloat64(Z,G,j);else H(!1);break;default:i(Y),H(!1)}}async flushAndClose($){if(!$)this.checkForEncoderError();if(this.customEncoder){if(!$)this.customEncoderCallSerializer.call(()=>this.customEncoder.flush());await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())}else if(this.encoder){if(!$)await this.encoder.flush();if(this.encoder.state!=="closed")this.encoder.close()}if(!$)this.checkForEncoderError()}getQueueSize(){if(this.customEncoder)return this.customEncoderQueueSize;if(this.isPcmEncoder)return 0;return this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error){if(this.errorNeedsNewStack)this.error.stack=Error().stack;throw this.error}}}class i8 extends O1{_encoder;constructor($){L6($);super($.codec);this._encoder=new F2(this,$)}add($){if(!($ instanceof K0))throw TypeError("audioSample must be an AudioSample.");return this._encoder.add($,!1)}_flushAndClose($){return this._encoder.flushAndClose($)}}class MY extends O1{_encoder;_accumulatedTime=0;constructor($){L6($);super($.codec);this._encoder=new F2(this,$)}async add($){if(!($ instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let J=K0._fromAudioBuffer($,this._accumulatedTime);this._accumulatedTime+=$.duration;for(let Y of J)await this._encoder.add(Y,!0)}_flushAndClose($){return this._encoder.flushAndClose($)}}class FY extends O1{_encoder;_abortController=null;_track;_audioContext=null;_scriptProcessorNode=null;_promiseWithResolvers=c();_errorPromiseAccessed=!1;_paused=!1;_lastSampleTimestamp=null;_pauseOffset=0;get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor($,J){if(!($ instanceof MediaStreamTrack)||$.kind!=="audio")throw TypeError("track must be an audio MediaStreamTrack.");L6(J);super(J.codec);this._encoder=new F2(this,J),this._track=$}async _start(){if(!this._errorPromiseAccessed)console.warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");this._abortController=new AbortController;let $=null,J=!1,Y=(j)=>{if(J){j.close();return}let X=j.timestamp;if(this._paused){if($!==null){if(this._lastSampleTimestamp!==null){let G=X-this._lastSampleTimestamp;this._pauseOffset-=G}this._lastSampleTimestamp=X}j.close();return}if($===null){$=j.timestamp;let Z=this._connectedTrack.output._muxer;if(Z.firstMediaStreamTimestamp===null)Z.firstMediaStreamTimestamp=performance.now()/1000,this._timestampOffset=-$;else this._timestampOffset=performance.now()/1000-Z.firstMediaStreamTimestamp-$}if(this._lastSampleTimestamp=X,this._encoder.getQueueSize()>=4){j.close();return}j.setTimestamp(X+this._pauseOffset),this._encoder.add(j,!0).catch((Z)=>{J=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(Z),this._audioContext?.suspend()})};if(typeof MediaStreamTrackProcessor<"u"){let j=new MediaStreamTrackProcessor({track:this._track}),X=new WritableStream({write:(Z)=>Y(new K0(Z))});j.readable.pipeTo(X,{signal:this._abortController.signal}).catch((Z)=>{if(Z instanceof DOMException&&Z.name==="AbortError")return;this._promiseWithResolvers.reject(Z)})}else{let j=window.AudioContext||window.webkitAudioContext;this._audioContext=new j({sampleRate:this._track.getSettings().sampleRate});let X=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));if(this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state==="suspended")await this._audioContext.resume();X.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let Z=0;this._scriptProcessorNode.onaudioprocess=(G)=>{let K=K0._fromAudioBuffer(G.inputBuffer,Z);Z+=G.inputBuffer.duration;for(let Q of K)Y(Q)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose($){if(this._abortController)this._abortController.abort(),this._abortController=null;if(this._audioContext)H(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend();await this._encoder.flushAndClose($)}}var Zj=()=>{let $=(j,X)=>{if(X)self.postMessage(j,{transfer:X});else self.postMessage(j)};$({type:"support",supported:typeof MediaStreamTrackProcessor<"u"});let J=new Map,Y=new Map;self.addEventListener("message",(j)=>{let X=j.data;switch(X.type){case"videoTrack":{Y.set(X.trackId,X.track);let Z=new MediaStreamTrackProcessor({track:X.track}),G=new WritableStream({write:(Q)=>{if(!Y.has(X.trackId)){Q.close();return}$({type:"videoFrame",trackId:X.trackId,videoFrame:Q},[Q])}}),K=new AbortController;J.set(X.trackId,K),Z.readable.pipeTo(G,{signal:K.signal}).catch((Q)=>{if(Q instanceof DOMException&&Q.name==="AbortError")return;$({type:"error",trackId:X.trackId,error:Q})})}break;case"stopTrack":{let Z=J.get(X.trackId);if(Z)Z.abort(),J.delete(X.trackId);Y.get(X.trackId)?.stop(),Y.delete(X.trackId),$({type:"trackStopped",trackId:X.trackId})}break;default:i(X)}})},Gj=0,T0=null,Kj=()=>{let $=new Blob([`(${Zj.toString()})()`],{type:"application/javascript"}),J=URL.createObjectURL($);T0=new Worker(J)},S$=null,Qj=async()=>{if(S$!==null)return S$;if(!T0)Kj();return new Promise(($)=>{H(T0);let J=(Y)=>{let j=Y.data;if(j.type==="support")S$=j.supported,T0.removeEventListener("message",J),$(j.supported)};T0.addEventListener("message",J)})},h$=($,J)=>{if(H(T0),J)T0.postMessage($,J);else T0.postMessage($)};class s8 extends o8{_connectedTrack=null;_codec;constructor($){super();if(!z0.includes($))throw TypeError(`Invalid subtitle codec '${$}'. Must be one of: ${z0.join(", ")}.`);this._codec=$}}class B2 extends s8{_parser;_error=null;constructor($){super($);this._parser=new c6({codec:$,output:(J,Y)=>{this._connectedTrack?.output._muxer.addSubtitleCue(this._connectedTrack,J,Y).catch((j)=>{this._error??=j instanceof Error?j:Error(String(j))})}})}add($){if(typeof $!=="string")throw TypeError("text must be a string.");return this._checkForError(),this._ensureValidAdd(),this._parser.parse($),this._connectedTrack.output._muxer.mutex.currentPromise}_checkForError(){if(this._error)throw this._error}async _flushAndClose($){if(!$)this._checkForError()}}/*!
365
+ `),Y=this.gl.createProgram();return this.gl.attachShader(Y,$),this.gl.attachShader(Y,J),this.gl.linkProgram(Y),Y}createShader($,J){let Y=this.gl.createShader($);if(this.gl.shaderSource(Y,J),this.gl.compileShader(Y),!this.gl.getShaderParameter(Y,this.gl.COMPILE_STATUS))console.error("Shader compile error:",this.gl.getShaderInfoLog(Y));return Y}createVAO(){let $=this.gl.createVertexArray();this.gl.bindVertexArray($);let J=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),Y=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,Y),this.gl.bufferData(this.gl.ARRAY_BUFFER,J,this.gl.STATIC_DRAW);let j=this.gl.getAttribLocation(this.colorProgram,"a_position"),X=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(j),this.gl.vertexAttribPointer(j,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(X),this.gl.vertexAttribPointer(X,2,this.gl.FLOAT,!1,16,8),$}createTexture(){let $=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,$),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),$}updateTexture($){if(this.lastFrame===$)return;if($.displayWidth!==this.canvas.width||$.displayHeight!==this.canvas.height)this.canvas.width=$.displayWidth,this.canvas.height=$.displayHeight;this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,$),this.lastFrame=$}extractColor($){return this.updateTexture($),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:$.timestamp,duration:$.duration??void 0,alpha:"discard"})}extractAlpha($){this.updateTexture($),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);let{width:J,height:Y}=this.canvas,j=Math.ceil(J/2)*Math.ceil(Y/2),X=J*Y+j*2,Z=Math.ceil(X/(J*4)),G=new Uint8Array(4*J*Z);this.gl.readPixels(0,0,J,Z,this.gl.RGBA,this.gl.UNSIGNED_BYTE,G),G=G.subarray(0,X),H(G[J*Y]===128),H(G[G.length-1]===128);let K={format:"I420",codedWidth:J,codedHeight:Y,timestamp:$.timestamp,duration:$.duration??void 0,transfer:[G.buffer]};return new VideoFrame(G,K)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class r8 extends w1{_encoder;constructor($){_6($);super($.codec);this._encoder=new L2(this,$)}add($,J){if(!($ instanceof J0))throw TypeError("videoSample must be a VideoSample.");return this._encoder.add($,!1,J)}_flushAndClose($){return this._encoder.flushAndClose($)}}class _Y extends w1{_encoder;_canvas;constructor($,J){if(!(typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&$ instanceof OffscreenCanvas))throw TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");_6(J);super(J.codec);this._encoder=new L2(this,J),this._canvas=$}add($,J=0,Y){if(!Number.isFinite($)||$<0)throw TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(J)||J<0)throw TypeError("duration must be a non-negative number.");let j=new J0(this._canvas,{timestamp:$,duration:J});return this._encoder.add(j,!0,Y)}_flushAndClose($){return this._encoder.flushAndClose($)}}class LY extends w1{_encoder;_abortController=null;_track;_workerTrackId=null;_workerListener=null;_promiseWithResolvers=c();_errorPromiseAccessed=!1;_paused=!1;_lastSampleTimestamp=null;_pauseOffset=0;get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor($,J){if(!($ instanceof MediaStreamTrack)||$.kind!=="video")throw TypeError("track must be a video MediaStreamTrack.");_6(J),J={...J,latencyMode:"realtime"};super(J.codec);this._encoder=new L2(this,J),this._track=$}async _start(){if(!this._errorPromiseAccessed)console.warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");this._abortController=new AbortController;let $=null,J=!1,Y=(j)=>{if(J){j.close();return}let X=j.timestamp/1e6;if(this._paused){if($!==null){if(this._lastSampleTimestamp!==null){let K=X-this._lastSampleTimestamp;this._pauseOffset-=K}this._lastSampleTimestamp=X}j.close();return}if($===null){$=X;let G=this._connectedTrack.output._muxer;if(G.firstMediaStreamTimestamp===null)G.firstMediaStreamTimestamp=performance.now()/1000,this._timestampOffset=-$;else this._timestampOffset=performance.now()/1000-G.firstMediaStreamTimestamp-$}if(this._lastSampleTimestamp=X,this._encoder.getQueueSize()>=4){j.close();return}let Z=new J0(j,{timestamp:X+this._pauseOffset});this._encoder.add(Z,!0).catch((G)=>{if(J=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(G),this._workerTrackId!==null)h$({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){let j=new MediaStreamTrackProcessor({track:this._track}),X=new WritableStream({write:Y});j.readable.pipeTo(X,{signal:this._abortController.signal}).catch((Z)=>{if(Z instanceof DOMException&&Z.name==="AbortError")return;this._promiseWithResolvers.reject(Z)})}else if(await Gj())this._workerTrackId=Xj++,h$({type:"videoTrack",trackId:this._workerTrackId,track:this._track}),this._workerListener=(X)=>{let Z=X.data;if(Z.type==="videoFrame"&&Z.trackId===this._workerTrackId)Y(Z.videoFrame);else if(Z.type==="error"&&Z.trackId===this._workerTrackId)this._promiseWithResolvers.reject(Z.error)},T0.addEventListener("message",this._workerListener);else throw Error("MediaStreamTrackProcessor is required but not supported by this browser.")}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose($){if(this._abortController)this._abortController.abort(),this._abortController=null;if(this._workerTrackId!==null)H(this._workerListener),h$({type:"stopTrack",trackId:this._workerTrackId}),await new Promise((J)=>{let Y=(j)=>{let X=j.data;if(X.type==="trackStopped"&&X.trackId===this._workerTrackId)H(this._workerListener),T0.removeEventListener("message",this._workerListener),T0.removeEventListener("message",Y),J()};T0.addEventListener("message",Y)});await this._encoder.flushAndClose($)}}class O1 extends o8{_connectedTrack=null;_codec;constructor($){super();if(!Z0.includes($))throw TypeError(`Invalid audio codec '${$}'. Must be one of: ${Z0.join(", ")}.`);this._codec=$}}class M2 extends O1{constructor($){super($)}add($,J){if(!($ instanceof I))throw TypeError("packet must be an EncodedPacket.");if($.isMetadataOnly)throw TypeError("Metadata-only packets cannot be added.");if(J!==void 0&&(!J||typeof J!=="object"))throw TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,$,J)}}class F2{source;encodingConfig;ensureEncoderPromise=null;encoderInitialized=!1;encoder=null;muxer=null;lastNumberOfChannels=null;lastSampleRate=null;isPcmEncoder=!1;outputSampleSize=null;writeOutputValue=null;customEncoder=null;customEncoderCallSerializer=new v1;customEncoderQueueSize=0;lastEndSampleIndex=null;error=null;errorNeedsNewStack=!0;constructor($,J){this.source=$;this.encodingConfig=J}async add($,J){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if($.numberOfChannels!==this.lastNumberOfChannels||$.sampleRate!==this.lastSampleRate)throw Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${$.numberOfChannels} channels at ${$.sampleRate} Hz.`)}else this.lastNumberOfChannels=$.numberOfChannels,this.lastSampleRate=$.sampleRate;if(!this.encoderInitialized){if(!this.ensureEncoderPromise)this.ensureEncoder($);if(!this.encoderInitialized)await this.ensureEncoderPromise}H(this.encoderInitialized);{let Y=Math.round($.timestamp*$.sampleRate),j=Math.round(($.timestamp+$.duration)*$.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=j;else{let X=Y-this.lastEndSampleIndex;if(X>=64){let Z=new K0({data:new Float32Array(X*$.numberOfChannels),format:"f32-planar",sampleRate:$.sampleRate,numberOfChannels:$.numberOfChannels,numberOfFrames:X,timestamp:this.lastEndSampleIndex/$.sampleRate});await this.add(Z,!0),this.lastEndSampleIndex+=$.numberOfFrames}}this.lastEndSampleIndex=j}if(this.customEncoder){this.customEncoderQueueSize++;let Y=$.clone(),j=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(Y)).then(()=>this.customEncoderQueueSize--).catch((X)=>this.error??=X).finally(()=>{Y.close()});if(this.customEncoderQueueSize>=4)await j;await this.muxer.mutex.currentPromise}else if(this.isPcmEncoder)await this.doPcmEncoding($,J);else{H(this.encoder);let Y=$.toAudioData();if(this.encoder.encode(Y),Y.close(),J)$.close();if(this.encoder.encodeQueueSize>=4)await new Promise((j)=>this.encoder.addEventListener("dequeue",j,{once:!0}));await this.muxer.mutex.currentPromise}}finally{if(J)$.close()}}async doPcmEncoding($,J){H(this.outputSampleSize),H(this.writeOutputValue);let{numberOfChannels:Y,numberOfFrames:j,sampleRate:X,timestamp:Z}=$,G=2048,K=[];for(let W=0;W<j;W+=G){let V=Math.min(G,$.numberOfFrames-W),N=V*Y*this.outputSampleSize,A=new ArrayBuffer(N),R=new DataView(A);K.push({frameCount:V,view:R})}let Q=$.allocationSize({planeIndex:0,format:"f32-planar"}),q=new Float32Array(Q/Float32Array.BYTES_PER_ELEMENT);for(let W=0;W<Y;W++){$.copyTo(q,{planeIndex:W,format:"f32-planar"});for(let V=0;V<K.length;V++){let{frameCount:N,view:A}=K[V];for(let R=0;R<N;R++)this.writeOutputValue(A,(R*Y+W)*this.outputSampleSize,q[V*G+R])}}if(J)$.close();let U={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:Y,sampleRate:X}};for(let W=0;W<K.length;W++){let{frameCount:V,view:N}=K[W],A=N.buffer,R=W*G,z=new I(new Uint8Array(A),"key",Z+R/X,V/X);this.encodingConfig.onEncodedPacket?.(z,U),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,z,U)}}ensureEncoder($){let J=Error();this.ensureEncoderPromise=(async()=>{let{numberOfChannels:Y,sampleRate:j}=$,X=z6({numberOfChannels:Y,sampleRate:j,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(X);let Z=S1.find((G)=>G.supports(this.encodingConfig.codec,X));if(Z)this.customEncoder=new Z,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=X,this.customEncoder.onPacket=(G,K)=>{if(!(G instanceof I))throw TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(K!==void 0&&(!K||typeof K!=="object"))throw TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(G,K),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,G,K).catch((Q)=>{this.error??=Q,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else if(o.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(X)).supported)throw Error(`This specific encoder configuration (${X.codec}, ${X.bitrate} bps, ${X.numberOfChannels} channels, ${X.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);this.encoder=new AudioEncoder({output:(K,Q)=>{if(this.encodingConfig.codec==="aac"&&Q?.decoderConfig){let U=!1;if(!Q.decoderConfig.description||Q.decoderConfig.description.byteLength<2)U=!0;else U=x1(l(Q.decoderConfig.description)).objectType===0;if(U){let W=Number(n(X.codec.split(".")));Q.decoderConfig.description=bJ({objectType:W,numberOfChannels:Q.decoderConfig.numberOfChannels,sampleRate:Q.decoderConfig.sampleRate})}}let q=I.fromEncodedChunk(K);this.encodingConfig.onEncodedPacket?.(q,Q),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,q,Q).catch((U)=>{this.error??=U,this.errorNeedsNewStack=!1})},error:(K)=>{K.stack=J.stack,this.error??=K}}),this.encoder.configure(X)}H(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let $=this.encodingConfig.codec,{dataType:J,sampleSize:Y,littleEndian:j}=U0($);switch(this.outputSampleSize=Y,Y){case 1:if(J==="unsigned")this.writeOutputValue=(X,Z,G)=>X.setUint8(Z,$0((G+1)*127.5,0,255));else if(J==="signed")this.writeOutputValue=(X,Z,G)=>{X.setInt8(Z,$0(Math.round(G*128),-128,127))};else if(J==="ulaw")this.writeOutputValue=(X,Z,G)=>{let K=$0(Math.floor(G*32767),-32768,32767);X.setUint8(Z,aJ(K))};else if(J==="alaw")this.writeOutputValue=(X,Z,G)=>{let K=$0(Math.floor(G*32767),-32768,32767);X.setUint8(Z,eJ(K))};else H(!1);break;case 2:if(J==="unsigned")this.writeOutputValue=(X,Z,G)=>X.setUint16(Z,$0((G+1)*32767.5,0,65535),j);else if(J==="signed")this.writeOutputValue=(X,Z,G)=>X.setInt16(Z,$0(Math.round(G*32767),-32768,32767),j);else H(!1);break;case 3:if(J==="unsigned")this.writeOutputValue=(X,Z,G)=>L8(X,Z,$0((G+1)*8388607.5,0,16777215),j);else if(J==="signed")this.writeOutputValue=(X,Z,G)=>AJ(X,Z,$0(Math.round(G*8388607),-8388608,8388607),j);else H(!1);break;case 4:if(J==="unsigned")this.writeOutputValue=(X,Z,G)=>X.setUint32(Z,$0((G+1)*2147483647.5,0,4294967295),j);else if(J==="signed")this.writeOutputValue=(X,Z,G)=>X.setInt32(Z,$0(Math.round(G*2147483647),-2147483648,2147483647),j);else if(J==="float")this.writeOutputValue=(X,Z,G)=>X.setFloat32(Z,G,j);else H(!1);break;case 8:if(J==="float")this.writeOutputValue=(X,Z,G)=>X.setFloat64(Z,G,j);else H(!1);break;default:i(Y),H(!1)}}async flushAndClose($){if(!$)this.checkForEncoderError();if(this.customEncoder){if(!$)this.customEncoderCallSerializer.call(()=>this.customEncoder.flush());await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())}else if(this.encoder){if(!$)await this.encoder.flush();if(this.encoder.state!=="closed")this.encoder.close()}if(!$)this.checkForEncoderError()}getQueueSize(){if(this.customEncoder)return this.customEncoderQueueSize;if(this.isPcmEncoder)return 0;return this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error){if(this.errorNeedsNewStack)this.error.stack=Error().stack;throw this.error}}}class i8 extends O1{_encoder;constructor($){L6($);super($.codec);this._encoder=new F2(this,$)}add($){if(!($ instanceof K0))throw TypeError("audioSample must be an AudioSample.");return this._encoder.add($,!1)}_flushAndClose($){return this._encoder.flushAndClose($)}}class MY extends O1{_encoder;_accumulatedTime=0;constructor($){L6($);super($.codec);this._encoder=new F2(this,$)}async add($){if(!($ instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let J=K0._fromAudioBuffer($,this._accumulatedTime);this._accumulatedTime+=$.duration;for(let Y of J)await this._encoder.add(Y,!0)}_flushAndClose($){return this._encoder.flushAndClose($)}}class FY extends O1{_encoder;_abortController=null;_track;_audioContext=null;_scriptProcessorNode=null;_promiseWithResolvers=c();_errorPromiseAccessed=!1;_paused=!1;_lastSampleTimestamp=null;_pauseOffset=0;get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor($,J){if(!($ instanceof MediaStreamTrack)||$.kind!=="audio")throw TypeError("track must be an audio MediaStreamTrack.");L6(J);super(J.codec);this._encoder=new F2(this,J),this._track=$}async _start(){if(!this._errorPromiseAccessed)console.warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");this._abortController=new AbortController;let $=null,J=!1,Y=(j)=>{if(J){j.close();return}let X=j.timestamp;if(this._paused){if($!==null){if(this._lastSampleTimestamp!==null){let G=X-this._lastSampleTimestamp;this._pauseOffset-=G}this._lastSampleTimestamp=X}j.close();return}if($===null){$=j.timestamp;let Z=this._connectedTrack.output._muxer;if(Z.firstMediaStreamTimestamp===null)Z.firstMediaStreamTimestamp=performance.now()/1000,this._timestampOffset=-$;else this._timestampOffset=performance.now()/1000-Z.firstMediaStreamTimestamp-$}if(this._lastSampleTimestamp=X,this._encoder.getQueueSize()>=4){j.close();return}j.setTimestamp(X+this._pauseOffset),this._encoder.add(j,!0).catch((Z)=>{J=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(Z),this._audioContext?.suspend()})};if(typeof MediaStreamTrackProcessor<"u"){let j=new MediaStreamTrackProcessor({track:this._track}),X=new WritableStream({write:(Z)=>Y(new K0(Z))});j.readable.pipeTo(X,{signal:this._abortController.signal}).catch((Z)=>{if(Z instanceof DOMException&&Z.name==="AbortError")return;this._promiseWithResolvers.reject(Z)})}else{let j=window.AudioContext||window.webkitAudioContext;this._audioContext=new j({sampleRate:this._track.getSettings().sampleRate});let X=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));if(this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state==="suspended")await this._audioContext.resume();X.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let Z=0;this._scriptProcessorNode.onaudioprocess=(G)=>{let K=K0._fromAudioBuffer(G.inputBuffer,Z);Z+=G.inputBuffer.duration;for(let Q of K)Y(Q)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose($){if(this._abortController)this._abortController.abort(),this._abortController=null;if(this._audioContext)H(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend();await this._encoder.flushAndClose($)}}var jj=()=>{let $=(j,X)=>{if(X)self.postMessage(j,{transfer:X});else self.postMessage(j)};$({type:"support",supported:typeof MediaStreamTrackProcessor<"u"});let J=new Map,Y=new Map;self.addEventListener("message",(j)=>{let X=j.data;switch(X.type){case"videoTrack":{Y.set(X.trackId,X.track);let Z=new MediaStreamTrackProcessor({track:X.track}),G=new WritableStream({write:(Q)=>{if(!Y.has(X.trackId)){Q.close();return}$({type:"videoFrame",trackId:X.trackId,videoFrame:Q},[Q])}}),K=new AbortController;J.set(X.trackId,K),Z.readable.pipeTo(G,{signal:K.signal}).catch((Q)=>{if(Q instanceof DOMException&&Q.name==="AbortError")return;$({type:"error",trackId:X.trackId,error:Q})})}break;case"stopTrack":{let Z=J.get(X.trackId);if(Z)Z.abort(),J.delete(X.trackId);Y.get(X.trackId)?.stop(),Y.delete(X.trackId),$({type:"trackStopped",trackId:X.trackId})}break;default:i(X)}})},Xj=0,T0=null,Zj=()=>{let $=new Blob([`(${jj.toString()})()`],{type:"application/javascript"}),J=URL.createObjectURL($);T0=new Worker(J)},S$=null,Gj=async()=>{if(S$!==null)return S$;if(!T0)Zj();return new Promise(($)=>{H(T0);let J=(Y)=>{let j=Y.data;if(j.type==="support")S$=j.supported,T0.removeEventListener("message",J),$(j.supported)};T0.addEventListener("message",J)})},h$=($,J)=>{if(H(T0),J)T0.postMessage($,J);else T0.postMessage($)};class s8 extends o8{_connectedTrack=null;_codec;constructor($){super();if(!z0.includes($))throw TypeError(`Invalid subtitle codec '${$}'. Must be one of: ${z0.join(", ")}.`);this._codec=$}}class B2 extends s8{_parser;_error=null;constructor($){super($);this._parser=new c6({codec:$,output:(J,Y)=>{this._connectedTrack?.output._muxer.addSubtitleCue(this._connectedTrack,J,Y).catch((j)=>{this._error??=j instanceof Error?j:Error(String(j))})}})}add($){if(typeof $!=="string")throw TypeError("text must be a string.");return this._checkForError(),this._ensureValidAdd(),this._parser.parse($),this._connectedTrack.output._muxer.mutex.currentPromise}_checkForError(){if(this._error)throw this._error}async _flushAndClose($){if(!$)this._checkForError()}}/*!
366
366
  * Copyright (c) 2025-present, Vanilagy and contributors
367
367
  *
368
368
  * This Source Code Form is subject to the terms of the Mozilla Public
@@ -392,39 +392,39 @@ ${K.join(`
392
392
  * This Source Code Form is subject to the terms of the Mozilla Public
393
393
  * License, v. 2.0. If a copy of the MPL was not distributed with this
394
394
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
395
- */var BY=new Uint8Array([102,76,97,67]),qj=38,Uj=34;class u$ extends V0{writer;metadataWritten=!1;blockSizes=[];frameSizes=[];sampleRate=null;channels=null;bitsPerSample=null;format;constructor($,J){super($);this.writer=$._writer,this.format=J}async start(){this.writer.write(BY)}writeHeader({bitsPerSample:$,minimumBlockSize:J,maximumBlockSize:Y,minimumFrameSize:j,maximumFrameSize:X,sampleRate:Z,channels:G,totalSamples:K}){H(this.writer.getPos()===4);let Q=!m1(this.output._metadataTags),q=new f(new Uint8Array(4));q.writeBits(1,Number(!Q)),q.writeBits(7,0),q.writeBits(24,Uj),this.writer.write(q.bytes);let U=new f(new Uint8Array(18));if(U.writeBits(16,J),U.writeBits(16,Y),U.writeBits(24,j),U.writeBits(24,X),U.writeBits(20,Z),U.writeBits(3,G-1),U.writeBits(5,$-1),K>=4294967296)throw Error("This muxer only supports writing up to 2 ** 32 samples");U.writeBits(4,0),U.writeBits(32,K),this.writer.write(U.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock($){let J=32+$.mimeType.length+($.description?.length??0)+$.data.length,Y=new Uint8Array(J),j=0,X=h(Y);X.setUint32(j,$.kind==="coverFront"?3:$.kind==="coverBack"?4:0),j+=4,X.setUint32(j,$.mimeType.length),j+=4,Y.set(m.encode($.mimeType),8),j+=$.mimeType.length,X.setUint32(j,$.description?.length??0),j+=4,Y.set(m.encode($.description??""),j),j+=$.description?.length??0,j+=16,X.setUint32(j,$.data.length),j+=4,Y.set($.data,j),j+=$.data.length,H(j===J);let Z=new f(new Uint8Array(4));Z.writeBits(1,0),Z.writeBits(7,6),Z.writeBits(24,J),this.writer.write(Z.bytes),this.writer.write(Y)}writeVorbisCommentAndPictureBlock(){if(this.writer.seek(qj+BY.byteLength),m1(this.output._metadataTags)){this.metadataWritten=!0;return}let $=this.output._metadataTags.images??[];for(let j of $)this.writePictureBlock(j);let J=C8(new Uint8Array(0),this.output._metadataTags,!1),Y=new f(new Uint8Array(4));Y.writeBits(1,1),Y.writeBits(7,4),Y.writeBits(24,J.length),this.writer.write(Y.bytes),this.writer.write(J),this.metadataWritten=!0}async getMimeType(){return"audio/flac"}async addEncodedVideoPacket(){throw Error("FLAC does not support video.")}async addEncodedAudioPacket($,J,Y){let j=await this.mutex.acquire();_0(Y),H(Y),H(Y.decoderConfig),H(Y.decoderConfig.description);try{if(this.validateAndNormalizeTimestamp($,J.timestamp,J.type==="key"),this.sampleRate===null)this.sampleRate=Y.decoderConfig.sampleRate;if(this.channels===null)this.channels=Y.decoderConfig.numberOfChannels;if(this.bitsPerSample===null){let U=new f(l(Y.decoderConfig.description));U.skipBits(167);let W=U.readBits(5)+1;this.bitsPerSample=W}if(!this.metadataWritten)this.writeVorbisCommentAndPictureBlock();let X=S0.tempFromBytes(J.data);D(X,2);let Z=D(X,2),G=new f(Z),K=s6(G.readBits(4));if(K===null)throw Error("Invalid FLAC frame: Invalid block size.");a6(X);let Q=t6(X,K);this.blockSizes.push(Q),this.frameSizes.push(J.data.length);let q=this.writer.getPos();if(this.writer.write(J.data),this.format._options.onFrame)this.format._options.onFrame(J.data,q);await this.writer.flush()}finally{j()}}addSubtitleCue(){throw Error("FLAC does not support subtitles.")}async finalize(){let $=await this.mutex.acquire(),J=Number.POSITIVE_INFINITY,Y=0,j=Number.POSITIVE_INFINITY,X=0,Z=0;for(let G=0;G<this.blockSizes.length;G++){if(j=Math.min(j,this.frameSizes[G]),X=Math.max(X,this.frameSizes[G]),Y=Math.max(Y,this.blockSizes[G]),Z+=this.blockSizes[G],G===this.blockSizes.length-1)continue;J=Math.min(J,this.blockSizes[G])}H(this.sampleRate!==null),H(this.channels!==null),H(this.bitsPerSample!==null),this.writer.seek(4),this.writeHeader({minimumBlockSize:J,maximumBlockSize:Y,minimumFrameSize:j,maximumFrameSize:X,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:Z}),$()}}x0();var wY=(()=>({}));/*!
395
+ */var BY=new Uint8Array([102,76,97,67]),Kj=38,Qj=34;class u$ extends V0{writer;metadataWritten=!1;blockSizes=[];frameSizes=[];sampleRate=null;channels=null;bitsPerSample=null;format;constructor($,J){super($);this.writer=$._writer,this.format=J}async start(){this.writer.write(BY)}writeHeader({bitsPerSample:$,minimumBlockSize:J,maximumBlockSize:Y,minimumFrameSize:j,maximumFrameSize:X,sampleRate:Z,channels:G,totalSamples:K}){H(this.writer.getPos()===4);let Q=!m1(this.output._metadataTags),q=new f(new Uint8Array(4));q.writeBits(1,Number(!Q)),q.writeBits(7,0),q.writeBits(24,Qj),this.writer.write(q.bytes);let U=new f(new Uint8Array(18));if(U.writeBits(16,J),U.writeBits(16,Y),U.writeBits(24,j),U.writeBits(24,X),U.writeBits(20,Z),U.writeBits(3,G-1),U.writeBits(5,$-1),K>=4294967296)throw Error("This muxer only supports writing up to 2 ** 32 samples");U.writeBits(4,0),U.writeBits(32,K),this.writer.write(U.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock($){let J=32+$.mimeType.length+($.description?.length??0)+$.data.length,Y=new Uint8Array(J),j=0,X=h(Y);X.setUint32(j,$.kind==="coverFront"?3:$.kind==="coverBack"?4:0),j+=4,X.setUint32(j,$.mimeType.length),j+=4,Y.set(m.encode($.mimeType),8),j+=$.mimeType.length,X.setUint32(j,$.description?.length??0),j+=4,Y.set(m.encode($.description??""),j),j+=$.description?.length??0,j+=16,X.setUint32(j,$.data.length),j+=4,Y.set($.data,j),j+=$.data.length,H(j===J);let Z=new f(new Uint8Array(4));Z.writeBits(1,0),Z.writeBits(7,6),Z.writeBits(24,J),this.writer.write(Z.bytes),this.writer.write(Y)}writeVorbisCommentAndPictureBlock(){if(this.writer.seek(Kj+BY.byteLength),m1(this.output._metadataTags)){this.metadataWritten=!0;return}let $=this.output._metadataTags.images??[];for(let j of $)this.writePictureBlock(j);let J=C8(new Uint8Array(0),this.output._metadataTags,!1),Y=new f(new Uint8Array(4));Y.writeBits(1,1),Y.writeBits(7,4),Y.writeBits(24,J.length),this.writer.write(Y.bytes),this.writer.write(J),this.metadataWritten=!0}async getMimeType(){return"audio/flac"}async addEncodedVideoPacket(){throw Error("FLAC does not support video.")}async addEncodedAudioPacket($,J,Y){let j=await this.mutex.acquire();_0(Y),H(Y),H(Y.decoderConfig),H(Y.decoderConfig.description);try{if(this.validateAndNormalizeTimestamp($,J.timestamp,J.type==="key"),this.sampleRate===null)this.sampleRate=Y.decoderConfig.sampleRate;if(this.channels===null)this.channels=Y.decoderConfig.numberOfChannels;if(this.bitsPerSample===null){let U=new f(l(Y.decoderConfig.description));U.skipBits(167);let W=U.readBits(5)+1;this.bitsPerSample=W}if(!this.metadataWritten)this.writeVorbisCommentAndPictureBlock();let X=S0.tempFromBytes(J.data);D(X,2);let Z=D(X,2),G=new f(Z),K=s6(G.readBits(4));if(K===null)throw Error("Invalid FLAC frame: Invalid block size.");a6(X);let Q=t6(X,K);this.blockSizes.push(Q),this.frameSizes.push(J.data.length);let q=this.writer.getPos();if(this.writer.write(J.data),this.format._options.onFrame)this.format._options.onFrame(J.data,q);await this.writer.flush()}finally{j()}}addSubtitleCue(){throw Error("FLAC does not support subtitles.")}async finalize(){let $=await this.mutex.acquire(),J=Number.POSITIVE_INFINITY,Y=0,j=Number.POSITIVE_INFINITY,X=0,Z=0;for(let G=0;G<this.blockSizes.length;G++){if(j=Math.min(j,this.frameSizes[G]),X=Math.max(X,this.frameSizes[G]),Y=Math.max(Y,this.blockSizes[G]),Z+=this.blockSizes[G],G===this.blockSizes.length-1)continue;J=Math.min(J,this.blockSizes[G])}H(this.sampleRate!==null),H(this.channels!==null),H(this.bitsPerSample!==null),this.writer.seek(4),this.writeHeader({minimumBlockSize:J,maximumBlockSize:Y,minimumFrameSize:j,maximumFrameSize:X,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:Z}),$()}}x0();/*!
396
396
  * Copyright (c) 2025-present, Vanilagy and contributors
397
397
  *
398
398
  * This Source Code Form is subject to the terms of the Mozilla Public
399
399
  * License, v. 2.0. If a copy of the MPL was not distributed with this
400
400
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
401
- */class w2{ensureMonotonicity=!1;start(){}trackedWrites=null;trackedStart=-1;trackedEnd=-1;maybeTrackWrites($){if(!this.trackedWrites)return;let J=this.getPos();if(J<this.trackedStart){if(J+$.byteLength<=this.trackedStart)return;$=$.subarray(this.trackedStart-J),J=0}let Y=J+$.byteLength-this.trackedStart,j=this.trackedWrites.byteLength;while(j<Y)j*=2;if(j!==this.trackedWrites.byteLength){let X=new Uint8Array(j);X.set(this.trackedWrites,0),this.trackedWrites=X}this.trackedWrites.set($,J-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,J+$.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error("Internal error: Can't get tracked writes since nothing was tracked.");let J={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,J}}var p$=65536,l$=4294967296;class a8 extends w2{pos=0;target;buffer;bytes;maxPos=0;supportsResize;constructor($){super();if(this.target=$,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(p$,{maxByteLength:l$})}catch{this.buffer=new ArrayBuffer(p$),this.supportsResize=!1}else this.buffer=new ArrayBuffer(p$);this.bytes=new Uint8Array(this.buffer)}ensureSize($){let J=this.buffer.byteLength;while(J<$)J*=2;if(J===this.buffer.byteLength)return;if(J>l$)throw Error(`ArrayBuffer exceeded maximum size of ${l$} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(J);else{let Y=new ArrayBuffer(J),j=new Uint8Array(Y);j.set(this.bytes,0),this.buffer=Y,this.bytes=j}}write($){this.maybeTrackWrites($),this.ensureSize(this.pos+$.byteLength),this.bytes.set($,this.pos),this.target.onwrite?.(this.pos,this.pos+$.byteLength),this.pos+=$.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek($){this.pos=$}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice($,J){return this.bytes.slice($,J)}}var Wj=16777216,Vj=2;class m$ extends w2{pos=0;target;sections=[];lastWriteEnd=0;lastFlushEnd=0;writer=null;chunked;chunkSize;chunks=[];constructor($){super();this.target=$,this.chunked=$._options.chunked??!1,this.chunkSize=$._options.chunkSize??Wj}start(){this.writer=this.target._writable.getWriter()}write($){if(this.pos>this.lastWriteEnd){let J=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(J))}this.maybeTrackWrites($),this.sections.push({data:$.slice(),start:this.pos}),this.target.onwrite?.(this.pos,this.pos+$.byteLength),this.pos+=$.byteLength,this.lastWriteEnd=Math.max(this.lastWriteEnd,this.pos)}seek($){this.pos=$}getPos(){return this.pos}async flush(){if(this.pos>this.lastWriteEnd){let Y=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(Y))}if(H(this.writer),this.sections.length===0)return;let $=[],J=[...this.sections].sort((Y,j)=>Y.start-j.start);$.push({start:J[0].start,size:J[0].data.byteLength});for(let Y=1;Y<J.length;Y++){let j=$[$.length-1],X=J[Y];if(X.start<=j.start+j.size)j.size=Math.max(j.size,X.start+X.data.byteLength-j.start);else $.push({start:X.start,size:X.data.byteLength})}for(let Y of $){Y.data=new Uint8Array(Y.size);for(let j of this.sections)if(Y.start<=j.start&&j.start<Y.start+Y.size)Y.data.set(j.data,j.start-Y.start);if(this.writer.desiredSize!==null&&this.writer.desiredSize<=0)await this.writer.ready;if(this.chunked)this.writeDataIntoChunks(Y.data,Y.start),this.tryToFlushChunks();else{if(this.ensureMonotonicity&&Y.start!==this.lastFlushEnd)throw Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:Y.data,position:Y.start}),this.lastFlushEnd=Y.start+Y.data.byteLength}}this.sections.length=0}writeDataIntoChunks($,J){let Y=this.chunks.findIndex((K)=>K.start<=J&&J<K.start+this.chunkSize);if(Y===-1)Y=this.createChunk(J);let j=this.chunks[Y],X=J-j.start,Z=$.subarray(0,Math.min(this.chunkSize-X,$.byteLength));j.data.set(Z,X);let G={start:X,end:X+Z.byteLength};if(this.insertSectionIntoChunk(j,G),j.written[0].start===0&&j.written[0].end===this.chunkSize)j.shouldFlush=!0;if(this.chunks.length>Vj){for(let K=0;K<this.chunks.length-1;K++)this.chunks[K].shouldFlush=!0;this.tryToFlushChunks()}if(Z.byteLength<$.byteLength)this.writeDataIntoChunks($.subarray(Z.byteLength),J+Z.byteLength)}insertSectionIntoChunk($,J){let Y=0,j=$.written.length-1,X=-1;while(Y<=j){let Z=Math.floor(Y+(j-Y+1)/2);if($.written[Z].start<=J.start)Y=Z+1,X=Z;else j=Z-1}if($.written.splice(X+1,0,J),X===-1||$.written[X].end<J.start)X++;while(X<$.written.length-1&&$.written[X].end>=$.written[X+1].start)$.written[X].end=Math.max($.written[X].end,$.written[X+1].end),$.written.splice(X+1,1)}createChunk($){let Y={start:Math.floor($/this.chunkSize)*this.chunkSize,data:new Uint8Array(this.chunkSize),written:[],shouldFlush:!1};return this.chunks.push(Y),this.chunks.sort((j,X)=>j.start-X.start),this.chunks.indexOf(Y)}tryToFlushChunks($=!1){H(this.writer);for(let J=0;J<this.chunks.length;J++){let Y=this.chunks[J];if(!Y.shouldFlush&&!$)continue;for(let j of Y.written){let X=Y.start+j.start;if(this.ensureMonotonicity&&X!==this.lastFlushEnd)throw Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:Y.data.subarray(j.start,j.end),position:X}),this.lastFlushEnd=Y.start+j.end}this.chunks.splice(J--,1)}}finalize(){if(this.chunked)this.tryToFlushChunks(!0);return H(this.writer),this.writer.close()}async close(){return this.writer?.close()}}class d$ extends w2{target;pos=0;constructor($){super();this.target=$}write($){this.maybeTrackWrites($),this.target.onwrite?.(this.pos,this.pos+$.byteLength),this.pos+=$.byteLength}getPos(){return this.pos}seek($){this.pos=$}async flush(){}async finalize(){}async close(){}}/*!
401
+ */class w2{ensureMonotonicity=!1;start(){}trackedWrites=null;trackedStart=-1;trackedEnd=-1;maybeTrackWrites($){if(!this.trackedWrites)return;let J=this.getPos();if(J<this.trackedStart){if(J+$.byteLength<=this.trackedStart)return;$=$.subarray(this.trackedStart-J),J=0}let Y=J+$.byteLength-this.trackedStart,j=this.trackedWrites.byteLength;while(j<Y)j*=2;if(j!==this.trackedWrites.byteLength){let X=new Uint8Array(j);X.set(this.trackedWrites,0),this.trackedWrites=X}this.trackedWrites.set($,J-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,J+$.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error("Internal error: Can't get tracked writes since nothing was tracked.");let J={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,J}}var p$=65536,l$=4294967296;class a8 extends w2{pos=0;target;buffer;bytes;maxPos=0;supportsResize;constructor($){super();if(this.target=$,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(p$,{maxByteLength:l$})}catch{this.buffer=new ArrayBuffer(p$),this.supportsResize=!1}else this.buffer=new ArrayBuffer(p$);this.bytes=new Uint8Array(this.buffer)}ensureSize($){let J=this.buffer.byteLength;while(J<$)J*=2;if(J===this.buffer.byteLength)return;if(J>l$)throw Error(`ArrayBuffer exceeded maximum size of ${l$} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(J);else{let Y=new ArrayBuffer(J),j=new Uint8Array(Y);j.set(this.bytes,0),this.buffer=Y,this.bytes=j}}write($){this.maybeTrackWrites($),this.ensureSize(this.pos+$.byteLength),this.bytes.set($,this.pos),this.target.onwrite?.(this.pos,this.pos+$.byteLength),this.pos+=$.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek($){this.pos=$}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice($,J){return this.bytes.slice($,J)}}var qj=16777216,Uj=2;class m$ extends w2{pos=0;target;sections=[];lastWriteEnd=0;lastFlushEnd=0;writer=null;chunked;chunkSize;chunks=[];constructor($){super();this.target=$,this.chunked=$._options.chunked??!1,this.chunkSize=$._options.chunkSize??qj}start(){this.writer=this.target._writable.getWriter()}write($){if(this.pos>this.lastWriteEnd){let J=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(J))}this.maybeTrackWrites($),this.sections.push({data:$.slice(),start:this.pos}),this.target.onwrite?.(this.pos,this.pos+$.byteLength),this.pos+=$.byteLength,this.lastWriteEnd=Math.max(this.lastWriteEnd,this.pos)}seek($){this.pos=$}getPos(){return this.pos}async flush(){if(this.pos>this.lastWriteEnd){let Y=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(Y))}if(H(this.writer),this.sections.length===0)return;let $=[],J=[...this.sections].sort((Y,j)=>Y.start-j.start);$.push({start:J[0].start,size:J[0].data.byteLength});for(let Y=1;Y<J.length;Y++){let j=$[$.length-1],X=J[Y];if(X.start<=j.start+j.size)j.size=Math.max(j.size,X.start+X.data.byteLength-j.start);else $.push({start:X.start,size:X.data.byteLength})}for(let Y of $){Y.data=new Uint8Array(Y.size);for(let j of this.sections)if(Y.start<=j.start&&j.start<Y.start+Y.size)Y.data.set(j.data,j.start-Y.start);if(this.writer.desiredSize!==null&&this.writer.desiredSize<=0)await this.writer.ready;if(this.chunked)this.writeDataIntoChunks(Y.data,Y.start),this.tryToFlushChunks();else{if(this.ensureMonotonicity&&Y.start!==this.lastFlushEnd)throw Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:Y.data,position:Y.start}),this.lastFlushEnd=Y.start+Y.data.byteLength}}this.sections.length=0}writeDataIntoChunks($,J){let Y=this.chunks.findIndex((K)=>K.start<=J&&J<K.start+this.chunkSize);if(Y===-1)Y=this.createChunk(J);let j=this.chunks[Y],X=J-j.start,Z=$.subarray(0,Math.min(this.chunkSize-X,$.byteLength));j.data.set(Z,X);let G={start:X,end:X+Z.byteLength};if(this.insertSectionIntoChunk(j,G),j.written[0].start===0&&j.written[0].end===this.chunkSize)j.shouldFlush=!0;if(this.chunks.length>Uj){for(let K=0;K<this.chunks.length-1;K++)this.chunks[K].shouldFlush=!0;this.tryToFlushChunks()}if(Z.byteLength<$.byteLength)this.writeDataIntoChunks($.subarray(Z.byteLength),J+Z.byteLength)}insertSectionIntoChunk($,J){let Y=0,j=$.written.length-1,X=-1;while(Y<=j){let Z=Math.floor(Y+(j-Y+1)/2);if($.written[Z].start<=J.start)Y=Z+1,X=Z;else j=Z-1}if($.written.splice(X+1,0,J),X===-1||$.written[X].end<J.start)X++;while(X<$.written.length-1&&$.written[X].end>=$.written[X+1].start)$.written[X].end=Math.max($.written[X].end,$.written[X+1].end),$.written.splice(X+1,1)}createChunk($){let Y={start:Math.floor($/this.chunkSize)*this.chunkSize,data:new Uint8Array(this.chunkSize),written:[],shouldFlush:!1};return this.chunks.push(Y),this.chunks.sort((j,X)=>j.start-X.start),this.chunks.indexOf(Y)}tryToFlushChunks($=!1){H(this.writer);for(let J=0;J<this.chunks.length;J++){let Y=this.chunks[J];if(!Y.shouldFlush&&!$)continue;for(let j of Y.written){let X=Y.start+j.start;if(this.ensureMonotonicity&&X!==this.lastFlushEnd)throw Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:Y.data.subarray(j.start,j.end),position:X}),this.lastFlushEnd=Y.start+j.end}this.chunks.splice(J--,1)}}finalize(){if(this.chunked)this.tryToFlushChunks(!0);return H(this.writer),this.writer.close()}async close(){return this.writer?.close()}}class d$ extends w2{target;pos=0;constructor($){super();this.target=$}write($){this.maybeTrackWrites($),this.target.onwrite?.(this.pos,this.pos+$.byteLength),this.pos+=$.byteLength}getPos(){return this.pos}seek($){this.pos=$}async flush(){}async finalize(){}async close(){}}var{default:Wj}=(()=>({}));/*!
402
402
  * Copyright (c) 2025-present, Vanilagy and contributors
403
403
  *
404
404
  * This Source Code Form is subject to the terms of the Mozilla Public
405
405
  * License, v. 2.0. If a copy of the MPL was not distributed with this
406
406
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
407
- */var Hj=typeof wY<"u"?wY:void 0;class P1{_output=null;onwrite=null}class O2 extends P1{buffer=null;_createWriter(){return new a8(this)}}class c$ extends P1{_writable;_options;constructor($,J={}){super();if(!($ instanceof WritableStream))throw TypeError("StreamTarget requires a WritableStream instance.");if(J!=null&&typeof J!=="object")throw TypeError("StreamTarget options, when provided, must be an object.");if(J.chunked!==void 0&&typeof J.chunked!=="boolean")throw TypeError("options.chunked, when provided, must be a boolean.");if(J.chunkSize!==void 0&&(!Number.isInteger(J.chunkSize)||J.chunkSize<1024))throw TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=$,this._options=J}_createWriter(){return new m$(this)}}class OY extends P1{_streamTarget;_fileHandle=null;constructor($,J={}){if(typeof $!=="string")throw TypeError("filePath must be a string.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");super();let Y=new WritableStream({start:async()=>{this._fileHandle=await Hj.fs.open($,"w")},write:async(j)=>{H(this._fileHandle),await this._fileHandle.write(j.data,0,j.data.byteLength,j.position)},close:async()=>{if(this._fileHandle)await this._fileHandle.close(),this._fileHandle=null}});this._streamTarget=new c$(Y,{chunked:!0,...J}),this._streamTarget._output=this._output}_createWriter(){return this._streamTarget._createWriter()}}class P2 extends P1{_createWriter(){return new d$(this)}}x0();/*!
407
+ */class P1{_output=null;onwrite=null}class O2 extends P1{buffer=null;_createWriter(){return new a8(this)}}class c$ extends P1{_writable;_options;constructor($,J={}){super();if(!($ instanceof WritableStream))throw TypeError("StreamTarget requires a WritableStream instance.");if(J!=null&&typeof J!=="object")throw TypeError("StreamTarget options, when provided, must be an object.");if(J.chunked!==void 0&&typeof J.chunked!=="boolean")throw TypeError("options.chunked, when provided, must be a boolean.");if(J.chunkSize!==void 0&&(!Number.isInteger(J.chunkSize)||J.chunkSize<1024))throw TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=$,this._options=J}_createWriter(){return new m$(this)}}class wY extends P1{_streamTarget;_fileHandle=null;constructor($,J={}){if(typeof $!=="string")throw TypeError("filePath must be a string.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");super();let Y=new WritableStream({start:async()=>{this._fileHandle=await Wj.open($,"w"),H(this._fileHandle)},write:async(j)=>{H(this._fileHandle),await this._fileHandle.write(j.data,0,j.data.byteLength,j.position)},close:async()=>{if(this._fileHandle)await this._fileHandle.close(),this._fileHandle=null}});this._streamTarget=new c$(Y,{chunked:!0,...J}),this._streamTarget._output=this._output}_createWriter(){return this._streamTarget._createWriter()}}class P2 extends P1{_createWriter(){return new d$(this)}}x0();/*!
408
408
  * Copyright (c) 2025-present, Vanilagy and contributors
409
409
  *
410
410
  * This Source Code Form is subject to the terms of the Mozilla Public
411
411
  * License, v. 2.0. If a copy of the MPL was not distributed with this
412
412
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
413
- */class D2{writer;helper=new Uint8Array(8);helperView=new DataView(this.helper.buffer);offsets=new WeakMap;constructor($){this.writer=$}writeU32($){this.helperView.setUint32(0,$,!1),this.writer.write(this.helper.subarray(0,4))}writeU64($){this.helperView.setUint32(0,Math.floor($/4294967296),!1),this.helperView.setUint32(4,$,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii($){for(let J=0;J<$.length;J++)if(this.helperView.setUint8(J%8,$.charCodeAt(J)),J%8===7)this.writer.write(this.helper);if($.length%8!==0)this.writer.write(this.helper.subarray(0,$.length%8))}writeBox($){if(this.offsets.set($,this.writer.getPos()),$.contents&&!$.children)this.writeBoxHeader($,$.size??$.contents.byteLength+8),this.writer.write($.contents);else{let J=this.writer.getPos();if(this.writeBoxHeader($,0),$.contents)this.writer.write($.contents);if($.children){for(let X of $.children)if(X)this.writeBox(X)}let Y=this.writer.getPos(),j=$.size??Y-J;this.writer.seek(J),this.writeBoxHeader($,j),this.writer.seek(Y)}}writeBoxHeader($,J){if(this.writeU32($.largeSize?1:J),this.writeAscii($.type),$.largeSize)this.writeU64(J)}measureBoxHeader($){return 8+($.largeSize?8:0)}patchBox($){let J=this.offsets.get($);H(J!==void 0);let Y=this.writer.getPos();this.writer.seek(J),this.writeBox($),this.writer.seek(Y)}measureBox($){if($.contents&&!$.children)return this.measureBoxHeader($)+$.contents.byteLength;let J=this.measureBoxHeader($);if($.contents)J+=$.contents.byteLength;if($.children){for(let Y of $.children)if(Y)J+=this.measureBox(Y)}return J}}var p=new Uint8Array(8),t0=new DataView(p.buffer),e=($)=>{return[($%256+256)%256]},b=($)=>{return t0.setUint16(0,$,!1),[p[0],p[1]]},DY=($)=>{return t0.setInt16(0,$,!1),[p[0],p[1]]},EY=($)=>{return t0.setUint32(0,$,!1),[p[1],p[2],p[3]]},O=($)=>{return t0.setUint32(0,$,!1),[p[0],p[1],p[2],p[3]]},D1=($)=>{return t0.setInt32(0,$,!1),[p[0],p[1],p[2],p[3]]},n1=($)=>{return t0.setUint32(0,Math.floor($/4294967296),!1),t0.setUint32(4,$,!1),[p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7]]},TY=($)=>{return t0.setInt16(0,256*$,!1),[p[0],p[1]]},V1=($)=>{return t0.setInt32(0,65536*$,!1),[p[0],p[1],p[2],p[3]]},n$=($)=>{return t0.setInt32(0,1073741824*$,!1),[p[0],p[1],p[2],p[3]]},o$=($,J)=>{let Y=[],j=$;do{let X=j&127;if(j>>=7,Y.length>0)X|=128;if(Y.push(X),J!==void 0)J--}while(j>0||J);return Y.reverse()},R0=($,J=!1)=>{let Y=Array($.length).fill(null).map((j,X)=>$.charCodeAt(X));if(J)Y.push(0);return Y},i$=($)=>{let J=null;for(let Y of $)if(!J||Y.timestamp>J.timestamp)J=Y;return J},yY=($)=>{let J=$*(Math.PI/180),Y=Math.round(Math.cos(J)),j=Math.round(Math.sin(J));return[Y,j,0,-j,Y,0,0,0,1]},vY=yY(0),bY=($)=>{return[V1($[0]),V1($[1]),n$($[2]),V1($[3]),V1($[4]),n$($[5]),V1($[6]),V1($[7]),n$($[8])]},x=($,J,Y)=>({type:$,contents:J&&new Uint8Array(J.flat(10)),children:Y}),d=($,J,Y,j,X)=>x($,[e(J),EY(Y),j??[]],X),xY=($)=>{if($.isQuickTime)return x("ftyp",[R0("qt "),O(512),R0("qt ")]);if($.fragmented)return x("ftyp",[R0("iso5"),O(512),R0("iso5"),R0("iso6"),R0("mp41")]);return x("ftyp",[R0("isom"),O(512),R0("isom"),$.holdsAvc?R0("avc1"):[],R0("mp41")])},t8=($)=>({type:"mdat",largeSize:$}),IY=($)=>({type:"free",size:$}),_8=($)=>x("moov",void 0,[Nj($.creationTime,$.trackDatas),...$.trackDatas.map((J)=>Aj(J,$.creationTime)),$.isFragmented?sj($.trackDatas):null,ZX($)]),Nj=($,J)=>{let Y=Q0(Math.max(0,...J.filter((G)=>G.samples.length>0).map((G)=>{let K=i$(G.samples);return K.timestamp+K.duration})),C2),j=Math.max(0,...J.map((G)=>G.track.id))+1,X=!E1($)||!E1(Y),Z=X?n1:O;return d("mvhd",+X,0,[Z($),Z($),O(C2),Z(Y),V1(1),TY(1),Array(10).fill(0),bY(vY),Array(24).fill(0),O(j)])},Aj=($,J)=>{let Y=mY($);return x("trak",void 0,[Rj($,J),zj($,J),Y.name!==void 0?x("udta",void 0,[x("name",[...m.encode(Y.name)])]):null])},Rj=($,J)=>{let Y=i$($.samples),j=Q0(Y?Y.timestamp+Y.duration:0,C2),X=!E1(J)||!E1(j),Z=X?n1:O,G;if($.type==="video"){let Q=$.track.metadata.rotation;G=yY(Q??0)}else G=vY;let K=2;if($.track.metadata.disposition?.default!==!1)K|=1;return d("tkhd",+X,K,[Z(J),Z(J),O($.track.id),O(0),Z(j),Array(8).fill(0),b(0),b($.track.id),TY($.type==="audio"?1:0),b(0),bY(G),V1($.type==="video"?$.info.width:0),V1($.type==="video"?$.info.height:0)])},zj=($,J)=>x("mdia",void 0,[_j($,J),s$(!0,Lj[$.type],Mj[$.type]),Fj($)]),_j=($,J)=>{let Y=i$($.samples),j=Q0(Y?Y.timestamp+Y.duration:0,$.timescale),X=!E1(J)||!E1(j),Z=X?n1:O;return d("mdhd",+X,0,[Z(J),Z(J),O($.timescale),Z(j),b(lY($.track.metadata.languageCode??a)),b(0)])},Lj={video:"vide",audio:"soun",subtitle:"text"},Mj={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},s$=($,J,Y,j="\x00\x00\x00\x00")=>d("hdlr",0,0,[$?R0("mhlr"):O(0),R0(J),R0(j),O(0),O(0),R0(Y,!0)]),Fj=($)=>x("minf",void 0,[Pj[$.type](),Cj(),Tj($)]),Bj=()=>d("vmhd",0,1,[b(0),b(0),b(0),b(0)]),wj=()=>d("smhd",0,0,[b(0),b(0)]),Oj=()=>d("nmhd",0,0),Pj={video:Bj,audio:wj,subtitle:Oj},Cj=()=>x("dinf",void 0,[Dj()]),Dj=()=>d("dref",0,0,[O(1)],[Ej()]),Ej=()=>d("url ",0,1),Tj=($)=>{let J=$.compositionTimeOffsetTable.length>1||$.compositionTimeOffsetTable.some((Y)=>Y.sampleCompositionTimeOffset!==0);return x("stbl",void 0,[yj($),mj($),J?rj($):null,J?ij($):null,cj($),nj($),oj($),dj($)])},yj=($)=>{let J;if($.type==="video")J=vj(qX($.track.source._codec,$.info.decoderConfig.codec),$);else if($.type==="audio"){let Y=pY($.track.source._codec,$.muxer.isQuickTime);H(Y),J=hj(Y,$)}else if($.type==="subtitle"){let Y=VX[$.track.source._codec];if(!Y)throw Error(`Subtitle codec '${$.track.source._codec}' is not supported in MP4/MOV. Only WebVTT is supported.`);J=pj(Y,$)}return H(J),d("stsd",0,0,[O(1)],[J])},vj=($,J)=>x($,[Array(6).fill(0),b(1),b(0),b(0),Array(12).fill(0),b(J.info.width),b(J.info.height),O(4718592),O(4718592),O(0),b(1),Array(32).fill(0),b(24),DY(65535)],[UX[J.track.source._codec](J),K6(J.info.decoderConfig.colorSpace)?bj(J):null]),bj=($)=>x("colr",[R0("nclx"),b(e0[$.info.decoderConfig.colorSpace.primaries]),b($1[$.info.decoderConfig.colorSpace.transfer]),b(J1[$.info.decoderConfig.colorSpace.matrix]),e(($.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),xj=($)=>$.info.decoderConfig&&x("avcC",[...l($.info.decoderConfig.description)]),Ij=($)=>$.info.decoderConfig&&x("hvcC",[...l($.info.decoderConfig.description)]),PY=($)=>{if(!$.info.decoderConfig)return null;let J=$.info.decoderConfig,Y=J.codec.split("."),j=Number(Y[1]),X=Number(Y[2]),Z=Number(Y[3]),G=Y[4]?Number(Y[4]):1,K=Y[8]?Number(Y[8]):Number(J.colorSpace?.fullRange??0),Q=(Z<<4)+(G<<1)+K,q=Y[5]?Number(Y[5]):J.colorSpace?.primaries?e0[J.colorSpace.primaries]:2,U=Y[6]?Number(Y[6]):J.colorSpace?.transfer?$1[J.colorSpace.transfer]:2,W=Y[7]?Number(Y[7]):J.colorSpace?.matrix?J1[J.colorSpace.matrix]:2;return d("vpcC",1,0,[e(j),e(X),e(Q),e(q),e(U),e(W),b(0)])},Sj=($)=>{return x("av1C",W6($.info.decoderConfig.codec))},hj=($,J)=>{let Y=0,j,X=16;if(o.includes(J.track.source._codec)){let Z=J.track.source._codec,{sampleSize:G}=U0(Z);if(X=8*G,X>16)Y=1}if(Y===0)j=[Array(6).fill(0),b(1),b(Y),b(0),O(0),b(J.info.numberOfChannels),b(X),b(0),b(0),b(J.info.sampleRate<65536?J.info.sampleRate:0),b(0)];else j=[Array(6).fill(0),b(1),b(Y),b(0),O(0),b(J.info.numberOfChannels),b(Math.min(X,16)),b(0),b(0),b(J.info.sampleRate<65536?J.info.sampleRate:0),b(0),O(1),O(X/8),O(J.info.numberOfChannels*X/8),O(2)];return x($,j,[WX(J.track.source._codec,J.muxer.isQuickTime)?.(J)??null])},r$=($)=>{let J;switch($.track.source._codec){case"aac":J=64;break;case"mp3":J=107;break;case"vorbis":J=221;break;default:throw Error(`Unhandled audio codec: ${$.track.source._codec}`)}let Y=[...e(J),...e(21),...EY(0),...O(0),...O(0)];if($.info.decoderConfig.description){let j=l($.info.decoderConfig.description);Y=[...Y,...e(5),...o$(j.byteLength),...j]}return Y=[...b(1),...e(0),...e(4),...o$(Y.length),...Y,...e(6),...e(1),...e(2)],Y=[...e(3),...o$(Y.length),...Y],d("esds",0,0,Y)},C1=($)=>{return x("wave",void 0,[fj($),gj($),x("\x00\x00\x00\x00")])},fj=($)=>{return x("frma",[R0(pY($.track.source._codec,$.muxer.isQuickTime))])},gj=($)=>{let{littleEndian:J}=U0($.track.source._codec);return x("enda",[b(+J)])},kj=($)=>{let J=$.info.numberOfChannels,Y=3840,j=$.info.sampleRate,X=0,Z=0,G=new Uint8Array(0),K=$.info.decoderConfig?.description;if(K){H(K.byteLength>=18);let Q=l(K),q=z1(Q);if(J=q.outputChannelCount,Y=q.preSkip,j=q.inputSampleRate,X=q.outputGain,Z=q.channelMappingFamily,q.channelMappingTable)G=q.channelMappingTable}return x("dOps",[e(0),e(J),b(Y),O(j),DY(X),e(Z),...G])},uj=($)=>{let J=$.info.decoderConfig?.description;H(J);let Y=l(J);return d("dfLa",0,0,[...Y.subarray(4)])},s0=($)=>{let{littleEndian:J,sampleSize:Y}=U0($.track.source._codec),j=+J;return d("pcmC",0,0,[e(j),e(8*Y)])},pj=($,J)=>{let Y=HX[J.track.source._codec];if(!Y)throw Error(`Subtitle codec '${J.track.source._codec}' is not supported in MP4/MOV. Only WebVTT is supported.`);return x($,[Array(6).fill(0),b(1)],[Y(J)])},lj=($)=>x("vttC",[...m.encode($.info.config.description)]);var mj=($)=>{return d("stts",0,0,[O($.timeToSampleTable.length),$.timeToSampleTable.map((J)=>[O(J.sampleCount),O(J.sampleDelta)])])},dj=($)=>{if($.samples.every((Y)=>Y.type==="key"))return null;let J=[...$.samples.entries()].filter(([,Y])=>Y.type==="key");return d("stss",0,0,[O(J.length),J.map(([Y])=>O(Y+1))])},cj=($)=>{return d("stsc",0,0,[O($.compactlyCodedChunkTable.length),$.compactlyCodedChunkTable.map((J)=>[O(J.firstChunk),O(J.samplesPerChunk),O(1)])])},nj=($)=>{if($.type==="audio"&&$.info.requiresPcmTransformation){let{sampleSize:J}=U0($.track.source._codec);return d("stsz",0,0,[O(J*$.info.numberOfChannels),O($.samples.reduce((Y,j)=>Y+Q0(j.duration,$.timescale),0))])}return d("stsz",0,0,[O(0),O($.samples.length),$.samples.map((J)=>O(J.size))])},oj=($)=>{if($.finalizedChunks.length>0&&n($.finalizedChunks).offset>=4294967296)return d("co64",0,0,[O($.finalizedChunks.length),$.finalizedChunks.map((J)=>n1(J.offset))]);return d("stco",0,0,[O($.finalizedChunks.length),$.finalizedChunks.map((J)=>O(J.offset))])},rj=($)=>{return d("ctts",1,0,[O($.compositionTimeOffsetTable.length),$.compositionTimeOffsetTable.map((J)=>[O(J.sampleCount),D1(J.sampleCompositionTimeOffset)])])},ij=($)=>{let{POSITIVE_INFINITY:J,NEGATIVE_INFINITY:Y,POSITIVE_INFINITY:j,NEGATIVE_INFINITY:X}=Number;H($.compositionTimeOffsetTable.length>0),H($.samples.length>0);for(let G=0;G<$.compositionTimeOffsetTable.length;G++){let K=$.compositionTimeOffsetTable[G];J=Math.min(J,K.sampleCompositionTimeOffset),Y=Math.max(Y,K.sampleCompositionTimeOffset)}for(let G=0;G<$.samples.length;G++){let K=$.samples[G];j=Math.min(j,Q0(K.timestamp,$.timescale)),X=Math.max(X,Q0(K.timestamp+K.duration,$.timescale))}let Z=Math.max(-J,0);if(X>=2147483648)return null;return d("cslg",0,0,[D1(Z),D1(J),D1(Y),D1(j),D1(X)])},sj=($)=>{return x("mvex",void 0,$.map(aj))},aj=($)=>{return d("trex",0,0,[O($.track.id),O(1),O(0),O(0),O(0)])},a$=($,J)=>{return x("moof",void 0,[tj($),...J.map(ej)])},tj=($)=>{return d("mfhd",0,0,[O($)])},SY=($)=>{let J=0,Y=0,j=0,X=0,Z=$.type==="delta";if(Y|=+Z,Z)J|=1;else J|=2;return J<<24|Y<<16|j<<8|X},ej=($)=>{return x("traf",void 0,[$X($),JX($),YX($)])},$X=($)=>{H($.currentChunk);let J=0;J|=8,J|=16,J|=32,J|=131072;let Y=$.currentChunk.samples[1]??$.currentChunk.samples[0],j={duration:Y.timescaleUnitsToNextSample,size:Y.size,flags:SY(Y)};return d("tfhd",0,J,[O($.track.id),O(j.duration),O(j.size),O(j.flags)])},JX=($)=>{return H($.currentChunk),d("tfdt",1,0,[n1(Q0($.currentChunk.startTimestamp,$.timescale))])},YX=($)=>{H($.currentChunk);let J=$.currentChunk.samples.map((R)=>R.timescaleUnitsToNextSample),Y=$.currentChunk.samples.map((R)=>R.size),j=$.currentChunk.samples.map(SY),X=$.currentChunk.samples.map((R)=>Q0(R.timestamp-R.decodeTimestamp,$.timescale)),Z=new Set(J),G=new Set(Y),K=new Set(j),Q=new Set(X),q=K.size===2&&j[0]!==j[1],U=Z.size>1,W=G.size>1,V=!q&&K.size>1,N=Q.size>1||[...Q].some((R)=>R!==0),A=0;return A|=1,A|=4*+q,A|=256*+U,A|=512*+W,A|=1024*+V,A|=2048*+N,d("trun",1,A,[O($.currentChunk.samples.length),O($.currentChunk.offset-$.currentChunk.moofOffset||0),q?O(j[0]):[],$.currentChunk.samples.map((R,z)=>[U?O(J[z]):[],W?O(Y[z]):[],V?O(j[z]):[],N?D1(X[z]):[]])])},hY=($)=>{return x("mfra",void 0,[...$.map(jX),XX()])},jX=($,J)=>{return d("tfra",1,0,[O($.track.id),O(63),O($.finalizedChunks.length),$.finalizedChunks.map((j)=>[n1(Q0(j.samples[0].timestamp,$.timescale)),n1(j.moofOffset),O(J+1),O(1),O(1)])])},XX=()=>{return d("mfro",0,0,[O(0)])},fY=()=>x("vtte"),gY=($,J,Y,j,X)=>x("vttc",void 0,[X!==null?x("vsid",[D1(X)]):null,Y!==null?x("iden",[...m.encode(Y)]):null,J!==null?x("ctim",[...m.encode(k1(J))]):null,j!==null?x("sttg",[...m.encode(j)]):null,x("payl",[...m.encode($)])]),kY=($)=>x("vtta",[...m.encode($)]),ZX=($)=>{let J=[],Y=$.format._options.metadataFormat??"auto",j=$.output._metadataTags;if(Y==="mdir"||Y==="auto"&&!$.isQuickTime){let X=KX(j);if(X)J.push(X)}else if(Y==="mdta"){let X=QX(j);if(X)J.push(X)}else if(Y==="udta"||Y==="auto"&&$.isQuickTime)GX(J,$.output._metadataTags);if(J.length===0)return null;return x("udta",void 0,J)},GX=($,J)=>{for(let{key:Y,value:j}of v0(J))switch(Y){case"title":$.push(a0("©nam",j));break;case"description":$.push(a0("©des",j));break;case"artist":$.push(a0("©ART",j));break;case"album":$.push(a0("©alb",j));break;case"albumArtist":$.push(a0("albr",j));break;case"genre":$.push(a0("©gen",j));break;case"date":$.push(a0("©day",j.toISOString().slice(0,10)));break;case"comment":$.push(a0("©cmt",j));break;case"lyrics":$.push(a0("©lyr",j));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:i(Y)}if(J.raw)for(let Y in J.raw){let j=J.raw[Y];if(j==null||Y.length!==4||$.some((X)=>X.type===Y))continue;if(typeof j==="string")$.push(a0(Y,j));else if(j instanceof Uint8Array)$.push(x(Y,Array.from(j)))}},a0=($,J)=>{let Y=m.encode(J);return x($,[b(Y.length),b(lY("und")),Array.from(Y)])},CY={"image/jpeg":13,"image/png":14,"image/bmp":27},uY=($,J)=>{let Y=[];for(let{key:j,value:X}of v0($))switch(j){case"title":Y.push({key:J?"title":"©nam",value:l0(X)});break;case"description":Y.push({key:J?"description":"©des",value:l0(X)});break;case"artist":Y.push({key:J?"artist":"©ART",value:l0(X)});break;case"album":Y.push({key:J?"album":"©alb",value:l0(X)});break;case"albumArtist":Y.push({key:J?"album_artist":"aART",value:l0(X)});break;case"comment":Y.push({key:J?"comment":"©cmt",value:l0(X)});break;case"genre":Y.push({key:J?"genre":"©gen",value:l0(X)});break;case"lyrics":Y.push({key:J?"lyrics":"©lyr",value:l0(X)});break;case"date":Y.push({key:J?"date":"©day",value:l0(X.toISOString().slice(0,10))});break;case"images":for(let Z of X){if(Z.kind!=="coverFront")continue;Y.push({key:"covr",value:x("data",[O(CY[Z.mimeType]??0),O(0),Array.from(Z.data)])})}break;case"trackNumber":if(J){let Z=$.tracksTotal!==void 0?`${X}/${$.tracksTotal}`:X.toString();Y.push({key:"track",value:l0(Z)})}else Y.push({key:"trkn",value:x("data",[O(0),O(0),b(0),b(X),b($.tracksTotal??0),b(0)])});break;case"discNumber":if(!J)Y.push({key:"disc",value:x("data",[O(0),O(0),b(0),b(X),b($.discsTotal??0),b(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:i(j)}if($.raw)for(let j in $.raw){let X=$.raw[j];if(X==null||!J&&j.length!==4||Y.some((Z)=>Z.key===j))continue;if(typeof X==="string")Y.push({key:j,value:l0(X)});else if(X instanceof Uint8Array)Y.push({key:j,value:x("data",[O(0),O(0),Array.from(X)])});else if(X instanceof I0)Y.push({key:j,value:x("data",[O(CY[X.mimeType]??0),O(0),Array.from(X.data)])})}return Y},KX=($)=>{let J=uY($,!1);if(J.length===0)return null;return d("meta",0,0,void 0,[s$(!1,"mdir","","appl"),x("ilst",void 0,J.map((Y)=>x(Y.key,void 0,[Y.value])))])},QX=($)=>{let J=uY($,!0);if(J.length===0)return null;return x("meta",void 0,[s$(!1,"mdta",""),d("keys",0,0,[O(J.length)],J.map((Y)=>x("mdta",[...m.encode(Y.key)]))),x("ilst",void 0,J.map((Y,j)=>{let X=String.fromCharCode(...O(j+1));return x(X,void 0,[Y.value])}))])},l0=($)=>{return x("data",[O(1),O(0),...m.encode($)])},qX=($,J)=>{switch($){case"avc":return J.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";default:throw Error(`Invalid codec name ${$}`)}};var UX={avc:xj,hevc:Ij,vp8:PY,vp9:PY,av1:Sj,mpeg4:()=>null},pY=($,J)=>{switch($){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"eac3":return"ec-3"}if(J)switch($){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"}switch($){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"}throw Error(`Unsupported audio codec: ${$}`)},WX=($,J)=>{switch($){case"aac":return r$;case"mp3":return r$;case"opus":return kj;case"vorbis":return r$;case"flac":return uj}if(J)switch($){case"pcm-s24":return C1;case"pcm-s24be":return C1;case"pcm-s32":return C1;case"pcm-s32be":return C1;case"pcm-f32":return C1;case"pcm-f32be":return C1;case"pcm-f64":return C1;case"pcm-f64be":return C1}switch($){case"pcm-s16":return s0;case"pcm-s16be":return s0;case"pcm-s24":return s0;case"pcm-s24be":return s0;case"pcm-s32":return s0;case"pcm-s32be":return s0;case"pcm-f32":return s0;case"pcm-f32be":return s0;case"pcm-f64":return s0;case"pcm-f64be":return s0}return null},VX={webvtt:"wvtt",tx3g:"tx3g",ttml:"stpp"},HX={webvtt:lj,tx3g:()=>null,ttml:()=>null},lY=($)=>{H($.length===3);let J=0;for(let Y=0;Y<3;Y++)J<<=5,J+=$.charCodeAt(Y)-96;return J};/*!
413
+ */class D2{writer;helper=new Uint8Array(8);helperView=new DataView(this.helper.buffer);offsets=new WeakMap;constructor($){this.writer=$}writeU32($){this.helperView.setUint32(0,$,!1),this.writer.write(this.helper.subarray(0,4))}writeU64($){this.helperView.setUint32(0,Math.floor($/4294967296),!1),this.helperView.setUint32(4,$,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii($){for(let J=0;J<$.length;J++)if(this.helperView.setUint8(J%8,$.charCodeAt(J)),J%8===7)this.writer.write(this.helper);if($.length%8!==0)this.writer.write(this.helper.subarray(0,$.length%8))}writeBox($){if(this.offsets.set($,this.writer.getPos()),$.contents&&!$.children)this.writeBoxHeader($,$.size??$.contents.byteLength+8),this.writer.write($.contents);else{let J=this.writer.getPos();if(this.writeBoxHeader($,0),$.contents)this.writer.write($.contents);if($.children){for(let X of $.children)if(X)this.writeBox(X)}let Y=this.writer.getPos(),j=$.size??Y-J;this.writer.seek(J),this.writeBoxHeader($,j),this.writer.seek(Y)}}writeBoxHeader($,J){if(this.writeU32($.largeSize?1:J),this.writeAscii($.type),$.largeSize)this.writeU64(J)}measureBoxHeader($){return 8+($.largeSize?8:0)}patchBox($){let J=this.offsets.get($);H(J!==void 0);let Y=this.writer.getPos();this.writer.seek(J),this.writeBox($),this.writer.seek(Y)}measureBox($){if($.contents&&!$.children)return this.measureBoxHeader($)+$.contents.byteLength;let J=this.measureBoxHeader($);if($.contents)J+=$.contents.byteLength;if($.children){for(let Y of $.children)if(Y)J+=this.measureBox(Y)}return J}}var p=new Uint8Array(8),t0=new DataView(p.buffer),e=($)=>{return[($%256+256)%256]},b=($)=>{return t0.setUint16(0,$,!1),[p[0],p[1]]},CY=($)=>{return t0.setInt16(0,$,!1),[p[0],p[1]]},DY=($)=>{return t0.setUint32(0,$,!1),[p[1],p[2],p[3]]},O=($)=>{return t0.setUint32(0,$,!1),[p[0],p[1],p[2],p[3]]},D1=($)=>{return t0.setInt32(0,$,!1),[p[0],p[1],p[2],p[3]]},n1=($)=>{return t0.setUint32(0,Math.floor($/4294967296),!1),t0.setUint32(4,$,!1),[p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7]]},EY=($)=>{return t0.setInt16(0,256*$,!1),[p[0],p[1]]},V1=($)=>{return t0.setInt32(0,65536*$,!1),[p[0],p[1],p[2],p[3]]},n$=($)=>{return t0.setInt32(0,1073741824*$,!1),[p[0],p[1],p[2],p[3]]},o$=($,J)=>{let Y=[],j=$;do{let X=j&127;if(j>>=7,Y.length>0)X|=128;if(Y.push(X),J!==void 0)J--}while(j>0||J);return Y.reverse()},R0=($,J=!1)=>{let Y=Array($.length).fill(null).map((j,X)=>$.charCodeAt(X));if(J)Y.push(0);return Y},i$=($)=>{let J=null;for(let Y of $)if(!J||Y.timestamp>J.timestamp)J=Y;return J},TY=($)=>{let J=$*(Math.PI/180),Y=Math.round(Math.cos(J)),j=Math.round(Math.sin(J));return[Y,j,0,-j,Y,0,0,0,1]},yY=TY(0),vY=($)=>{return[V1($[0]),V1($[1]),n$($[2]),V1($[3]),V1($[4]),n$($[5]),V1($[6]),V1($[7]),n$($[8])]},x=($,J,Y)=>({type:$,contents:J&&new Uint8Array(J.flat(10)),children:Y}),d=($,J,Y,j,X)=>x($,[e(J),DY(Y),j??[]],X),bY=($)=>{if($.isQuickTime)return x("ftyp",[R0("qt "),O(512),R0("qt ")]);if($.fragmented)return x("ftyp",[R0("iso5"),O(512),R0("iso5"),R0("iso6"),R0("mp41")]);return x("ftyp",[R0("isom"),O(512),R0("isom"),$.holdsAvc?R0("avc1"):[],R0("mp41")])},t8=($)=>({type:"mdat",largeSize:$}),xY=($)=>({type:"free",size:$}),_8=($)=>x("moov",void 0,[Vj($.creationTime,$.trackDatas),...$.trackDatas.map((J)=>Hj(J,$.creationTime)),$.isFragmented?rj($.trackDatas):null,jX($)]),Vj=($,J)=>{let Y=Q0(Math.max(0,...J.filter((G)=>G.samples.length>0).map((G)=>{let K=i$(G.samples);return K.timestamp+K.duration})),C2),j=Math.max(0,...J.map((G)=>G.track.id))+1,X=!E1($)||!E1(Y),Z=X?n1:O;return d("mvhd",+X,0,[Z($),Z($),O(C2),Z(Y),V1(1),EY(1),Array(10).fill(0),vY(yY),Array(24).fill(0),O(j)])},Hj=($,J)=>{let Y=lY($);return x("trak",void 0,[Nj($,J),Aj($,J),Y.name!==void 0?x("udta",void 0,[x("name",[...m.encode(Y.name)])]):null])},Nj=($,J)=>{let Y=i$($.samples),j=Q0(Y?Y.timestamp+Y.duration:0,C2),X=!E1(J)||!E1(j),Z=X?n1:O,G;if($.type==="video"){let Q=$.track.metadata.rotation;G=TY(Q??0)}else G=yY;let K=2;if($.track.metadata.disposition?.default!==!1)K|=1;return d("tkhd",+X,K,[Z(J),Z(J),O($.track.id),O(0),Z(j),Array(8).fill(0),b(0),b($.track.id),EY($.type==="audio"?1:0),b(0),vY(G),V1($.type==="video"?$.info.width:0),V1($.type==="video"?$.info.height:0)])},Aj=($,J)=>x("mdia",void 0,[Rj($,J),s$(!0,zj[$.type],_j[$.type]),Lj($)]),Rj=($,J)=>{let Y=i$($.samples),j=Q0(Y?Y.timestamp+Y.duration:0,$.timescale),X=!E1(J)||!E1(j),Z=X?n1:O;return d("mdhd",+X,0,[Z(J),Z(J),O($.timescale),Z(j),b(pY($.track.metadata.languageCode??a)),b(0)])},zj={video:"vide",audio:"soun",subtitle:"text"},_j={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},s$=($,J,Y,j="\x00\x00\x00\x00")=>d("hdlr",0,0,[$?R0("mhlr"):O(0),R0(J),R0(j),O(0),O(0),R0(Y,!0)]),Lj=($)=>x("minf",void 0,[wj[$.type](),Oj(),Dj($)]),Mj=()=>d("vmhd",0,1,[b(0),b(0),b(0),b(0)]),Fj=()=>d("smhd",0,0,[b(0),b(0)]),Bj=()=>d("nmhd",0,0),wj={video:Mj,audio:Fj,subtitle:Bj},Oj=()=>x("dinf",void 0,[Pj()]),Pj=()=>d("dref",0,0,[O(1)],[Cj()]),Cj=()=>d("url ",0,1),Dj=($)=>{let J=$.compositionTimeOffsetTable.length>1||$.compositionTimeOffsetTable.some((Y)=>Y.sampleCompositionTimeOffset!==0);return x("stbl",void 0,[Ej($),pj($),J?nj($):null,J?oj($):null,mj($),dj($),cj($),lj($)])},Ej=($)=>{let J;if($.type==="video")J=Tj(KX($.track.source._codec,$.info.decoderConfig.codec),$);else if($.type==="audio"){let Y=uY($.track.source._codec,$.muxer.isQuickTime);H(Y),J=Ij(Y,$)}else if($.type==="subtitle"){let Y=UX[$.track.source._codec];if(!Y)throw Error(`Subtitle codec '${$.track.source._codec}' is not supported in MP4/MOV. Only WebVTT is supported.`);J=kj(Y,$)}return H(J),d("stsd",0,0,[O(1)],[J])},Tj=($,J)=>x($,[Array(6).fill(0),b(1),b(0),b(0),Array(12).fill(0),b(J.info.width),b(J.info.height),O(4718592),O(4718592),O(0),b(1),Array(32).fill(0),b(24),CY(65535)],[QX[J.track.source._codec](J),K6(J.info.decoderConfig.colorSpace)?yj(J):null]),yj=($)=>x("colr",[R0("nclx"),b(e0[$.info.decoderConfig.colorSpace.primaries]),b($1[$.info.decoderConfig.colorSpace.transfer]),b(J1[$.info.decoderConfig.colorSpace.matrix]),e(($.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),vj=($)=>$.info.decoderConfig&&x("avcC",[...l($.info.decoderConfig.description)]),bj=($)=>$.info.decoderConfig&&x("hvcC",[...l($.info.decoderConfig.description)]),OY=($)=>{if(!$.info.decoderConfig)return null;let J=$.info.decoderConfig,Y=J.codec.split("."),j=Number(Y[1]),X=Number(Y[2]),Z=Number(Y[3]),G=Y[4]?Number(Y[4]):1,K=Y[8]?Number(Y[8]):Number(J.colorSpace?.fullRange??0),Q=(Z<<4)+(G<<1)+K,q=Y[5]?Number(Y[5]):J.colorSpace?.primaries?e0[J.colorSpace.primaries]:2,U=Y[6]?Number(Y[6]):J.colorSpace?.transfer?$1[J.colorSpace.transfer]:2,W=Y[7]?Number(Y[7]):J.colorSpace?.matrix?J1[J.colorSpace.matrix]:2;return d("vpcC",1,0,[e(j),e(X),e(Q),e(q),e(U),e(W),b(0)])},xj=($)=>{return x("av1C",W6($.info.decoderConfig.codec))},Ij=($,J)=>{let Y=0,j,X=16;if(o.includes(J.track.source._codec)){let Z=J.track.source._codec,{sampleSize:G}=U0(Z);if(X=8*G,X>16)Y=1}if(Y===0)j=[Array(6).fill(0),b(1),b(Y),b(0),O(0),b(J.info.numberOfChannels),b(X),b(0),b(0),b(J.info.sampleRate<65536?J.info.sampleRate:0),b(0)];else j=[Array(6).fill(0),b(1),b(Y),b(0),O(0),b(J.info.numberOfChannels),b(Math.min(X,16)),b(0),b(0),b(J.info.sampleRate<65536?J.info.sampleRate:0),b(0),O(1),O(X/8),O(J.info.numberOfChannels*X/8),O(2)];return x($,j,[qX(J.track.source._codec,J.muxer.isQuickTime)?.(J)??null])},r$=($)=>{let J;switch($.track.source._codec){case"aac":J=64;break;case"mp3":J=107;break;case"vorbis":J=221;break;default:throw Error(`Unhandled audio codec: ${$.track.source._codec}`)}let Y=[...e(J),...e(21),...DY(0),...O(0),...O(0)];if($.info.decoderConfig.description){let j=l($.info.decoderConfig.description);Y=[...Y,...e(5),...o$(j.byteLength),...j]}return Y=[...b(1),...e(0),...e(4),...o$(Y.length),...Y,...e(6),...e(1),...e(2)],Y=[...e(3),...o$(Y.length),...Y],d("esds",0,0,Y)},C1=($)=>{return x("wave",void 0,[Sj($),hj($),x("\x00\x00\x00\x00")])},Sj=($)=>{return x("frma",[R0(uY($.track.source._codec,$.muxer.isQuickTime))])},hj=($)=>{let{littleEndian:J}=U0($.track.source._codec);return x("enda",[b(+J)])},fj=($)=>{let J=$.info.numberOfChannels,Y=3840,j=$.info.sampleRate,X=0,Z=0,G=new Uint8Array(0),K=$.info.decoderConfig?.description;if(K){H(K.byteLength>=18);let Q=l(K),q=z1(Q);if(J=q.outputChannelCount,Y=q.preSkip,j=q.inputSampleRate,X=q.outputGain,Z=q.channelMappingFamily,q.channelMappingTable)G=q.channelMappingTable}return x("dOps",[e(0),e(J),b(Y),O(j),CY(X),e(Z),...G])},gj=($)=>{let J=$.info.decoderConfig?.description;H(J);let Y=l(J);return d("dfLa",0,0,[...Y.subarray(4)])},s0=($)=>{let{littleEndian:J,sampleSize:Y}=U0($.track.source._codec),j=+J;return d("pcmC",0,0,[e(j),e(8*Y)])},kj=($,J)=>{let Y=WX[J.track.source._codec];if(!Y)throw Error(`Subtitle codec '${J.track.source._codec}' is not supported in MP4/MOV. Only WebVTT is supported.`);return x($,[Array(6).fill(0),b(1)],[Y(J)])},uj=($)=>x("vttC",[...m.encode($.info.config.description)]);var pj=($)=>{return d("stts",0,0,[O($.timeToSampleTable.length),$.timeToSampleTable.map((J)=>[O(J.sampleCount),O(J.sampleDelta)])])},lj=($)=>{if($.samples.every((Y)=>Y.type==="key"))return null;let J=[...$.samples.entries()].filter(([,Y])=>Y.type==="key");return d("stss",0,0,[O(J.length),J.map(([Y])=>O(Y+1))])},mj=($)=>{return d("stsc",0,0,[O($.compactlyCodedChunkTable.length),$.compactlyCodedChunkTable.map((J)=>[O(J.firstChunk),O(J.samplesPerChunk),O(1)])])},dj=($)=>{if($.type==="audio"&&$.info.requiresPcmTransformation){let{sampleSize:J}=U0($.track.source._codec);return d("stsz",0,0,[O(J*$.info.numberOfChannels),O($.samples.reduce((Y,j)=>Y+Q0(j.duration,$.timescale),0))])}return d("stsz",0,0,[O(0),O($.samples.length),$.samples.map((J)=>O(J.size))])},cj=($)=>{if($.finalizedChunks.length>0&&n($.finalizedChunks).offset>=4294967296)return d("co64",0,0,[O($.finalizedChunks.length),$.finalizedChunks.map((J)=>n1(J.offset))]);return d("stco",0,0,[O($.finalizedChunks.length),$.finalizedChunks.map((J)=>O(J.offset))])},nj=($)=>{return d("ctts",1,0,[O($.compositionTimeOffsetTable.length),$.compositionTimeOffsetTable.map((J)=>[O(J.sampleCount),D1(J.sampleCompositionTimeOffset)])])},oj=($)=>{let{POSITIVE_INFINITY:J,NEGATIVE_INFINITY:Y,POSITIVE_INFINITY:j,NEGATIVE_INFINITY:X}=Number;H($.compositionTimeOffsetTable.length>0),H($.samples.length>0);for(let G=0;G<$.compositionTimeOffsetTable.length;G++){let K=$.compositionTimeOffsetTable[G];J=Math.min(J,K.sampleCompositionTimeOffset),Y=Math.max(Y,K.sampleCompositionTimeOffset)}for(let G=0;G<$.samples.length;G++){let K=$.samples[G];j=Math.min(j,Q0(K.timestamp,$.timescale)),X=Math.max(X,Q0(K.timestamp+K.duration,$.timescale))}let Z=Math.max(-J,0);if(X>=2147483648)return null;return d("cslg",0,0,[D1(Z),D1(J),D1(Y),D1(j),D1(X)])},rj=($)=>{return x("mvex",void 0,$.map(ij))},ij=($)=>{return d("trex",0,0,[O($.track.id),O(1),O(0),O(0),O(0)])},a$=($,J)=>{return x("moof",void 0,[sj($),...J.map(aj)])},sj=($)=>{return d("mfhd",0,0,[O($)])},IY=($)=>{let J=0,Y=0,j=0,X=0,Z=$.type==="delta";if(Y|=+Z,Z)J|=1;else J|=2;return J<<24|Y<<16|j<<8|X},aj=($)=>{return x("traf",void 0,[tj($),ej($),$X($)])},tj=($)=>{H($.currentChunk);let J=0;J|=8,J|=16,J|=32,J|=131072;let Y=$.currentChunk.samples[1]??$.currentChunk.samples[0],j={duration:Y.timescaleUnitsToNextSample,size:Y.size,flags:IY(Y)};return d("tfhd",0,J,[O($.track.id),O(j.duration),O(j.size),O(j.flags)])},ej=($)=>{return H($.currentChunk),d("tfdt",1,0,[n1(Q0($.currentChunk.startTimestamp,$.timescale))])},$X=($)=>{H($.currentChunk);let J=$.currentChunk.samples.map((R)=>R.timescaleUnitsToNextSample),Y=$.currentChunk.samples.map((R)=>R.size),j=$.currentChunk.samples.map(IY),X=$.currentChunk.samples.map((R)=>Q0(R.timestamp-R.decodeTimestamp,$.timescale)),Z=new Set(J),G=new Set(Y),K=new Set(j),Q=new Set(X),q=K.size===2&&j[0]!==j[1],U=Z.size>1,W=G.size>1,V=!q&&K.size>1,N=Q.size>1||[...Q].some((R)=>R!==0),A=0;return A|=1,A|=4*+q,A|=256*+U,A|=512*+W,A|=1024*+V,A|=2048*+N,d("trun",1,A,[O($.currentChunk.samples.length),O($.currentChunk.offset-$.currentChunk.moofOffset||0),q?O(j[0]):[],$.currentChunk.samples.map((R,z)=>[U?O(J[z]):[],W?O(Y[z]):[],V?O(j[z]):[],N?D1(X[z]):[]])])},SY=($)=>{return x("mfra",void 0,[...$.map(JX),YX()])},JX=($,J)=>{return d("tfra",1,0,[O($.track.id),O(63),O($.finalizedChunks.length),$.finalizedChunks.map((j)=>[n1(Q0(j.samples[0].timestamp,$.timescale)),n1(j.moofOffset),O(J+1),O(1),O(1)])])},YX=()=>{return d("mfro",0,0,[O(0)])},hY=()=>x("vtte"),fY=($,J,Y,j,X)=>x("vttc",void 0,[X!==null?x("vsid",[D1(X)]):null,Y!==null?x("iden",[...m.encode(Y)]):null,J!==null?x("ctim",[...m.encode(k1(J))]):null,j!==null?x("sttg",[...m.encode(j)]):null,x("payl",[...m.encode($)])]),gY=($)=>x("vtta",[...m.encode($)]),jX=($)=>{let J=[],Y=$.format._options.metadataFormat??"auto",j=$.output._metadataTags;if(Y==="mdir"||Y==="auto"&&!$.isQuickTime){let X=ZX(j);if(X)J.push(X)}else if(Y==="mdta"){let X=GX(j);if(X)J.push(X)}else if(Y==="udta"||Y==="auto"&&$.isQuickTime)XX(J,$.output._metadataTags);if(J.length===0)return null;return x("udta",void 0,J)},XX=($,J)=>{for(let{key:Y,value:j}of v0(J))switch(Y){case"title":$.push(a0("©nam",j));break;case"description":$.push(a0("©des",j));break;case"artist":$.push(a0("©ART",j));break;case"album":$.push(a0("©alb",j));break;case"albumArtist":$.push(a0("albr",j));break;case"genre":$.push(a0("©gen",j));break;case"date":$.push(a0("©day",j.toISOString().slice(0,10)));break;case"comment":$.push(a0("©cmt",j));break;case"lyrics":$.push(a0("©lyr",j));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:i(Y)}if(J.raw)for(let Y in J.raw){let j=J.raw[Y];if(j==null||Y.length!==4||$.some((X)=>X.type===Y))continue;if(typeof j==="string")$.push(a0(Y,j));else if(j instanceof Uint8Array)$.push(x(Y,Array.from(j)))}},a0=($,J)=>{let Y=m.encode(J);return x($,[b(Y.length),b(pY("und")),Array.from(Y)])},PY={"image/jpeg":13,"image/png":14,"image/bmp":27},kY=($,J)=>{let Y=[];for(let{key:j,value:X}of v0($))switch(j){case"title":Y.push({key:J?"title":"©nam",value:l0(X)});break;case"description":Y.push({key:J?"description":"©des",value:l0(X)});break;case"artist":Y.push({key:J?"artist":"©ART",value:l0(X)});break;case"album":Y.push({key:J?"album":"©alb",value:l0(X)});break;case"albumArtist":Y.push({key:J?"album_artist":"aART",value:l0(X)});break;case"comment":Y.push({key:J?"comment":"©cmt",value:l0(X)});break;case"genre":Y.push({key:J?"genre":"©gen",value:l0(X)});break;case"lyrics":Y.push({key:J?"lyrics":"©lyr",value:l0(X)});break;case"date":Y.push({key:J?"date":"©day",value:l0(X.toISOString().slice(0,10))});break;case"images":for(let Z of X){if(Z.kind!=="coverFront")continue;Y.push({key:"covr",value:x("data",[O(PY[Z.mimeType]??0),O(0),Array.from(Z.data)])})}break;case"trackNumber":if(J){let Z=$.tracksTotal!==void 0?`${X}/${$.tracksTotal}`:X.toString();Y.push({key:"track",value:l0(Z)})}else Y.push({key:"trkn",value:x("data",[O(0),O(0),b(0),b(X),b($.tracksTotal??0),b(0)])});break;case"discNumber":if(!J)Y.push({key:"disc",value:x("data",[O(0),O(0),b(0),b(X),b($.discsTotal??0),b(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:i(j)}if($.raw)for(let j in $.raw){let X=$.raw[j];if(X==null||!J&&j.length!==4||Y.some((Z)=>Z.key===j))continue;if(typeof X==="string")Y.push({key:j,value:l0(X)});else if(X instanceof Uint8Array)Y.push({key:j,value:x("data",[O(0),O(0),Array.from(X)])});else if(X instanceof I0)Y.push({key:j,value:x("data",[O(PY[X.mimeType]??0),O(0),Array.from(X.data)])})}return Y},ZX=($)=>{let J=kY($,!1);if(J.length===0)return null;return d("meta",0,0,void 0,[s$(!1,"mdir","","appl"),x("ilst",void 0,J.map((Y)=>x(Y.key,void 0,[Y.value])))])},GX=($)=>{let J=kY($,!0);if(J.length===0)return null;return x("meta",void 0,[s$(!1,"mdta",""),d("keys",0,0,[O(J.length)],J.map((Y)=>x("mdta",[...m.encode(Y.key)]))),x("ilst",void 0,J.map((Y,j)=>{let X=String.fromCharCode(...O(j+1));return x(X,void 0,[Y.value])}))])},l0=($)=>{return x("data",[O(1),O(0),...m.encode($)])},KX=($,J)=>{switch($){case"avc":return J.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";default:throw Error(`Invalid codec name ${$}`)}};var QX={avc:vj,hevc:bj,vp8:OY,vp9:OY,av1:xj,mpeg4:()=>null},uY=($,J)=>{switch($){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"eac3":return"ec-3"}if(J)switch($){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"}switch($){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"}throw Error(`Unsupported audio codec: ${$}`)},qX=($,J)=>{switch($){case"aac":return r$;case"mp3":return r$;case"opus":return fj;case"vorbis":return r$;case"flac":return gj}if(J)switch($){case"pcm-s24":return C1;case"pcm-s24be":return C1;case"pcm-s32":return C1;case"pcm-s32be":return C1;case"pcm-f32":return C1;case"pcm-f32be":return C1;case"pcm-f64":return C1;case"pcm-f64be":return C1}switch($){case"pcm-s16":return s0;case"pcm-s16be":return s0;case"pcm-s24":return s0;case"pcm-s24be":return s0;case"pcm-s32":return s0;case"pcm-s32be":return s0;case"pcm-f32":return s0;case"pcm-f32be":return s0;case"pcm-f64":return s0;case"pcm-f64be":return s0}return null},UX={webvtt:"wvtt",tx3g:"tx3g",ttml:"stpp"},WX={webvtt:uj,tx3g:()=>null,ttml:()=>null},pY=($)=>{H($.length===3);let J=0;for(let Y=0;Y<3;Y++)J<<=5,J+=$.charCodeAt(Y)-96;return J};/*!
414
414
  * Copyright (c) 2025-present, Vanilagy and contributors
415
415
  *
416
416
  * This Source Code Form is subject to the terms of the Mozilla Public
417
417
  * License, v. 2.0. If a copy of the MPL was not distributed with this
418
418
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
419
- */var C2=1000,NX=2082844800,mY=($)=>{let J={},Y=$.track;if(Y.metadata.name!==void 0)J.name=Y.metadata.name;return J},Q0=($,J,Y=!0)=>{let j=$*J;return Y?Math.round(j):j};class t$ extends V0{format;writer;boxWriter;fastStart;isFragmented;isQuickTime;auxTarget=new O2;auxWriter=this.auxTarget._createWriter();auxBoxWriter=new D2(this.auxWriter);mdat=null;ftypSize=null;trackDatas=[];allTracksKnown=c();creationTime=Math.floor(Date.now()/1000)+NX;finalizedChunks=[];nextFragmentNumber=1;maxWrittenTimestamp=Number.NEGATIVE_INFINITY;minimumFragmentDuration;constructor($,J){super($);this.format=J,this.writer=$._writer,this.boxWriter=new D2(this.writer),this.isQuickTime=J instanceof e8;let Y=this.writer instanceof a8?"in-memory":!1;if(this.fastStart=J._options.fastStart??Y,this.isFragmented=this.fastStart==="fragmented",this.fastStart==="in-memory"||this.isFragmented)this.writer.ensureMonotonicity=!0;this.minimumFragmentDuration=J._options.minimumFragmentDuration??1}async start(){let $=await this.mutex.acquire(),J=this.output._tracks.some((Y)=>Y.type==="video"&&Y.source._codec==="avc");if(this.format._options.onFtyp)this.writer.startTrackingWrites();if(this.boxWriter.writeBox(xY({isQuickTime:this.isQuickTime,holdsAvc:J,fragmented:this.isFragmented})),this.format._options.onFtyp){let{data:Y,start:j}=this.writer.stopTrackingWrites();this.format._options.onFtyp(Y,j)}if(this.ftypSize=this.writer.getPos(),this.fastStart==="in-memory");else if(this.fastStart==="reserve"){for(let Y of this.output._tracks)if(Y.metadata.maximumPacketCount===void 0)throw Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else if(this.isFragmented);else{if(this.format._options.onMdat)this.writer.startTrackingWrites();this.mdat=t8(!0),this.boxWriter.writeBox(this.mdat)}await this.writer.flush(),$()}allTracksAreKnown(){for(let $ of this.output._tracks)if(!$.source._closed&&!this.trackDatas.some((J)=>J.track===$))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let $=this.trackDatas.map((J)=>{if(J.type==="video")return J.info.decoderConfig.codec;if(J.type==="audio")return J.info.decoderConfig.codec;return{webvtt:"wvtt",tx3g:"tx3g",ttml:"stpp",srt:"wvtt",ass:"wvtt",ssa:"wvtt"}[J.track.source._codec]});return $2({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some((J)=>J.type==="video"),hasAudio:this.trackDatas.some((J)=>J.type==="audio"),codecStrings:$})}getVideoTrackData($,J,Y){let j=this.trackDatas.find((Q)=>Q.track===$);if(j)return j;t1(Y),H(Y),H(Y.decoderConfig);let X={...Y.decoderConfig};H(X.codedWidth!==void 0),H(X.codedHeight!==void 0);let Z=!1;if($.source._codec==="avc"&&!X.description){let Q=v6(J.data);if(!Q)throw Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");X.description=nJ(Q),Z=!0}else if($.source._codec==="hevc"&&!X.description){let Q=b6(J.data);if(!Q)throw Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");X.description=rJ(Q),Z=!0}let G=_J(1/($.metadata.frameRate??57600),1e6).denominator,K={muxer:this,track:$,type:"video",info:{width:X.codedWidth,height:X.codedHeight,decoderConfig:X,requiresAnnexBTransformation:Z},timescale:G,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};if(this.trackDatas.push(K),this.trackDatas.sort((Q,q)=>Q.track.id-q.track.id),this.allTracksAreKnown())this.allTracksKnown.resolve();return K}getAudioTrackData($,J){let Y=this.trackDatas.find((X)=>X.track===$);if(Y)return Y;_0(J),H(J),H(J.decoderConfig);let j={muxer:this,track:$,type:"audio",info:{numberOfChannels:J.decoderConfig.numberOfChannels,sampleRate:J.decoderConfig.sampleRate,decoderConfig:J.decoderConfig,requiresPcmTransformation:!this.isFragmented&&o.includes($.source._codec)},timescale:J.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};if(this.trackDatas.push(j),this.trackDatas.sort((X,Z)=>X.track.id-Z.track.id),this.allTracksAreKnown())this.allTracksKnown.resolve();return j}getSubtitleTrackData($,J){let Y=this.trackDatas.find((X)=>X.track===$);if(Y)return Y;A6(J),H(J),H(J.config);let j={muxer:this,track:$,type:"subtitle",info:{config:J.config},timescale:1000,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};if(this.trackDatas.push(j),this.trackDatas.sort((X,Z)=>X.track.id-Z.track.id),this.allTracksAreKnown())this.allTracksKnown.resolve();return j}async addEncodedVideoPacket($,J,Y){let j=await this.mutex.acquire();try{let X=this.getVideoTrackData($,J,Y),Z=J.data;if(X.info.requiresAnnexBTransformation){let Q=dJ(Z);if(!Q)throw Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");Z=Q}let G=this.validateAndNormalizeTimestamp(X.track,J.timestamp,J.type==="key"),K=this.createSampleForTrack(X,Z,G,J.duration,J.type);await this.registerSample(X,K)}finally{j()}}async addEncodedAudioPacket($,J,Y){let j=await this.mutex.acquire();try{let X=this.getAudioTrackData($,Y),Z=this.validateAndNormalizeTimestamp(X.track,J.timestamp,J.type==="key"),G=this.createSampleForTrack(X,J.data,Z,J.duration,J.type);if(X.info.requiresPcmTransformation)await this.maybePadWithSilence(X,Z);await this.registerSample(X,G)}finally{j()}}async maybePadWithSilence($,J){let Y=n($.samples),j=Y?Y.timestamp+Y.duration:0,X=J-j,Z=Q0(X,$.timescale);if(Z>0){let{sampleSize:G,silentValue:K}=U0($.info.decoderConfig.codec),Q=Z*$.info.numberOfChannels,q=new Uint8Array(G*Q).fill(K),U=this.createSampleForTrack($,new Uint8Array(q.buffer),j,X,"key");await this.registerSample($,U)}}async addSubtitleCue($,J,Y){let j=await this.mutex.acquire();try{let X=this.getSubtitleTrackData($,Y);if(this.validateAndNormalizeTimestamp(X.track,J.timestamp,!0),$.source._codec==="webvtt")X.cueQueue.push(J),await this.processWebVTTCues(X,J.timestamp);else throw Error(`${$.source._codec} subtitles are not supported in ${this.format._name}. Only WebVTT is supported.`)}finally{j()}}async processWebVTTCues($,J){while($.cueQueue.length>0){let Y=new Set([]);for(let Q of $.cueQueue)H(Q.timestamp<=J),H($.lastCueEndTimestamp<=Q.timestamp+Q.duration),Y.add(Math.max(Q.timestamp,$.lastCueEndTimestamp)),Y.add(Q.timestamp+Q.duration);let j=[...Y].sort((Q,q)=>Q-q),X=j[0],Z=j[1]??X;if(J<Z)break;if($.lastCueEndTimestamp<X){this.auxWriter.seek(0);let Q=fY();this.auxBoxWriter.writeBox(Q);let q=this.auxWriter.getSlice(0,this.auxWriter.getPos()),U=this.createSampleForTrack($,q,$.lastCueEndTimestamp,X-$.lastCueEndTimestamp,"key");await this.registerSample($,U),$.lastCueEndTimestamp=X}this.auxWriter.seek(0);for(let Q=0;Q<$.cueQueue.length;Q++){let q=$.cueQueue[Q];if(q.timestamp>=Z)break;u1.lastIndex=0;let U=u1.test(q.text),W=q.timestamp+q.duration,V=$.cueToSourceId.get(q);if(V===void 0&&Z<W)V=$.nextSourceId++,$.cueToSourceId.set(q,V);if(q.notes){let A=kY(q.notes);this.auxBoxWriter.writeBox(A)}let N=gY(q.text,U?X:null,q.identifier??null,q.settings??null,V??null);if(this.auxBoxWriter.writeBox(N),W===Z)$.cueQueue.splice(Q--,1)}let G=this.auxWriter.getSlice(0,this.auxWriter.getPos()),K=this.createSampleForTrack($,G,X,Z-X,"key");await this.registerSample($,K),$.lastCueEndTimestamp=Z}}createSampleForTrack($,J,Y,j,X){return{timestamp:Y,decodeTimestamp:Y,duration:j,data:J,size:J.byteLength,type:X,timescaleUnitsToNextSample:Q0(j,$.timescale)}}processTimestamps($,J){if($.timestampProcessingQueue.length===0)return;if($.type==="audio"&&$.info.requiresPcmTransformation){let j=0;for(let X=0;X<$.timestampProcessingQueue.length;X++){let Z=$.timestampProcessingQueue[X],G=Q0(Z.duration,$.timescale);j+=G}if($.timeToSampleTable.length===0)$.timeToSampleTable.push({sampleCount:j,sampleDelta:1});else{let X=n($.timeToSampleTable);X.sampleCount+=j}$.timestampProcessingQueue.length=0;return}let Y=$.timestampProcessingQueue.map((j)=>j.timestamp).sort((j,X)=>j-X);for(let j=0;j<$.timestampProcessingQueue.length;j++){let X=$.timestampProcessingQueue[j];if(X.decodeTimestamp=Y[j],!this.isFragmented&&$.lastTimescaleUnits===null)X.decodeTimestamp=0;let Z=Q0(X.timestamp-X.decodeTimestamp,$.timescale),G=Q0(X.duration,$.timescale);if($.lastTimescaleUnits!==null){H($.lastSample);let K=Q0(X.decodeTimestamp,$.timescale,!1),Q=Math.round(K-$.lastTimescaleUnits);if(H(Q>=0),$.lastTimescaleUnits+=Q,$.lastSample.timescaleUnitsToNextSample=Q,!this.isFragmented){let q=n($.timeToSampleTable);if(H(q),q.sampleCount===1){q.sampleDelta=Q;let W=$.timeToSampleTable[$.timeToSampleTable.length-2];if(W&&W.sampleDelta===Q)W.sampleCount++,$.timeToSampleTable.pop(),q=W}else if(q.sampleDelta!==Q)q.sampleCount--,$.timeToSampleTable.push(q={sampleCount:1,sampleDelta:Q});if(q.sampleDelta===G)q.sampleCount++;else $.timeToSampleTable.push({sampleCount:1,sampleDelta:G});let U=n($.compositionTimeOffsetTable);if(H(U),U.sampleCompositionTimeOffset===Z)U.sampleCount++;else $.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:Z})}}else if($.lastTimescaleUnits=Q0(X.decodeTimestamp,$.timescale,!1),!this.isFragmented)$.timeToSampleTable.push({sampleCount:1,sampleDelta:G}),$.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:Z});$.lastSample=X}if($.timestampProcessingQueue.length=0,H($.lastSample),H($.lastTimescaleUnits!==null),J!==void 0&&$.lastSample.timescaleUnitsToNextSample===0){H(J.type==="key");let j=Q0(J.timestamp,$.timescale,!1),X=Math.round(j-$.lastTimescaleUnits);$.lastSample.timescaleUnitsToNextSample=X}}async registerSample($,J){if(J.type==="key")this.processTimestamps($,J);if($.timestampProcessingQueue.push(J),this.isFragmented)$.sampleQueue.push(J),await this.interleaveSamples();else if(this.fastStart==="reserve")await this.registerSampleFastStartReserve($,J);else await this.addSampleToTrack($,J)}async addSampleToTrack($,J){if(!this.isFragmented){if($.samples.push(J),this.fastStart==="reserve"){let j=$.track.metadata.maximumPacketCount;if(H(j!==void 0),$.samples.length>j)throw Error(`Track #${$.track.id} has already reached the maximum packet count (${j}). Either add less packets or increase the maximum packet count.`)}}let Y=!1;if(!$.currentChunk)Y=!0;else{$.currentChunk.startTimestamp=Math.min($.currentChunk.startTimestamp,J.timestamp);let j=J.timestamp-$.currentChunk.startTimestamp;if(this.isFragmented){let X=this.trackDatas.every((Z)=>{if($===Z)return J.type==="key";let G=Z.sampleQueue[0];if(G)return G.type==="key";return Z.track.source._closed});if(j>=this.minimumFragmentDuration&&X&&J.timestamp>this.maxWrittenTimestamp)Y=!0,await this.finalizeFragment()}else Y=j>=0.5}if(Y){if($.currentChunk)await this.finalizeCurrentChunk($);$.currentChunk={startTimestamp:J.timestamp,samples:[],offset:null,moofOffset:null}}if(H($.currentChunk),$.currentChunk.samples.push(J),this.isFragmented)this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,J.timestamp)}async finalizeCurrentChunk($){if(H(!this.isFragmented),!$.currentChunk)return;$.finalizedChunks.push($.currentChunk),this.finalizedChunks.push($.currentChunk);let J=$.currentChunk.samples.length;if($.type==="audio"&&$.info.requiresPcmTransformation)J=$.currentChunk.samples.reduce((Y,j)=>Y+Q0(j.duration,$.timescale),0);if($.compactlyCodedChunkTable.length===0||n($.compactlyCodedChunkTable).samplesPerChunk!==J)$.compactlyCodedChunkTable.push({firstChunk:$.finalizedChunks.length,samplesPerChunk:J});if(this.fastStart==="in-memory"){$.currentChunk.offset=0;return}$.currentChunk.offset=this.writer.getPos();for(let Y of $.currentChunk.samples)H(Y.data),this.writer.write(Y.data),Y.data=null;await this.writer.flush()}async interleaveSamples($=!1){if(H(this.isFragmented),!$&&!this.allTracksAreKnown())return;$:while(!0){let J=null,Y=Number.POSITIVE_INFINITY;for(let X of this.trackDatas){if(!$&&X.sampleQueue.length===0&&!X.track.source._closed)break $;if(X.sampleQueue.length>0&&X.sampleQueue[0].timestamp<Y)J=X,Y=X.sampleQueue[0].timestamp}if(!J)break;let j=J.sampleQueue.shift();await this.addSampleToTrack(J,j)}}async finalizeFragment($=!0){H(this.isFragmented);let J=this.nextFragmentNumber++;if(J===1){if(this.format._options.onMoov)this.writer.startTrackingWrites();let V=_8(this);if(this.boxWriter.writeBox(V),this.format._options.onMoov){let{data:N,start:A}=this.writer.stopTrackingWrites();this.format._options.onMoov(N,A)}}let Y=this.trackDatas.filter((V)=>V.currentChunk),j=a$(J,Y),X=this.writer.getPos(),Z=X+this.boxWriter.measureBox(j),G=Z+f0,K=Number.POSITIVE_INFINITY;for(let V of Y){V.currentChunk.offset=G,V.currentChunk.moofOffset=X;for(let N of V.currentChunk.samples)G+=N.size;K=Math.min(K,V.currentChunk.startTimestamp)}let Q=G-Z,q=Q>=4294967296;if(q)for(let V of Y)V.currentChunk.offset+=U1-f0;if(this.format._options.onMoof)this.writer.startTrackingWrites();let U=a$(J,Y);if(this.boxWriter.writeBox(U),this.format._options.onMoof){let{data:V,start:N}=this.writer.stopTrackingWrites();this.format._options.onMoof(V,N,K)}if(H(this.writer.getPos()===Z),this.format._options.onMdat)this.writer.startTrackingWrites();let W=t8(q);W.size=Q,this.boxWriter.writeBox(W),this.writer.seek(Z+(q?U1:f0));for(let V of Y)for(let N of V.currentChunk.samples)this.writer.write(N.data),N.data=null;if(this.format._options.onMdat){let{data:V,start:N}=this.writer.stopTrackingWrites();this.format._options.onMdat(V,N)}for(let V of Y)V.finalizedChunks.push(V.currentChunk),this.finalizedChunks.push(V.currentChunk),V.currentChunk=null;if($)await this.writer.flush()}async registerSampleFastStartReserve($,J){if(this.allTracksAreKnown()){if(!this.mdat){let Y=_8(this),X=this.boxWriter.measureBox(Y)+this.computeSampleTableSizeUpperBound()+4096;if(H(this.ftypSize!==null),this.writer.seek(this.ftypSize+X),this.format._options.onMdat)this.writer.startTrackingWrites();this.mdat=t8(!0),this.boxWriter.writeBox(this.mdat);for(let Z of this.trackDatas){for(let G of Z.sampleQueue)await this.addSampleToTrack(Z,G);Z.sampleQueue.length=0}}await this.addSampleToTrack($,J)}else $.sampleQueue.push(J)}computeSampleTableSizeUpperBound(){H(this.fastStart==="reserve");let $=0;for(let J of this.trackDatas){let Y=J.track.metadata.maximumPacketCount;H(Y!==void 0),$+=8*Math.ceil(0.6666666666666666*Y),$+=4*Y,$+=8*Math.ceil(0.6666666666666666*Y),$+=12*Math.ceil(0.6666666666666666*Y),$+=4*Y,$+=8*Y}return $}async onTrackClose($){let J=await this.mutex.acquire();if($.type==="subtitle"&&$.source._codec==="webvtt"){let Y=this.trackDatas.find((j)=>j.track===$);if(Y)await this.processWebVTTCues(Y,Number.POSITIVE_INFINITY)}if(this.allTracksAreKnown())this.allTracksKnown.resolve();if(this.isFragmented)await this.interleaveSamples();J()}async finalize(){let $=await this.mutex.acquire();this.allTracksKnown.resolve();for(let J of this.trackDatas)if(J.type==="subtitle"&&J.track.source._codec==="webvtt")await this.processWebVTTCues(J,Number.POSITIVE_INFINITY);if(this.isFragmented){await this.interleaveSamples(!0);for(let J of this.trackDatas)this.processTimestamps(J);await this.finalizeFragment(!1)}else for(let J of this.trackDatas)this.processTimestamps(J),await this.finalizeCurrentChunk(J);if(this.fastStart==="in-memory"){this.mdat=t8(!1);let J;for(let j=0;j<2;j++){let X=_8(this),Z=this.boxWriter.measureBox(X);J=this.boxWriter.measureBox(this.mdat);let G=this.writer.getPos()+Z+J;for(let K of this.finalizedChunks){K.offset=G;for(let{data:Q}of K.samples)H(Q),G+=Q.byteLength,J+=Q.byteLength}if(G<4294967296)break;if(J>=4294967296)this.mdat.largeSize=!0}if(this.format._options.onMoov)this.writer.startTrackingWrites();let Y=_8(this);if(this.boxWriter.writeBox(Y),this.format._options.onMoov){let{data:j,start:X}=this.writer.stopTrackingWrites();this.format._options.onMoov(j,X)}if(this.format._options.onMdat)this.writer.startTrackingWrites();this.mdat.size=J,this.boxWriter.writeBox(this.mdat);for(let j of this.finalizedChunks)for(let X of j.samples)H(X.data),this.writer.write(X.data),X.data=null;if(this.format._options.onMdat){let{data:j,start:X}=this.writer.stopTrackingWrites();this.format._options.onMdat(j,X)}}else if(this.isFragmented){let J=this.writer.getPos(),Y=hY(this.trackDatas);this.boxWriter.writeBox(Y);let j=this.writer.getPos()-J;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(j)}else{H(this.mdat);let J=this.boxWriter.offsets.get(this.mdat);H(J!==void 0);let Y=this.writer.getPos()-J;if(this.mdat.size=Y,this.mdat.largeSize=Y>=4294967296,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:X,start:Z}=this.writer.stopTrackingWrites();this.format._options.onMdat(X,Z)}let j=_8(this);if(this.fastStart==="reserve"){if(H(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov)this.writer.startTrackingWrites();this.boxWriter.writeBox(j);let X=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(IY(X))}else{if(this.format._options.onMoov)this.writer.startTrackingWrites();this.boxWriter.writeBox(j)}if(this.format._options.onMoov){let{data:X,start:Z}=this.writer.stopTrackingWrites();this.format._options.onMoov(X,Z)}}$()}}x0();/*!
419
+ */var C2=1000,VX=2082844800,lY=($)=>{let J={},Y=$.track;if(Y.metadata.name!==void 0)J.name=Y.metadata.name;return J},Q0=($,J,Y=!0)=>{let j=$*J;return Y?Math.round(j):j};class t$ extends V0{format;writer;boxWriter;fastStart;isFragmented;isQuickTime;auxTarget=new O2;auxWriter=this.auxTarget._createWriter();auxBoxWriter=new D2(this.auxWriter);mdat=null;ftypSize=null;trackDatas=[];allTracksKnown=c();creationTime=Math.floor(Date.now()/1000)+VX;finalizedChunks=[];nextFragmentNumber=1;maxWrittenTimestamp=Number.NEGATIVE_INFINITY;minimumFragmentDuration;constructor($,J){super($);this.format=J,this.writer=$._writer,this.boxWriter=new D2(this.writer),this.isQuickTime=J instanceof e8;let Y=this.writer instanceof a8?"in-memory":!1;if(this.fastStart=J._options.fastStart??Y,this.isFragmented=this.fastStart==="fragmented",this.fastStart==="in-memory"||this.isFragmented)this.writer.ensureMonotonicity=!0;this.minimumFragmentDuration=J._options.minimumFragmentDuration??1}async start(){let $=await this.mutex.acquire(),J=this.output._tracks.some((Y)=>Y.type==="video"&&Y.source._codec==="avc");if(this.format._options.onFtyp)this.writer.startTrackingWrites();if(this.boxWriter.writeBox(bY({isQuickTime:this.isQuickTime,holdsAvc:J,fragmented:this.isFragmented})),this.format._options.onFtyp){let{data:Y,start:j}=this.writer.stopTrackingWrites();this.format._options.onFtyp(Y,j)}if(this.ftypSize=this.writer.getPos(),this.fastStart==="in-memory");else if(this.fastStart==="reserve"){for(let Y of this.output._tracks)if(Y.metadata.maximumPacketCount===void 0)throw Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else if(this.isFragmented);else{if(this.format._options.onMdat)this.writer.startTrackingWrites();this.mdat=t8(!0),this.boxWriter.writeBox(this.mdat)}await this.writer.flush(),$()}allTracksAreKnown(){for(let $ of this.output._tracks)if(!$.source._closed&&!this.trackDatas.some((J)=>J.track===$))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let $=this.trackDatas.map((J)=>{if(J.type==="video")return J.info.decoderConfig.codec;if(J.type==="audio")return J.info.decoderConfig.codec;return{webvtt:"wvtt",tx3g:"tx3g",ttml:"stpp",srt:"wvtt",ass:"wvtt",ssa:"wvtt"}[J.track.source._codec]});return $2({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some((J)=>J.type==="video"),hasAudio:this.trackDatas.some((J)=>J.type==="audio"),codecStrings:$})}getVideoTrackData($,J,Y){let j=this.trackDatas.find((Q)=>Q.track===$);if(j)return j;t1(Y),H(Y),H(Y.decoderConfig);let X={...Y.decoderConfig};H(X.codedWidth!==void 0),H(X.codedHeight!==void 0);let Z=!1;if($.source._codec==="avc"&&!X.description){let Q=v6(J.data);if(!Q)throw Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");X.description=nJ(Q),Z=!0}else if($.source._codec==="hevc"&&!X.description){let Q=b6(J.data);if(!Q)throw Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");X.description=rJ(Q),Z=!0}let G=_J(1/($.metadata.frameRate??57600),1e6).denominator,K={muxer:this,track:$,type:"video",info:{width:X.codedWidth,height:X.codedHeight,decoderConfig:X,requiresAnnexBTransformation:Z},timescale:G,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};if(this.trackDatas.push(K),this.trackDatas.sort((Q,q)=>Q.track.id-q.track.id),this.allTracksAreKnown())this.allTracksKnown.resolve();return K}getAudioTrackData($,J){let Y=this.trackDatas.find((X)=>X.track===$);if(Y)return Y;_0(J),H(J),H(J.decoderConfig);let j={muxer:this,track:$,type:"audio",info:{numberOfChannels:J.decoderConfig.numberOfChannels,sampleRate:J.decoderConfig.sampleRate,decoderConfig:J.decoderConfig,requiresPcmTransformation:!this.isFragmented&&o.includes($.source._codec)},timescale:J.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};if(this.trackDatas.push(j),this.trackDatas.sort((X,Z)=>X.track.id-Z.track.id),this.allTracksAreKnown())this.allTracksKnown.resolve();return j}getSubtitleTrackData($,J){let Y=this.trackDatas.find((X)=>X.track===$);if(Y)return Y;A6(J),H(J),H(J.config);let j={muxer:this,track:$,type:"subtitle",info:{config:J.config},timescale:1000,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};if(this.trackDatas.push(j),this.trackDatas.sort((X,Z)=>X.track.id-Z.track.id),this.allTracksAreKnown())this.allTracksKnown.resolve();return j}async addEncodedVideoPacket($,J,Y){let j=await this.mutex.acquire();try{let X=this.getVideoTrackData($,J,Y),Z=J.data;if(X.info.requiresAnnexBTransformation){let Q=dJ(Z);if(!Q)throw Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");Z=Q}let G=this.validateAndNormalizeTimestamp(X.track,J.timestamp,J.type==="key"),K=this.createSampleForTrack(X,Z,G,J.duration,J.type);await this.registerSample(X,K)}finally{j()}}async addEncodedAudioPacket($,J,Y){let j=await this.mutex.acquire();try{let X=this.getAudioTrackData($,Y),Z=this.validateAndNormalizeTimestamp(X.track,J.timestamp,J.type==="key"),G=this.createSampleForTrack(X,J.data,Z,J.duration,J.type);if(X.info.requiresPcmTransformation)await this.maybePadWithSilence(X,Z);await this.registerSample(X,G)}finally{j()}}async maybePadWithSilence($,J){let Y=n($.samples),j=Y?Y.timestamp+Y.duration:0,X=J-j,Z=Q0(X,$.timescale);if(Z>0){let{sampleSize:G,silentValue:K}=U0($.info.decoderConfig.codec),Q=Z*$.info.numberOfChannels,q=new Uint8Array(G*Q).fill(K),U=this.createSampleForTrack($,new Uint8Array(q.buffer),j,X,"key");await this.registerSample($,U)}}async addSubtitleCue($,J,Y){let j=await this.mutex.acquire();try{let X=this.getSubtitleTrackData($,Y);if(this.validateAndNormalizeTimestamp(X.track,J.timestamp,!0),$.source._codec==="webvtt")X.cueQueue.push(J),await this.processWebVTTCues(X,J.timestamp);else throw Error(`${$.source._codec} subtitles are not supported in ${this.format._name}. Only WebVTT is supported.`)}finally{j()}}async processWebVTTCues($,J){while($.cueQueue.length>0){let Y=new Set([]);for(let Q of $.cueQueue)H(Q.timestamp<=J),H($.lastCueEndTimestamp<=Q.timestamp+Q.duration),Y.add(Math.max(Q.timestamp,$.lastCueEndTimestamp)),Y.add(Q.timestamp+Q.duration);let j=[...Y].sort((Q,q)=>Q-q),X=j[0],Z=j[1]??X;if(J<Z)break;if($.lastCueEndTimestamp<X){this.auxWriter.seek(0);let Q=hY();this.auxBoxWriter.writeBox(Q);let q=this.auxWriter.getSlice(0,this.auxWriter.getPos()),U=this.createSampleForTrack($,q,$.lastCueEndTimestamp,X-$.lastCueEndTimestamp,"key");await this.registerSample($,U),$.lastCueEndTimestamp=X}this.auxWriter.seek(0);for(let Q=0;Q<$.cueQueue.length;Q++){let q=$.cueQueue[Q];if(q.timestamp>=Z)break;u1.lastIndex=0;let U=u1.test(q.text),W=q.timestamp+q.duration,V=$.cueToSourceId.get(q);if(V===void 0&&Z<W)V=$.nextSourceId++,$.cueToSourceId.set(q,V);if(q.notes){let A=gY(q.notes);this.auxBoxWriter.writeBox(A)}let N=fY(q.text,U?X:null,q.identifier??null,q.settings??null,V??null);if(this.auxBoxWriter.writeBox(N),W===Z)$.cueQueue.splice(Q--,1)}let G=this.auxWriter.getSlice(0,this.auxWriter.getPos()),K=this.createSampleForTrack($,G,X,Z-X,"key");await this.registerSample($,K),$.lastCueEndTimestamp=Z}}createSampleForTrack($,J,Y,j,X){return{timestamp:Y,decodeTimestamp:Y,duration:j,data:J,size:J.byteLength,type:X,timescaleUnitsToNextSample:Q0(j,$.timescale)}}processTimestamps($,J){if($.timestampProcessingQueue.length===0)return;if($.type==="audio"&&$.info.requiresPcmTransformation){let j=0;for(let X=0;X<$.timestampProcessingQueue.length;X++){let Z=$.timestampProcessingQueue[X],G=Q0(Z.duration,$.timescale);j+=G}if($.timeToSampleTable.length===0)$.timeToSampleTable.push({sampleCount:j,sampleDelta:1});else{let X=n($.timeToSampleTable);X.sampleCount+=j}$.timestampProcessingQueue.length=0;return}let Y=$.timestampProcessingQueue.map((j)=>j.timestamp).sort((j,X)=>j-X);for(let j=0;j<$.timestampProcessingQueue.length;j++){let X=$.timestampProcessingQueue[j];if(X.decodeTimestamp=Y[j],!this.isFragmented&&$.lastTimescaleUnits===null)X.decodeTimestamp=0;let Z=Q0(X.timestamp-X.decodeTimestamp,$.timescale),G=Q0(X.duration,$.timescale);if($.lastTimescaleUnits!==null){H($.lastSample);let K=Q0(X.decodeTimestamp,$.timescale,!1),Q=Math.round(K-$.lastTimescaleUnits);if(H(Q>=0),$.lastTimescaleUnits+=Q,$.lastSample.timescaleUnitsToNextSample=Q,!this.isFragmented){let q=n($.timeToSampleTable);if(H(q),q.sampleCount===1){q.sampleDelta=Q;let W=$.timeToSampleTable[$.timeToSampleTable.length-2];if(W&&W.sampleDelta===Q)W.sampleCount++,$.timeToSampleTable.pop(),q=W}else if(q.sampleDelta!==Q)q.sampleCount--,$.timeToSampleTable.push(q={sampleCount:1,sampleDelta:Q});if(q.sampleDelta===G)q.sampleCount++;else $.timeToSampleTable.push({sampleCount:1,sampleDelta:G});let U=n($.compositionTimeOffsetTable);if(H(U),U.sampleCompositionTimeOffset===Z)U.sampleCount++;else $.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:Z})}}else if($.lastTimescaleUnits=Q0(X.decodeTimestamp,$.timescale,!1),!this.isFragmented)$.timeToSampleTable.push({sampleCount:1,sampleDelta:G}),$.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:Z});$.lastSample=X}if($.timestampProcessingQueue.length=0,H($.lastSample),H($.lastTimescaleUnits!==null),J!==void 0&&$.lastSample.timescaleUnitsToNextSample===0){H(J.type==="key");let j=Q0(J.timestamp,$.timescale,!1),X=Math.round(j-$.lastTimescaleUnits);$.lastSample.timescaleUnitsToNextSample=X}}async registerSample($,J){if(J.type==="key")this.processTimestamps($,J);if($.timestampProcessingQueue.push(J),this.isFragmented)$.sampleQueue.push(J),await this.interleaveSamples();else if(this.fastStart==="reserve")await this.registerSampleFastStartReserve($,J);else await this.addSampleToTrack($,J)}async addSampleToTrack($,J){if(!this.isFragmented){if($.samples.push(J),this.fastStart==="reserve"){let j=$.track.metadata.maximumPacketCount;if(H(j!==void 0),$.samples.length>j)throw Error(`Track #${$.track.id} has already reached the maximum packet count (${j}). Either add less packets or increase the maximum packet count.`)}}let Y=!1;if(!$.currentChunk)Y=!0;else{$.currentChunk.startTimestamp=Math.min($.currentChunk.startTimestamp,J.timestamp);let j=J.timestamp-$.currentChunk.startTimestamp;if(this.isFragmented){let X=this.trackDatas.every((Z)=>{if($===Z)return J.type==="key";let G=Z.sampleQueue[0];if(G)return G.type==="key";return Z.track.source._closed});if(j>=this.minimumFragmentDuration&&X&&J.timestamp>this.maxWrittenTimestamp)Y=!0,await this.finalizeFragment()}else Y=j>=0.5}if(Y){if($.currentChunk)await this.finalizeCurrentChunk($);$.currentChunk={startTimestamp:J.timestamp,samples:[],offset:null,moofOffset:null}}if(H($.currentChunk),$.currentChunk.samples.push(J),this.isFragmented)this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,J.timestamp)}async finalizeCurrentChunk($){if(H(!this.isFragmented),!$.currentChunk)return;$.finalizedChunks.push($.currentChunk),this.finalizedChunks.push($.currentChunk);let J=$.currentChunk.samples.length;if($.type==="audio"&&$.info.requiresPcmTransformation)J=$.currentChunk.samples.reduce((Y,j)=>Y+Q0(j.duration,$.timescale),0);if($.compactlyCodedChunkTable.length===0||n($.compactlyCodedChunkTable).samplesPerChunk!==J)$.compactlyCodedChunkTable.push({firstChunk:$.finalizedChunks.length,samplesPerChunk:J});if(this.fastStart==="in-memory"){$.currentChunk.offset=0;return}$.currentChunk.offset=this.writer.getPos();for(let Y of $.currentChunk.samples)H(Y.data),this.writer.write(Y.data),Y.data=null;await this.writer.flush()}async interleaveSamples($=!1){if(H(this.isFragmented),!$&&!this.allTracksAreKnown())return;$:while(!0){let J=null,Y=Number.POSITIVE_INFINITY;for(let X of this.trackDatas){if(!$&&X.sampleQueue.length===0&&!X.track.source._closed)break $;if(X.sampleQueue.length>0&&X.sampleQueue[0].timestamp<Y)J=X,Y=X.sampleQueue[0].timestamp}if(!J)break;let j=J.sampleQueue.shift();await this.addSampleToTrack(J,j)}}async finalizeFragment($=!0){H(this.isFragmented);let J=this.nextFragmentNumber++;if(J===1){if(this.format._options.onMoov)this.writer.startTrackingWrites();let V=_8(this);if(this.boxWriter.writeBox(V),this.format._options.onMoov){let{data:N,start:A}=this.writer.stopTrackingWrites();this.format._options.onMoov(N,A)}}let Y=this.trackDatas.filter((V)=>V.currentChunk),j=a$(J,Y),X=this.writer.getPos(),Z=X+this.boxWriter.measureBox(j),G=Z+f0,K=Number.POSITIVE_INFINITY;for(let V of Y){V.currentChunk.offset=G,V.currentChunk.moofOffset=X;for(let N of V.currentChunk.samples)G+=N.size;K=Math.min(K,V.currentChunk.startTimestamp)}let Q=G-Z,q=Q>=4294967296;if(q)for(let V of Y)V.currentChunk.offset+=U1-f0;if(this.format._options.onMoof)this.writer.startTrackingWrites();let U=a$(J,Y);if(this.boxWriter.writeBox(U),this.format._options.onMoof){let{data:V,start:N}=this.writer.stopTrackingWrites();this.format._options.onMoof(V,N,K)}if(H(this.writer.getPos()===Z),this.format._options.onMdat)this.writer.startTrackingWrites();let W=t8(q);W.size=Q,this.boxWriter.writeBox(W),this.writer.seek(Z+(q?U1:f0));for(let V of Y)for(let N of V.currentChunk.samples)this.writer.write(N.data),N.data=null;if(this.format._options.onMdat){let{data:V,start:N}=this.writer.stopTrackingWrites();this.format._options.onMdat(V,N)}for(let V of Y)V.finalizedChunks.push(V.currentChunk),this.finalizedChunks.push(V.currentChunk),V.currentChunk=null;if($)await this.writer.flush()}async registerSampleFastStartReserve($,J){if(this.allTracksAreKnown()){if(!this.mdat){let Y=_8(this),X=this.boxWriter.measureBox(Y)+this.computeSampleTableSizeUpperBound()+4096;if(H(this.ftypSize!==null),this.writer.seek(this.ftypSize+X),this.format._options.onMdat)this.writer.startTrackingWrites();this.mdat=t8(!0),this.boxWriter.writeBox(this.mdat);for(let Z of this.trackDatas){for(let G of Z.sampleQueue)await this.addSampleToTrack(Z,G);Z.sampleQueue.length=0}}await this.addSampleToTrack($,J)}else $.sampleQueue.push(J)}computeSampleTableSizeUpperBound(){H(this.fastStart==="reserve");let $=0;for(let J of this.trackDatas){let Y=J.track.metadata.maximumPacketCount;H(Y!==void 0),$+=8*Math.ceil(0.6666666666666666*Y),$+=4*Y,$+=8*Math.ceil(0.6666666666666666*Y),$+=12*Math.ceil(0.6666666666666666*Y),$+=4*Y,$+=8*Y}return $}async onTrackClose($){let J=await this.mutex.acquire();if($.type==="subtitle"&&$.source._codec==="webvtt"){let Y=this.trackDatas.find((j)=>j.track===$);if(Y)await this.processWebVTTCues(Y,Number.POSITIVE_INFINITY)}if(this.allTracksAreKnown())this.allTracksKnown.resolve();if(this.isFragmented)await this.interleaveSamples();J()}async finalize(){let $=await this.mutex.acquire();this.allTracksKnown.resolve();for(let J of this.trackDatas)if(J.type==="subtitle"&&J.track.source._codec==="webvtt")await this.processWebVTTCues(J,Number.POSITIVE_INFINITY);if(this.isFragmented){await this.interleaveSamples(!0);for(let J of this.trackDatas)this.processTimestamps(J);await this.finalizeFragment(!1)}else for(let J of this.trackDatas)this.processTimestamps(J),await this.finalizeCurrentChunk(J);if(this.fastStart==="in-memory"){this.mdat=t8(!1);let J;for(let j=0;j<2;j++){let X=_8(this),Z=this.boxWriter.measureBox(X);J=this.boxWriter.measureBox(this.mdat);let G=this.writer.getPos()+Z+J;for(let K of this.finalizedChunks){K.offset=G;for(let{data:Q}of K.samples)H(Q),G+=Q.byteLength,J+=Q.byteLength}if(G<4294967296)break;if(J>=4294967296)this.mdat.largeSize=!0}if(this.format._options.onMoov)this.writer.startTrackingWrites();let Y=_8(this);if(this.boxWriter.writeBox(Y),this.format._options.onMoov){let{data:j,start:X}=this.writer.stopTrackingWrites();this.format._options.onMoov(j,X)}if(this.format._options.onMdat)this.writer.startTrackingWrites();this.mdat.size=J,this.boxWriter.writeBox(this.mdat);for(let j of this.finalizedChunks)for(let X of j.samples)H(X.data),this.writer.write(X.data),X.data=null;if(this.format._options.onMdat){let{data:j,start:X}=this.writer.stopTrackingWrites();this.format._options.onMdat(j,X)}}else if(this.isFragmented){let J=this.writer.getPos(),Y=SY(this.trackDatas);this.boxWriter.writeBox(Y);let j=this.writer.getPos()-J;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(j)}else{H(this.mdat);let J=this.boxWriter.offsets.get(this.mdat);H(J!==void 0);let Y=this.writer.getPos()-J;if(this.mdat.size=Y,this.mdat.largeSize=Y>=4294967296,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:X,start:Z}=this.writer.stopTrackingWrites();this.format._options.onMdat(X,Z)}let j=_8(this);if(this.fastStart==="reserve"){if(H(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov)this.writer.startTrackingWrites();this.boxWriter.writeBox(j);let X=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(xY(X))}else{if(this.format._options.onMoov)this.writer.startTrackingWrites();this.boxWriter.writeBox(j)}if(this.format._options.onMoov){let{data:X,start:Z}=this.writer.stopTrackingWrites();this.format._options.onMoov(X,Z)}}$()}}x0();/*!
420
420
  * Copyright (c) 2025-present, Vanilagy and contributors
421
421
  *
422
422
  * This Source Code Form is subject to the terms of the Mozilla Public
423
423
  * License, v. 2.0. If a copy of the MPL was not distributed with this
424
424
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
425
- */var AX=-32768,RX=32767,dY="Mediabunny",cY=6,nY=5,zX={video:1,audio:2,subtitle:17};class e$ extends V0{writer;ebmlWriter;format;trackDatas=[];allTracksKnown=c();segment=null;segmentInfo=null;seekHead=null;tracksElement=null;tagsElement=null;attachmentsElement=null;segmentDuration=null;cues=null;currentCluster=null;currentClusterStartMsTimestamp=null;currentClusterMaxMsTimestamp=null;trackDatasInCurrentCluster=new Map;duration=0;constructor($,J){super($);if(this.writer=$._writer,this.format=J,this.ebmlWriter=new A$(this.writer),this.format._options.appendOnly)this.writer.ensureMonotonicity=!0}async start(){let $=await this.mutex.acquire();this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),$()}writeEBMLHeader(){if(this.format._options.onEbmlHeader)this.writer.startTrackingWrites();let $={id:440786851,data:[{id:17030,data:1},{id:17143,data:1},{id:17138,data:4},{id:17139,data:8},{id:17026,data:this.format instanceof $6?"webm":"matroska"},{id:17031,data:2},{id:17029,data:2}]};if(this.ebmlWriter.writeEBML($),this.format._options.onEbmlHeader){let{data:J,start:Y}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(J,Y)}}maybeCreateSeekHead($){if(this.format._options.appendOnly)return;let J=new Uint8Array([28,83,187,107]),Y=new Uint8Array([21,73,169,102]),j=new Uint8Array([22,84,174,107]),X=new Uint8Array([25,65,164,105]),Z=new Uint8Array([18,84,195,103]),G={id:290298740,data:[{id:19899,data:[{id:21419,data:J},{id:21420,size:5,data:$?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:19899,data:[{id:21419,data:Y},{id:21420,size:5,data:$?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:19899,data:[{id:21419,data:j},{id:21420,size:5,data:$?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:19899,data:[{id:21419,data:X},{id:21420,size:5,data:$?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:19899,data:[{id:21419,data:Z},{id:21420,size:5,data:$?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=G}createSegmentInfo(){let $={id:17545,data:new m8(0)};this.segmentDuration=$;let J={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:dY},{id:22337,data:dY},!this.format._options.appendOnly?$:null]};this.segmentInfo=J}createTracks(){let $={id:374648427,data:[]};this.tracksElement=$;for(let J of this.trackDatas){let Y=A0[J.track.source._codec];H(Y);let j=0;if(J.type==="audio"&&J.track.source._codec==="opus"){j=80000000;let X=J.info.decoderConfig.description;if(X){let Z=l(X),G=z1(Z);j=Math.round(1e9*(G.preSkip/b0))}}$.data.push({id:174,data:[{id:215,data:J.track.id},{id:29637,data:J.track.id},{id:131,data:zX[J.type]},J.track.metadata.disposition?.default===!1?{id:136,data:0}:null,J.track.metadata.disposition?.forced?{id:21930,data:1}:null,J.track.metadata.disposition?.hearingImpaired?{id:21931,data:1}:null,J.track.metadata.disposition?.visuallyImpaired?{id:21932,data:1}:null,J.track.metadata.disposition?.original?{id:21934,data:1}:null,J.track.metadata.disposition?.commentary?{id:21935,data:1}:null,{id:156,data:0},{id:2274716,data:J.track.metadata.languageCode??a},{id:134,data:Y},{id:22186,data:0},{id:22203,data:j},J.track.metadata.name!==void 0?{id:21358,data:new r0(J.track.metadata.name)}:null,J.type==="video"?this.videoSpecificTrackInfo(J):null,J.type==="audio"?this.audioSpecificTrackInfo(J):null,J.type==="subtitle"?this.subtitleSpecificTrackInfo(J):null]})}}videoSpecificTrackInfo($){let{frameRate:J,rotation:Y}=$.track.metadata,j=[$.info.decoderConfig.description?{id:25506,data:l($.info.decoderConfig.description)}:null,J?{id:2352003,data:1e9/J}:null],X=Y?N1(-Y):0,Z=$.info.decoderConfig.colorSpace,G={id:224,data:[{id:176,data:$.info.width},{id:186,data:$.info.height},$.info.alphaMode?{id:21440,data:1}:null,K6(Z)?{id:21936,data:[{id:21937,data:J1[Z.matrix]},{id:21946,data:$1[Z.transfer]},{id:21947,data:e0[Z.primaries]},{id:21945,data:Z.fullRange?2:1}]}:null,X?{id:30320,data:[{id:30321,data:0},{id:30325,data:new l8((X+180)%360-180)}]}:null]};return j.push(G),j}audioSpecificTrackInfo($){let J=o.includes($.track.source._codec)?U0($.track.source._codec):null;return[$.info.decoderConfig.description?{id:25506,data:l($.info.decoderConfig.description)}:null,{id:225,data:[{id:181,data:new l8($.info.sampleRate)},{id:159,data:$.info.numberOfChannels},J?{id:25188,data:8*J.sampleSize}:null]}]}subtitleSpecificTrackInfo($){return[{id:25506,data:m.encode($.info.config.description)}]}maybeCreateTags(){let $=[],J=(X,Z)=>{$.push({id:26568,data:[{id:17827,data:new r0(X)},typeof Z==="string"?{id:17543,data:new r0(Z)}:{id:17541,data:Z}]})},Y=this.output._metadataTags,j=new Set;for(let{key:X,value:Z}of v0(Y))switch(X){case"title":J("TITLE",Z),j.add("TITLE");break;case"description":J("DESCRIPTION",Z),j.add("DESCRIPTION");break;case"artist":J("ARTIST",Z),j.add("ARTIST");break;case"album":J("ALBUM",Z),j.add("ALBUM");break;case"albumArtist":J("ALBUM_ARTIST",Z),j.add("ALBUM_ARTIST");break;case"genre":J("GENRE",Z),j.add("GENRE");break;case"comment":J("COMMENT",Z),j.add("COMMENT");break;case"lyrics":J("LYRICS",Z),j.add("LYRICS");break;case"date":J("DATE",Z.toISOString().slice(0,10)),j.add("DATE");break;case"trackNumber":{let G=Y.tracksTotal!==void 0?`${Z}/${Y.tracksTotal}`:Z.toString();J("PART_NUMBER",G),j.add("PART_NUMBER")}break;case"discNumber":{let G=Y.discsTotal!==void 0?`${Z}/${Y.discsTotal}`:Z.toString();J("DISC",G),j.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":break;default:i(X)}if(Y.raw)for(let X in Y.raw){let Z=Y.raw[X];if(Z==null||j.has(X))continue;if(typeof Z==="string"||Z instanceof Uint8Array)J(X,Z)}if($.length===0)return;this.tagsElement={id:307544935,data:[{id:29555,data:[{id:25536,data:[{id:26826,data:50},{id:25546,data:"MOVIE"}]},...$]}]}}maybeCreateAttachments(){let $=this.output._metadataTags,J=[],Y=new Set,j=$.images??[];for(let X of j){let Z=X.name;if(Z===void 0)Z=(X.kind==="coverFront"?"cover":X.kind==="coverBack"?"back":"image")+(MJ(X.mimeType)??"");let G;while(!0){G=0n;for(let K=0;K<8;K++)G<<=8n,G|=BigInt(Math.floor(Math.random()*256));if(G!==0n&&!Y.has(G))break}Y.add(G),J.push({id:24999,data:[X.description!==void 0?{id:18046,data:new r0(X.description)}:null,{id:18030,data:new r0(Z)},{id:18016,data:X.mimeType},{id:18012,data:X.data},{id:18094,data:G}]})}for(let[X,Z]of Object.entries($.raw??{})){if(!(Z instanceof l1))continue;if(!/^\d+$/.test(X))continue;if(j.find((K)=>K.mimeType===Z.mimeType&&wJ(K.data,Z.data)))continue;J.push({id:24999,data:[Z.description!==void 0?{id:18046,data:new r0(Z.description)}:null,{id:18030,data:new r0(Z.name??"")},{id:18016,data:Z.mimeType??""},{id:18012,data:Z.data},{id:18094,data:BigInt(X)}]})}if(J.length===0)return;this.attachmentsElement={id:423732329,data:J}}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);let $={id:408125543,size:this.format._options.appendOnly?-1:cY,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=$,this.format._options.onSegmentHeader)this.writer.startTrackingWrites();if(this.ebmlWriter.writeEBML($),this.format._options.onSegmentHeader){let{data:J,start:Y}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(J,Y)}}createCues(){this.cues={id:475249515,data:[]}}get segmentDataOffset(){return H(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(let $ of this.output._tracks)if(!$.source._closed&&!this.trackDatas.some((J)=>J.track===$))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let $=this.trackDatas.map((J)=>{if(J.type==="video")return J.info.decoderConfig.codec;if(J.type==="audio")return J.info.decoderConfig.codec;return{webvtt:"S_TEXT/WEBVTT",tx3g:"S_TEXT/UTF8",ttml:"S_TEXT/WEBVTT",srt:"S_TEXT/UTF8",ass:"S_TEXT/ASS",ssa:"S_TEXT/SSA"}[J.track.source._codec]});return Q2({isWebM:this.format instanceof $6,hasVideo:this.trackDatas.some((J)=>J.type==="video"),hasAudio:this.trackDatas.some((J)=>J.type==="audio"),codecStrings:$})}getVideoTrackData($,J,Y){let j=this.trackDatas.find((Z)=>Z.track===$);if(j)return j;t1(Y),H(Y),H(Y.decoderConfig),H(Y.decoderConfig.codedWidth!==void 0),H(Y.decoderConfig.codedHeight!==void 0);let X={track:$,type:"video",info:{width:Y.decoderConfig.codedWidth,height:Y.decoderConfig.codedHeight,decoderConfig:Y.decoderConfig,alphaMode:!!J.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null};if($.source._codec==="vp9")X.info.decoderConfig={...X.info.decoderConfig,description:new Uint8Array(yJ(X.info.decoderConfig.codec))};else if($.source._codec==="av1")X.info.decoderConfig={...X.info.decoderConfig,description:new Uint8Array(W6(X.info.decoderConfig.codec))};if(this.trackDatas.push(X),this.trackDatas.sort((Z,G)=>Z.track.id-G.track.id),this.allTracksAreKnown())this.allTracksKnown.resolve();return X}getAudioTrackData($,J){let Y=this.trackDatas.find((X)=>X.track===$);if(Y)return Y;_0(J),H(J),H(J.decoderConfig);let j={track:$,type:"audio",info:{numberOfChannels:J.decoderConfig.numberOfChannels,sampleRate:J.decoderConfig.sampleRate,decoderConfig:J.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};if(this.trackDatas.push(j),this.trackDatas.sort((X,Z)=>X.track.id-Z.track.id),this.allTracksAreKnown())this.allTracksKnown.resolve();return j}getSubtitleTrackData($,J){let Y=this.trackDatas.find((X)=>X.track===$);if(Y)return Y;A6(J),H(J),H(J.config);let j={track:$,type:"subtitle",info:{config:J.config},chunkQueue:[],lastWrittenMsTimestamp:null};if(this.trackDatas.push(j),this.trackDatas.sort((X,Z)=>X.track.id-Z.track.id),this.allTracksAreKnown())this.allTracksKnown.resolve();return j}async addEncodedVideoPacket($,J,Y){let j=await this.mutex.acquire();try{let X=this.getVideoTrackData($,J,Y),Z=J.type==="key",G=this.validateAndNormalizeTimestamp(X.track,J.timestamp,Z),K=J.duration;if($.metadata.frameRate!==void 0)G=F8(G,1/$.metadata.frameRate),K=F8(K,1/$.metadata.frameRate);let Q=X.info.alphaMode?J.sideData.alpha??null:null,q=this.createInternalChunk(J.data,G,K,J.type,Q);if($.source._codec==="vp9")this.fixVP9ColorSpace(X,q);X.chunkQueue.push(q),await this.interleaveChunks()}finally{j()}}async addEncodedAudioPacket($,J,Y){let j=await this.mutex.acquire();try{let X=this.getAudioTrackData($,Y),Z=J.type==="key",G=this.validateAndNormalizeTimestamp(X.track,J.timestamp,Z),K=this.createInternalChunk(J.data,G,J.duration,J.type);X.chunkQueue.push(K),await this.interleaveChunks()}finally{j()}}async addSubtitleCue($,J,Y){let j=await this.mutex.acquire();try{let X=this.getSubtitleTrackData($,Y),Z=this.validateAndNormalizeTimestamp(X.track,J.timestamp,!0),G=J.text,K=Math.round(Z*1000);if($.source._codec==="ass"||$.source._codec==="ssa")G=Y$(G);else u1.lastIndex=0,G=G.replace(u1,(W)=>{let N=I8(W.slice(1,-1))-K;return`<${k1(N)}>`});let Q=m.encode(G),q=`${J.settings??""}
425
+ */var HX=-32768,NX=32767,mY="Mediabunny",dY=6,cY=5,AX={video:1,audio:2,subtitle:17};class e$ extends V0{writer;ebmlWriter;format;trackDatas=[];allTracksKnown=c();segment=null;segmentInfo=null;seekHead=null;tracksElement=null;tagsElement=null;attachmentsElement=null;segmentDuration=null;cues=null;currentCluster=null;currentClusterStartMsTimestamp=null;currentClusterMaxMsTimestamp=null;trackDatasInCurrentCluster=new Map;duration=0;constructor($,J){super($);if(this.writer=$._writer,this.format=J,this.ebmlWriter=new A$(this.writer),this.format._options.appendOnly)this.writer.ensureMonotonicity=!0}async start(){let $=await this.mutex.acquire();this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),$()}writeEBMLHeader(){if(this.format._options.onEbmlHeader)this.writer.startTrackingWrites();let $={id:440786851,data:[{id:17030,data:1},{id:17143,data:1},{id:17138,data:4},{id:17139,data:8},{id:17026,data:this.format instanceof $6?"webm":"matroska"},{id:17031,data:2},{id:17029,data:2}]};if(this.ebmlWriter.writeEBML($),this.format._options.onEbmlHeader){let{data:J,start:Y}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(J,Y)}}maybeCreateSeekHead($){if(this.format._options.appendOnly)return;let J=new Uint8Array([28,83,187,107]),Y=new Uint8Array([21,73,169,102]),j=new Uint8Array([22,84,174,107]),X=new Uint8Array([25,65,164,105]),Z=new Uint8Array([18,84,195,103]),G={id:290298740,data:[{id:19899,data:[{id:21419,data:J},{id:21420,size:5,data:$?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:19899,data:[{id:21419,data:Y},{id:21420,size:5,data:$?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:19899,data:[{id:21419,data:j},{id:21420,size:5,data:$?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:19899,data:[{id:21419,data:X},{id:21420,size:5,data:$?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:19899,data:[{id:21419,data:Z},{id:21420,size:5,data:$?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=G}createSegmentInfo(){let $={id:17545,data:new m8(0)};this.segmentDuration=$;let J={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:mY},{id:22337,data:mY},!this.format._options.appendOnly?$:null]};this.segmentInfo=J}createTracks(){let $={id:374648427,data:[]};this.tracksElement=$;for(let J of this.trackDatas){let Y=A0[J.track.source._codec];H(Y);let j=0;if(J.type==="audio"&&J.track.source._codec==="opus"){j=80000000;let X=J.info.decoderConfig.description;if(X){let Z=l(X),G=z1(Z);j=Math.round(1e9*(G.preSkip/b0))}}$.data.push({id:174,data:[{id:215,data:J.track.id},{id:29637,data:J.track.id},{id:131,data:AX[J.type]},J.track.metadata.disposition?.default===!1?{id:136,data:0}:null,J.track.metadata.disposition?.forced?{id:21930,data:1}:null,J.track.metadata.disposition?.hearingImpaired?{id:21931,data:1}:null,J.track.metadata.disposition?.visuallyImpaired?{id:21932,data:1}:null,J.track.metadata.disposition?.original?{id:21934,data:1}:null,J.track.metadata.disposition?.commentary?{id:21935,data:1}:null,{id:156,data:0},{id:2274716,data:J.track.metadata.languageCode??a},{id:134,data:Y},{id:22186,data:0},{id:22203,data:j},J.track.metadata.name!==void 0?{id:21358,data:new r0(J.track.metadata.name)}:null,J.type==="video"?this.videoSpecificTrackInfo(J):null,J.type==="audio"?this.audioSpecificTrackInfo(J):null,J.type==="subtitle"?this.subtitleSpecificTrackInfo(J):null]})}}videoSpecificTrackInfo($){let{frameRate:J,rotation:Y}=$.track.metadata,j=[$.info.decoderConfig.description?{id:25506,data:l($.info.decoderConfig.description)}:null,J?{id:2352003,data:1e9/J}:null],X=Y?N1(-Y):0,Z=$.info.decoderConfig.colorSpace,G={id:224,data:[{id:176,data:$.info.width},{id:186,data:$.info.height},$.info.alphaMode?{id:21440,data:1}:null,K6(Z)?{id:21936,data:[{id:21937,data:J1[Z.matrix]},{id:21946,data:$1[Z.transfer]},{id:21947,data:e0[Z.primaries]},{id:21945,data:Z.fullRange?2:1}]}:null,X?{id:30320,data:[{id:30321,data:0},{id:30325,data:new l8((X+180)%360-180)}]}:null]};return j.push(G),j}audioSpecificTrackInfo($){let J=o.includes($.track.source._codec)?U0($.track.source._codec):null;return[$.info.decoderConfig.description?{id:25506,data:l($.info.decoderConfig.description)}:null,{id:225,data:[{id:181,data:new l8($.info.sampleRate)},{id:159,data:$.info.numberOfChannels},J?{id:25188,data:8*J.sampleSize}:null]}]}subtitleSpecificTrackInfo($){return[{id:25506,data:m.encode($.info.config.description)}]}maybeCreateTags(){let $=[],J=(X,Z)=>{$.push({id:26568,data:[{id:17827,data:new r0(X)},typeof Z==="string"?{id:17543,data:new r0(Z)}:{id:17541,data:Z}]})},Y=this.output._metadataTags,j=new Set;for(let{key:X,value:Z}of v0(Y))switch(X){case"title":J("TITLE",Z),j.add("TITLE");break;case"description":J("DESCRIPTION",Z),j.add("DESCRIPTION");break;case"artist":J("ARTIST",Z),j.add("ARTIST");break;case"album":J("ALBUM",Z),j.add("ALBUM");break;case"albumArtist":J("ALBUM_ARTIST",Z),j.add("ALBUM_ARTIST");break;case"genre":J("GENRE",Z),j.add("GENRE");break;case"comment":J("COMMENT",Z),j.add("COMMENT");break;case"lyrics":J("LYRICS",Z),j.add("LYRICS");break;case"date":J("DATE",Z.toISOString().slice(0,10)),j.add("DATE");break;case"trackNumber":{let G=Y.tracksTotal!==void 0?`${Z}/${Y.tracksTotal}`:Z.toString();J("PART_NUMBER",G),j.add("PART_NUMBER")}break;case"discNumber":{let G=Y.discsTotal!==void 0?`${Z}/${Y.discsTotal}`:Z.toString();J("DISC",G),j.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":break;default:i(X)}if(Y.raw)for(let X in Y.raw){let Z=Y.raw[X];if(Z==null||j.has(X))continue;if(typeof Z==="string"||Z instanceof Uint8Array)J(X,Z)}if($.length===0)return;this.tagsElement={id:307544935,data:[{id:29555,data:[{id:25536,data:[{id:26826,data:50},{id:25546,data:"MOVIE"}]},...$]}]}}maybeCreateAttachments(){let $=this.output._metadataTags,J=[],Y=new Set,j=$.images??[];for(let X of j){let Z=X.name;if(Z===void 0)Z=(X.kind==="coverFront"?"cover":X.kind==="coverBack"?"back":"image")+(MJ(X.mimeType)??"");let G;while(!0){G=0n;for(let K=0;K<8;K++)G<<=8n,G|=BigInt(Math.floor(Math.random()*256));if(G!==0n&&!Y.has(G))break}Y.add(G),J.push({id:24999,data:[X.description!==void 0?{id:18046,data:new r0(X.description)}:null,{id:18030,data:new r0(Z)},{id:18016,data:X.mimeType},{id:18012,data:X.data},{id:18094,data:G}]})}for(let[X,Z]of Object.entries($.raw??{})){if(!(Z instanceof l1))continue;if(!/^\d+$/.test(X))continue;if(j.find((K)=>K.mimeType===Z.mimeType&&wJ(K.data,Z.data)))continue;J.push({id:24999,data:[Z.description!==void 0?{id:18046,data:new r0(Z.description)}:null,{id:18030,data:new r0(Z.name??"")},{id:18016,data:Z.mimeType??""},{id:18012,data:Z.data},{id:18094,data:BigInt(X)}]})}if(J.length===0)return;this.attachmentsElement={id:423732329,data:J}}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);let $={id:408125543,size:this.format._options.appendOnly?-1:dY,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=$,this.format._options.onSegmentHeader)this.writer.startTrackingWrites();if(this.ebmlWriter.writeEBML($),this.format._options.onSegmentHeader){let{data:J,start:Y}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(J,Y)}}createCues(){this.cues={id:475249515,data:[]}}get segmentDataOffset(){return H(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(let $ of this.output._tracks)if(!$.source._closed&&!this.trackDatas.some((J)=>J.track===$))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let $=this.trackDatas.map((J)=>{if(J.type==="video")return J.info.decoderConfig.codec;if(J.type==="audio")return J.info.decoderConfig.codec;return{webvtt:"S_TEXT/WEBVTT",tx3g:"S_TEXT/UTF8",ttml:"S_TEXT/WEBVTT",srt:"S_TEXT/UTF8",ass:"S_TEXT/ASS",ssa:"S_TEXT/SSA"}[J.track.source._codec]});return Q2({isWebM:this.format instanceof $6,hasVideo:this.trackDatas.some((J)=>J.type==="video"),hasAudio:this.trackDatas.some((J)=>J.type==="audio"),codecStrings:$})}getVideoTrackData($,J,Y){let j=this.trackDatas.find((Z)=>Z.track===$);if(j)return j;t1(Y),H(Y),H(Y.decoderConfig),H(Y.decoderConfig.codedWidth!==void 0),H(Y.decoderConfig.codedHeight!==void 0);let X={track:$,type:"video",info:{width:Y.decoderConfig.codedWidth,height:Y.decoderConfig.codedHeight,decoderConfig:Y.decoderConfig,alphaMode:!!J.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null};if($.source._codec==="vp9")X.info.decoderConfig={...X.info.decoderConfig,description:new Uint8Array(yJ(X.info.decoderConfig.codec))};else if($.source._codec==="av1")X.info.decoderConfig={...X.info.decoderConfig,description:new Uint8Array(W6(X.info.decoderConfig.codec))};if(this.trackDatas.push(X),this.trackDatas.sort((Z,G)=>Z.track.id-G.track.id),this.allTracksAreKnown())this.allTracksKnown.resolve();return X}getAudioTrackData($,J){let Y=this.trackDatas.find((X)=>X.track===$);if(Y)return Y;_0(J),H(J),H(J.decoderConfig);let j={track:$,type:"audio",info:{numberOfChannels:J.decoderConfig.numberOfChannels,sampleRate:J.decoderConfig.sampleRate,decoderConfig:J.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};if(this.trackDatas.push(j),this.trackDatas.sort((X,Z)=>X.track.id-Z.track.id),this.allTracksAreKnown())this.allTracksKnown.resolve();return j}getSubtitleTrackData($,J){let Y=this.trackDatas.find((X)=>X.track===$);if(Y)return Y;A6(J),H(J),H(J.config);let j={track:$,type:"subtitle",info:{config:J.config},chunkQueue:[],lastWrittenMsTimestamp:null};if(this.trackDatas.push(j),this.trackDatas.sort((X,Z)=>X.track.id-Z.track.id),this.allTracksAreKnown())this.allTracksKnown.resolve();return j}async addEncodedVideoPacket($,J,Y){let j=await this.mutex.acquire();try{let X=this.getVideoTrackData($,J,Y),Z=J.type==="key",G=this.validateAndNormalizeTimestamp(X.track,J.timestamp,Z),K=J.duration;if($.metadata.frameRate!==void 0)G=F8(G,1/$.metadata.frameRate),K=F8(K,1/$.metadata.frameRate);let Q=X.info.alphaMode?J.sideData.alpha??null:null,q=this.createInternalChunk(J.data,G,K,J.type,Q);if($.source._codec==="vp9")this.fixVP9ColorSpace(X,q);X.chunkQueue.push(q),await this.interleaveChunks()}finally{j()}}async addEncodedAudioPacket($,J,Y){let j=await this.mutex.acquire();try{let X=this.getAudioTrackData($,Y),Z=J.type==="key",G=this.validateAndNormalizeTimestamp(X.track,J.timestamp,Z),K=this.createInternalChunk(J.data,G,J.duration,J.type);X.chunkQueue.push(K),await this.interleaveChunks()}finally{j()}}async addSubtitleCue($,J,Y){let j=await this.mutex.acquire();try{let X=this.getSubtitleTrackData($,Y),Z=this.validateAndNormalizeTimestamp(X.track,J.timestamp,!0),G=J.text,K=Math.round(Z*1000);if($.source._codec==="ass"||$.source._codec==="ssa")G=Y$(G);else u1.lastIndex=0,G=G.replace(u1,(W)=>{let N=I8(W.slice(1,-1))-K;return`<${k1(N)}>`});let Q=m.encode(G),q=`${J.settings??""}
426
426
  ${J.identifier??""}
427
- ${J.notes??""}`,U=this.createInternalChunk(Q,Z,J.duration,"key",q.trim()?m.encode(q):null);X.chunkQueue.push(U),await this.interleaveChunks()}finally{j()}}async interleaveChunks($=!1){if(!$&&!this.allTracksAreKnown())return;$:while(!0){let J=null,Y=Number.POSITIVE_INFINITY;for(let X of this.trackDatas){if(!$&&X.chunkQueue.length===0&&!X.track.source._closed)break $;if(X.chunkQueue.length>0&&X.chunkQueue[0].timestamp<Y)J=X,Y=X.chunkQueue[0].timestamp}if(!J)break;let j=J.chunkQueue.shift();this.writeBlock(J,j)}if(!$)await this.writer.flush()}fixVP9ColorSpace($,J){if(J.type!=="key")return;if(!$.info.decoderConfig.colorSpace||!$.info.decoderConfig.colorSpace.matrix)return;let Y=new f(J.data);Y.skipBits(2);let j=Y.readBits(1),Z=(Y.readBits(1)<<1)+j;if(Z===3)Y.skipBits(1);if(Y.readBits(1))return;if(Y.readBits(1)!==0)return;if(Y.skipBits(2),Y.readBits(24)!==4817730)return;if(Z>=2)Y.skipBits(1);let q={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[$.info.decoderConfig.colorSpace.matrix];WJ(J.data,Y.pos,Y.pos+3,q)}createInternalChunk($,J,Y,j,X=null){return{data:$,type:j,timestamp:J,duration:Y,additions:X}}writeBlock($,J){if(!this.segment)this.createSegment();let Y=Math.round(1000*J.timestamp),j=this.trackDatas.every((q)=>{if($===q)return J.type==="key";let U=q.chunkQueue[0];if(U)return U.type==="key";return q.track.source._closed}),X=!1;if(!this.currentCluster)X=!0;else{H(this.currentClusterStartMsTimestamp!==null),H(this.currentClusterMaxMsTimestamp!==null);let q=Y-this.currentClusterStartMsTimestamp;X=j&&Y>this.currentClusterMaxMsTimestamp&&q>=1000*(this.format._options.minimumClusterDuration??1)||q>RX}if(X)this.createNewCluster(Y);let Z=Y-this.currentClusterStartMsTimestamp;if(Z<AX)return;let G=new Uint8Array(4),K=new DataView(G.buffer);K.setUint8(0,128|$.track.id),K.setInt16(1,Z,!1);let Q=Math.round(1000*J.duration);if(!J.additions){K.setUint8(3,Number(J.type==="key")<<7);let q={id:163,data:[G,J.data]};this.ebmlWriter.writeEBML(q)}else{let q={id:160,data:[{id:161,data:[G,J.data]},J.type==="delta"?{id:251,data:new X2($.lastWrittenMsTimestamp-Y)}:null,J.additions?{id:30113,data:[{id:166,data:[{id:238,data:1},{id:165,data:J.additions}]}]}:null,Q>0?{id:155,data:Q}:null]};this.ebmlWriter.writeEBML(q)}if(this.duration=Math.max(this.duration,Y+Q),$.lastWrittenMsTimestamp=Y,!this.trackDatasInCurrentCluster.has($))this.trackDatasInCurrentCluster.set($,{firstMsTimestamp:Y});this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,Y)}createNewCluster($){if(this.currentCluster)this.finalizeCurrentCluster();if(this.format._options.onCluster)this.writer.startTrackingWrites();this.currentCluster={id:524531317,size:this.format._options.appendOnly?-1:nY,data:[{id:231,data:$}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=$,this.currentClusterMaxMsTimestamp=$,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(H(this.currentCluster),!this.format._options.appendOnly){let j=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),X=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(j,nY),this.writer.seek(X)}if(this.format._options.onCluster){H(this.currentClusterStartMsTimestamp!==null);let{data:j,start:X}=this.writer.stopTrackingWrites();this.format._options.onCluster(j,X,this.currentClusterStartMsTimestamp/1000)}let $=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,J=new Map;for(let[j,{firstMsTimestamp:X}]of this.trackDatasInCurrentCluster){if(!J.has(X))J.set(X,[]);J.get(X).push(j)}let Y=[...J.entries()].sort((j,X)=>j[0]-X[0]);for(let[j,X]of Y)H(this.cues),this.cues.data.push({id:187,data:[{id:179,data:j},...X.map((Z)=>{return{id:183,data:[{id:247,data:Z.track.id},{id:241,data:$}]}})]})}async onTrackClose(){let $=await this.mutex.acquire();if(this.allTracksAreKnown())this.allTracksKnown.resolve();await this.interleaveChunks(),$()}async finalize(){let $=await this.mutex.acquire();if(this.allTracksKnown.resolve(),!this.segment)this.createSegment();if(await this.interleaveChunks(!0),this.currentCluster)this.finalizeCurrentCluster();if(H(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let J=this.writer.getPos(),Y=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(Y,cY),this.segmentDuration.data=new m8(this.duration),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),H(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead),this.writer.seek(J)}$()}}/*!
427
+ ${J.notes??""}`,U=this.createInternalChunk(Q,Z,J.duration,"key",q.trim()?m.encode(q):null);X.chunkQueue.push(U),await this.interleaveChunks()}finally{j()}}async interleaveChunks($=!1){if(!$&&!this.allTracksAreKnown())return;$:while(!0){let J=null,Y=Number.POSITIVE_INFINITY;for(let X of this.trackDatas){if(!$&&X.chunkQueue.length===0&&!X.track.source._closed)break $;if(X.chunkQueue.length>0&&X.chunkQueue[0].timestamp<Y)J=X,Y=X.chunkQueue[0].timestamp}if(!J)break;let j=J.chunkQueue.shift();this.writeBlock(J,j)}if(!$)await this.writer.flush()}fixVP9ColorSpace($,J){if(J.type!=="key")return;if(!$.info.decoderConfig.colorSpace||!$.info.decoderConfig.colorSpace.matrix)return;let Y=new f(J.data);Y.skipBits(2);let j=Y.readBits(1),Z=(Y.readBits(1)<<1)+j;if(Z===3)Y.skipBits(1);if(Y.readBits(1))return;if(Y.readBits(1)!==0)return;if(Y.skipBits(2),Y.readBits(24)!==4817730)return;if(Z>=2)Y.skipBits(1);let q={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[$.info.decoderConfig.colorSpace.matrix];WJ(J.data,Y.pos,Y.pos+3,q)}createInternalChunk($,J,Y,j,X=null){return{data:$,type:j,timestamp:J,duration:Y,additions:X}}writeBlock($,J){if(!this.segment)this.createSegment();let Y=Math.round(1000*J.timestamp),j=this.trackDatas.every((q)=>{if($===q)return J.type==="key";let U=q.chunkQueue[0];if(U)return U.type==="key";return q.track.source._closed}),X=!1;if(!this.currentCluster)X=!0;else{H(this.currentClusterStartMsTimestamp!==null),H(this.currentClusterMaxMsTimestamp!==null);let q=Y-this.currentClusterStartMsTimestamp;X=j&&Y>this.currentClusterMaxMsTimestamp&&q>=1000*(this.format._options.minimumClusterDuration??1)||q>NX}if(X)this.createNewCluster(Y);let Z=Y-this.currentClusterStartMsTimestamp;if(Z<HX)return;let G=new Uint8Array(4),K=new DataView(G.buffer);K.setUint8(0,128|$.track.id),K.setInt16(1,Z,!1);let Q=Math.round(1000*J.duration);if(!J.additions){K.setUint8(3,Number(J.type==="key")<<7);let q={id:163,data:[G,J.data]};this.ebmlWriter.writeEBML(q)}else{let q={id:160,data:[{id:161,data:[G,J.data]},J.type==="delta"?{id:251,data:new X2($.lastWrittenMsTimestamp-Y)}:null,J.additions?{id:30113,data:[{id:166,data:[{id:238,data:1},{id:165,data:J.additions}]}]}:null,Q>0?{id:155,data:Q}:null]};this.ebmlWriter.writeEBML(q)}if(this.duration=Math.max(this.duration,Y+Q),$.lastWrittenMsTimestamp=Y,!this.trackDatasInCurrentCluster.has($))this.trackDatasInCurrentCluster.set($,{firstMsTimestamp:Y});this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,Y)}createNewCluster($){if(this.currentCluster)this.finalizeCurrentCluster();if(this.format._options.onCluster)this.writer.startTrackingWrites();this.currentCluster={id:524531317,size:this.format._options.appendOnly?-1:cY,data:[{id:231,data:$}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=$,this.currentClusterMaxMsTimestamp=$,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(H(this.currentCluster),!this.format._options.appendOnly){let j=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),X=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(j,cY),this.writer.seek(X)}if(this.format._options.onCluster){H(this.currentClusterStartMsTimestamp!==null);let{data:j,start:X}=this.writer.stopTrackingWrites();this.format._options.onCluster(j,X,this.currentClusterStartMsTimestamp/1000)}let $=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,J=new Map;for(let[j,{firstMsTimestamp:X}]of this.trackDatasInCurrentCluster){if(!J.has(X))J.set(X,[]);J.get(X).push(j)}let Y=[...J.entries()].sort((j,X)=>j[0]-X[0]);for(let[j,X]of Y)H(this.cues),this.cues.data.push({id:187,data:[{id:179,data:j},...X.map((Z)=>{return{id:183,data:[{id:247,data:Z.track.id},{id:241,data:$}]}})]})}async onTrackClose(){let $=await this.mutex.acquire();if(this.allTracksAreKnown())this.allTracksKnown.resolve();await this.interleaveChunks(),$()}async finalize(){let $=await this.mutex.acquire();if(this.allTracksKnown.resolve(),!this.segment)this.createSegment();if(await this.interleaveChunks(!0),this.currentCluster)this.finalizeCurrentCluster();if(H(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let J=this.writer.getPos(),Y=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(Y,dY),this.segmentDuration.data=new m8(this.duration),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),H(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead),this.writer.seek(J)}$()}}/*!
428
428
  * Copyright (c) 2025-present, Vanilagy and contributors
429
429
  *
430
430
  * This Source Code Form is subject to the terms of the Mozilla Public
@@ -442,7 +442,7 @@ ${J.notes??""}`,U=this.createInternalChunk(Q,Z,J.duration,"key",q.trim()?m.encod
442
442
  * This Source Code Form is subject to the terms of the Mozilla Public
443
443
  * License, v. 2.0. If a copy of the MPL was not distributed with this
444
444
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
445
- */var _X=8192;class YJ extends V0{format;writer;trackDatas=[];bosPagesWritten=!1;allTracksKnown=c();pageBytes=new Uint8Array(H2);pageView=new DataView(this.pageBytes.buffer);constructor($,J){super($);this.format=J,this.writer=$._writer,this.writer.ensureMonotonicity=!0}async start(){}async getMimeType(){return await this.allTracksKnown.promise,V2({codecStrings:this.trackDatas.map(($)=>$.codecInfo.codec)})}addEncodedVideoPacket(){throw Error("Video tracks are not supported.")}getTrackData($,J){let Y=this.trackDatas.find((Z)=>Z.track===$);if(Y)return Y;let j;do j=Math.floor(4294967296*Math.random());while(this.trackDatas.some((Z)=>Z.serialNumber===j));H($.source._codec==="vorbis"||$.source._codec==="opus"),_0(J),H(J),H(J.decoderConfig);let X={track:$,serialNumber:j,internalSampleRate:$.source._codec==="opus"?b0:J.decoderConfig.sampleRate,codecInfo:{codec:$.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],currentTimestampInSamples:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0};if(this.queueHeaderPackets(X,J),this.trackDatas.push(X),this.allTracksAreKnown())this.allTracksKnown.resolve();return X}queueHeaderPackets($,J){if(H(J.decoderConfig),$.track.source._codec==="vorbis"){H(J.decoderConfig.description);let Y=l(J.decoderConfig.description);if(Y[0]!==2)throw TypeError("First byte of Vorbis decoder description must be 2.");let j=1,X=()=>{let A=0;while(!0){let R=Y[j++];if(R===void 0)throw TypeError("Vorbis decoder description is too short.");if(A+=R,R<255)return A}},Z=X(),G=X();if(Y.length-j<=0)throw TypeError("Vorbis decoder description is too short.");let Q=Y.subarray(j,j+=Z);j+=G;let q=Y.subarray(j),U=new Uint8Array(7);U[0]=3,U[1]=118,U[2]=111,U[3]=114,U[4]=98,U[5]=105,U[6]=115;let W=C8(U,this.output._metadataTags,!0);$.packetQueue.push({data:Q,endGranulePosition:0,timestamp:0,forcePageFlush:!0},{data:W,endGranulePosition:0,timestamp:0,forcePageFlush:!1},{data:q,endGranulePosition:0,timestamp:0,forcePageFlush:!0});let N=h(Q).getUint8(28);$.codecInfo.vorbisInfo={blocksizes:[1<<(N&15),1<<(N>>4)],modeBlockflags:S6(q).modeBlockflags}}else if($.track.source._codec==="opus"){if(!J.decoderConfig.description)throw TypeError("For Ogg, Opus decoder description is required.");let Y=l(J.decoderConfig.description),j=new Uint8Array(8),X=h(j);X.setUint32(0,1332770163,!1),X.setUint32(4,1415669619,!1);let Z=C8(j,this.output._metadataTags,!0);$.packetQueue.push({data:Y,endGranulePosition:0,timestamp:0,forcePageFlush:!0},{data:Z,endGranulePosition:0,timestamp:0,forcePageFlush:!0}),$.codecInfo.opusInfo={preSkip:z1(Y).preSkip}}}async addEncodedAudioPacket($,J,Y){let j=await this.mutex.acquire();try{let X=this.getTrackData($,Y);this.validateAndNormalizeTimestamp(X.track,J.timestamp,J.type==="key");let Z=X.currentTimestampInSamples,{durationInSamples:G,vorbisBlockSize:K}=W2(J.data,X.codecInfo,X.vorbisLastBlocksize);X.currentTimestampInSamples+=G,X.vorbisLastBlocksize=K,X.packetQueue.push({data:J.data,endGranulePosition:X.currentTimestampInSamples,timestamp:Z/X.internalSampleRate,forcePageFlush:!1}),await this.interleavePages()}finally{j()}}addSubtitleCue(){throw Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(let $ of this.output._tracks)if(!$.source._closed&&!this.trackDatas.some((J)=>J.track===$))return!1;return!0}async interleavePages($=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown())return;for(let J of this.trackDatas)while(J.packetQueue.length>0){let Y=J.packetQueue.shift();if(this.writePacket(J,Y,!1),Y.forcePageFlush)break}this.bosPagesWritten=!0}$:while(!0){let J=null,Y=Number.POSITIVE_INFINITY;for(let Z of this.trackDatas){if(!$&&Z.packetQueue.length<=1&&!Z.track.source._closed)break $;if(Z.packetQueue.length>0&&Z.packetQueue[0].timestamp<Y)J=Z,Y=Z.packetQueue[0].timestamp}if(!J)break;let j=J.packetQueue.shift(),X=J.packetQueue.length===0;this.writePacket(J,j,X)}if(!$)await this.writer.flush()}writePacket($,J,Y){let j=J.data.length,X=0,Z=0;while(!0){if($.currentLacingValues.length===0&&X>0)$.currentPageStartsWithFreshPacket=!1;let K=Math.min(255,j);$.currentLacingValues.push(K),$.currentPageSize++,Z+=K;let Q=j<255;if($.currentLacingValues.length===255){let q=J.data.subarray(X,Z);if(X=Z,$.currentPageData.push(q),$.currentPageSize+=q.length,this.writePage($,Y&&Q),Q)return}if(Q)break;j-=255}let G=J.data.subarray(X);if($.currentPageData.push(G),$.currentPageSize+=G.length,$.currentGranulePosition=J.endGranulePosition,$.currentPageSize>=_X||J.forcePageFlush)this.writePage($,Y)}writePage($,J){this.pageView.setUint32(0,n8,!0),this.pageView.setUint8(4,0);let Y=0;if(!$.currentPageStartsWithFreshPacket)Y|=1;if($.pagesWritten===0)Y|=2;if(J)Y|=4;this.pageView.setUint8(5,Y);let j=$.currentLacingValues.every((K)=>K===255)?-1:$.currentGranulePosition;RJ(this.pageView,6,j,!0),this.pageView.setUint32(14,$.serialNumber,!0),this.pageView.setUint32(18,$.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,$.currentLacingValues.length),this.pageBytes.set($.currentLacingValues,27);let X=27+$.currentLacingValues.length;for(let K of $.currentPageData)this.pageBytes.set(K,X),X+=K.length;let Z=this.pageBytes.subarray(0,X),G=U2(Z);if(this.pageView.setUint32(22,G,!0),$.pagesWritten++,$.currentLacingValues.length=0,$.currentPageData.length=0,$.currentPageSize=27,$.currentPageStartsWithFreshPacket=!0,this.format._options.onPage)this.writer.startTrackingWrites();if(this.writer.write(Z),this.format._options.onPage){let{data:K,start:Q}=this.writer.stopTrackingWrites();this.format._options.onPage(K,Q,$.track.source)}}async onTrackClose(){let $=await this.mutex.acquire();if(this.allTracksAreKnown())this.allTracksKnown.resolve();await this.interleavePages(),$()}async finalize(){let $=await this.mutex.acquire();this.allTracksKnown.resolve(),await this.interleavePages(!0);for(let J of this.trackDatas)if(J.currentLacingValues.length>0)this.writePage(J,!0);$()}}/*!
445
+ */var RX=8192;class YJ extends V0{format;writer;trackDatas=[];bosPagesWritten=!1;allTracksKnown=c();pageBytes=new Uint8Array(H2);pageView=new DataView(this.pageBytes.buffer);constructor($,J){super($);this.format=J,this.writer=$._writer,this.writer.ensureMonotonicity=!0}async start(){}async getMimeType(){return await this.allTracksKnown.promise,V2({codecStrings:this.trackDatas.map(($)=>$.codecInfo.codec)})}addEncodedVideoPacket(){throw Error("Video tracks are not supported.")}getTrackData($,J){let Y=this.trackDatas.find((Z)=>Z.track===$);if(Y)return Y;let j;do j=Math.floor(4294967296*Math.random());while(this.trackDatas.some((Z)=>Z.serialNumber===j));H($.source._codec==="vorbis"||$.source._codec==="opus"),_0(J),H(J),H(J.decoderConfig);let X={track:$,serialNumber:j,internalSampleRate:$.source._codec==="opus"?b0:J.decoderConfig.sampleRate,codecInfo:{codec:$.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],currentTimestampInSamples:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0};if(this.queueHeaderPackets(X,J),this.trackDatas.push(X),this.allTracksAreKnown())this.allTracksKnown.resolve();return X}queueHeaderPackets($,J){if(H(J.decoderConfig),$.track.source._codec==="vorbis"){H(J.decoderConfig.description);let Y=l(J.decoderConfig.description);if(Y[0]!==2)throw TypeError("First byte of Vorbis decoder description must be 2.");let j=1,X=()=>{let A=0;while(!0){let R=Y[j++];if(R===void 0)throw TypeError("Vorbis decoder description is too short.");if(A+=R,R<255)return A}},Z=X(),G=X();if(Y.length-j<=0)throw TypeError("Vorbis decoder description is too short.");let Q=Y.subarray(j,j+=Z);j+=G;let q=Y.subarray(j),U=new Uint8Array(7);U[0]=3,U[1]=118,U[2]=111,U[3]=114,U[4]=98,U[5]=105,U[6]=115;let W=C8(U,this.output._metadataTags,!0);$.packetQueue.push({data:Q,endGranulePosition:0,timestamp:0,forcePageFlush:!0},{data:W,endGranulePosition:0,timestamp:0,forcePageFlush:!1},{data:q,endGranulePosition:0,timestamp:0,forcePageFlush:!0});let N=h(Q).getUint8(28);$.codecInfo.vorbisInfo={blocksizes:[1<<(N&15),1<<(N>>4)],modeBlockflags:S6(q).modeBlockflags}}else if($.track.source._codec==="opus"){if(!J.decoderConfig.description)throw TypeError("For Ogg, Opus decoder description is required.");let Y=l(J.decoderConfig.description),j=new Uint8Array(8),X=h(j);X.setUint32(0,1332770163,!1),X.setUint32(4,1415669619,!1);let Z=C8(j,this.output._metadataTags,!0);$.packetQueue.push({data:Y,endGranulePosition:0,timestamp:0,forcePageFlush:!0},{data:Z,endGranulePosition:0,timestamp:0,forcePageFlush:!0}),$.codecInfo.opusInfo={preSkip:z1(Y).preSkip}}}async addEncodedAudioPacket($,J,Y){let j=await this.mutex.acquire();try{let X=this.getTrackData($,Y);this.validateAndNormalizeTimestamp(X.track,J.timestamp,J.type==="key");let Z=X.currentTimestampInSamples,{durationInSamples:G,vorbisBlockSize:K}=W2(J.data,X.codecInfo,X.vorbisLastBlocksize);X.currentTimestampInSamples+=G,X.vorbisLastBlocksize=K,X.packetQueue.push({data:J.data,endGranulePosition:X.currentTimestampInSamples,timestamp:Z/X.internalSampleRate,forcePageFlush:!1}),await this.interleavePages()}finally{j()}}addSubtitleCue(){throw Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(let $ of this.output._tracks)if(!$.source._closed&&!this.trackDatas.some((J)=>J.track===$))return!1;return!0}async interleavePages($=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown())return;for(let J of this.trackDatas)while(J.packetQueue.length>0){let Y=J.packetQueue.shift();if(this.writePacket(J,Y,!1),Y.forcePageFlush)break}this.bosPagesWritten=!0}$:while(!0){let J=null,Y=Number.POSITIVE_INFINITY;for(let Z of this.trackDatas){if(!$&&Z.packetQueue.length<=1&&!Z.track.source._closed)break $;if(Z.packetQueue.length>0&&Z.packetQueue[0].timestamp<Y)J=Z,Y=Z.packetQueue[0].timestamp}if(!J)break;let j=J.packetQueue.shift(),X=J.packetQueue.length===0;this.writePacket(J,j,X)}if(!$)await this.writer.flush()}writePacket($,J,Y){let j=J.data.length,X=0,Z=0;while(!0){if($.currentLacingValues.length===0&&X>0)$.currentPageStartsWithFreshPacket=!1;let K=Math.min(255,j);$.currentLacingValues.push(K),$.currentPageSize++,Z+=K;let Q=j<255;if($.currentLacingValues.length===255){let q=J.data.subarray(X,Z);if(X=Z,$.currentPageData.push(q),$.currentPageSize+=q.length,this.writePage($,Y&&Q),Q)return}if(Q)break;j-=255}let G=J.data.subarray(X);if($.currentPageData.push(G),$.currentPageSize+=G.length,$.currentGranulePosition=J.endGranulePosition,$.currentPageSize>=RX||J.forcePageFlush)this.writePage($,Y)}writePage($,J){this.pageView.setUint32(0,n8,!0),this.pageView.setUint8(4,0);let Y=0;if(!$.currentPageStartsWithFreshPacket)Y|=1;if($.pagesWritten===0)Y|=2;if(J)Y|=4;this.pageView.setUint8(5,Y);let j=$.currentLacingValues.every((K)=>K===255)?-1:$.currentGranulePosition;RJ(this.pageView,6,j,!0),this.pageView.setUint32(14,$.serialNumber,!0),this.pageView.setUint32(18,$.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,$.currentLacingValues.length),this.pageBytes.set($.currentLacingValues,27);let X=27+$.currentLacingValues.length;for(let K of $.currentPageData)this.pageBytes.set(K,X),X+=K.length;let Z=this.pageBytes.subarray(0,X),G=U2(Z);if(this.pageView.setUint32(22,G,!0),$.pagesWritten++,$.currentLacingValues.length=0,$.currentPageData.length=0,$.currentPageSize=27,$.currentPageStartsWithFreshPacket=!0,this.format._options.onPage)this.writer.startTrackingWrites();if(this.writer.write(Z),this.format._options.onPage){let{data:K,start:Q}=this.writer.stopTrackingWrites();this.format._options.onPage(K,Q,$.track.source)}}async onTrackClose(){let $=await this.mutex.acquire();if(this.allTracksAreKnown())this.allTracksKnown.resolve();await this.interleavePages(),$()}async finalize(){let $=await this.mutex.acquire();this.allTracksKnown.resolve(),await this.interleavePages(!0);for(let J of this.trackDatas)if(J.currentLacingValues.length>0)this.writePage(J,!0);$()}}/*!
446
446
  * Copyright (c) 2025-present, Vanilagy and contributors
447
447
  *
448
448
  * This Source Code Form is subject to the terms of the Mozilla Public
@@ -460,19 +460,19 @@ ${J.notes??""}`,U=this.createInternalChunk(Q,Z,J.duration,"key",q.trim()?m.encod
460
460
  * This Source Code Form is subject to the terms of the Mozilla Public
461
461
  * License, v. 2.0. If a copy of the MPL was not distributed with this
462
462
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
463
- */class y0{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(($)=>j0.includes($))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(($)=>Z0.includes($))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(($)=>z0.includes($))}_codecUnsupportedHint($){return""}}class T2 extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes($.fastStart))throw TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if($.minimumFragmentDuration!==void 0&&(!Number.isFinite($.minimumFragmentDuration)||$.minimumFragmentDuration<0))throw TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if($.onFtyp!==void 0&&typeof $.onFtyp!=="function")throw TypeError("options.onFtyp, when provided, must be a function.");if($.onMoov!==void 0&&typeof $.onMoov!=="function")throw TypeError("options.onMoov, when provided, must be a function.");if($.onMdat!==void 0&&typeof $.onMdat!=="function")throw TypeError("options.onMdat, when provided, must be a function.");if($.onMoof!==void 0&&typeof $.onMoof!=="function")throw TypeError("options.onMoof, when provided, must be a function.");if($.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes($.metadataFormat))throw TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super();this._options=$}getSupportedTrackCounts(){return{video:{min:0,max:Number.POSITIVE_INFINITY},audio:{min:0,max:Number.POSITIVE_INFINITY},subtitle:{min:0,max:Number.POSITIVE_INFINITY},total:{min:1,max:4294967295}}}get supportsVideoRotationMetadata(){return!0}_createMuxer($){return new t$($,this)}}class J6 extends T2{constructor($){super($)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...j0,...X1,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","webvtt"]}_codecUnsupportedHint($){if(new e8().getSupportedCodecs().includes($))return" Switching to MOV will grant support for this codec.";return""}}class e8 extends T2{constructor($){super($)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...j0,...Z0,"webvtt"]}_codecUnsupportedHint($){if(new J6().getSupportedCodecs().includes($))return" Switching to MP4 will grant support for this codec.";return""}}class E2 extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.appendOnly!==void 0&&typeof $.appendOnly!=="boolean")throw TypeError("options.appendOnly, when provided, must be a boolean.");if($.minimumClusterDuration!==void 0&&(!Number.isFinite($.minimumClusterDuration)||$.minimumClusterDuration<0))throw TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if($.onEbmlHeader!==void 0&&typeof $.onEbmlHeader!=="function")throw TypeError("options.onEbmlHeader, when provided, must be a function.");if($.onSegmentHeader!==void 0&&typeof $.onSegmentHeader!=="function")throw TypeError("options.onHeader, when provided, must be a function.");if($.onCluster!==void 0&&typeof $.onCluster!=="function")throw TypeError("options.onCluster, when provided, must be a function.");super();this._options=$}_createMuxer($){return new e$($,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:Number.POSITIVE_INFINITY},audio:{min:0,max:Number.POSITIVE_INFINITY},subtitle:{min:0,max:Number.POSITIVE_INFINITY},total:{min:1,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...j0,...X1,...o.filter(($)=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes($)),...z0]}get supportsVideoRotationMetadata(){return!1}}class $6 extends E2{constructor($){super($)}getSupportedCodecs(){return[...j0.filter(($)=>["vp8","vp9","av1"].includes($)),...Z0.filter(($)=>["opus","vorbis"].includes($)),...z0]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint($){if(new E2().getSupportedCodecs().includes($))return" Switching to MKV will grant support for this codec.";return""}}class oY extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.xingHeader!==void 0&&typeof $.xingHeader!=="boolean")throw TypeError("options.xingHeader, when provided, must be a boolean.");if($.onXingFrame!==void 0&&typeof $.onXingFrame!=="function")throw TypeError("options.onXingFrame, when provided, must be a function.");super();this._options=$}_createMuxer($){return new JJ($,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 supportsVideoRotationMetadata(){return!1}}class rY extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.large!==void 0&&typeof $.large!=="boolean")throw TypeError("options.large, when provided, must be a boolean.");if($.metadataFormat!==void 0&&!["info","id3"].includes($.metadataFormat))throw TypeError("options.metadataFormat, when provided, must be either 'info' or 'id3'.");if($.onHeader!==void 0&&typeof $.onHeader!=="function")throw TypeError("options.onHeader, when provided, must be a function.");super();this._options=$}_createMuxer($){return new XJ($,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[...o.filter(($)=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-u8","ulaw","alaw"].includes($))]}get supportsVideoRotationMetadata(){return!1}}class iY extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.onPage!==void 0&&typeof $.onPage!=="function")throw TypeError("options.onPage, when provided, must be a function.");super();this._options=$}_createMuxer($){return new YJ($,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:Number.POSITIVE_INFINITY},subtitle:{min:0,max:0},total:{min:1,max:4294967296}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...Z0.filter(($)=>["vorbis","opus"].includes($))]}get supportsVideoRotationMetadata(){return!1}}class sY extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.onFrame!==void 0&&typeof $.onFrame!=="function")throw TypeError("options.onFrame, when provided, must be a function.");super();this._options=$}_createMuxer($){return new f$($,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 supportsVideoRotationMetadata(){return!1}}class aY extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.large!==void 0&&typeof $.large!=="boolean")throw TypeError("options.large, when provided, must be a boolean.");if($.onHeader!==void 0&&typeof $.onHeader!=="function")throw TypeError("options.onHeader, when provided, must be a function.");if($.onIndex!==void 0&&typeof $.onIndex!=="function")throw TypeError("options.onIndex, when provided, must be a function.");super();this._options=$}_createMuxer($){return new k$($,this)}get _name(){return"AVI"}getSupportedTrackCounts(){return{video:{min:0,max:Number.POSITIVE_INFINITY},audio:{min:0,max:Number.POSITIVE_INFINITY},subtitle:{min:0,max:0},total:{min:1,max:4294967295}}}get fileExtension(){return".avi"}get mimeType(){return"video/x-msvideo"}getSupportedCodecs(){return[...j0.filter(($)=>["avc","hevc","vp8","vp9","av1","mpeg4"].includes($)),...Z0.filter(($)=>["mp3","aac","vorbis","flac","ac3","pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-u8","ulaw","alaw"].includes($))]}get supportsVideoRotationMetadata(){return!1}}class tY extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");super();this._options=$}_createMuxer($){return new u$($,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 supportsVideoRotationMetadata(){return!1}}/*!
463
+ */class y0{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(($)=>j0.includes($))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(($)=>Z0.includes($))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(($)=>z0.includes($))}_codecUnsupportedHint($){return""}}class T2 extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes($.fastStart))throw TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if($.minimumFragmentDuration!==void 0&&(!Number.isFinite($.minimumFragmentDuration)||$.minimumFragmentDuration<0))throw TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if($.onFtyp!==void 0&&typeof $.onFtyp!=="function")throw TypeError("options.onFtyp, when provided, must be a function.");if($.onMoov!==void 0&&typeof $.onMoov!=="function")throw TypeError("options.onMoov, when provided, must be a function.");if($.onMdat!==void 0&&typeof $.onMdat!=="function")throw TypeError("options.onMdat, when provided, must be a function.");if($.onMoof!==void 0&&typeof $.onMoof!=="function")throw TypeError("options.onMoof, when provided, must be a function.");if($.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes($.metadataFormat))throw TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super();this._options=$}getSupportedTrackCounts(){return{video:{min:0,max:Number.POSITIVE_INFINITY},audio:{min:0,max:Number.POSITIVE_INFINITY},subtitle:{min:0,max:Number.POSITIVE_INFINITY},total:{min:1,max:4294967295}}}get supportsVideoRotationMetadata(){return!0}_createMuxer($){return new t$($,this)}}class J6 extends T2{constructor($){super($)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...j0,...X1,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","webvtt"]}_codecUnsupportedHint($){if(new e8().getSupportedCodecs().includes($))return" Switching to MOV will grant support for this codec.";return""}}class e8 extends T2{constructor($){super($)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...j0,...Z0,"webvtt"]}_codecUnsupportedHint($){if(new J6().getSupportedCodecs().includes($))return" Switching to MP4 will grant support for this codec.";return""}}class E2 extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.appendOnly!==void 0&&typeof $.appendOnly!=="boolean")throw TypeError("options.appendOnly, when provided, must be a boolean.");if($.minimumClusterDuration!==void 0&&(!Number.isFinite($.minimumClusterDuration)||$.minimumClusterDuration<0))throw TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if($.onEbmlHeader!==void 0&&typeof $.onEbmlHeader!=="function")throw TypeError("options.onEbmlHeader, when provided, must be a function.");if($.onSegmentHeader!==void 0&&typeof $.onSegmentHeader!=="function")throw TypeError("options.onHeader, when provided, must be a function.");if($.onCluster!==void 0&&typeof $.onCluster!=="function")throw TypeError("options.onCluster, when provided, must be a function.");super();this._options=$}_createMuxer($){return new e$($,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:Number.POSITIVE_INFINITY},audio:{min:0,max:Number.POSITIVE_INFINITY},subtitle:{min:0,max:Number.POSITIVE_INFINITY},total:{min:1,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...j0,...X1,...o.filter(($)=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes($)),...z0]}get supportsVideoRotationMetadata(){return!1}}class $6 extends E2{constructor($){super($)}getSupportedCodecs(){return[...j0.filter(($)=>["vp8","vp9","av1"].includes($)),...Z0.filter(($)=>["opus","vorbis"].includes($)),...z0]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint($){if(new E2().getSupportedCodecs().includes($))return" Switching to MKV will grant support for this codec.";return""}}class nY extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.xingHeader!==void 0&&typeof $.xingHeader!=="boolean")throw TypeError("options.xingHeader, when provided, must be a boolean.");if($.onXingFrame!==void 0&&typeof $.onXingFrame!=="function")throw TypeError("options.onXingFrame, when provided, must be a function.");super();this._options=$}_createMuxer($){return new JJ($,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 supportsVideoRotationMetadata(){return!1}}class oY extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.large!==void 0&&typeof $.large!=="boolean")throw TypeError("options.large, when provided, must be a boolean.");if($.metadataFormat!==void 0&&!["info","id3"].includes($.metadataFormat))throw TypeError("options.metadataFormat, when provided, must be either 'info' or 'id3'.");if($.onHeader!==void 0&&typeof $.onHeader!=="function")throw TypeError("options.onHeader, when provided, must be a function.");super();this._options=$}_createMuxer($){return new XJ($,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[...o.filter(($)=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-u8","ulaw","alaw"].includes($))]}get supportsVideoRotationMetadata(){return!1}}class rY extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.onPage!==void 0&&typeof $.onPage!=="function")throw TypeError("options.onPage, when provided, must be a function.");super();this._options=$}_createMuxer($){return new YJ($,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:Number.POSITIVE_INFINITY},subtitle:{min:0,max:0},total:{min:1,max:4294967296}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...Z0.filter(($)=>["vorbis","opus"].includes($))]}get supportsVideoRotationMetadata(){return!1}}class iY extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.onFrame!==void 0&&typeof $.onFrame!=="function")throw TypeError("options.onFrame, when provided, must be a function.");super();this._options=$}_createMuxer($){return new f$($,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 supportsVideoRotationMetadata(){return!1}}class sY extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.large!==void 0&&typeof $.large!=="boolean")throw TypeError("options.large, when provided, must be a boolean.");if($.onHeader!==void 0&&typeof $.onHeader!=="function")throw TypeError("options.onHeader, when provided, must be a function.");if($.onIndex!==void 0&&typeof $.onIndex!=="function")throw TypeError("options.onIndex, when provided, must be a function.");super();this._options=$}_createMuxer($){return new k$($,this)}get _name(){return"AVI"}getSupportedTrackCounts(){return{video:{min:0,max:Number.POSITIVE_INFINITY},audio:{min:0,max:Number.POSITIVE_INFINITY},subtitle:{min:0,max:0},total:{min:1,max:4294967295}}}get fileExtension(){return".avi"}get mimeType(){return"video/x-msvideo"}getSupportedCodecs(){return[...j0.filter(($)=>["avc","hevc","vp8","vp9","av1","mpeg4"].includes($)),...Z0.filter(($)=>["mp3","aac","vorbis","flac","ac3","pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-u8","ulaw","alaw"].includes($))]}get supportsVideoRotationMetadata(){return!1}}class aY extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");super();this._options=$}_createMuxer($){return new u$($,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 supportsVideoRotationMetadata(){return!1}}/*!
464
464
  * Copyright (c) 2025-present, Vanilagy and contributors
465
465
  *
466
466
  * This Source Code Form is subject to the terms of the Mozilla Public
467
467
  * License, v. 2.0. If a copy of the MPL was not distributed with this
468
468
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
469
- */var eY=["video","audio","subtitle"],ZJ=($)=>{if(!$||typeof $!=="object")throw TypeError("metadata must be an object.");if($.languageCode!==void 0&&!d0($.languageCode))throw TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if($.name!==void 0&&typeof $.name!=="string")throw TypeError("metadata.name, when provided, must be a string.");if($.disposition!==void 0)U5($.disposition);if($.maximumPacketCount!==void 0&&(!Number.isInteger($.maximumPacketCount)||$.maximumPacketCount<0))throw TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.")};class Y6{format;target;state="pending";_muxer;_writer;_tracks=[];_startPromise=null;_cancelPromise=null;_finalizePromise=null;_mutex=new w0;_metadataTags={};constructor($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if(!($.format instanceof y0))throw TypeError("options.format must be an OutputFormat.");if(!($.target instanceof P1))throw TypeError("options.target must be a Target.");if($.target._output)throw Error("Target is already used for another output.");$.target._output=this,this.format=$.format,this.target=$.target,this._writer=$.target._createWriter(),this._muxer=$.format._createMuxer(this)}addVideoTrack($,J={}){if(!($ instanceof w1))throw TypeError("source must be a VideoSource.");if(ZJ(J),J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError(`Invalid video rotation: ${J.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&J.rotation)throw Error(`${this.format._name} does not support video rotation metadata.`);if(J.frameRate!==void 0&&(!Number.isFinite(J.frameRate)||J.frameRate<=0))throw TypeError(`Invalid video frame rate: ${J.frameRate}. Must be a positive number.`);this._addTrack("video",$,J)}addAudioTrack($,J={}){if(!($ instanceof O1))throw TypeError("source must be an AudioSource.");ZJ(J),this._addTrack("audio",$,J)}addSubtitleTrack($,J={}){if(!($ instanceof s8))throw TypeError("source must be a SubtitleSource.");ZJ(J),this._addTrack("subtitle",$,J)}setMetadataTags($){if(h8($),this.state!=="pending")throw Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=$}_addTrack($,J,Y){if(this.state!=="pending")throw Error("Cannot add track after output has been started or canceled.");if(J._connectedTrack)throw Error("Source is already used for a track.");let j=this.format.getSupportedTrackCounts(),X=this._tracks.reduce((Q,q)=>Q+(q.type===$?1:0),0),Z=j[$].max;if(X===Z)throw Error(Z===0?`${this.format._name} does not support ${$} tracks.`:`${this.format._name} does not support more than ${Z} ${$} track${Z===1?"":"s"}.`);let G=j.total.max;if(this._tracks.length===G)throw Error(`${this.format._name} does not support more than ${G} tracks${G===1?"":"s"} in total.`);let K={id:this._tracks.length+1,output:this,type:$,source:J,metadata:Y};if(K.type==="video"){let Q=this.format.getSupportedVideoCodecs();if(Q.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(K.source._codec));if(!Q.includes(K.source._codec))throw Error(`Codec '${K.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${Q.map((q)=>`'${q}'`).join(", ")}.`+this.format._codecUnsupportedHint(K.source._codec))}else if(K.type==="audio"){let Q=this.format.getSupportedAudioCodecs();if(Q.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(K.source._codec));if(!Q.includes(K.source._codec))throw Error(`Codec '${K.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${Q.map((q)=>`'${q}'`).join(", ")}.`+this.format._codecUnsupportedHint(K.source._codec))}else if(K.type==="subtitle"){let Q=this.format.getSupportedSubtitleCodecs();if(Q.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(K.source._codec));if(!Q.includes(K.source._codec))throw Error(`Codec '${K.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${Q.map((q)=>`'${q}'`).join(", ")}.`+this.format._codecUnsupportedHint(K.source._codec))}this._tracks.push(K),J._connectedTrack=K}async start(){let $=this.format.getSupportedTrackCounts();for(let Y of eY){let j=this._tracks.reduce((Z,G)=>Z+(G.type===Y?1:0),0),X=$[Y].min;if(j<X)throw Error(X===$[Y].max?`${this.format._name} requires exactly ${X} ${Y} track${X===1?"":"s"}.`:`${this.format._name} requires at least ${X} ${Y} track${X===1?"":"s"}.`)}let J=$.total.min;if(this._tracks.length<J)throw Error(J===$.total.max?`${this.format._name} requires exactly ${J} track${J===1?"":"s"}.`:`${this.format._name} requires at least ${J} track${J===1?"":"s"}.`);if(this.state==="canceled")throw Error("Output has been canceled.");if(this._startPromise)return console.warn("Output has already been started."),this._startPromise;return this._startPromise=(async()=>{this.state="started",this._writer.start();let Y=await this._mutex.acquire();await this._muxer.start();let j=this._tracks.map((X)=>X.source._start());await Promise.all(j),Y()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return console.warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){console.warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let $=await this._mutex.acquire(),J=this._tracks.map((Y)=>Y.source._flushOrWaitForOngoingClose(!0));await Promise.all(J),await this._writer.close(),$()})()}async finalize(){if(this.state==="pending")throw Error("Cannot finalize before starting.");if(this.state==="canceled")throw Error("Cannot finalize after canceling.");if(this._finalizePromise)return console.warn("Output has already been finalized."),this._finalizePromise;return this._finalizePromise=(async()=>{this.state="finalizing";let $=await this._mutex.acquire(),J=this._tracks.map((Y)=>Y.source._flushOrWaitForOngoingClose(!1));await Promise.all(J),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",$()})()}}x0();/*!
469
+ */var tY=["video","audio","subtitle"],ZJ=($)=>{if(!$||typeof $!=="object")throw TypeError("metadata must be an object.");if($.languageCode!==void 0&&!d0($.languageCode))throw TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if($.name!==void 0&&typeof $.name!=="string")throw TypeError("metadata.name, when provided, must be a string.");if($.disposition!==void 0)U5($.disposition);if($.maximumPacketCount!==void 0&&(!Number.isInteger($.maximumPacketCount)||$.maximumPacketCount<0))throw TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.")};class Y6{format;target;state="pending";_muxer;_writer;_tracks=[];_startPromise=null;_cancelPromise=null;_finalizePromise=null;_mutex=new w0;_metadataTags={};constructor($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if(!($.format instanceof y0))throw TypeError("options.format must be an OutputFormat.");if(!($.target instanceof P1))throw TypeError("options.target must be a Target.");if($.target._output)throw Error("Target is already used for another output.");$.target._output=this,this.format=$.format,this.target=$.target,this._writer=$.target._createWriter(),this._muxer=$.format._createMuxer(this)}addVideoTrack($,J={}){if(!($ instanceof w1))throw TypeError("source must be a VideoSource.");if(ZJ(J),J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError(`Invalid video rotation: ${J.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&J.rotation)throw Error(`${this.format._name} does not support video rotation metadata.`);if(J.frameRate!==void 0&&(!Number.isFinite(J.frameRate)||J.frameRate<=0))throw TypeError(`Invalid video frame rate: ${J.frameRate}. Must be a positive number.`);this._addTrack("video",$,J)}addAudioTrack($,J={}){if(!($ instanceof O1))throw TypeError("source must be an AudioSource.");ZJ(J),this._addTrack("audio",$,J)}addSubtitleTrack($,J={}){if(!($ instanceof s8))throw TypeError("source must be a SubtitleSource.");ZJ(J),this._addTrack("subtitle",$,J)}setMetadataTags($){if(h8($),this.state!=="pending")throw Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=$}_addTrack($,J,Y){if(this.state!=="pending")throw Error("Cannot add track after output has been started or canceled.");if(J._connectedTrack)throw Error("Source is already used for a track.");let j=this.format.getSupportedTrackCounts(),X=this._tracks.reduce((Q,q)=>Q+(q.type===$?1:0),0),Z=j[$].max;if(X===Z)throw Error(Z===0?`${this.format._name} does not support ${$} tracks.`:`${this.format._name} does not support more than ${Z} ${$} track${Z===1?"":"s"}.`);let G=j.total.max;if(this._tracks.length===G)throw Error(`${this.format._name} does not support more than ${G} tracks${G===1?"":"s"} in total.`);let K={id:this._tracks.length+1,output:this,type:$,source:J,metadata:Y};if(K.type==="video"){let Q=this.format.getSupportedVideoCodecs();if(Q.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(K.source._codec));if(!Q.includes(K.source._codec))throw Error(`Codec '${K.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${Q.map((q)=>`'${q}'`).join(", ")}.`+this.format._codecUnsupportedHint(K.source._codec))}else if(K.type==="audio"){let Q=this.format.getSupportedAudioCodecs();if(Q.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(K.source._codec));if(!Q.includes(K.source._codec))throw Error(`Codec '${K.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${Q.map((q)=>`'${q}'`).join(", ")}.`+this.format._codecUnsupportedHint(K.source._codec))}else if(K.type==="subtitle"){let Q=this.format.getSupportedSubtitleCodecs();if(Q.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(K.source._codec));if(!Q.includes(K.source._codec))throw Error(`Codec '${K.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${Q.map((q)=>`'${q}'`).join(", ")}.`+this.format._codecUnsupportedHint(K.source._codec))}this._tracks.push(K),J._connectedTrack=K}async start(){let $=this.format.getSupportedTrackCounts();for(let Y of tY){let j=this._tracks.reduce((Z,G)=>Z+(G.type===Y?1:0),0),X=$[Y].min;if(j<X)throw Error(X===$[Y].max?`${this.format._name} requires exactly ${X} ${Y} track${X===1?"":"s"}.`:`${this.format._name} requires at least ${X} ${Y} track${X===1?"":"s"}.`)}let J=$.total.min;if(this._tracks.length<J)throw Error(J===$.total.max?`${this.format._name} requires exactly ${J} track${J===1?"":"s"}.`:`${this.format._name} requires at least ${J} track${J===1?"":"s"}.`);if(this.state==="canceled")throw Error("Output has been canceled.");if(this._startPromise)return console.warn("Output has already been started."),this._startPromise;return this._startPromise=(async()=>{this.state="started",this._writer.start();let Y=await this._mutex.acquire();await this._muxer.start();let j=this._tracks.map((X)=>X.source._start());await Promise.all(j),Y()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return console.warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){console.warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let $=await this._mutex.acquire(),J=this._tracks.map((Y)=>Y.source._flushOrWaitForOngoingClose(!0));await Promise.all(J),await this._writer.close(),$()})()}async finalize(){if(this.state==="pending")throw Error("Cannot finalize before starting.");if(this.state==="canceled")throw Error("Cannot finalize after canceling.");if(this._finalizePromise)return console.warn("Output has already been finalized."),this._finalizePromise;return this._finalizePromise=(async()=>{this.state="finalizing";let $=await this._mutex.acquire(),J=this._tracks.map((Y)=>Y.source._flushOrWaitForOngoingClose(!1));await Promise.all(J),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",$()})()}}x0();/*!
470
470
  * Copyright (c) 2025-present, Vanilagy and contributors
471
471
  *
472
472
  * This Source Code Form is subject to the terms of the Mozilla Public
473
473
  * License, v. 2.0. If a copy of the MPL was not distributed with this
474
474
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
475
- */var $7=($)=>{if($!==void 0&&(!$||typeof $!=="object"))throw TypeError("options.video, when provided, must be an object.");if($?.discard!==void 0&&typeof $.discard!=="boolean")throw TypeError("options.video.discard, when provided, must be a boolean.");if($?.forceTranscode!==void 0&&typeof $.forceTranscode!=="boolean")throw TypeError("options.video.forceTranscode, when provided, must be a boolean.");if($?.codec!==void 0&&!j0.includes($.codec))throw TypeError(`options.video.codec, when provided, must be one of: ${j0.join(", ")}.`);if($?.bitrate!==void 0&&!($.bitrate instanceof N0)&&(!Number.isInteger($.bitrate)||$.bitrate<=0))throw TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if($?.width!==void 0&&(!Number.isInteger($.width)||$.width<=0))throw TypeError("options.video.width, when provided, must be a positive integer.");if($?.height!==void 0&&(!Number.isInteger($.height)||$.height<=0))throw TypeError("options.video.height, when provided, must be a positive integer.");if($?.fit!==void 0&&!["fill","contain","cover"].includes($.fit))throw TypeError("options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.");if($?.width!==void 0&&$.height!==void 0&&$.fit===void 0)throw TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if($?.rotate!==void 0&&![0,90,180,270].includes($.rotate))throw TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if($?.allowRotationMetadata!==void 0&&typeof $.allowRotationMetadata!=="boolean")throw TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if($?.crop!==void 0)b8($.crop,"options.video.");if($?.frameRate!==void 0&&(!Number.isFinite($.frameRate)||$.frameRate<=0))throw TypeError("options.video.frameRate, when provided, must be a finite positive number.");if($?.alpha!==void 0&&!["discard","keep"].includes($.alpha))throw TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if($?.keyFrameInterval!==void 0&&(!Number.isFinite($.keyFrameInterval)||$.keyFrameInterval<0))throw TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if($?.process!==void 0&&typeof $.process!=="function")throw TypeError("options.video.process, when provided, must be a function.");if($?.processedWidth!==void 0&&(!Number.isInteger($.processedWidth)||$.processedWidth<=0))throw TypeError("options.video.processedWidth, when provided, must be a positive integer.");if($?.processedHeight!==void 0&&(!Number.isInteger($.processedHeight)||$.processedHeight<=0))throw TypeError("options.video.processedHeight, when provided, must be a positive integer.");if($?.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes($.hardwareAcceleration))throw TypeError("options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.")},J7=($)=>{if($!==void 0&&(!$||typeof $!=="object"))throw TypeError("options.audio, when provided, must be an object.");if($?.discard!==void 0&&typeof $.discard!=="boolean")throw TypeError("options.audio.discard, when provided, must be a boolean.");if($?.forceTranscode!==void 0&&typeof $.forceTranscode!=="boolean")throw TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if($?.codec!==void 0&&!Z0.includes($.codec))throw TypeError(`options.audio.codec, when provided, must be one of: ${Z0.join(", ")}.`);if($?.bitrate!==void 0&&!($.bitrate instanceof N0)&&(!Number.isInteger($.bitrate)||$.bitrate<=0))throw TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if($?.numberOfChannels!==void 0&&(!Number.isInteger($.numberOfChannels)||$.numberOfChannels<=0))throw TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if($?.sampleRate!==void 0&&(!Number.isInteger($.sampleRate)||$.sampleRate<=0))throw TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if($?.process!==void 0&&typeof $.process!=="function")throw TypeError("options.audio.process, when provided, must be a function.");if($?.processedNumberOfChannels!==void 0&&(!Number.isInteger($.processedNumberOfChannels)||$.processedNumberOfChannels<=0))throw TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if($?.processedSampleRate!==void 0&&(!Number.isInteger($.processedSampleRate)||$.processedSampleRate<=0))throw TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.")},Y7=($)=>{if($!==void 0&&(!$||typeof $!=="object"))throw TypeError("options.subtitle, when provided, must be an object.");if($?.discard!==void 0&&typeof $.discard!=="boolean")throw TypeError("options.subtitle.discard, when provided, must be a boolean.");if($?.codec!==void 0&&!z0.includes($.codec))throw TypeError(`options.subtitle.codec, when provided, must be one of: ${z0.join(", ")}.`)},GJ=2,KJ=48000;class QJ{input;output;_options;_startTimestamp;_endTimestamp;_addedCounts={video:0,audio:0,subtitle:0};_totalTrackCount=0;_trackPromises=[];_started;_start;_executed=!1;_synchronizer=new X7;_totalDuration=null;_maxTimestamps=new Map;_canceled=!1;_externalSubtitleSources=[];onProgress=void 0;_computeProgress=!1;_lastProgress=0;isValid=!1;utilizedTracks=[];discardedTracks=[];static async init($){let J=new QJ($);return await J._init(),J}constructor($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if(!($.input instanceof z8))throw TypeError("options.input must be an Input.");if(!($.output instanceof Y6))throw TypeError("options.output must be an Output.");if($.output._tracks.length>0||Object.keys($.output._metadataTags).length>0||$.output.state!=="pending")throw TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");if(typeof $.video!=="function")$7($.video);if(typeof $.audio!=="function")J7($.audio);if(typeof $.subtitle!=="function")Y7($.subtitle);if($.trim!==void 0&&(!$.trim||typeof $.trim!=="object"))throw TypeError("options.trim, when provided, must be an object.");if($.trim?.start!==void 0&&(!Number.isFinite($.trim.start)||$.trim.start<0))throw TypeError("options.trim.start, when provided, must be a non-negative number.");if($.trim?.end!==void 0&&(!Number.isFinite($.trim.end)||$.trim.end<0))throw TypeError("options.trim.end, when provided, must be a non-negative number.");if($.trim?.start!==void 0&&$.trim.end!==void 0&&$.trim.start>=$.trim.end)throw TypeError("options.trim.start must be less than options.trim.end.");if($.tags!==void 0&&(typeof $.tags!=="object"||!$.tags)&&typeof $.tags!=="function")throw TypeError("options.tags, when provided, must be an object or a function.");if(typeof $.tags==="object")h8($.tags);if($.showWarnings!==void 0&&typeof $.showWarnings!=="boolean")throw TypeError("options.showWarnings, when provided, must be a boolean.");this._options=$,this.input=$.input,this.output=$.output,this._startTimestamp=$.trim?.start??0,this._endTimestamp=$.trim?.end??Number.POSITIVE_INFINITY;let{promise:J,resolve:Y}=c();this._started=J,this._start=Y}async _init(){let $=await this.input.getTracks(),J=this.output.format.getSupportedTrackCounts(),Y=1,j=1,X=1;for(let q of $){let U;if(q.isVideoTrack()){if(this._options.video)if(typeof this._options.video==="function")U=await this._options.video(q,Y),$7(U),Y++;else U=this._options.video}else if(q.isAudioTrack()){if(this._options.audio)if(typeof this._options.audio==="function")U=await this._options.audio(q,j),J7(U),j++;else U=this._options.audio}else if(q.isSubtitleTrack()){if(this._options.subtitle)if(typeof this._options.subtitle==="function")U=await this._options.subtitle(q,X),Y7(U),X++;else U=this._options.subtitle}else H(!1);if(U?.discard){this.discardedTracks.push({track:q,reason:"discarded_by_user"});continue}if(this._totalTrackCount===J.total.max){this.discardedTracks.push({track:q,reason:"max_track_count_reached"});continue}if(this._addedCounts[q.type]===J[q.type].max){this.discardedTracks.push({track:q,reason:"max_track_count_of_type_reached"});continue}if(q.isVideoTrack())await this._processVideoTrack(q,U??{});else if(q.isAudioTrack())await this._processAudioTrack(q,U??{});else if(q.isSubtitleTrack())await this._processSubtitleTrack(q,U??{})}let Z=await this.input.getMetadataTags(),G;if(this._options.tags){let q=typeof this._options.tags==="function"?await this._options.tags(Z):this._options.tags;h8(q),G=q}else G=Z;let K=(await this.input.getFormat()).mimeType===this.output.format.mimeType,Q=Z.raw===G.raw;if(Z.raw&&Q&&!K)delete G.raw;if(this.output.setMetadataTags(G),this.isValid=this._totalTrackCount>=J.total.min&&this._addedCounts.video>=J.video.min&&this._addedCounts.audio>=J.audio.min&&this._addedCounts.subtitle>=J.subtitle.min,this._options.showWarnings??!0){let q=[],U=this.discardedTracks.filter((W)=>W.reason!=="discarded_by_user");if(U.length>0)q.push("Some tracks had to be discarded from the conversion:",U);if(!this.isValid)q.push(`
475
+ */var eY=($)=>{if($!==void 0&&(!$||typeof $!=="object"))throw TypeError("options.video, when provided, must be an object.");if($?.discard!==void 0&&typeof $.discard!=="boolean")throw TypeError("options.video.discard, when provided, must be a boolean.");if($?.forceTranscode!==void 0&&typeof $.forceTranscode!=="boolean")throw TypeError("options.video.forceTranscode, when provided, must be a boolean.");if($?.codec!==void 0&&!j0.includes($.codec))throw TypeError(`options.video.codec, when provided, must be one of: ${j0.join(", ")}.`);if($?.bitrate!==void 0&&!($.bitrate instanceof N0)&&(!Number.isInteger($.bitrate)||$.bitrate<=0))throw TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if($?.width!==void 0&&(!Number.isInteger($.width)||$.width<=0))throw TypeError("options.video.width, when provided, must be a positive integer.");if($?.height!==void 0&&(!Number.isInteger($.height)||$.height<=0))throw TypeError("options.video.height, when provided, must be a positive integer.");if($?.fit!==void 0&&!["fill","contain","cover"].includes($.fit))throw TypeError("options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.");if($?.width!==void 0&&$.height!==void 0&&$.fit===void 0)throw TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if($?.rotate!==void 0&&![0,90,180,270].includes($.rotate))throw TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if($?.allowRotationMetadata!==void 0&&typeof $.allowRotationMetadata!=="boolean")throw TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if($?.crop!==void 0)b8($.crop,"options.video.");if($?.frameRate!==void 0&&(!Number.isFinite($.frameRate)||$.frameRate<=0))throw TypeError("options.video.frameRate, when provided, must be a finite positive number.");if($?.alpha!==void 0&&!["discard","keep"].includes($.alpha))throw TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if($?.keyFrameInterval!==void 0&&(!Number.isFinite($.keyFrameInterval)||$.keyFrameInterval<0))throw TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if($?.process!==void 0&&typeof $.process!=="function")throw TypeError("options.video.process, when provided, must be a function.");if($?.processedWidth!==void 0&&(!Number.isInteger($.processedWidth)||$.processedWidth<=0))throw TypeError("options.video.processedWidth, when provided, must be a positive integer.");if($?.processedHeight!==void 0&&(!Number.isInteger($.processedHeight)||$.processedHeight<=0))throw TypeError("options.video.processedHeight, when provided, must be a positive integer.");if($?.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes($.hardwareAcceleration))throw TypeError("options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.")},$7=($)=>{if($!==void 0&&(!$||typeof $!=="object"))throw TypeError("options.audio, when provided, must be an object.");if($?.discard!==void 0&&typeof $.discard!=="boolean")throw TypeError("options.audio.discard, when provided, must be a boolean.");if($?.forceTranscode!==void 0&&typeof $.forceTranscode!=="boolean")throw TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if($?.codec!==void 0&&!Z0.includes($.codec))throw TypeError(`options.audio.codec, when provided, must be one of: ${Z0.join(", ")}.`);if($?.bitrate!==void 0&&!($.bitrate instanceof N0)&&(!Number.isInteger($.bitrate)||$.bitrate<=0))throw TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if($?.numberOfChannels!==void 0&&(!Number.isInteger($.numberOfChannels)||$.numberOfChannels<=0))throw TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if($?.sampleRate!==void 0&&(!Number.isInteger($.sampleRate)||$.sampleRate<=0))throw TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if($?.process!==void 0&&typeof $.process!=="function")throw TypeError("options.audio.process, when provided, must be a function.");if($?.processedNumberOfChannels!==void 0&&(!Number.isInteger($.processedNumberOfChannels)||$.processedNumberOfChannels<=0))throw TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if($?.processedSampleRate!==void 0&&(!Number.isInteger($.processedSampleRate)||$.processedSampleRate<=0))throw TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.")},J7=($)=>{if($!==void 0&&(!$||typeof $!=="object"))throw TypeError("options.subtitle, when provided, must be an object.");if($?.discard!==void 0&&typeof $.discard!=="boolean")throw TypeError("options.subtitle.discard, when provided, must be a boolean.");if($?.codec!==void 0&&!z0.includes($.codec))throw TypeError(`options.subtitle.codec, when provided, must be one of: ${z0.join(", ")}.`)},GJ=2,KJ=48000;class QJ{input;output;_options;_startTimestamp;_endTimestamp;_addedCounts={video:0,audio:0,subtitle:0};_totalTrackCount=0;_trackPromises=[];_started;_start;_executed=!1;_synchronizer=new j7;_totalDuration=null;_maxTimestamps=new Map;_canceled=!1;_externalSubtitleSources=[];onProgress=void 0;_computeProgress=!1;_lastProgress=0;isValid=!1;utilizedTracks=[];discardedTracks=[];static async init($){let J=new QJ($);return await J._init(),J}constructor($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if(!($.input instanceof z8))throw TypeError("options.input must be an Input.");if(!($.output instanceof Y6))throw TypeError("options.output must be an Output.");if($.output._tracks.length>0||Object.keys($.output._metadataTags).length>0||$.output.state!=="pending")throw TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");if(typeof $.video!=="function")eY($.video);if(typeof $.audio!=="function")$7($.audio);if(typeof $.subtitle!=="function")J7($.subtitle);if($.trim!==void 0&&(!$.trim||typeof $.trim!=="object"))throw TypeError("options.trim, when provided, must be an object.");if($.trim?.start!==void 0&&(!Number.isFinite($.trim.start)||$.trim.start<0))throw TypeError("options.trim.start, when provided, must be a non-negative number.");if($.trim?.end!==void 0&&(!Number.isFinite($.trim.end)||$.trim.end<0))throw TypeError("options.trim.end, when provided, must be a non-negative number.");if($.trim?.start!==void 0&&$.trim.end!==void 0&&$.trim.start>=$.trim.end)throw TypeError("options.trim.start must be less than options.trim.end.");if($.tags!==void 0&&(typeof $.tags!=="object"||!$.tags)&&typeof $.tags!=="function")throw TypeError("options.tags, when provided, must be an object or a function.");if(typeof $.tags==="object")h8($.tags);if($.showWarnings!==void 0&&typeof $.showWarnings!=="boolean")throw TypeError("options.showWarnings, when provided, must be a boolean.");this._options=$,this.input=$.input,this.output=$.output,this._startTimestamp=$.trim?.start??0,this._endTimestamp=$.trim?.end??Number.POSITIVE_INFINITY;let{promise:J,resolve:Y}=c();this._started=J,this._start=Y}async _init(){let $=await this.input.getTracks(),J=this.output.format.getSupportedTrackCounts(),Y=1,j=1,X=1;for(let q of $){let U;if(q.isVideoTrack()){if(this._options.video)if(typeof this._options.video==="function")U=await this._options.video(q,Y),eY(U),Y++;else U=this._options.video}else if(q.isAudioTrack()){if(this._options.audio)if(typeof this._options.audio==="function")U=await this._options.audio(q,j),$7(U),j++;else U=this._options.audio}else if(q.isSubtitleTrack()){if(this._options.subtitle)if(typeof this._options.subtitle==="function")U=await this._options.subtitle(q,X),J7(U),X++;else U=this._options.subtitle}else H(!1);if(U?.discard){this.discardedTracks.push({track:q,reason:"discarded_by_user"});continue}if(this._totalTrackCount===J.total.max){this.discardedTracks.push({track:q,reason:"max_track_count_reached"});continue}if(this._addedCounts[q.type]===J[q.type].max){this.discardedTracks.push({track:q,reason:"max_track_count_of_type_reached"});continue}if(q.isVideoTrack())await this._processVideoTrack(q,U??{});else if(q.isAudioTrack())await this._processAudioTrack(q,U??{});else if(q.isSubtitleTrack())await this._processSubtitleTrack(q,U??{})}let Z=await this.input.getMetadataTags(),G;if(this._options.tags){let q=typeof this._options.tags==="function"?await this._options.tags(Z):this._options.tags;h8(q),G=q}else G=Z;let K=(await this.input.getFormat()).mimeType===this.output.format.mimeType,Q=Z.raw===G.raw;if(Z.raw&&Q&&!K)delete G.raw;if(this.output.setMetadataTags(G),this.isValid=this._totalTrackCount>=J.total.min&&this._addedCounts.video>=J.video.min&&this._addedCounts.audio>=J.audio.min&&this._addedCounts.subtitle>=J.subtitle.min,this._options.showWarnings??!0){let q=[],U=this.discardedTracks.filter((W)=>W.reason!=="discarded_by_user");if(U.length>0)q.push("Some tracks had to be discarded from the conversion:",U);if(!this.isValid)q.push(`
476
476
 
477
477
  `+this._getInvalidityExplanation().join(""));if(q.length>0)console.warn(...q)}}_getInvalidityExplanation(){let $=[];if(this.discardedTracks.length===0)$.push("Due to missing tracks, this conversion cannot be executed.");else{let J=this.discardedTracks.every((Y)=>Y.reason==="discarded_by_user"||Y.reason==="no_encodable_target_codec");if($.push("Due to discarded tracks, this conversion cannot be executed."),J){let Y=this.discardedTracks.flatMap((j)=>{if(j.reason==="discarded_by_user")return[];if(j.track.type==="video")return this.output.format.getSupportedVideoCodecs();if(j.track.type==="audio")return this.output.format.getSupportedAudioCodecs();return this.output.format.getSupportedSubtitleCodecs()});if(Y.length===1)$.push(`
478
478
  Tracks were discarded because your environment is not able to encode '${Y[0]}'.`);else $.push(`
@@ -481,10 +481,10 @@ The @mediabunny/mp3-encoder extension package provides support for encoding MP3.
481
481
  The @mediabunny/mpeg4 extension package provides support for encoding and decoding MPEG-4 Part 2.`);if(Y.includes("ac3")||Y.includes("eac3"))$.push(`
482
482
  The @mediabunny/eac3 extension package provides support for encoding and decoding AC-3 and E-AC-3.`)}else $.push(`
483
483
  Check the discardedTracks field for more info.`)}return $}addExternalSubtitleTrack($,J={},Y){if(this._executed)throw Error("Cannot add subtitle tracks after conversion has been executed.");if(this.output.state!=="pending")throw Error("Cannot add subtitle tracks after output has been started.");let j=this.output.format.getSupportedTrackCounts();if(this._addedCounts.subtitle+this._externalSubtitleSources.length>=j.subtitle.max)throw Error(`Cannot add more subtitle tracks. Maximum of ${j.subtitle.max} subtitle track(s) allowed.`);if(this._totalTrackCount+this._externalSubtitleSources.length+1>j.total.max)throw Error(`Cannot add more tracks. Maximum of ${j.total.max} total track(s) allowed.`);this._externalSubtitleSources.push({source:$,metadata:J,contentProvider:Y}),this.isValid=this._totalTrackCount+this._externalSubtitleSources.length>=j.total.min&&this._addedCounts.video>=j.video.min&&this._addedCounts.audio>=j.audio.min&&this._addedCounts.subtitle+this._externalSubtitleSources.length>=j.subtitle.min}async execute(){if(!this.isValid)throw Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.
484
- `+this._getInvalidityExplanation().join(""));if(this._executed)throw Error("Conversion cannot be executed twice.");if(this._executed=!0,this.onProgress){this._computeProgress=!0,this._totalDuration=Math.min(await this.input.computeDuration()-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let J of this.utilizedTracks)this._maxTimestamps.set(J.id,0);this.onProgress?.(0)}for(let{source:J,metadata:Y}of this._externalSubtitleSources)this.output.addSubtitleTrack(J,Y);await this.output.start(),this._start();let $=this._externalSubtitleSources.filter((J)=>J.contentProvider).map((J)=>J.contentProvider());if($.length>0)this._trackPromises.push(...$);try{await Promise.all(this._trackPromises)}catch(J){if(!this._canceled)this.cancel();throw J}if(this._canceled)await new Promise(()=>{});if(await this.output.finalize(),this._computeProgress)this.onProgress?.(1)}async cancel(){if(this.output.state==="finalizing"||this.output.state==="finalized")return;if(this._canceled){console.warn("Conversion already canceled.");return}this._canceled=!0,await this.output.cancel()}async _processVideoTrack($,J){let Y=$.codec;if(!Y){this.discardedTracks.push({track:$,reason:"unknown_source_codec"});return}let j,X=N1($.rotation+(J.rotate??0)),Z=this.output.format.supportsVideoRotationMetadata&&(J.allowRotationMetadata??!0),[G,K]=X%180===0?[$.codedWidth,$.codedHeight]:[$.codedHeight,$.codedWidth],Q=J.crop;if(Q)v8(Q,G,K);let[q,U]=Q?[Q.width,Q.height]:[G,K],W=q,V=U,N=W/V,A=(B)=>Math.ceil(B/2)*2;if(J.width!==void 0&&J.height===void 0)W=A(J.width),V=A(Math.round(W/N));else if(J.width===void 0&&J.height!==void 0)V=A(J.height),W=A(Math.round(V*N));else if(J.width!==void 0&&J.height!==void 0)W=A(J.width),V=A(J.height);let R=await $.getFirstTimestamp(),z=!!J.forceTranscode||this._startTimestamp>0||R<0||!!J.frameRate||J.keyFrameInterval!==void 0||J.process!==void 0,_=W!==q||V!==U||X!==0&&(!Z||J.process!==void 0)||!!Q,L=J.alpha??"discard",M=this.output.format.getSupportedVideoCodecs();if(!z&&!J.bitrate&&!_&&M.includes(Y)&&(!J.codec||J.codec===Y)){let B=new _2(Y);j=B,this._trackPromises.push((async()=>{await this._started;let F=new K1($),w={decoderConfig:await $.getDecoderConfig()??void 0},v=Number.isFinite(this._endTimestamp)?await F.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let k of F.packets(void 0,v,{verifyKeyPackets:!0})){if(this._canceled)return;if(L==="discard")delete k.sideData.alpha,delete k.sideData.alphaByteLength;if(this._reportProgress($.id,k.timestamp),await B.add(k,w),this._synchronizer.shouldWait($.id,k.timestamp))await this._synchronizer.wait(k.timestamp)}B.close(),this._synchronizer.closeTrack($.id)})())}else{if(!await $.canDecode()){this.discardedTracks.push({track:$,reason:"undecodable_source_codec"});return}if(J.codec)M=M.filter((k)=>k===J.codec);let F=J.bitrate??M6,C=await n2(M,{width:J.process&&J.processedWidth?J.processedWidth:W,height:J.process&&J.processedHeight?J.processedHeight:V,bitrate:F});if(!C){this.discardedTracks.push({track:$,reason:"no_encodable_target_codec"});return}let w={codec:C,bitrate:F,keyFrameInterval:J.keyFrameInterval,sizeChangeBehavior:J.fit??"passThrough",alpha:L,hardwareAcceleration:J.hardwareAcceleration},v=new r8(w);if(j=v,!_){let k=new Y6({format:new J6,target:new P2}),S=new r8(w);k.addVideoTrack(S),await k.start();let r=await new X8($).getSample(R);if(r)try{await S.add(r),r.close(),await k.finalize()}catch(H0){console.info("Error when probing encoder support. Falling back to rerender path.",H0),_=!0,k.cancel()}else await k.cancel()}if(_)this._trackPromises.push((async()=>{await this._started;let S=new u6($,{width:W,height:V,fit:J.fit??"fill",rotation:X,crop:J.crop,poolSize:1,alpha:L==="keep"}).canvases(this._startTimestamp,this._endTimestamp),T=J.frameRate,r=null,H0=null,o1=null,F0=async(B0)=>{H(r),H(T!==void 0);let C0=Math.round((B0-H0)*T);for(let r1=1;r1<C0;r1++){let H1=new J0(r,{timestamp:H0+r1/T,duration:1/T});await this._registerVideoSample($,J,v,H1),H1.close()}};for await(let{canvas:B0,timestamp:C0,duration:r1}of S){if(this._canceled)return;let H1=Math.max(C0-this._startTimestamp,0);if(o1=H1+r1,T!==void 0){let j6=Math.floor(H1*T)/T;if(r!==null){if(j6<=H0){r=B0,H0=j6;continue}await F0(j6)}H1=j6}let qJ=new J0(B0,{timestamp:H1,duration:T!==void 0?1/T:r1});if(await this._registerVideoSample($,J,v,qJ),qJ.close(),T!==void 0)r=B0,H0=H1}if(r)H(o1!==null),H(T!==void 0),await F0(Math.floor(o1*T)/T);v.close(),this._synchronizer.closeTrack($.id)})());else this._trackPromises.push((async()=>{await this._started;let k=new X8($),S=J.frameRate,T=null,r=null,H0=null,o1=async(F0)=>{H(T),H(S!==void 0);let B0=Math.round((F0-r)*S);for(let C0=1;C0<B0;C0++)T.setTimestamp(r+C0/S),T.setDuration(1/S),await this._registerVideoSample($,J,v,T);T.close()};for await(let F0 of k.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled){T?.close();return}let B0=Math.max(F0.timestamp-this._startTimestamp,0);if(H0=B0+F0.duration,S!==void 0){let C0=Math.floor(B0*S)/S;if(T!==null){if(C0<=r){T.close(),T=F0,r=C0;continue}await o1(C0)}B0=C0,F0.setDuration(1/S)}if(F0.setTimestamp(B0),await this._registerVideoSample($,J,v,F0),S!==void 0)T=F0,r=B0;else F0.close()}if(T)H(H0!==null),H(S!==void 0),await o1(Math.floor(H0*S)/S);v.close(),this._synchronizer.closeTrack($.id)})())}this.output.addVideoTrack(j,{frameRate:J.frameRate,languageCode:d0($.languageCode)?$.languageCode:void 0,name:$.name??void 0,disposition:$.disposition,rotation:_?0:X}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push($)}async _registerVideoSample($,J,Y,j){if(this._canceled)return;this._reportProgress($.id,j.timestamp);let X;if(!J.process)X=[j];else{let Z=J.process(j);if(Z instanceof Promise)Z=await Z;if(!Array.isArray(Z))Z=Z===null?[]:[Z];X=Z.map((G)=>{if(G instanceof J0)return G;if(typeof VideoFrame<"u"&&G instanceof VideoFrame)return new J0(G);return new J0(G,{timestamp:j.timestamp,duration:j.duration})})}for(let Z of X){if(this._canceled)break;if(await Y.add(Z),this._synchronizer.shouldWait($.id,Z.timestamp))await this._synchronizer.wait(Z.timestamp)}for(let Z of X)if(Z!==j)Z.close()}async _processAudioTrack($,J){let Y=$.codec;if(!Y){this.discardedTracks.push({track:$,reason:"unknown_source_codec"});return}let j,X=$.numberOfChannels,Z=$.sampleRate,G=await $.getFirstTimestamp(),K=J.numberOfChannels??X,Q=J.sampleRate??Z,q=K!==X||Q!==Z||this._startTimestamp>0||G<0,U=this.output.format.getSupportedAudioCodecs();if(!J.forceTranscode&&!J.bitrate&&!q&&U.includes(Y)&&(!J.codec||J.codec===Y)&&!J.process){let W=new M2(Y);j=W,this._trackPromises.push((async()=>{await this._started;let V=new K1($),A={decoderConfig:await $.getDecoderConfig()??void 0},R=Number.isFinite(this._endTimestamp)?await V.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let z of V.packets(void 0,R)){if(this._canceled)return;if(this._reportProgress($.id,z.timestamp),await W.add(z,A),this._synchronizer.shouldWait($.id,z.timestamp))await this._synchronizer.wait(z.timestamp)}W.close(),this._synchronizer.closeTrack($.id)})())}else{if(!await $.canDecode()){this.discardedTracks.push({track:$,reason:"undecodable_source_codec"});return}let V=null;if(J.codec)U=U.filter((R)=>R===J.codec);let N=J.bitrate??M6,A=await w8(U,{numberOfChannels:J.process&&J.processedNumberOfChannels?J.processedNumberOfChannels:K,sampleRate:J.process&&J.processedSampleRate?J.processedSampleRate:Q,bitrate:N});if(!A.some((R)=>X1.includes(R))&&U.some((R)=>X1.includes(R))&&(K!==GJ||Q!==KJ)){let z=(await w8(U,{numberOfChannels:GJ,sampleRate:KJ,bitrate:N})).find((_)=>X1.includes(_));if(z)q=!0,V=z,K=GJ,Q=KJ}else V=A[0]??null;if(V===null){this.discardedTracks.push({track:$,reason:"no_encodable_target_codec"});return}if(q)j=this._resampleAudio($,J,V,K,Q,N);else{let R=new i8({codec:V,bitrate:N});j=R,this._trackPromises.push((async()=>{await this._started;let z=new Z8($);for await(let _ of z.samples(void 0,this._endTimestamp)){if(this._canceled)return;await this._registerAudioSample($,J,R,_),_.close()}R.close(),this._synchronizer.closeTrack($.id)})())}}this.output.addAudioTrack(j,{languageCode:d0($.languageCode)?$.languageCode:void 0,name:$.name??void 0,disposition:$.disposition}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push($)}async _registerAudioSample($,J,Y,j){if(this._canceled)return;this._reportProgress($.id,j.timestamp);let X;if(!J.process)X=[j];else{let Z=J.process(j);if(Z instanceof Promise)Z=await Z;if(!Array.isArray(Z))Z=Z===null?[]:[Z];if(!Z.every((G)=>G instanceof K0))throw TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");X=Z}for(let Z of X){if(this._canceled)break;if(await Y.add(Z),this._synchronizer.shouldWait($.id,Z.timestamp))await this._synchronizer.wait(Z.timestamp)}for(let Z of X)if(Z!==j)Z.close()}async _processSubtitleTrack($,J){let Y=$.codec;if(!Y){this.discardedTracks.push({track:$,reason:"unknown_source_codec"});return}let j=J.codec??Y,X=this.output.format.getSupportedSubtitleCodecs();if(!X.includes(j))if(!J.codec&&X.includes(Y))j=Y;else{this.discardedTracks.push({track:$,reason:"no_encodable_target_codec"});return}let Z=new B2(j);this._trackPromises.push((async()=>{await this._started;let G;if(this._startTimestamp===0&&!Number.isFinite(this._endTimestamp)&&j===Y)G=await $.exportToText();else{let K=[];for await(let Q of $.getCues()){let q=Q.timestamp+Q.duration;if(this._startTimestamp>0||Number.isFinite(this._endTimestamp)){if(q<=this._startTimestamp||Q.timestamp>=this._endTimestamp)continue;let U=Math.max(Q.timestamp-this._startTimestamp,0),W=Math.min(q-this._startTimestamp,this._endTimestamp-this._startTimestamp);K.push({...Q,timestamp:U,duration:W-U})}else K.push(Q);if(this._canceled)return}if(j==="srt")G=n6(K);else if(j==="webvtt")G=o6(K);else if(j==="ass"||j==="ssa")G=r6(K,"");else G=await $.exportToText(j)}await Z.add(G),Z.close()})()),this.output.addSubtitleTrack(Z,{languageCode:d0($.languageCode)?$.languageCode:void 0,name:$.name??void 0}),this._addedCounts.subtitle++,this._totalTrackCount++,this.utilizedTracks.push($)}_resampleAudio($,J,Y,j,X,Z){let G=new i8({codec:Y,bitrate:Z});return this._trackPromises.push((async()=>{await this._started;let K=new Z7({targetNumberOfChannels:j,targetSampleRate:X,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async(U)=>{await this._registerAudioSample($,J,G,U),U.close()}}),q=new Z8($).samples(this._startTimestamp,this._endTimestamp);for await(let U of q){if(this._canceled)return;await K.add(U),U.close()}await K.finalize(),G.close(),this._synchronizer.closeTrack($.id)})()),G}_reportProgress($,J){if(!this._computeProgress)return;H(this._totalDuration!==null),this._maxTimestamps.set($,Math.max(J,this._maxTimestamps.get($)));let Y=Math.min(...this._maxTimestamps.values()),j=$0(Y/this._totalDuration,0,1);if(j!==this._lastProgress)this._lastProgress=j,this.onProgress?.(j)}}var j7=5;class X7{maxTimestamps=new Map;resolvers=[];computeMinAndMaybeResolve(){let $=Number.POSITIVE_INFINITY;for(let[,J]of this.maxTimestamps)$=Math.min($,J);for(let J=0;J<this.resolvers.length;J++){let Y=this.resolvers[J];if(Y.timestamp-$<j7)Y.resolve(),this.resolvers.splice(J,1),J--}return $}shouldWait($,J){this.maxTimestamps.set($,Math.max(J,this.maxTimestamps.get($)??Number.NEGATIVE_INFINITY));let Y=this.computeMinAndMaybeResolve();return J-Y>=j7}wait($){let{promise:J,resolve:Y}=c();return this.resolvers.push({timestamp:$,resolve:Y}),J}closeTrack($){this.maxTimestamps.delete($),this.computeMinAndMaybeResolve()}}class Z7{sourceSampleRate=null;targetSampleRate;sourceNumberOfChannels=null;targetNumberOfChannels;startTime;endTime;onSample;bufferSizeInFrames;bufferSizeInSamples;outputBuffer;bufferStartFrame;maxWrittenFrame;channelMixer;tempSourceBuffer;constructor($){this.targetSampleRate=$.targetSampleRate,this.targetNumberOfChannels=$.targetNumberOfChannels,this.startTime=$.startTime,this.endTime=$.endTime,this.onSample=$.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=0,this.maxWrittenFrame=-1}doChannelMixerSetup(){H(this.sourceNumberOfChannels!==null);let $=this.sourceNumberOfChannels,J=this.targetNumberOfChannels;if($===1&&J===2)this.channelMixer=(Y,j)=>{return Y[j*$]};else if($===1&&J===4)this.channelMixer=(Y,j,X)=>{return Y[j*$]*+(X<2)};else if($===1&&J===6)this.channelMixer=(Y,j,X)=>{return Y[j*$]*+(X===2)};else if($===2&&J===1)this.channelMixer=(Y,j)=>{let X=j*$;return 0.5*(Y[X]+Y[X+1])};else if($===2&&J===4)this.channelMixer=(Y,j,X)=>{return Y[j*$+X]*+(X<2)};else if($===2&&J===6)this.channelMixer=(Y,j,X)=>{return Y[j*$+X]*+(X<2)};else if($===4&&J===1)this.channelMixer=(Y,j)=>{let X=j*$;return 0.25*(Y[X]+Y[X+1]+Y[X+2]+Y[X+3])};else if($===4&&J===2)this.channelMixer=(Y,j,X)=>{let Z=j*$;return 0.5*(Y[Z+X]+Y[Z+X+2])};else if($===4&&J===6)this.channelMixer=(Y,j,X)=>{let Z=j*$;if(X<2)return Y[Z+X];if(X===2||X===3)return 0;return Y[Z+X-2]};else if($===6&&J===1)this.channelMixer=(Y,j)=>{let X=j*$;return Math.SQRT1_2*(Y[X]+Y[X+1])+Y[X+2]+0.5*(Y[X+4]+Y[X+5])};else if($===6&&J===2)this.channelMixer=(Y,j,X)=>{let Z=j*$;return Y[Z+X]+Math.SQRT1_2*(Y[Z+2]+Y[Z+X+4])};else if($===6&&J===4)this.channelMixer=(Y,j,X)=>{let Z=j*$;if(X<2)return Y[Z+X]+Math.SQRT1_2*Y[Z+2];return Y[Z+X+2]};else this.channelMixer=(Y,j,X)=>{return X<$?Y[j*$+X]:0}}ensureTempBufferSize($){let J=this.tempSourceBuffer.length;while(J<$)J*=2;if(J!==this.tempSourceBuffer.length){let Y=new Float32Array(J);Y.set(this.tempSourceBuffer),this.tempSourceBuffer=Y}}async add($){if(this.sourceSampleRate===null)this.sourceSampleRate=$.sampleRate,this.sourceNumberOfChannels=$.numberOfChannels,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup();let J=$.numberOfFrames*$.numberOfChannels;this.ensureTempBufferSize(J);let Y=$.allocationSize({planeIndex:0,format:"f32"}),j=new Float32Array(this.tempSourceBuffer.buffer,0,Y/4);$.copyTo(j,{planeIndex:0,format:"f32"});let X=$.timestamp-this.startTime,Z=$.numberOfFrames/this.sourceSampleRate,G=Math.min(X+Z,this.endTime-this.startTime),K=Math.floor(X*this.targetSampleRate),Q=Math.ceil(G*this.targetSampleRate);for(let q=K;q<Q;q++){if(q<this.bufferStartFrame)continue;while(q>=this.bufferStartFrame+this.bufferSizeInFrames)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let U=q-this.bufferStartFrame;H(U<this.bufferSizeInFrames);let N=(q/this.targetSampleRate-X)*this.sourceSampleRate,A=Math.floor(N),R=Math.ceil(N),z=N-A;for(let _=0;_<this.targetNumberOfChannels;_++){let L=0,M=0;if(A>=0&&A<$.numberOfFrames)L=this.channelMixer(j,A,_);if(R>=0&&R<$.numberOfFrames)M=this.channelMixer(j,R,_);let B=L+z*(M-L),F=U*this.targetNumberOfChannels+_;this.outputBuffer[F]+=B}this.maxWrittenFrame=Math.max(this.maxWrittenFrame,U)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame<0)return;let $=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,J=new Float32Array($);J.set(this.outputBuffer.subarray(0,$));let Y=this.bufferStartFrame/this.targetSampleRate,j=new K0({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:Y,data:J});await this.onSample(j),this.outputBuffer.fill(0),this.maxWrittenFrame=-1}finalize(){return this.finalizeCurrentBuffer()}}class G7 extends z8{_resolvedDemuxer=null;constructor($){super({source:$,formats:[R2]})}async _ensureDemuxer(){if(!this._resolvedDemuxer)this._resolvedDemuxer=await this._getDemuxer();return this._resolvedDemuxer}async getVideoTracks(){let $=await this._ensureDemuxer();return(await this.getTracks()).filter((j)=>j.isVideoTrack()).map((j)=>this._wrapVideoTrackWithCuePoints(j,$))}async getPrimaryVideoTrack(){let $=await this._ensureDemuxer(),Y=(await this.getTracks()).find((j)=>j.isVideoTrack());if(!Y)return null;return this._wrapVideoTrackWithCuePoints(Y,$)}get videoTracks(){return this.getVideoTracks()}async getAudioTracks(){let $=await this._ensureDemuxer();return(await this.getTracks()).filter((j)=>j.isAudioTrack()).map((j)=>this._wrapAudioTrackWithCuePoints(j,$))}get audioTracks(){return this.getAudioTracks()}async getPrimaryAudioTrack(){let $=await this._ensureDemuxer(),Y=(await this.getTracks()).find((j)=>j.isAudioTrack());if(!Y)return null;return this._wrapAudioTrackWithCuePoints(Y,$)}async getSubtitleTracks(){let $=await this._ensureDemuxer();return(await this.getTracks()).filter((j)=>j.isSubtitleTrack()).map((j)=>this._wrapSubtitleTrackWithCuePoints(j,$))}get subtitleTracks(){return this.getSubtitleTracks()}_wrapVideoTrackWithCuePoints($,J){let Y=$,j=this._getCuePointsForTrack(J,$.id);return Y.getCuePoints=()=>j,Y}_wrapAudioTrackWithCuePoints($,J){let Y=$,j=this._getCuePointsForTrack(J,$.id);return Y.getCuePoints=()=>j,Y}_wrapSubtitleTrackWithCuePoints($,J){let Y=$,j=this._getCuePointsForTrack(J,$.id);return Y.getCuePoints=()=>j,Y}_getCuePointsForTrack($,J){let Y=this._findInternalTrack($,J);if(!Y)return[];return Y.cuePoints.map((j)=>({time:j.time/Y.segment.timestampFactor,trackId:j.trackId,clusterPosition:j.clusterPosition}))}_findInternalTrack($,J){for(let Y of $.segments){let j=Y.tracks.find((X)=>X.id===J);if(j)return j}return null}}x0();/*!
484
+ `+this._getInvalidityExplanation().join(""));if(this._executed)throw Error("Conversion cannot be executed twice.");if(this._executed=!0,this.onProgress){this._computeProgress=!0,this._totalDuration=Math.min(await this.input.computeDuration()-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let J of this.utilizedTracks)this._maxTimestamps.set(J.id,0);this.onProgress?.(0)}for(let{source:J,metadata:Y}of this._externalSubtitleSources)this.output.addSubtitleTrack(J,Y);await this.output.start(),this._start();let $=this._externalSubtitleSources.filter((J)=>J.contentProvider).map((J)=>J.contentProvider());if($.length>0)this._trackPromises.push(...$);try{await Promise.all(this._trackPromises)}catch(J){if(!this._canceled)this.cancel();throw J}if(this._canceled)await new Promise(()=>{});if(await this.output.finalize(),this._computeProgress)this.onProgress?.(1)}async cancel(){if(this.output.state==="finalizing"||this.output.state==="finalized")return;if(this._canceled){console.warn("Conversion already canceled.");return}this._canceled=!0,await this.output.cancel()}async _processVideoTrack($,J){let Y=$.codec;if(!Y){this.discardedTracks.push({track:$,reason:"unknown_source_codec"});return}let j,X=N1($.rotation+(J.rotate??0)),Z=this.output.format.supportsVideoRotationMetadata&&(J.allowRotationMetadata??!0),[G,K]=X%180===0?[$.codedWidth,$.codedHeight]:[$.codedHeight,$.codedWidth],Q=J.crop;if(Q)v8(Q,G,K);let[q,U]=Q?[Q.width,Q.height]:[G,K],W=q,V=U,N=W/V,A=(B)=>Math.ceil(B/2)*2;if(J.width!==void 0&&J.height===void 0)W=A(J.width),V=A(Math.round(W/N));else if(J.width===void 0&&J.height!==void 0)V=A(J.height),W=A(Math.round(V*N));else if(J.width!==void 0&&J.height!==void 0)W=A(J.width),V=A(J.height);let R=await $.getFirstTimestamp(),z=!!J.forceTranscode||this._startTimestamp>0||R<0||!!J.frameRate||J.keyFrameInterval!==void 0||J.process!==void 0,_=W!==q||V!==U||X!==0&&(!Z||J.process!==void 0)||!!Q,L=J.alpha??"discard",M=this.output.format.getSupportedVideoCodecs();if(!z&&!J.bitrate&&!_&&M.includes(Y)&&(!J.codec||J.codec===Y)){let B=new _2(Y);j=B,this._trackPromises.push((async()=>{await this._started;let F=new K1($),w={decoderConfig:await $.getDecoderConfig()??void 0},v=Number.isFinite(this._endTimestamp)?await F.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let k of F.packets(void 0,v,{verifyKeyPackets:!0})){if(this._canceled)return;if(L==="discard")delete k.sideData.alpha,delete k.sideData.alphaByteLength;if(this._reportProgress($.id,k.timestamp),await B.add(k,w),this._synchronizer.shouldWait($.id,k.timestamp))await this._synchronizer.wait(k.timestamp)}B.close(),this._synchronizer.closeTrack($.id)})())}else{if(!await $.canDecode()){this.discardedTracks.push({track:$,reason:"undecodable_source_codec"});return}if(J.codec)M=M.filter((k)=>k===J.codec);let F=J.bitrate??M6,C=await n2(M,{width:J.process&&J.processedWidth?J.processedWidth:W,height:J.process&&J.processedHeight?J.processedHeight:V,bitrate:F});if(!C){this.discardedTracks.push({track:$,reason:"no_encodable_target_codec"});return}let w={codec:C,bitrate:F,keyFrameInterval:J.keyFrameInterval,sizeChangeBehavior:J.fit??"passThrough",alpha:L,hardwareAcceleration:J.hardwareAcceleration},v=new r8(w);if(j=v,!_){let k=new Y6({format:new J6,target:new P2}),S=new r8(w);k.addVideoTrack(S),await k.start();let r=await new X8($).getSample(R);if(r)try{await S.add(r),r.close(),await k.finalize()}catch(H0){console.info("Error when probing encoder support. Falling back to rerender path.",H0),_=!0,k.cancel()}else await k.cancel()}if(_)this._trackPromises.push((async()=>{await this._started;let S=new u6($,{width:W,height:V,fit:J.fit??"fill",rotation:X,crop:J.crop,poolSize:1,alpha:L==="keep"}).canvases(this._startTimestamp,this._endTimestamp),T=J.frameRate,r=null,H0=null,o1=null,F0=async(B0)=>{H(r),H(T!==void 0);let C0=Math.round((B0-H0)*T);for(let r1=1;r1<C0;r1++){let H1=new J0(r,{timestamp:H0+r1/T,duration:1/T});await this._registerVideoSample($,J,v,H1),H1.close()}};for await(let{canvas:B0,timestamp:C0,duration:r1}of S){if(this._canceled)return;let H1=Math.max(C0-this._startTimestamp,0);if(o1=H1+r1,T!==void 0){let j6=Math.floor(H1*T)/T;if(r!==null){if(j6<=H0){r=B0,H0=j6;continue}await F0(j6)}H1=j6}let qJ=new J0(B0,{timestamp:H1,duration:T!==void 0?1/T:r1});if(await this._registerVideoSample($,J,v,qJ),qJ.close(),T!==void 0)r=B0,H0=H1}if(r)H(o1!==null),H(T!==void 0),await F0(Math.floor(o1*T)/T);v.close(),this._synchronizer.closeTrack($.id)})());else this._trackPromises.push((async()=>{await this._started;let k=new X8($),S=J.frameRate,T=null,r=null,H0=null,o1=async(F0)=>{H(T),H(S!==void 0);let B0=Math.round((F0-r)*S);for(let C0=1;C0<B0;C0++)T.setTimestamp(r+C0/S),T.setDuration(1/S),await this._registerVideoSample($,J,v,T);T.close()};for await(let F0 of k.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled){T?.close();return}let B0=Math.max(F0.timestamp-this._startTimestamp,0);if(H0=B0+F0.duration,S!==void 0){let C0=Math.floor(B0*S)/S;if(T!==null){if(C0<=r){T.close(),T=F0,r=C0;continue}await o1(C0)}B0=C0,F0.setDuration(1/S)}if(F0.setTimestamp(B0),await this._registerVideoSample($,J,v,F0),S!==void 0)T=F0,r=B0;else F0.close()}if(T)H(H0!==null),H(S!==void 0),await o1(Math.floor(H0*S)/S);v.close(),this._synchronizer.closeTrack($.id)})())}this.output.addVideoTrack(j,{frameRate:J.frameRate,languageCode:d0($.languageCode)?$.languageCode:void 0,name:$.name??void 0,disposition:$.disposition,rotation:_?0:X}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push($)}async _registerVideoSample($,J,Y,j){if(this._canceled)return;this._reportProgress($.id,j.timestamp);let X;if(!J.process)X=[j];else{let Z=J.process(j);if(Z instanceof Promise)Z=await Z;if(!Array.isArray(Z))Z=Z===null?[]:[Z];X=Z.map((G)=>{if(G instanceof J0)return G;if(typeof VideoFrame<"u"&&G instanceof VideoFrame)return new J0(G);return new J0(G,{timestamp:j.timestamp,duration:j.duration})})}for(let Z of X){if(this._canceled)break;if(await Y.add(Z),this._synchronizer.shouldWait($.id,Z.timestamp))await this._synchronizer.wait(Z.timestamp)}for(let Z of X)if(Z!==j)Z.close()}async _processAudioTrack($,J){let Y=$.codec;if(!Y){this.discardedTracks.push({track:$,reason:"unknown_source_codec"});return}let j,X=$.numberOfChannels,Z=$.sampleRate,G=await $.getFirstTimestamp(),K=J.numberOfChannels??X,Q=J.sampleRate??Z,q=K!==X||Q!==Z||this._startTimestamp>0||G<0,U=this.output.format.getSupportedAudioCodecs();if(!J.forceTranscode&&!J.bitrate&&!q&&U.includes(Y)&&(!J.codec||J.codec===Y)&&!J.process){let W=new M2(Y);j=W,this._trackPromises.push((async()=>{await this._started;let V=new K1($),A={decoderConfig:await $.getDecoderConfig()??void 0},R=Number.isFinite(this._endTimestamp)?await V.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let z of V.packets(void 0,R)){if(this._canceled)return;if(this._reportProgress($.id,z.timestamp),await W.add(z,A),this._synchronizer.shouldWait($.id,z.timestamp))await this._synchronizer.wait(z.timestamp)}W.close(),this._synchronizer.closeTrack($.id)})())}else{if(!await $.canDecode()){this.discardedTracks.push({track:$,reason:"undecodable_source_codec"});return}let V=null;if(J.codec)U=U.filter((R)=>R===J.codec);let N=J.bitrate??M6,A=await w8(U,{numberOfChannels:J.process&&J.processedNumberOfChannels?J.processedNumberOfChannels:K,sampleRate:J.process&&J.processedSampleRate?J.processedSampleRate:Q,bitrate:N});if(!A.some((R)=>X1.includes(R))&&U.some((R)=>X1.includes(R))&&(K!==GJ||Q!==KJ)){let z=(await w8(U,{numberOfChannels:GJ,sampleRate:KJ,bitrate:N})).find((_)=>X1.includes(_));if(z)q=!0,V=z,K=GJ,Q=KJ}else V=A[0]??null;if(V===null){this.discardedTracks.push({track:$,reason:"no_encodable_target_codec"});return}if(q)j=this._resampleAudio($,J,V,K,Q,N);else{let R=new i8({codec:V,bitrate:N});j=R,this._trackPromises.push((async()=>{await this._started;let z=new Z8($);for await(let _ of z.samples(void 0,this._endTimestamp)){if(this._canceled)return;await this._registerAudioSample($,J,R,_),_.close()}R.close(),this._synchronizer.closeTrack($.id)})())}}this.output.addAudioTrack(j,{languageCode:d0($.languageCode)?$.languageCode:void 0,name:$.name??void 0,disposition:$.disposition}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push($)}async _registerAudioSample($,J,Y,j){if(this._canceled)return;this._reportProgress($.id,j.timestamp);let X;if(!J.process)X=[j];else{let Z=J.process(j);if(Z instanceof Promise)Z=await Z;if(!Array.isArray(Z))Z=Z===null?[]:[Z];if(!Z.every((G)=>G instanceof K0))throw TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");X=Z}for(let Z of X){if(this._canceled)break;if(await Y.add(Z),this._synchronizer.shouldWait($.id,Z.timestamp))await this._synchronizer.wait(Z.timestamp)}for(let Z of X)if(Z!==j)Z.close()}async _processSubtitleTrack($,J){let Y=$.codec;if(!Y){this.discardedTracks.push({track:$,reason:"unknown_source_codec"});return}let j=J.codec??Y,X=this.output.format.getSupportedSubtitleCodecs();if(!X.includes(j))if(!J.codec&&X.includes(Y))j=Y;else{this.discardedTracks.push({track:$,reason:"no_encodable_target_codec"});return}let Z=new B2(j);this._trackPromises.push((async()=>{await this._started;let G;if(this._startTimestamp===0&&!Number.isFinite(this._endTimestamp)&&j===Y)G=await $.exportToText();else{let K=[];for await(let Q of $.getCues()){let q=Q.timestamp+Q.duration;if(this._startTimestamp>0||Number.isFinite(this._endTimestamp)){if(q<=this._startTimestamp||Q.timestamp>=this._endTimestamp)continue;let U=Math.max(Q.timestamp-this._startTimestamp,0),W=Math.min(q-this._startTimestamp,this._endTimestamp-this._startTimestamp);K.push({...Q,timestamp:U,duration:W-U})}else K.push(Q);if(this._canceled)return}if(j==="srt")G=n6(K);else if(j==="webvtt")G=o6(K);else if(j==="ass"||j==="ssa")G=r6(K,"");else G=await $.exportToText(j)}await Z.add(G),Z.close()})()),this.output.addSubtitleTrack(Z,{languageCode:d0($.languageCode)?$.languageCode:void 0,name:$.name??void 0}),this._addedCounts.subtitle++,this._totalTrackCount++,this.utilizedTracks.push($)}_resampleAudio($,J,Y,j,X,Z){let G=new i8({codec:Y,bitrate:Z});return this._trackPromises.push((async()=>{await this._started;let K=new X7({targetNumberOfChannels:j,targetSampleRate:X,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async(U)=>{await this._registerAudioSample($,J,G,U),U.close()}}),q=new Z8($).samples(this._startTimestamp,this._endTimestamp);for await(let U of q){if(this._canceled)return;await K.add(U),U.close()}await K.finalize(),G.close(),this._synchronizer.closeTrack($.id)})()),G}_reportProgress($,J){if(!this._computeProgress)return;H(this._totalDuration!==null),this._maxTimestamps.set($,Math.max(J,this._maxTimestamps.get($)));let Y=Math.min(...this._maxTimestamps.values()),j=$0(Y/this._totalDuration,0,1);if(j!==this._lastProgress)this._lastProgress=j,this.onProgress?.(j)}}var Y7=5;class j7{maxTimestamps=new Map;resolvers=[];computeMinAndMaybeResolve(){let $=Number.POSITIVE_INFINITY;for(let[,J]of this.maxTimestamps)$=Math.min($,J);for(let J=0;J<this.resolvers.length;J++){let Y=this.resolvers[J];if(Y.timestamp-$<Y7)Y.resolve(),this.resolvers.splice(J,1),J--}return $}shouldWait($,J){this.maxTimestamps.set($,Math.max(J,this.maxTimestamps.get($)??Number.NEGATIVE_INFINITY));let Y=this.computeMinAndMaybeResolve();return J-Y>=Y7}wait($){let{promise:J,resolve:Y}=c();return this.resolvers.push({timestamp:$,resolve:Y}),J}closeTrack($){this.maxTimestamps.delete($),this.computeMinAndMaybeResolve()}}class X7{sourceSampleRate=null;targetSampleRate;sourceNumberOfChannels=null;targetNumberOfChannels;startTime;endTime;onSample;bufferSizeInFrames;bufferSizeInSamples;outputBuffer;bufferStartFrame;maxWrittenFrame;channelMixer;tempSourceBuffer;constructor($){this.targetSampleRate=$.targetSampleRate,this.targetNumberOfChannels=$.targetNumberOfChannels,this.startTime=$.startTime,this.endTime=$.endTime,this.onSample=$.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=0,this.maxWrittenFrame=-1}doChannelMixerSetup(){H(this.sourceNumberOfChannels!==null);let $=this.sourceNumberOfChannels,J=this.targetNumberOfChannels;if($===1&&J===2)this.channelMixer=(Y,j)=>{return Y[j*$]};else if($===1&&J===4)this.channelMixer=(Y,j,X)=>{return Y[j*$]*+(X<2)};else if($===1&&J===6)this.channelMixer=(Y,j,X)=>{return Y[j*$]*+(X===2)};else if($===2&&J===1)this.channelMixer=(Y,j)=>{let X=j*$;return 0.5*(Y[X]+Y[X+1])};else if($===2&&J===4)this.channelMixer=(Y,j,X)=>{return Y[j*$+X]*+(X<2)};else if($===2&&J===6)this.channelMixer=(Y,j,X)=>{return Y[j*$+X]*+(X<2)};else if($===4&&J===1)this.channelMixer=(Y,j)=>{let X=j*$;return 0.25*(Y[X]+Y[X+1]+Y[X+2]+Y[X+3])};else if($===4&&J===2)this.channelMixer=(Y,j,X)=>{let Z=j*$;return 0.5*(Y[Z+X]+Y[Z+X+2])};else if($===4&&J===6)this.channelMixer=(Y,j,X)=>{let Z=j*$;if(X<2)return Y[Z+X];if(X===2||X===3)return 0;return Y[Z+X-2]};else if($===6&&J===1)this.channelMixer=(Y,j)=>{let X=j*$;return Math.SQRT1_2*(Y[X]+Y[X+1])+Y[X+2]+0.5*(Y[X+4]+Y[X+5])};else if($===6&&J===2)this.channelMixer=(Y,j,X)=>{let Z=j*$;return Y[Z+X]+Math.SQRT1_2*(Y[Z+2]+Y[Z+X+4])};else if($===6&&J===4)this.channelMixer=(Y,j,X)=>{let Z=j*$;if(X<2)return Y[Z+X]+Math.SQRT1_2*Y[Z+2];return Y[Z+X+2]};else this.channelMixer=(Y,j,X)=>{return X<$?Y[j*$+X]:0}}ensureTempBufferSize($){let J=this.tempSourceBuffer.length;while(J<$)J*=2;if(J!==this.tempSourceBuffer.length){let Y=new Float32Array(J);Y.set(this.tempSourceBuffer),this.tempSourceBuffer=Y}}async add($){if(this.sourceSampleRate===null)this.sourceSampleRate=$.sampleRate,this.sourceNumberOfChannels=$.numberOfChannels,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup();let J=$.numberOfFrames*$.numberOfChannels;this.ensureTempBufferSize(J);let Y=$.allocationSize({planeIndex:0,format:"f32"}),j=new Float32Array(this.tempSourceBuffer.buffer,0,Y/4);$.copyTo(j,{planeIndex:0,format:"f32"});let X=$.timestamp-this.startTime,Z=$.numberOfFrames/this.sourceSampleRate,G=Math.min(X+Z,this.endTime-this.startTime),K=Math.floor(X*this.targetSampleRate),Q=Math.ceil(G*this.targetSampleRate);for(let q=K;q<Q;q++){if(q<this.bufferStartFrame)continue;while(q>=this.bufferStartFrame+this.bufferSizeInFrames)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let U=q-this.bufferStartFrame;H(U<this.bufferSizeInFrames);let N=(q/this.targetSampleRate-X)*this.sourceSampleRate,A=Math.floor(N),R=Math.ceil(N),z=N-A;for(let _=0;_<this.targetNumberOfChannels;_++){let L=0,M=0;if(A>=0&&A<$.numberOfFrames)L=this.channelMixer(j,A,_);if(R>=0&&R<$.numberOfFrames)M=this.channelMixer(j,R,_);let B=L+z*(M-L),F=U*this.targetNumberOfChannels+_;this.outputBuffer[F]+=B}this.maxWrittenFrame=Math.max(this.maxWrittenFrame,U)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame<0)return;let $=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,J=new Float32Array($);J.set(this.outputBuffer.subarray(0,$));let Y=this.bufferStartFrame/this.targetSampleRate,j=new K0({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:Y,data:J});await this.onSample(j),this.outputBuffer.fill(0),this.maxWrittenFrame=-1}finalize(){return this.finalizeCurrentBuffer()}}class Z7 extends z8{_resolvedDemuxer=null;constructor($){super({source:$,formats:[R2]})}async _ensureDemuxer(){if(!this._resolvedDemuxer)this._resolvedDemuxer=await this._getDemuxer();return this._resolvedDemuxer}async getVideoTracks(){let $=await this._ensureDemuxer();return(await this.getTracks()).filter((j)=>j.isVideoTrack()).map((j)=>this._wrapVideoTrackWithCuePoints(j,$))}async getPrimaryVideoTrack(){let $=await this._ensureDemuxer(),Y=(await this.getTracks()).find((j)=>j.isVideoTrack());if(!Y)return null;return this._wrapVideoTrackWithCuePoints(Y,$)}get videoTracks(){return this.getVideoTracks()}async getAudioTracks(){let $=await this._ensureDemuxer();return(await this.getTracks()).filter((j)=>j.isAudioTrack()).map((j)=>this._wrapAudioTrackWithCuePoints(j,$))}get audioTracks(){return this.getAudioTracks()}async getPrimaryAudioTrack(){let $=await this._ensureDemuxer(),Y=(await this.getTracks()).find((j)=>j.isAudioTrack());if(!Y)return null;return this._wrapAudioTrackWithCuePoints(Y,$)}async getSubtitleTracks(){let $=await this._ensureDemuxer();return(await this.getTracks()).filter((j)=>j.isSubtitleTrack()).map((j)=>this._wrapSubtitleTrackWithCuePoints(j,$))}get subtitleTracks(){return this.getSubtitleTracks()}_wrapVideoTrackWithCuePoints($,J){let Y=$,j=this._getCuePointsForTrack(J,$.id);return Y.getCuePoints=()=>j,Y}_wrapAudioTrackWithCuePoints($,J){let Y=$,j=this._getCuePointsForTrack(J,$.id);return Y.getCuePoints=()=>j,Y}_wrapSubtitleTrackWithCuePoints($,J){let Y=$,j=this._getCuePointsForTrack(J,$.id);return Y.getCuePoints=()=>j,Y}_getCuePointsForTrack($,J){let Y=this._findInternalTrack($,J);if(!Y)return[];return Y.cuePoints.map((j)=>({time:j.time/Y.segment.timestampFactor,trackId:j.trackId,clusterPosition:j.clusterPosition}))}_findInternalTrack($,J){for(let Y of $.segments){let j=Y.tracks.find((X)=>X.id===J);if(j)return j}return null}}x0();/*!
485
485
  * Copyright (c) 2025-present, Vanilagy and contributors
486
486
  *
487
487
  * This Source Code Form is subject to the terms of the Mozilla Public
488
488
  * License, v. 2.0. If a copy of the MPL was not distributed with this
489
489
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
490
- */export{$$ as splitSrtIntoCues,J$ as splitAssIntoCues,_7 as registerEncoder,z7 as registerDecoder,p6 as parseSrtTimestamp,m6 as parseAssTimestamp,n2 as getFirstEncodableVideoCodec,C7 as getFirstEncodableSubtitleCodec,P7 as getFirstEncodableAudioCodec,gJ as getEncodableVideoCodecs,kJ as getEncodableSubtitleCodecs,O7 as getEncodableCodecs,w8 as getEncodableAudioCodecs,l6 as formatSrtTimestamp,o6 as formatCuesToWebVTT,n6 as formatCuesToSrt,r6 as formatCuesToAss,d6 as formatAssTimestamp,F6 as canEncodeVideo,w6 as canEncodeSubtitles,B6 as canEncodeAudio,w7 as canEncode,$6 as WebMOutputFormat,C$ as WebMInputFormat,E$ as WaveInputFormat,rY as WavOutputFormat,jY as WEBM,ZY as WAVE,w1 as VideoSource,r8 as VideoSampleSource,X8 as VideoSampleSink,T8 as VideoSampleColorSpace,J0 as VideoSample,t2 as VIDEO_SAMPLE_PIXEL_FORMATS,j0 as VIDEO_CODECS,NY as UrlSource,B2 as TextSubtitleSource,P1 as Target,s8 as SubtitleSource,c$ as StreamTarget,x$ as StreamSource,i0 as Source,z0 as SUBTITLE_CODECS,I0 as RichImageData,RY as ReadableStreamSource,P$ as QuickTimeInputFormat,N0 as Quality,L7 as QUALITY_VERY_LOW,B7 as QUALITY_VERY_HIGH,F7 as QUALITY_MEDIUM,M7 as QUALITY_LOW,M6 as QUALITY_HIGH,YY as QTFF,o as PCM_AUDIO_CODECS,y0 as OutputFormat,Y6 as Output,iY as OggOutputFormat,T$ as OggInputFormat,GY as OGG,P2 as NullTarget,X1 as NON_PCM_AUDIO_CODECS,J6 as Mp4OutputFormat,O$ as Mp4InputFormat,oY as Mp3OutputFormat,D$ as Mp3InputFormat,e8 as MovOutputFormat,E2 as MkvOutputFormat,LY as MediaStreamVideoTrackSource,FY as MediaStreamAudioTrackSource,o8 as MediaSource,A2 as MatroskaInputFormat,G7 as MatroskaInput,JY as MP4,XY as MP3,R2 as MATROSKA,T2 as IsobmffOutputFormat,N2 as IsobmffInputFormat,D0 as InputVideoTrack,g1 as InputTrack,p1 as InputSubtitleTrack,E0 as InputFormat,q0 as InputDisposedError,t as InputAudioTrack,z8 as Input,tY as FlacOutputFormat,y$ as FlacInputFormat,OY as FilePathTarget,AY as FilePathSource,QY as FLAC,_2 as EncodedVideoPacketSource,K1 as EncodedPacketSink,I as EncodedPacket,M2 as EncodedAudioPacketSource,d2 as CustomVideoEncoder,l2 as CustomVideoDecoder,c2 as CustomAudioEncoder,m2 as CustomAudioDecoder,QJ as Conversion,_Y as CanvasSource,u6 as CanvasSink,O2 as BufferTarget,WY as BufferSource,VY as BlobSource,k6 as BaseMediaSampleSink,aY as AviOutputFormat,b$ as AviInputFormat,O1 as AudioSource,i8 as AudioSampleSource,Z8 as AudioSampleSink,K0 as AudioSample,MY as AudioBufferSource,Q5 as AudioBufferSink,l1 as AttachedFile,sY as AdtsOutputFormat,v$ as AdtsInputFormat,qY as AVI,Z0 as AUDIO_CODECS,eY as ALL_TRACK_TYPES,Yj as ALL_FORMATS,KY as ADTS};
490
+ */export{$$ as splitSrtIntoCues,J$ as splitAssIntoCues,z7 as registerEncoder,R7 as registerDecoder,p6 as parseSrtTimestamp,m6 as parseAssTimestamp,n2 as getFirstEncodableVideoCodec,P7 as getFirstEncodableSubtitleCodec,O7 as getFirstEncodableAudioCodec,gJ as getEncodableVideoCodecs,kJ as getEncodableSubtitleCodecs,w7 as getEncodableCodecs,w8 as getEncodableAudioCodecs,l6 as formatSrtTimestamp,o6 as formatCuesToWebVTT,n6 as formatCuesToSrt,r6 as formatCuesToAss,d6 as formatAssTimestamp,F6 as canEncodeVideo,w6 as canEncodeSubtitles,B6 as canEncodeAudio,B7 as canEncode,$6 as WebMOutputFormat,C$ as WebMInputFormat,E$ as WaveInputFormat,oY as WavOutputFormat,jY as WEBM,ZY as WAVE,w1 as VideoSource,r8 as VideoSampleSource,X8 as VideoSampleSink,T8 as VideoSampleColorSpace,J0 as VideoSample,t2 as VIDEO_SAMPLE_PIXEL_FORMATS,j0 as VIDEO_CODECS,NY as UrlSource,B2 as TextSubtitleSource,P1 as Target,s8 as SubtitleSource,c$ as StreamTarget,x$ as StreamSource,i0 as Source,z0 as SUBTITLE_CODECS,I0 as RichImageData,RY as ReadableStreamSource,P$ as QuickTimeInputFormat,N0 as Quality,_7 as QUALITY_VERY_LOW,F7 as QUALITY_VERY_HIGH,M7 as QUALITY_MEDIUM,L7 as QUALITY_LOW,M6 as QUALITY_HIGH,YY as QTFF,o as PCM_AUDIO_CODECS,y0 as OutputFormat,Y6 as Output,rY as OggOutputFormat,T$ as OggInputFormat,GY as OGG,P2 as NullTarget,X1 as NON_PCM_AUDIO_CODECS,J6 as Mp4OutputFormat,O$ as Mp4InputFormat,nY as Mp3OutputFormat,D$ as Mp3InputFormat,e8 as MovOutputFormat,E2 as MkvOutputFormat,LY as MediaStreamVideoTrackSource,FY as MediaStreamAudioTrackSource,o8 as MediaSource,A2 as MatroskaInputFormat,Z7 as MatroskaInput,JY as MP4,XY as MP3,R2 as MATROSKA,T2 as IsobmffOutputFormat,N2 as IsobmffInputFormat,D0 as InputVideoTrack,g1 as InputTrack,p1 as InputSubtitleTrack,E0 as InputFormat,q0 as InputDisposedError,t as InputAudioTrack,z8 as Input,aY as FlacOutputFormat,y$ as FlacInputFormat,wY as FilePathTarget,AY as FilePathSource,QY as FLAC,_2 as EncodedVideoPacketSource,K1 as EncodedPacketSink,I as EncodedPacket,M2 as EncodedAudioPacketSource,d2 as CustomVideoEncoder,l2 as CustomVideoDecoder,c2 as CustomAudioEncoder,m2 as CustomAudioDecoder,QJ as Conversion,_Y as CanvasSource,u6 as CanvasSink,O2 as BufferTarget,WY as BufferSource,VY as BlobSource,k6 as BaseMediaSampleSink,sY as AviOutputFormat,b$ as AviInputFormat,O1 as AudioSource,i8 as AudioSampleSource,Z8 as AudioSampleSink,K0 as AudioSample,MY as AudioBufferSource,Q5 as AudioBufferSink,l1 as AttachedFile,iY as AdtsOutputFormat,v$ as AdtsInputFormat,qY as AVI,Z0 as AUDIO_CODECS,tY as ALL_TRACK_TYPES,Jj as ALL_FORMATS,KY as ADTS};