@omnimedia/omnitool 1.1.0-70 → 1.1.0-71
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/s/driver/parts/compositor.ts +46 -14
- package/x/demo/demo.bundle.min.js +5 -5
- package/x/demo/demo.bundle.min.js.map +3 -3
- package/x/driver/parts/compositor.d.ts +8 -0
- package/x/driver/parts/compositor.js +41 -14
- package/x/driver/parts/compositor.js.map +1 -1
- package/x/index.html +2 -2
- package/x/tests.bundle.min.js +10 -10
- package/x/tests.bundle.min.js.map +3 -3
- package/x/tests.html +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./chunk-T3METYEY.js";import{c as Ir,j as Fi,k as Di,l as ho}from"./chunk-5ZZYIILO.js";import"./chunk-P3PTHHFE.js";import"./chunk-USLRKDKD.js";import"./chunk-Q4MWBZHL.js";import{b as Ar}from"./chunk-YISSXWBT.js";import{Aa as go,D as fo,H as $t,N as mo,Q as Ei,R as Kt,T as
|
|
1
|
+
import"./chunk-T3METYEY.js";import{c as Ir,j as Fi,k as Di,l as ho}from"./chunk-5ZZYIILO.js";import"./chunk-P3PTHHFE.js";import"./chunk-USLRKDKD.js";import"./chunk-Q4MWBZHL.js";import{b as Ar}from"./chunk-YISSXWBT.js";import{Aa as go,D as fo,H as $t,N as mo,Q as Ei,R as Kt,T as gt,a as oc,b as ic,c as Cr,d as Ci,da as po,h as uo,i as Ii,k as Ai,m as _i}from"./chunk-PYG4RZZ2.js";var Pa=oc((Gg,va)=>{va.exports=[{name:"Bounce",paramsTypes:{shadow_colour:"vec4",shadow_height:"float",bounces:"float"},defaultParams:{shadow_colour:[0,0,0,.6],shadow_height:.075,bounces:3},glsl:`// Author: Adrian Purser
|
|
2
2
|
// License: MIT
|
|
3
3
|
|
|
4
4
|
uniform vec4 shadow_colour; // = vec4(0.,0.,0.,.6)
|
|
@@ -2331,13 +2331,13 @@ vec4 transition(vec2 uv) {
|
|
|
2331
2331
|
vec4 b=getToColor(p);
|
|
2332
2332
|
return mix(a, b, step(0.0+p.y,progress));
|
|
2333
2333
|
}
|
|
2334
|
-
`,author:"Jake Nelson",license:"MIT",createdAt:"Wed, 1 Nov 2017 15:24:36 -0500",updatedAt:"Thu, 2 Nov 2017 18:37:42 -0500"}]});var gt=Object.freeze({eq(r,e){if(r.length!==e.length)return!1;for(let t=0;t<=r.length;t++)if(r.at(t)!==e.at(t))return!1;return!0},random(r){return crypto.getRandomValues(new Uint8Array(r))}});var X=class{lexicon;static lexicons=Object.freeze({base2:{characters:"01"},hex:{characters:"0123456789abcdef"},base36:{characters:"0123456789abcdefghijklmnopqrstuvwxyz"},base58:{characters:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"},base62:{characters:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"},base64url:{negativePrefix:"~",characters:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"},base64:{characters:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",padding:{character:"=",size:4}}});lookup;negativePrefix;constructor(e){this.lexicon=e,this.lookup=Object.fromEntries([...e.characters].map((t,n)=>[t,n])),this.negativePrefix=e.negativePrefix??"-"}toBytes(e){let t=Math.log2(this.lexicon.characters.length);if(Number.isInteger(t)){let a=0,c=0,l=[];for(let d of e){if(d===this.lexicon.padding?.character)continue;let u=this.lookup[d];if(u===void 0)throw new Error(`Invalid character: ${d}`);for(a=a<<t|u,c+=t;c>=8;)c-=8,l.push(a>>c&255)}return new Uint8Array(l)}let n=0n,o=BigInt(this.lexicon.characters.length),i=!1;e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),i=!0);for(let a of e){let c=this.lookup[a];if(c===void 0)throw new Error(`Invalid character: ${a}`);n=n*o+BigInt(c)}let s=[];for(;n>0n;)s.unshift(Number(n%256n)),n=n/256n;return new Uint8Array(s)}fromBytes(e){let t=Math.log2(this.lexicon.characters.length);if(Number.isInteger(t)){let s=0,a=0,c="";for(let l of e)for(s=s<<8|l,a+=8;a>=t;){a-=t;let d=s>>a&(1<<t)-1;c+=this.lexicon.characters[d]}if(a>0){let l=s<<t-a&(1<<t)-1;c+=this.lexicon.characters[l]}if(this.lexicon.padding)for(;c.length%this.lexicon.padding.size!==0;)c+=this.lexicon.padding.character;return c}let n=0n;for(let s of e)n=(n<<8n)+BigInt(s);if(n===0n)return this.lexicon.characters[0];let o=BigInt(this.lexicon.characters.length),i="";for(;n>0n;)i=this.lexicon.characters[Number(n%o)]+i,n=n/o;return i}toInteger(e){if(!e)return 0;let t=0n,n=!1,o=BigInt(this.lexicon.characters.length);e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),n=!0);for(let i of e){let s=this.lookup[i];if(s===void 0)throw new Error(`Invalid character: ${i}`);t=t*o+BigInt(s)}return Number(n?-t:t)}fromInteger(e){e=Math.floor(e);let t=e<0,n=BigInt(t?-e:e);if(n===0n)return this.lexicon.characters[0];let o=BigInt(this.lexicon.characters.length),i="";for(;n>0n;)i=this.lexicon.characters[Number(n%o)]+i,n=n/o;return t?`${this.negativePrefix}${i}`:i}random(e=32){return this.fromBytes(gt.random(e))}};var he=new X(X.lexicons.hex),cl=new X(X.lexicons.base2),ll=new X(X.lexicons.base36),xo=new X(X.lexicons.base58),ul=new X(X.lexicons.base62),dl=new X(X.lexicons.base64),fl=new X(X.lexicons.base64url);var bo=["doz","mar","bin","wan","sam","lit","sig","hid","fid","lis","sog","dir","wac","sab","wis","sib","rig","sol","dop","mod","fog","lid","hop","dar","dor","lor","hod","fol","rin","tog","sil","mir","hol","pas","lac","rov","liv","dal","sat","lib","tab","han","tic","pid","tor","bol","fos","dot","los","dil","for","pil","ram","tir","win","tad","bic","dif","roc","wid","bis","das","mid","lop","ril","nar","dap","mol","san","loc","nov","sit","nid","tip","sic","rop","wit","nat","pan","min","rit","pod","mot","tam","tol","sav","pos","nap","nop","som","fin","fon","ban","mor","wor","sip","ron","nor","bot","wic","soc","wat","dol","mag","pic","dav","bid","bal","tim","tas","mal","lig","siv","tag","pad","sal","div","dac","tan","sid","fab","tar","mon","ran","nis","wol","mis","pal","las","dis","map","rab","tob","rol","lat","lon","nod","nav","fig","nom","nib","pag","sop","ral","bil","had","doc","rid","moc","pac","rav","rip","fal","tod","til","tin","hap","mic","fan","pat","tac","lab","mog","sim","son","pin","lom","ric","tap","fir","has","bos","bat","poc","hac","tid","hav","sap","lin","dib","hos","dab","bit","bar","rac","par","lod","dos","bor","toc","hil","mac","tom","dig","fil","fas","mit","hob","har","mig","hin","rad","mas","hal","rag","lag","fad","top","mop","hab","nil","nos","mil","fop","fam","dat","nol","din","hat","nac","ris","fot","rib","hoc","nim","lar","fit","wal","rap","sar","nal","mos","lan","don","dan","lad","dov","riv","bac","pol","lap","tal","pit","nam","bon","ros","ton","fod","pon","sov","noc","sor","lav","mat","mip","fip"];var yo=["zod","nec","bud","wes","sev","per","sut","let","ful","pen","syt","dur","wep","ser","wyl","sun","ryp","syx","dyr","nup","heb","peg","lup","dep","dys","put","lug","hec","ryt","tyv","syd","nex","lun","mep","lut","sep","pes","del","sul","ped","tem","led","tul","met","wen","byn","hex","feb","pyl","dul","het","mev","rut","tyl","wyd","tep","bes","dex","sef","wyc","bur","der","nep","pur","rys","reb","den","nut","sub","pet","rul","syn","reg","tyd","sup","sem","wyn","rec","meg","net","sec","mul","nym","tev","web","sum","mut","nyx","rex","teb","fus","hep","ben","mus","wyx","sym","sel","ruc","dec","wex","syr","wet","dyl","myn","mes","det","bet","bel","tux","tug","myr","pel","syp","ter","meb","set","dut","deg","tex","sur","fel","tud","nux","rux","ren","wyt","nub","med","lyt","dus","neb","rum","tyn","seg","lyx","pun","res","red","fun","rev","ref","mec","ted","rus","bex","leb","dux","ryn","num","pyx","ryg","ryx","fep","tyr","tus","tyc","leg","nem","fer","mer","ten","lus","nus","syl","tec","mex","pub","rym","tuc","fyl","lep","deb","ber","mug","hut","tun","byl","sud","pem","dev","lur","def","bus","bep","run","mel","pex","dyt","byt","typ","lev","myl","wed","duc","fur","fex","nul","luc","len","ner","lex","rup","ned","lec","ryd","lyd","fen","wel","nyd","hus","rel","rud","nes","hes","fet","des","ret","dun","ler","nyr","seb","hul","ryl","lud","rem","lys","fyn","wer","ryc","sug","nys","nyl","lyn","dyn","dem","lux","fed","sed","bec","mun","lyr","tes","mud","nyt","byr","sen","weg","fyr","mur","tel","rep","teg","pec","nel","nev","fes"];var Se={defaults:{groupSize:4,wordSeparator:".",groupSeparator:" "},random(r,e){let t=gt.random(r);return this.fromBytes(t,e)},fromBytes(r,e={}){let{groupSize:t=Se.defaults.groupSize,wordSeparator:n=Se.defaults.wordSeparator,groupSeparator:o=Se.defaults.groupSeparator}=e,i=[],s=[];r.forEach((c,l)=>{let d=l%2===0?bo:yo;s.push(d[c]),s.length===2&&(i.push(s.join("")),s=[])}),s.length&&i.push(s.join(""));let a=[];for(let c=0;c<i.length;c+=t)a.push(i.slice(c,c+t).join(n));return a.join(o)},toBytes(r){let e=r.toLowerCase().replace(/[^a-z]/g,"");if(e.length/3%1!==0)throw new Error(`invalid triplet count, ${e.length} does not divide into triplets`);let n=[];for(let o=0;o<e.length;o+=3)n.push(e.slice(o,o+3));return new Uint8Array(n.map((o,i)=>{let a=(i%2===0?bo:yo).findIndex(c=>c===o);if(a===-1)throw new Error(`unknown triplet ${o}`);return a}))},toHex(r){return he.fromBytes(Se.toBytes(r))},fromHex(r,e){return Se.fromBytes(he.toBytes(r),e)}};var ge={defaults:{delimiter:".",sigilBytes:4,previewBytes:8},toBytes(r){r=r.trim();let e=r.split(/[^a-zA-Z0-9]+/m).filter(Boolean).map(o=>o.trim());if(e.length<2)return Se.toBytes(e.join(""));let t=e.pop(),n=e.join("");return new Uint8Array([...Se.toBytes(n),...xo.toBytes(t)])},parse(r,e){let t=ge.toBytes(r);return ge.build.fromBytes(t,e)},build:{fromBytes(r,e={}){let{delimiter:t,previewBytes:n,sigilBytes:o}={...ge.defaults,...e},i=d=>r.length>0?Se.fromBytes(r.slice(0,d),{wordSeparator:t,groupSeparator:t}):"",s=i(o),a=i(n),c=r.length>n?xo.fromBytes(r.slice(n)):"",l=[a,c].filter(d=>d.length>0).join(t);return{raw:r,full:l,preview:a,bulk:c,sigil:s,bytes:r,thumbprint:l}},fromHex(r,e){let t=he.toBytes(r);return ge.build.fromBytes(t,e)}},toHex(r){let e=ge.toBytes(r);return he.fromBytes(e)},fromBytes(r,e){return ge.build.fromBytes(r,e).full},fromHex(r,e){return ge.fromBytes(he.toBytes(r),e)},sigil:{fromHex(r,e){return ge.build.fromHex(r,e).sigil},fromBytes(r,e){return ge.build.fromBytes(r,e).sigil}}},Ri=ge;var _r=Object.freeze({fromBytes(r){return[...r].map(e=>e.toString(16).padStart(2,"0")).join("")},toBytes(r){if(r.length%2!==0)throw new Error("must have even number of hex characters");let e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)e[t/2]=parseInt(r.slice(t,t+2),16);return e},random(r=32){return this.fromBytes(gt.random(r))},string(r){return _r.fromBytes(r)},bytes(r){return _r.toBytes(r)}});function xe(){let r,e,t=new Promise((o,i)=>{r=o,e=i});function n(o){return o.then(r).catch(e),t}return{promise:t,resolve:r,reject:e,entangle:n}}var Er=Object.freeze({happy:r=>r!=null,sad:r=>r==null,boolean:r=>typeof r=="boolean",number:r=>typeof r=="number",string:r=>typeof r=="string",bigint:r=>typeof r=="bigint",object:r=>typeof r=="object"&&r!==null,array:r=>Array.isArray(r),fn:r=>typeof r=="function",symbol:r=>typeof r=="symbol"});var Fr=class r extends Map{static require(e,t){if(e.has(t))return e.get(t);throw new Error(`required key not found: "${t}"`)}static guarantee(e,t,n){if(e.has(t))return e.get(t);{let o=n();return e.set(t,o),o}}array(){return[...this]}require(e){return r.require(this,e)}guarantee(e,t){return r.guarantee(this,e,t)}};var Xt=class extends Error{milliseconds;name=this.constructor.name;constructor(e){super(`deadline exceeded (${(e/1e3).toFixed(1)} seconds)`),this.milliseconds=e}};function Mi(r,e){return r<=0||r===1/0?e():new Promise((t,n)=>{let o=setTimeout(()=>n(new Xt(r)),r);e().then(t).catch(n).finally(()=>clearTimeout(o))})}function Dr(){let r=[];function e(){for(let t of r)t();r=[]}return e.schedule=(...t)=>(r.push(...t),e),e}function Bi(r,e){let t=r;for(let n of e)if(t=t[n],Er.sad(t))break;return t}function sc(){let r=new Set;async function e(...c){await Promise.all([...r].map(l=>l(...c)))}function t(c){return r.add(c),()=>{r.delete(c)}}async function n(...c){return e(...c)}function o(c){return t(c)}async function i(c){let{promise:l,resolve:d}=xe(),u=o(async(...f)=>{c&&await c(...f),d(f),u()});return l}function s(){r.clear()}let a={pub:n,sub:o,publish:e,subscribe:t,on:t,next:i,clear:s};return Object.assign(o,a),Object.assign(n,a),a}function xt(r){let e=sc();return r&&e.sub(r),e.pub}function To(r,e){return{error:t=>r.error({...e,...t}),rpcRequest:t=>r.rpcRequest({...e,...t}),rpcError:t=>r.rpcError({...e,...t})}}var Rr=()=>r=>({plain:r.none,errMessage:r.mix(r.brightRed,r.bold),errName:r.red,errStack:r.mix(r.red,r.dim),timestamp:r.blue,timestampErr:r.red});function Oi(){return Rr()}var Me=Object.freeze({black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",brightBlack:"\x1B[90m",brightRed:"\x1B[91m",brightGreen:"\x1B[92m",brightYellow:"\x1B[93m",brightBlue:"\x1B[94m",brightMagenta:"\x1B[95m",brightCyan:"\x1B[96m",brightWhite:"\x1B[97m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m",bgBrightBlack:"\x1B[100m",bgBrightRed:"\x1B[101m",bgBrightGreen:"\x1B[102m",bgBrightYellow:"\x1B[103m",bgBrightBlue:"\x1B[104m",bgBrightMagenta:"\x1B[105m",bgBrightCyan:"\x1B[106m",bgBrightWhite:"\x1B[107m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",inverse:"\x1B[7m",hidden:"\x1B[8m",strikethrough:"\x1B[9m",reset:"\x1B[0m"});var Mr=()=>({none:r=>r,uncolor:cc,mix:lc,hex:uc,rgb:zi,bgRgb:dc});function cc(r){return r.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"")}function lc(...r){return e=>{for(let t of r)e=t(e);return e}}function uc(r){r=r.replace(/^#/,"");let e,t,n,o;if(r.length===3)e=parseInt(r.split("").map(i=>i+i).join(""),16);else if(r.length===6)e=parseInt(r,16);else throw new Error("Invalid hex color");return t=e>>16&255,n=e>>8&255,o=e&255,zi(t,n,o)}function zi(r,e,t){let n=`\x1B[38;2;${r};${e};${t}m`;return o=>`${n}${o}${Me.reset}`}function dc(r,e,t){let n=`\x1B[48;2;${r};${e};${t}m`;return o=>`${n}${o}${Me.reset}`}var Qt={...Object.fromEntries(Object.entries(Me).map(([r])=>[r,e=>e])),...Mr()};var Yt={...Object.fromEntries(Object.entries(Me).map(([r,e])=>[r,t=>`${e}${t}${Me.reset}`])),...Mr()};function wo(){return typeof Deno<"u"&&typeof Deno.version<"u"}function ko(){return typeof process<"u"&&process.versions&&process.versions.node}function Ui(){return ko()?process.env.FORCE_COLOR||process.stdout.isTTY&&process.env.TERM!=="dumb":wo()?Deno.env.get("FORCE_COLOR")||Deno.isatty(Deno.stdout.rid)&&Deno.env.get("TERM")!=="dumb":!1}var So=()=>Ui()?Yt:Qt;var Br=()=>({colors:r,theme:e})=>{let t=e(r);function n(s){let a=s.stack?`
|
|
2334
|
+
`,author:"Jake Nelson",license:"MIT",createdAt:"Wed, 1 Nov 2017 15:24:36 -0500",updatedAt:"Thu, 2 Nov 2017 18:37:42 -0500"}]});var xt=Object.freeze({eq(r,e){if(r.length!==e.length)return!1;for(let t=0;t<=r.length;t++)if(r.at(t)!==e.at(t))return!1;return!0},random(r){return crypto.getRandomValues(new Uint8Array(r))}});var X=class{lexicon;static lexicons=Object.freeze({base2:{characters:"01"},hex:{characters:"0123456789abcdef"},base36:{characters:"0123456789abcdefghijklmnopqrstuvwxyz"},base58:{characters:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"},base62:{characters:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"},base64url:{negativePrefix:"~",characters:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"},base64:{characters:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",padding:{character:"=",size:4}}});lookup;negativePrefix;constructor(e){this.lexicon=e,this.lookup=Object.fromEntries([...e.characters].map((t,n)=>[t,n])),this.negativePrefix=e.negativePrefix??"-"}toBytes(e){let t=Math.log2(this.lexicon.characters.length);if(Number.isInteger(t)){let a=0,c=0,l=[];for(let d of e){if(d===this.lexicon.padding?.character)continue;let u=this.lookup[d];if(u===void 0)throw new Error(`Invalid character: ${d}`);for(a=a<<t|u,c+=t;c>=8;)c-=8,l.push(a>>c&255)}return new Uint8Array(l)}let n=0n,o=BigInt(this.lexicon.characters.length),i=!1;e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),i=!0);for(let a of e){let c=this.lookup[a];if(c===void 0)throw new Error(`Invalid character: ${a}`);n=n*o+BigInt(c)}let s=[];for(;n>0n;)s.unshift(Number(n%256n)),n=n/256n;return new Uint8Array(s)}fromBytes(e){let t=Math.log2(this.lexicon.characters.length);if(Number.isInteger(t)){let s=0,a=0,c="";for(let l of e)for(s=s<<8|l,a+=8;a>=t;){a-=t;let d=s>>a&(1<<t)-1;c+=this.lexicon.characters[d]}if(a>0){let l=s<<t-a&(1<<t)-1;c+=this.lexicon.characters[l]}if(this.lexicon.padding)for(;c.length%this.lexicon.padding.size!==0;)c+=this.lexicon.padding.character;return c}let n=0n;for(let s of e)n=(n<<8n)+BigInt(s);if(n===0n)return this.lexicon.characters[0];let o=BigInt(this.lexicon.characters.length),i="";for(;n>0n;)i=this.lexicon.characters[Number(n%o)]+i,n=n/o;return i}toInteger(e){if(!e)return 0;let t=0n,n=!1,o=BigInt(this.lexicon.characters.length);e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),n=!0);for(let i of e){let s=this.lookup[i];if(s===void 0)throw new Error(`Invalid character: ${i}`);t=t*o+BigInt(s)}return Number(n?-t:t)}fromInteger(e){e=Math.floor(e);let t=e<0,n=BigInt(t?-e:e);if(n===0n)return this.lexicon.characters[0];let o=BigInt(this.lexicon.characters.length),i="";for(;n>0n;)i=this.lexicon.characters[Number(n%o)]+i,n=n/o;return t?`${this.negativePrefix}${i}`:i}random(e=32){return this.fromBytes(xt.random(e))}};var he=new X(X.lexicons.hex),cl=new X(X.lexicons.base2),ll=new X(X.lexicons.base36),xo=new X(X.lexicons.base58),ul=new X(X.lexicons.base62),dl=new X(X.lexicons.base64),fl=new X(X.lexicons.base64url);var bo=["doz","mar","bin","wan","sam","lit","sig","hid","fid","lis","sog","dir","wac","sab","wis","sib","rig","sol","dop","mod","fog","lid","hop","dar","dor","lor","hod","fol","rin","tog","sil","mir","hol","pas","lac","rov","liv","dal","sat","lib","tab","han","tic","pid","tor","bol","fos","dot","los","dil","for","pil","ram","tir","win","tad","bic","dif","roc","wid","bis","das","mid","lop","ril","nar","dap","mol","san","loc","nov","sit","nid","tip","sic","rop","wit","nat","pan","min","rit","pod","mot","tam","tol","sav","pos","nap","nop","som","fin","fon","ban","mor","wor","sip","ron","nor","bot","wic","soc","wat","dol","mag","pic","dav","bid","bal","tim","tas","mal","lig","siv","tag","pad","sal","div","dac","tan","sid","fab","tar","mon","ran","nis","wol","mis","pal","las","dis","map","rab","tob","rol","lat","lon","nod","nav","fig","nom","nib","pag","sop","ral","bil","had","doc","rid","moc","pac","rav","rip","fal","tod","til","tin","hap","mic","fan","pat","tac","lab","mog","sim","son","pin","lom","ric","tap","fir","has","bos","bat","poc","hac","tid","hav","sap","lin","dib","hos","dab","bit","bar","rac","par","lod","dos","bor","toc","hil","mac","tom","dig","fil","fas","mit","hob","har","mig","hin","rad","mas","hal","rag","lag","fad","top","mop","hab","nil","nos","mil","fop","fam","dat","nol","din","hat","nac","ris","fot","rib","hoc","nim","lar","fit","wal","rap","sar","nal","mos","lan","don","dan","lad","dov","riv","bac","pol","lap","tal","pit","nam","bon","ros","ton","fod","pon","sov","noc","sor","lav","mat","mip","fip"];var yo=["zod","nec","bud","wes","sev","per","sut","let","ful","pen","syt","dur","wep","ser","wyl","sun","ryp","syx","dyr","nup","heb","peg","lup","dep","dys","put","lug","hec","ryt","tyv","syd","nex","lun","mep","lut","sep","pes","del","sul","ped","tem","led","tul","met","wen","byn","hex","feb","pyl","dul","het","mev","rut","tyl","wyd","tep","bes","dex","sef","wyc","bur","der","nep","pur","rys","reb","den","nut","sub","pet","rul","syn","reg","tyd","sup","sem","wyn","rec","meg","net","sec","mul","nym","tev","web","sum","mut","nyx","rex","teb","fus","hep","ben","mus","wyx","sym","sel","ruc","dec","wex","syr","wet","dyl","myn","mes","det","bet","bel","tux","tug","myr","pel","syp","ter","meb","set","dut","deg","tex","sur","fel","tud","nux","rux","ren","wyt","nub","med","lyt","dus","neb","rum","tyn","seg","lyx","pun","res","red","fun","rev","ref","mec","ted","rus","bex","leb","dux","ryn","num","pyx","ryg","ryx","fep","tyr","tus","tyc","leg","nem","fer","mer","ten","lus","nus","syl","tec","mex","pub","rym","tuc","fyl","lep","deb","ber","mug","hut","tun","byl","sud","pem","dev","lur","def","bus","bep","run","mel","pex","dyt","byt","typ","lev","myl","wed","duc","fur","fex","nul","luc","len","ner","lex","rup","ned","lec","ryd","lyd","fen","wel","nyd","hus","rel","rud","nes","hes","fet","des","ret","dun","ler","nyr","seb","hul","ryl","lud","rem","lys","fyn","wer","ryc","sug","nys","nyl","lyn","dyn","dem","lux","fed","sed","bec","mun","lyr","tes","mud","nyt","byr","sen","weg","fyr","mur","tel","rep","teg","pec","nel","nev","fes"];var Se={defaults:{groupSize:4,wordSeparator:".",groupSeparator:" "},random(r,e){let t=xt.random(r);return this.fromBytes(t,e)},fromBytes(r,e={}){let{groupSize:t=Se.defaults.groupSize,wordSeparator:n=Se.defaults.wordSeparator,groupSeparator:o=Se.defaults.groupSeparator}=e,i=[],s=[];r.forEach((c,l)=>{let d=l%2===0?bo:yo;s.push(d[c]),s.length===2&&(i.push(s.join("")),s=[])}),s.length&&i.push(s.join(""));let a=[];for(let c=0;c<i.length;c+=t)a.push(i.slice(c,c+t).join(n));return a.join(o)},toBytes(r){let e=r.toLowerCase().replace(/[^a-z]/g,"");if(e.length/3%1!==0)throw new Error(`invalid triplet count, ${e.length} does not divide into triplets`);let n=[];for(let o=0;o<e.length;o+=3)n.push(e.slice(o,o+3));return new Uint8Array(n.map((o,i)=>{let a=(i%2===0?bo:yo).findIndex(c=>c===o);if(a===-1)throw new Error(`unknown triplet ${o}`);return a}))},toHex(r){return he.fromBytes(Se.toBytes(r))},fromHex(r,e){return Se.fromBytes(he.toBytes(r),e)}};var ge={defaults:{delimiter:".",sigilBytes:4,previewBytes:8},toBytes(r){r=r.trim();let e=r.split(/[^a-zA-Z0-9]+/m).filter(Boolean).map(o=>o.trim());if(e.length<2)return Se.toBytes(e.join(""));let t=e.pop(),n=e.join("");return new Uint8Array([...Se.toBytes(n),...xo.toBytes(t)])},parse(r,e){let t=ge.toBytes(r);return ge.build.fromBytes(t,e)},build:{fromBytes(r,e={}){let{delimiter:t,previewBytes:n,sigilBytes:o}={...ge.defaults,...e},i=d=>r.length>0?Se.fromBytes(r.slice(0,d),{wordSeparator:t,groupSeparator:t}):"",s=i(o),a=i(n),c=r.length>n?xo.fromBytes(r.slice(n)):"",l=[a,c].filter(d=>d.length>0).join(t);return{raw:r,full:l,preview:a,bulk:c,sigil:s,bytes:r,thumbprint:l}},fromHex(r,e){let t=he.toBytes(r);return ge.build.fromBytes(t,e)}},toHex(r){let e=ge.toBytes(r);return he.fromBytes(e)},fromBytes(r,e){return ge.build.fromBytes(r,e).full},fromHex(r,e){return ge.fromBytes(he.toBytes(r),e)},sigil:{fromHex(r,e){return ge.build.fromHex(r,e).sigil},fromBytes(r,e){return ge.build.fromBytes(r,e).sigil}}},Ri=ge;var _r=Object.freeze({fromBytes(r){return[...r].map(e=>e.toString(16).padStart(2,"0")).join("")},toBytes(r){if(r.length%2!==0)throw new Error("must have even number of hex characters");let e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)e[t/2]=parseInt(r.slice(t,t+2),16);return e},random(r=32){return this.fromBytes(xt.random(r))},string(r){return _r.fromBytes(r)},bytes(r){return _r.toBytes(r)}});function xe(){let r,e,t=new Promise((o,i)=>{r=o,e=i});function n(o){return o.then(r).catch(e),t}return{promise:t,resolve:r,reject:e,entangle:n}}var Er=Object.freeze({happy:r=>r!=null,sad:r=>r==null,boolean:r=>typeof r=="boolean",number:r=>typeof r=="number",string:r=>typeof r=="string",bigint:r=>typeof r=="bigint",object:r=>typeof r=="object"&&r!==null,array:r=>Array.isArray(r),fn:r=>typeof r=="function",symbol:r=>typeof r=="symbol"});var Fr=class r extends Map{static require(e,t){if(e.has(t))return e.get(t);throw new Error(`required key not found: "${t}"`)}static guarantee(e,t,n){if(e.has(t))return e.get(t);{let o=n();return e.set(t,o),o}}array(){return[...this]}require(e){return r.require(this,e)}guarantee(e,t){return r.guarantee(this,e,t)}};var Xt=class extends Error{milliseconds;name=this.constructor.name;constructor(e){super(`deadline exceeded (${(e/1e3).toFixed(1)} seconds)`),this.milliseconds=e}};function Mi(r,e){return r<=0||r===1/0?e():new Promise((t,n)=>{let o=setTimeout(()=>n(new Xt(r)),r);e().then(t).catch(n).finally(()=>clearTimeout(o))})}function Dr(){let r=[];function e(){for(let t of r)t();r=[]}return e.schedule=(...t)=>(r.push(...t),e),e}function Bi(r,e){let t=r;for(let n of e)if(t=t[n],Er.sad(t))break;return t}function sc(){let r=new Set;async function e(...c){await Promise.all([...r].map(l=>l(...c)))}function t(c){return r.add(c),()=>{r.delete(c)}}async function n(...c){return e(...c)}function o(c){return t(c)}async function i(c){let{promise:l,resolve:d}=xe(),u=o(async(...f)=>{c&&await c(...f),d(f),u()});return l}function s(){r.clear()}let a={pub:n,sub:o,publish:e,subscribe:t,on:t,next:i,clear:s};return Object.assign(o,a),Object.assign(n,a),a}function ve(r){let e=sc();return r&&e.sub(r),e.pub}function To(r,e){return{error:t=>r.error({...e,...t}),rpcRequest:t=>r.rpcRequest({...e,...t}),rpcError:t=>r.rpcError({...e,...t})}}var Rr=()=>r=>({plain:r.none,errMessage:r.mix(r.brightRed,r.bold),errName:r.red,errStack:r.mix(r.red,r.dim),timestamp:r.blue,timestampErr:r.red});function Oi(){return Rr()}var Be=Object.freeze({black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",brightBlack:"\x1B[90m",brightRed:"\x1B[91m",brightGreen:"\x1B[92m",brightYellow:"\x1B[93m",brightBlue:"\x1B[94m",brightMagenta:"\x1B[95m",brightCyan:"\x1B[96m",brightWhite:"\x1B[97m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m",bgBrightBlack:"\x1B[100m",bgBrightRed:"\x1B[101m",bgBrightGreen:"\x1B[102m",bgBrightYellow:"\x1B[103m",bgBrightBlue:"\x1B[104m",bgBrightMagenta:"\x1B[105m",bgBrightCyan:"\x1B[106m",bgBrightWhite:"\x1B[107m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",inverse:"\x1B[7m",hidden:"\x1B[8m",strikethrough:"\x1B[9m",reset:"\x1B[0m"});var Mr=()=>({none:r=>r,uncolor:cc,mix:lc,hex:uc,rgb:zi,bgRgb:dc});function cc(r){return r.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"")}function lc(...r){return e=>{for(let t of r)e=t(e);return e}}function uc(r){r=r.replace(/^#/,"");let e,t,n,o;if(r.length===3)e=parseInt(r.split("").map(i=>i+i).join(""),16);else if(r.length===6)e=parseInt(r,16);else throw new Error("Invalid hex color");return t=e>>16&255,n=e>>8&255,o=e&255,zi(t,n,o)}function zi(r,e,t){let n=`\x1B[38;2;${r};${e};${t}m`;return o=>`${n}${o}${Be.reset}`}function dc(r,e,t){let n=`\x1B[48;2;${r};${e};${t}m`;return o=>`${n}${o}${Be.reset}`}var Qt={...Object.fromEntries(Object.entries(Be).map(([r])=>[r,e=>e])),...Mr()};var Yt={...Object.fromEntries(Object.entries(Be).map(([r,e])=>[r,t=>`${e}${t}${Be.reset}`])),...Mr()};function wo(){return typeof Deno<"u"&&typeof Deno.version<"u"}function ko(){return typeof process<"u"&&process.versions&&process.versions.node}function Ui(){return ko()?process.env.FORCE_COLOR||process.stdout.isTTY&&process.env.TERM!=="dumb":wo()?Deno.env.get("FORCE_COLOR")||Deno.isatty(Deno.stdout.rid)&&Deno.env.get("TERM")!=="dumb":!1}var So=()=>Ui()?Yt:Qt;var Br=()=>({colors:r,theme:e})=>{let t=e(r);function n(s){let a=s.stack?`
|
|
2335
2335
|
`+s.stack+`
|
|
2336
2336
|
`:"";return[t.errName(s.name+":"),t.errMessage(s.message)].join(" ")+t.errStack(a)}function o(s){return s&&s instanceof Error?n(s):s}function i(s){return s&&s instanceof Error?n(s):t.errMessage(s)}return{stdout:s=>s.map(o),stderr:s=>s.map(i)}};function Zt(...r){return e=>({stdout:t=>{for(let n of r)t=n(e).stdout(t);return t},stderr:t=>{for(let n of r)t=n(e).stderr(t);return t}})}function fc(){return{icon:"\u{1F6A8}",now:()=>Date.now()}}var Or=r=>({colors:e,theme:t})=>{let n={...fc(),...r},o=t(e),i=new Date(n.now()),s=i.getUTCFullYear().toString().padStart(4,"0"),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),c=i.getUTCDate().toString().padStart(2,"0"),l=`${s}-${a}-${c}`,d=i.getUTCHours().toString().padStart(2,"0"),u=i.getUTCMinutes().toString().padStart(2,"0"),f=i.getUTCSeconds().toString().padStart(2,"0"),m=i.getUTCMilliseconds().toString().padStart(3,"0"),p=`${d}:${u}:${f}.${m}`,g=`${l}::${p}`;return{stdout:x=>[o.timestamp(g),...x],stderr:x=>[o.timestampErr(g),...[n.icon].filter(Boolean),...x]}};function Ni(){return Zt(Br(),Or())}var zr=()=>({stdout:async r=>{await Deno.stdout.write(new TextEncoder().encode(r+`
|
|
2337
2337
|
`))},stderr:async r=>{await Deno.stderr.write(new TextEncoder().encode(r+`
|
|
2338
2338
|
`))}});var Ur=()=>({stdout:async r=>{process.stdout.write(r+`
|
|
2339
2339
|
`)},stderr:async r=>{process.stderr.write(r+`
|
|
2340
|
-
`)}});var Nr=()=>({stdout:async r=>console.log(r),stderr:async r=>console.error(r)});var Vi=()=>wo()?zr():ko()?Ur():Nr();var Li=()=>({stdout:async()=>{},stderr:async()=>{}});function Hi(){return()=>({stdout:r=>r,stderr:r=>r})}var bt=class r{static writers={auto:Vi,void:Li,deno:zr,node:Ur,console:Nr};static colors={auto:So,colorful:()=>Yt,colorless:()=>Qt};static themes={auto:Oi,basic:Rr};static shapers={auto:Ni,none:Hi,errors:Br,timestamp:Or};writer=r.writers.auto();colors=r.colors.auto();theme=r.themes.auto();shaper=r.shapers.auto();async log(...e){await this.writer.stdout(this.shaper(this).stdout(e).join(" "))}async error(...e){await this.writer.stderr(this.shaper(this).stderr(e).join(" "))}setWriter(e){return this.writer=e,this}setColors(e){return this.colors=e,this}setTheme(e){return this.theme=e,this}setShaper(...e){return this.shaper=Zt(...e),this}};var Jt=class extends bt{static dummy(){return new this().setWriter(bt.writers.void())}rpcRequest=async({request:e,...t})=>{let n=this.colors.none;this.log(...this.#e(t),n(`${e.method}()`))};rpcError=async({request:e,error:t,...n})=>{this.error(...this.#e(n),`${e.method}()`,t)};#e({meta:e,label:t,remote:n}){let o=this.colors.mix(this.colors.blue,this.colors.dim),i=this.colors.mix(this.colors.cyan,this.colors.dim);return[e?this.#t(e):void 0,t||void 0,n===void 0?void 0:n?o("<-"):i("->")].filter(Boolean)}#t(e){let{headers:t}=e.request;return[this.colors.yellow(`[${e.ip}]`),this.colors.green(t.origin?t.origin:"(no-origin)")].join(" ")}};var be=class extends Jt{rpcRequest=async()=>{}};var ve;(function(r){r.version="2.0";function e(t){return"id"in t?t.id:null}r.getId=e,r.errorCodes={serverError:-32e3,unexposedError:-32001}})(ve||(ve={}));var Vr=class extends Error{name=this.constructor.name},We=class extends Error{name=this.constructor.name};async function qi({tap:r,request:e,action:t}){let n=ve.getId(e);try{let o=await t();return n===null?null:{id:n,result:o,jsonrpc:ve.version}}catch(o){return r.rpcError({request:e,error:o}),n===null?null:{id:n,jsonrpc:ve.version,error:o instanceof Vr?{code:ve.errorCodes.serverError,message:o.message}:{code:ve.errorCodes.unexposedError,message:"unexposed error"}}}}function Lr(r){let e=r.tap??new be;return async t=>{let n=t.method.split("."),o=Bi(r.fns,n),i=async()=>await o(...t.params);return e.rpcRequest({request:t}),await qi({tap:e,request:t,action:i})}}var yt=Symbol("tune"),mc=Symbol("query"),pc=Symbol("notify"),hc=Symbol("settings");function Gi(r){function e(t){let n={notify:void 0};return new Proxy((()=>{}),{apply:(o,i,s)=>r(t,s,n),get:(o,i)=>{if(i!=="then")return i===yt?s=>(...a)=>r(t,a,{...n,...s}):i===pc?(...s)=>r(t,s,{...n,notify:!0}):i===mc?(...s)=>r(t,s,{...n,notify:!1}):i===hc?n:(o[i]||(o[i]=e([...t,i])),o[i])},set:(o,i,s)=>(o[i]=s,!0)})}return e([])}function je(r){let{endpoint:e,tap:t=new be}=r,n=1;return Gi(async(o,i,s)=>{let a=s.notify??r.notify??!1,c=s.transfer,l={jsonrpc:"2.0",method:o.join("."),params:i},d=a?l:{...l,id:n++};t.rpcRequest({request:d});let u=await e(d,{transfer:c});if(a&&!u)return null;if(!u)throw new We("response was null, but shouldn't be, because the request was not a notification");if("error"in u)throw new We(r.label?`${r.label}: ${u.error.message}`:u.error.message);return u.result})}function er(r){return je({endpoint:Lr(r),tap:r.tap})}var $e=class{recv=xt();sendRequest=xt();sendResponse=xt();static makeEntangledPair({origin:e="example.e280.org"}={}){let t=new this,n=new this,o=[t.sendRequest.sub(s=>n.recv(s,{origin:e})),t.sendResponse.sub(s=>n.recv(s,{origin:e})),n.sendRequest.sub(s=>t.recv(s,{origin:e})),n.sendResponse.sub(s=>t.recv(s,{origin:e}))];return[t,n,()=>o.forEach(s=>s())]}};function Hr(r,e){return r.addEventListener("message",e),()=>r.removeEventListener("message",e)}function Wi(r,e){return async(t,{transfer:n}={})=>{if("id"in t){let o=xe();return e(t,n,o.promise),r.wait(t.id,t.method).then(i=>(o.resolve(i),i))}else{let o=Promise.resolve(null);return e(t,n,o),o}}}function ji(r){let e=[],t=[];for(let n of Array.isArray(r)?r:[r])"method"in n?e.push(n):t.push(n);return{requests:e,responses:t}}async function $i(r,e){let t=(await Promise.all(e.map(async n=>r(n)))).filter(n=>n!==null);return t.length===0?null:t.length===1?t[0]:t}var Tt=class extends $e{dispose=Dr();constructor(e){super(),this.dispose.schedule(this.sendRequest.sub((t,n)=>e.postMessage(t,n)),this.sendResponse.sub((t,n)=>e.postMessage(t,n)),Hr(e,t=>this.recv(t.data,t)))}};var qr=class{remote;transfer;constructor(e){this.remote=e}};var vo=Object.freeze({timeout:6e4,maxRequestBytes:1e7});var Gr=class{timeout;pending=new Map;constructor(e){this.timeout=e}async wait(e,t){let n=xe();return this.pending.set(e,{method:t,deferred:n}),await Mi(this.timeout,()=>n.promise).catch(o=>{throw o instanceof Xt&&(o.message=`request #${e} ${t}(), ${o.message}`),o})}deliverResponse(e){let t=this.pending.get(e.id);t&&("error"in e?t.deferred.reject(new We(e.error.message)):t.deferred.resolve(e))}};var Ke=class{options;remote;remoteEndpoint;dispose=Dr();#e;constructor(e){this.options=e;let{conduit:t,tap:n}=e;this.#e=new Gr(e.timeout??vo.timeout),this.remoteEndpoint=Wi(this.#e,t.sendRequest.pub.bind(t.sendRequest)),this.remote=je({endpoint:this.remoteEndpoint,tap:n&&To(n,{remote:!0})}),this.dispose.schedule(t.recv.sub(o=>this.recv(o)))}async recv(e){let t=new qr(this.remote),{conduit:n,rpc:o,tap:i}=this.options,{requests:s,responses:a}=ji(e);for(let u of a)this.#e.deliverResponse(u);if(!o)return;let c=await o(t),l=Lr({fns:c,tap:i&&To(i,{remote:!1})}),d=await $i(l,s);d&&await n.sendResponse(d,t.transfer)}};var Pe={derive:{host:r=>({host:r.remote.host,get transfer(){return r.transfer},set transfer(e){r.transfer=e}}),work:r=>({work:r.remote,get transfer(){return r.transfer},set transfer(e){r.transfer=e}})},mock:{host:()=>({host:void 0,transfer:void 0}),work:()=>({work:void 0,transfer:void 0})}};var Ce=new be;async function Ki(r,e,t={}){let n=t.tap??Ce,o=new Ke({tap:n,timeout:t.timeout??1/0,conduit:new Tt(r.getSelf()),rpc:async i=>e(Pe.derive.host(i))});return await o.remote.infra.ready(),o.remote.host}var wt=class{worker;messenger;constructor(e,t){this.worker=e,this.messenger=t}static async make(e,t){let n=t.tap??Ce,o=t.label??"comrade",i=e.loadWorker(t.workerUrl,o),s=xe(),a={async ready(){s.resolve()}},c=new Ke({tap:n,timeout:t.timeout??1/0,conduit:new Tt(i),rpc:async l=>({infra:a,host:t.setupHost(Pe.derive.work(l))})});return await s.promise,new this(i,c)}get work(){return this.messenger.remote}terminate(){this.worker.terminate()}};var Wr=class{threads;static async make(e,t){let n=t.workerCount??e.guessOptimalThreadCount(),o=await Promise.all([...Array(n)].map(async(i,s)=>wt.make(e,{...t,label:t.label??`${t.label??"comrade"}_${s+1}`})));return new this(o,{tap:t.tap})}work;#e=new Set;#t=[];constructor(e,t={}){this.threads=e;let n=t.tap??Ce,o=async(i,s)=>this.#r({request:i,prom:xe(),transfer:s?.transfer});this.work=je({tap:n,endpoint:o}),e.forEach(i=>this.#e.add(i))}get threadCount(){return this.threads.length}terminate(){for(let e of this.threads)e.terminate()}#r(e){return this.#t.push(e),this.#n(),e.prom.promise}#n(){for(;this.#e.size>0&&this.#t.length>0;){let e=[...this.#e].pop();this.#e.delete(e);let t=this.#t.shift();this.#e.delete(e);let n=e.messenger.remoteEndpoint(t.request,{transfer:t.transfer});t.prom.entangle(n).finally(()=>{this.#e.add(e),this.#n()})}}};var Xi=r=>({thread:e=>wt.make(r,e),cluster:e=>Wr.make(r,e),worker:(e,t={})=>Ki(r,e,t),work:e=>e,host:e=>e,mocks(e){let{setupWork:t,setupHost:n,tap:o=Ce}=e,i=Pe.mock.host(),s=Pe.mock.work();return s.work=er({tap:o,fns:t(i)}),i.host=er({tap:o,fns:n(s)}),{workShell:s,hostShell:i,work:s.work,host:i.host}},mockWork(e,t=Ce){let n=Pe.mock.host(),o=Pe.mock.work();return o.work=er({tap:t,fns:e(n)}),{workShell:o,hostShell:n,work:o.work,mockHost:i=>(n.host=er({tap:t,fns:i(o)}),{workShell:o,hostShell:n,work:o.work,host:n.host})}}});var Qi=()=>({getSelf(){return self},guessOptimalThreadCount(){let r=navigator.hardwareConcurrency??1;return Math.max(1,r-1)},loadWorker(r,e){return new window.Worker(r,{name:e,type:"module"})},async loadWasm(r){return WebAssembly.instantiateStreaming(fetch(r))}});var bc=Qi(),jr=Xi(bc);function h(r){if(!r)throw new Error("Assertion failed.")}var $r=r=>{let e=(r%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${r}.`)},Y=r=>r&&r[r.length-1];var N=class r{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),o=(t&1<<n)>>n;return this.pos++,o}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let o=this.pos;o<n;o++){let i=Math.floor(o/8),s=this.bytes[i],a=7-(o&7);s&=~(1<<a),s|=(t&1<<n-o-1)>>n-o-1<<a,this.bytes[i]=s}this.pos=n}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new r(this.bytes);return e.pos=this.pos,e}},I=r=>{let e=0;for(;r.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+r.readBits(e)},Te=r=>{let e=I(r);return(e&1)===0?-(e>>1):e+1>>1};var le=r=>r.constructor===Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),z=r=>r.constructor===DataView?r:ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r),$=new TextDecoder;var _o=r=>Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),Eo={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Kr=_o(Eo),Fo={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Xr=_o(Fo),Do={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Qr=_o(Do);var Yr=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r),ye=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e,t=new Promise(o=>{e=o}),n=this.currentPromise;return this.currentPromise=t,await n,e}},Ro=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),Mo=r=>(r=r>>1&1431655765|(r&1431655765)<<1,r=r>>2&858993459|(r&858993459)<<2,r=r>>4&252645135|(r&252645135)<<4,r=r>>8&16711935|(r&16711935)<<8,r=r>>16&65535|(r&65535)<<16,r>>>0),Xe=(r,e,t)=>{let n=0,o=r.length-1,i=-1;for(;n<=o;){let s=n+o>>1,a=t(r[s]);a===e?(i=s,o=s-1):a<e?n=s+1:o=s-1}return i},B=(r,e,t)=>{let n=0,o=r.length-1,i=-1;for(;n<=o;){let s=n+(o-n+1)/2|0;t(r[s])<=e?(i=s,n=s+1):o=s-1}return i},Bo=(r,e,t)=>{let n=B(r,t(e),t);r.splice(n+1,0,e)},Z=()=>{let r,e;return{promise:new Promise((n,o)=>{r=n,e=o}),resolve:r,reject:e}};var Oo=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return r[t]},Zr=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1},Zi=async function*(r){Symbol.iterator in r?yield*r[Symbol.iterator]():yield*r[Symbol.asyncIterator]()},Ji=r=>{if(!(Symbol.iterator in r)&&!(Symbol.asyncIterator in r))throw new TypeError("Argument must be an iterable or async iterable.")},se=r=>{throw new Error(`Unexpected value: ${r}`)},Qe=(r,e,t)=>{let n=r.getUint8(e),o=r.getUint8(e+1),i=r.getUint8(e+2);return t?n|o<<8|i<<16:n<<16|o<<8|i},es=(r,e,t)=>Qe(r,e,t)<<8>>8,ts=(r,e,t,n)=>{t=t>>>0,t=t&16777215,n?(r.setUint8(e,t&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t>>>16&255)):(r.setUint8(e,t>>>16&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t&255))};var zo=(r,e)=>({async next(){let t=await r.next();return t.done?{value:void 0,done:!0}:{value:e(t.value),done:!1}},return(){return r.return()},throw(t){return r.throw(t)},[Symbol.asyncIterator](){return this}}),Ye=(r,e,t)=>Math.max(e,Math.min(t,r)),K="und",Ze=r=>{let e=Math.round(r);return Math.abs(r/e-1)<10*Number.EPSILON?e:r},rs=(r,e)=>Math.round(r/e)*e,ns=r=>{let e=0;for(;r;)e++,r>>=1;return e},yc=/^[a-z]{3}$/,Jr=r=>yc.test(r),we=1e6*(1+Number.EPSILON),Uo=(r,e)=>{let t={...r,...e};if(r.headers||e.headers){let n=r.headers?Yi(r.headers):{},o=e.headers?Yi(e.headers):{},i={...n};Object.entries(o).forEach(([s,a])=>{let c=Object.keys(i).find(l=>l.toLowerCase()===s.toLowerCase());c&&delete i[c],i[s]=a}),t.headers=i}return t},Yi=r=>{if(r instanceof Headers){let e={};return r.forEach((t,n)=>{e[n]=t}),e}if(Array.isArray(r)){let e={};return r.forEach(([t,n])=>{e[t]=n}),e}return r},No=async(r,e,t,n,o)=>{let i=0;for(;;)try{return await r(e,t)}catch(s){if(o())throw s;i++;let a=n(i,s,e);if(a===null)throw s;if(console.error("Retrying failed fetch. Error:",s),!Number.isFinite(a)||a<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(a>0&&await new Promise(c=>setTimeout(c,1e3*a)),o())throw s}};var tr=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},Po=null,Be=()=>Po!==null?Po:Po=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),Co=null,rr=()=>Co!==null?Co:Co=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),Io=null,nr=()=>Io!==null?Io:Io=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),Ao=null,os=()=>{if(Ao!==null)return Ao;if(typeof navigator>"u")return null;let r=/\bChrome\/(\d+)/.exec(navigator.userAgent);return r?Ao=Number(r[1]):null},Je=(r,e)=>r!==-1?r:e,en=(r,e,t,n)=>r<=n&&t<=e;var is=r=>{let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t};var tn=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},or=r=>typeof r=="number"&&!Number.isNaN(r);var Oe=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof t!="string")throw new TypeError("mimeType must be a string.")}},rn=class{constructor(e,t,n,o){if(this.data=e,this.mimeType=t,this.name=n,this.description=o,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!==void 0&&typeof t!="string")throw new TypeError("mimeType, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("name, when provided, must be a string.");if(o!==void 0&&typeof o!="string")throw new TypeError("description, when provided, must be a string.")}};var te={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};var ze=["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"],Tc=["aac","opus","mp3","vorbis","flac"],jm=[...Tc,...ze];var et=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}];var ss=".01.01.01.01.00",as=".0.110.01.01.01.0";var nn=r=>{let{codec:e,codecDescription:t,colorSpace:n,avcCodecInfo:o,hevcCodecInfo:i,vp9CodecInfo:s,av1CodecInfo:a}=r;if(e==="avc"){if(h(r.avcType!==null),o){let c=new Uint8Array([o.avcProfileIndication,o.profileCompatibility,o.avcLevelIndication]);return`avc${r.avcType}.${Ro(c)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${r.avcType}.${Ro(t.subarray(1,4))}`}else if(e==="hevc"){let c,l,d,u,f,m;if(i)c=i.generalProfileSpace,l=i.generalProfileIdc,d=Mo(i.generalProfileCompatibilityFlags),u=i.generalTierFlag,f=i.generalLevelIdc,m=[...i.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let g=z(t),x=g.getUint8(1);c=x>>6&3,l=x&31,d=Mo(g.getUint32(2)),u=x>>5&1,f=g.getUint8(12),m=[];for(let y=0;y<6;y++)m.push(g.getUint8(6+y))}let p="hev1.";for(p+=["","A","B","C"][c]+l,p+=".",p+=d.toString(16).toUpperCase(),p+=".",p+=u===0?"L":"H",p+=f;m.length>0&&m[m.length-1]===0;)m.pop();return m.length>0&&(p+=".",p+=m.map(g=>g.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!s){let y=r.width*r.height,b=Y(et).level;for(let w of et)if(y<=w.maxPictureSize){b=w.level;break}return`vp09.00.${b.toString().padStart(2,"0")}.08`}let c=s.profile.toString().padStart(2,"0"),l=s.level.toString().padStart(2,"0"),d=s.bitDepth.toString().padStart(2,"0"),u=s.chromaSubsampling.toString().padStart(2,"0"),f=s.colourPrimaries.toString().padStart(2,"0"),m=s.transferCharacteristics.toString().padStart(2,"0"),p=s.matrixCoefficients.toString().padStart(2,"0"),g=s.videoFullRangeFlag.toString().padStart(2,"0"),x=`vp09.${c}.${l}.${d}.${u}`;return x+=`.${f}.${m}.${p}.${g}`,x.endsWith(ss)&&(x=x.slice(0,-ss.length)),x}else if(e==="av1"){if(!a){let w=r.width*r.height,k=Y(et).level;for(let P of et)if(w<=P.maxPictureSize){k=P.level;break}return`av01.0.${k.toString().padStart(2,"0")}M.08`}let c=a.profile,l=a.level.toString().padStart(2,"0"),d=a.tier?"H":"M",u=a.bitDepth.toString().padStart(2,"0"),f=a.monochrome?"1":"0",m=100*a.chromaSubsamplingX+10*a.chromaSubsamplingY+1*(a.chromaSubsamplingX&&a.chromaSubsamplingY?a.chromaSamplePosition:0),p=n?.primaries?Eo[n.primaries]:1,g=n?.transfer?Fo[n.transfer]:1,x=n?.matrix?Do[n.matrix]:1,y=n?.fullRange?1:0,b=`av01.${c}.${l}${d}.${u}`;return b+=`.${f}.${m.toString().padStart(3,"0")}`,b+=`.${p.toString().padStart(2,"0")}`,b+=`.${g.toString().padStart(2,"0")}`,b+=`.${x.toString().padStart(2,"0")}`,b+=`.${y}`,b.endsWith(as)&&(b=b.slice(0,-as.length)),b}}throw new TypeError(`Unhandled codec '${e}'.`)};var on=r=>{let{codec:e,codecDescription:t,aacCodecInfo:n}=r;if(e==="aac"){if(!n)throw new TypeError("AAC codec info must be provided.");return n.isMpeg2?"mp4a.67":`mp4a.40.${Lo(t).objectType}`}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e&&ze.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},ir=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Vo=[-1,1,2,3,4,5,6,8],Lo=r=>{if(!r||r.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new N(r),t=e.readBits(5);t===31&&(t=32+e.readBits(6));let n=e.readBits(4),o=null;n===15?o=e.readBits(24):n<ir.length&&(o=ir[n]);let i=e.readBits(4),s=null;return i>=1&&i<=7&&(s=Vo[i]),{objectType:t,frequencyIndex:n,sampleRate:o,channelConfiguration:i,numberOfChannels:s}};var tt=48e3,wc=/^pcm-([usf])(\d+)+(be)?$/,sn=r=>{if(h(ze.includes(r)),r==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(r==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=wc.exec(r);h(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";let n=Number(e[2])/8,o=e[3]!=="be",i=r==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:n,littleEndian:o,silentValue:i}};var rt;(function(r){r[r.IDR=5]="IDR",r[r.SEI=6]="SEI",r[r.SPS=7]="SPS",r[r.PPS=8]="PPS",r[r.SPS_EXT=13]="SPS_EXT"})(rt||(rt={}));var J;(function(r){r[r.RASL_N=8]="RASL_N",r[r.RASL_R=9]="RASL_R",r[r.BLA_W_LP=16]="BLA_W_LP",r[r.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",r[r.VPS_NUT=32]="VPS_NUT",r[r.SPS_NUT=33]="SPS_NUT",r[r.PPS_NUT=34]="PPS_NUT",r[r.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",r[r.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(J||(J={}));var cn=r=>{let e=[],t=0;for(;t<r.length;){let n=-1,o=0;for(let i=t;i<r.length-3;i++){if(r[i]===0&&r[i+1]===0&&r[i+2]===1){n=i,o=3;break}if(i<r.length-4&&r[i]===0&&r[i+1]===0&&r[i+2]===0&&r[i+3]===1){n=i,o=4;break}}if(n===-1)break;if(t>0&&n>t){let i=r.subarray(t,n);i.length>0&&e.push(i)}t=n+o}if(t<r.length){let n=r.subarray(t);n.length>0&&e.push(n)}return e},us=(r,e)=>{let t=[],n=0,o=new DataView(r.buffer,r.byteOffset,r.byteLength);for(;n+e<=r.length;){let i;e===1?i=o.getUint8(n):e===2?i=o.getUint16(n,!1):e===3?i=Qe(o,n,!1):e===4?i=o.getUint32(n,!1):(se(e),h(!1)),n+=e;let s=r.subarray(n,n+i);t.push(s),n+=i}return t},an=r=>{let e=[],t=r.length;for(let n=0;n<t;n++)n+2<t&&r[n]===0&&r[n+1]===0&&r[n+2]===3?(e.push(0,0),n+=2):e.push(r[n]);return new Uint8Array(e)},Ho=new Uint8Array([0,0,0,1]),Sc=r=>{let e=r.reduce((o,i)=>o+Ho.byteLength+i.byteLength,0),t=new Uint8Array(e),n=0;for(let o of r)t.set(Ho,n),n+=Ho.byteLength,t.set(o,n),n+=o.byteLength;return t},vc=(r,e)=>{let t=r.reduce((i,s)=>i+e+s.byteLength,0),n=new Uint8Array(t),o=0;for(let i of r){let s=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(e){case 1:s.setUint8(o,i.byteLength);break;case 2:s.setUint16(o,i.byteLength,!1);break;case 3:ts(s,o,i.byteLength,!1);break;case 4:s.setUint32(o,i.byteLength,!1);break}o+=e,n.set(i,o),o+=i.byteLength}return n},qo=(r,e)=>{if(e.description){let o=(le(e.description)[4]&3)+1;return us(r,o)}else return cn(r)},ds=(r,e)=>{if(e.description){let o=(le(e.description)[4]&3)+1;return vc(r,o)}else return Sc(r)},nt=r=>r[0]&31,fs=r=>{try{let e=cn(r),t=e.filter(c=>nt(c)===rt.SPS),n=e.filter(c=>nt(c)===rt.PPS),o=e.filter(c=>nt(c)===rt.SPS_EXT);if(t.length===0||n.length===0)return null;let i=t[0],s=Go(i);h(s!==null);let a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:n,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?o:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}};var ms=r=>{try{let e=z(r),t=0,n=e.getUint8(t++),o=e.getUint8(t++),i=e.getUint8(t++),s=e.getUint8(t++),a=e.getUint8(t++)&3,c=e.getUint8(t++)&31,l=[];for(let m=0;m<c;m++){let p=e.getUint16(t,!1);t+=2,l.push(r.subarray(t,t+p)),t+=p}let d=e.getUint8(t++),u=[];for(let m=0;m<d;m++){let p=e.getUint16(t,!1);t+=2,u.push(r.subarray(t,t+p)),t+=p}let f={configurationVersion:n,avcProfileIndication:o,profileCompatibility:i,avcLevelIndication:s,lengthSizeMinusOne:a,sequenceParameterSets:l,pictureParameterSets:u,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((o===100||o===110||o===122||o===144)&&t+4<=r.length){let m=e.getUint8(t++)&3,p=e.getUint8(t++)&7,g=e.getUint8(t++)&7,x=e.getUint8(t++);f.chromaFormat=m,f.bitDepthLumaMinus8=p,f.bitDepthChromaMinus8=g;let y=[];for(let b=0;b<x;b++){let w=e.getUint16(t,!1);t+=2,y.push(r.subarray(t,t+w)),t+=w}f.sequenceParameterSetExt=y}return f}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}},Go=r=>{try{let e=new N(an(r));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let n=e.readAlignedByte(),o=e.readAlignedByte(),i=e.readAlignedByte();I(e);let s=null,a=null,c=null;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(s=I(e),s===3&&e.skipBits(1),a=I(e),c=I(e),e.skipBits(1),e.readBits(1))){for(let f=0;f<(s!==3?8:12);f++)if(e.readBits(1)){let p=f<6?16:64,g=8,x=8;for(let y=0;y<p;y++){if(x!==0){let b=Te(e);x=(g+b+256)%256}g=x===0?g:x}}}I(e);let l=I(e);if(l===0)I(e);else if(l===1){e.skipBits(1),Te(e),Te(e);let u=I(e);for(let f=0;f<u;f++)Te(e)}I(e),e.skipBits(1),I(e),I(e);let d=e.readBits(1);return{profileIdc:n,constraintFlags:o,levelIdc:i,frameMbsOnlyFlag:d,chromaFormatIdc:s,bitDepthLumaMinus8:a,bitDepthChromaMinus8:c}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},Wo=(r,e)=>{if(e.description){let o=(le(e.description)[21]&3)+1;return us(r,o)}else return cn(r)},Ie=r=>r[0]>>1&63,ps=r=>{try{let e=cn(r),t=e.filter(O=>Ie(O)===J.VPS_NUT),n=e.filter(O=>Ie(O)===J.SPS_NUT),o=e.filter(O=>Ie(O)===J.PPS_NUT),i=e.filter(O=>Ie(O)===J.PREFIX_SEI_NUT||Ie(O)===J.SUFFIX_SEI_NUT);if(n.length===0||o.length===0)return null;let s=n[0],a=new N(an(s));a.skipBits(16),a.readBits(4);let c=a.readBits(3),l=a.readBits(1),{general_profile_space:d,general_tier_flag:u,general_profile_idc:f,general_profile_compatibility_flags:m,general_constraint_indicator_flags:p,general_level_idc:g}=Pc(a,c);I(a);let x=I(a);x===3&&a.skipBits(1),I(a),I(a),a.readBits(1)&&(I(a),I(a),I(a),I(a));let y=I(a),b=I(a);I(a);let k=a.readBits(1)?0:c;for(let O=k;O<=c;O++)I(a),I(a),I(a);I(a),I(a),I(a),I(a),I(a),I(a),a.readBits(1)&&a.readBits(1)&&Cc(a),a.skipBits(1),a.skipBits(1),a.readBits(1)&&(a.skipBits(4),a.skipBits(4),I(a),I(a),a.skipBits(1));let P=I(a);if(Ic(a,P),a.readBits(1)){let O=I(a);for(let R=0;R<O;R++)I(a),a.skipBits(1)}a.skipBits(1),a.skipBits(1);let S=0;a.readBits(1)&&(S=_c(a,c));let _=0;if(o.length>0){let O=o[0],R=new N(an(O));R.skipBits(16),I(R),I(R),R.skipBits(1),R.skipBits(1),R.skipBits(3),R.skipBits(1),R.skipBits(1),I(R),I(R),Te(R),R.skipBits(1),R.skipBits(1),R.readBits(1)&&I(R),Te(R),Te(R),R.skipBits(1),R.skipBits(1),R.skipBits(1),R.skipBits(1);let j=R.readBits(1),Ge=R.readBits(1);!j&&!Ge?_=0:j&&!Ge?_=2:!j&&Ge?_=3:_=0}let C=[...t.length?[{arrayCompleteness:1,nalUnitType:J.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:J.SPS_NUT,nalUnits:n}]:[],...o.length?[{arrayCompleteness:1,nalUnitType:J.PPS_NUT,nalUnits:o}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ie(i[0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:d,generalTierFlag:u,generalProfileIdc:f,generalProfileCompatibilityFlags:m,generalConstraintIndicatorFlags:p,generalLevelIdc:g,minSpatialSegmentationIdc:S,parallelismType:_,chromaFormatIdc:x,bitDepthLumaMinus8:y,bitDepthChromaMinus8:b,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:l,lengthSizeMinusOne:3,arrays:C}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},Pc=(r,e)=>{let t=r.readBits(2),n=r.readBits(1),o=r.readBits(5),i=0;for(let d=0;d<32;d++)i=i<<1|r.readBits(1);let s=new Uint8Array(6);for(let d=0;d<6;d++)s[d]=r.readBits(8);let a=r.readBits(8),c=[],l=[];for(let d=0;d<e;d++)c.push(r.readBits(1)),l.push(r.readBits(1));if(e>0)for(let d=e;d<8;d++)r.skipBits(2);for(let d=0;d<e;d++)c[d]&&r.skipBits(88),l[d]&&r.skipBits(8);return{general_profile_space:t,general_tier_flag:n,general_profile_idc:o,general_profile_compatibility_flags:i,general_constraint_indicator_flags:s,general_level_idc:a}},Cc=r=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!r.readBits(1))I(r);else{let o=Math.min(64,1<<4+(e<<1));e>1&&Te(r);for(let i=0;i<o;i++)Te(r)}},Ic=(r,e)=>{let t=[];for(let n=0;n<e;n++)t[n]=Ac(r,n,e,t)},Ac=(r,e,t,n)=>{let o=0,i=0,s=0;if(e!==0&&(i=r.readBits(1)),i){if(e===t){let c=I(r);s=e-(c+1)}else s=e-1;r.readBits(1),I(r);let a=n[s]??0;for(let c=0;c<=a;c++)r.readBits(1)||r.readBits(1);o=n[s]}else{let a=I(r),c=I(r);for(let l=0;l<a;l++)I(r),r.readBits(1);for(let l=0;l<c;l++)I(r),r.readBits(1);o=a+c}return o},_c=(r,e)=>{if(r.readBits(1)&&r.readBits(8)===255&&(r.readBits(16),r.readBits(16)),r.readBits(1)&&r.readBits(1),r.readBits(1)&&(r.readBits(3),r.readBits(1),r.readBits(1)&&(r.readBits(8),r.readBits(8),r.readBits(8))),r.readBits(1)&&(I(r),I(r)),r.readBits(1),r.readBits(1),r.readBits(1),r.readBits(1)&&(I(r),I(r),I(r),I(r)),r.readBits(1)&&(r.readBits(32),r.readBits(32),r.readBits(1)&&I(r),r.readBits(1)&&Ec(r,!0,e)),r.readBits(1)){r.readBits(1),r.readBits(1),r.readBits(1);let t=I(r);return I(r),I(r),I(r),I(r),t}return 0},Ec=(r,e,t)=>{let n=!1,o=!1,i=!1;e&&(n=r.readBits(1)===1,o=r.readBits(1)===1,(n||o)&&(i=r.readBits(1)===1,i&&(r.readBits(8),r.readBits(5),r.readBits(1),r.readBits(5)),r.readBits(4),r.readBits(4),i&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5)));for(let s=0;s<=t;s++){let a=r.readBits(1)===1,c=!0;a||(c=r.readBits(1)===1);let l=!1;c?I(r):l=r.readBits(1)===1;let d=1;l||(d=I(r)+1),n&&cs(r,d,i),o&&cs(r,d,i)}},cs=(r,e,t)=>{for(let n=0;n<e;n++)I(r),I(r),t&&(I(r),I(r)),r.readBits(1)};var ln=r=>{let e=new N(r);if(e.readBits(2)!==2)return null;let n=e.readBits(1),i=(e.readBits(1)<<1)+n;if(i===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;i>=2&&(l=e.readBits(1)?12:10);let d=e.readBits(3),u=0,f=0;if(d!==7)if(f=e.readBits(1),i===1||i===3){let _=e.readBits(1),C=e.readBits(1);u=!_&&!C?3:_&&!C?2:1,e.skipBits(1)}else u=1;else u=3,f=1;let m=e.readBits(16),p=e.readBits(16),g=m+1,x=p+1,y=g*x,b=Y(et).level;for(let S of et)if(y<=S.maxPictureSize){b=S.level;break}return{profile:i,level:b,bitDepth:l,chromaSubsampling:u,videoFullRangeFlag:f,colourPrimaries:d===2?1:d===1?6:2,transferCharacteristics:d===2?1:d===1?6:2,matrixCoefficients:d===7?0:d===2?1:d===1?6:2}},hs=function*(r){let e=new N(r),t=()=>{let n=0;for(let o=0;o<8;o++){let i=e.readAlignedByte();if(n|=(i&127)<<o*7,!(i&128))break;if(o===7&&i&128)return null}return n>=2**32-1?null:n};for(;e.getBitsLeft()>=8;){e.skipBits(1);let n=e.readBits(4),o=e.readBits(1),i=e.readBits(1);e.skipBits(1),o&&e.skipBits(8);let s;if(i){let a=t();if(a===null)return;s=a}else s=Math.floor(e.getBitsLeft()/8);h(e.pos%8===0),yield{type:n,data:r.subarray(e.pos/8,e.pos/8+s)},e.skipBits(s*8)}},un=r=>{for(let{type:e,data:t}of hs(r)){if(e!==1)continue;let n=new N(t),o=n.readBits(3),i=n.readBits(1),s=n.readBits(1),a=0,c=0,l=0;if(s)a=n.readBits(5);else{if(n.readBits(1)&&(n.skipBits(32),n.skipBits(32),n.readBits(1)))return null;let S=n.readBits(1);S&&(l=n.readBits(5),n.skipBits(32),n.skipBits(5),n.skipBits(5));let _=n.readBits(5);for(let C=0;C<=_;C++){n.skipBits(12);let F=n.readBits(5);if(C===0&&(a=F),F>7){let R=n.readBits(1);C===0&&(c=R)}if(S&&n.readBits(1)){let j=l+1;n.skipBits(j),n.skipBits(j),n.skipBits(1)}n.readBits(1)&&n.skipBits(4)}}let d=n.readBits(4),u=n.readBits(4),f=d+1;n.skipBits(f);let m=u+1;n.skipBits(m);let p=0;if(s?p=0:p=n.readBits(1),p&&(n.skipBits(4),n.skipBits(3)),n.skipBits(1),n.skipBits(1),n.skipBits(1),!s){n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let P=n.readBits(1);P&&(n.skipBits(1),n.skipBits(1));let S=n.readBits(1),_=0;S?_=2:_=n.readBits(1),_>0&&(n.readBits(1)||n.skipBits(1)),P&&n.skipBits(3)}n.skipBits(1),n.skipBits(1),n.skipBits(1);let g=n.readBits(1),x=8;o===2&&g?x=n.readBits(1)?12:10:o<=2&&(x=g?10:8);let y=0;o!==1&&(y=n.readBits(1));let b=1,w=1,k=0;return y||(o===0?(b=1,w=1):o===1?(b=0,w=0):x===12&&(b=n.readBits(1),b&&(w=n.readBits(1))),b&&w&&(k=n.readBits(2))),{profile:o,level:a,tier:c,bitDepth:x,monochrome:y,chromaSubsamplingX:b,chromaSubsamplingY:w,chromaSamplePosition:k}}return null},gs=r=>{let e=z(r),t=e.getUint8(9),n=e.getUint16(10,!0),o=e.getUint32(12,!0),i=e.getInt16(16,!0),s=e.getUint8(18),a=null;return s&&(a=r.subarray(19,21+t)),{outputChannelCount:t,preSkip:n,inputSampleRate:o,outputGain:i,channelMappingFamily:s,channelMappingTable:a}},Fc=[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],xs=r=>{let e=r[0]>>3;return{durationInSamples:Fc[e]}},bs=r=>{if(r.length<7)throw new Error("Setup header is too short.");if(r[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...r.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let t=r.length,n=new Uint8Array(t);for(let u=0;u<t;u++)n[u]=r[t-1-u];let o=new N(n),i=0;for(;o.getBitsLeft()>97;)if(o.readBits(1)===1){i=o.pos;break}if(i===0)throw new Error("Invalid Setup header: framing bit not found.");let s=0,a=!1,c=0;for(;o.getBitsLeft()>=97;){let u=o.pos,f=o.readBits(8),m=o.readBits(16),p=o.readBits(16);if(f>63||m!==0||p!==0){o.pos=u;break}if(o.skipBits(1),s++,s>64)break;o.clone().readBits(6)+1===s&&(a=!0,c=s)}if(!a)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);let l=c;o.pos=0,o.skipBits(i);let d=Array(l).fill(0);for(let u=l-1;u>=0;u--)o.skipBits(40),d[u]=o.readBits(1);return{modeBlockflags:d}},dn=(r,e,t)=>{switch(r){case"avc":{let n=qo(t,e),o=n.some(i=>nt(i)===rt.IDR);if(!o&&(!nr()||os()>=144))for(let i of n){if(nt(i)!==rt.SEI)continue;let a=an(i),c=1;do{let l=0;for(;;){let f=a[c++];if(f===void 0||(l+=f,f<255))break}let d=0;for(;;){let f=a[c++];if(f===void 0||(d+=f,f<255))break}if(l===6){let f=new N(a);f.pos=8*c;let m=I(f),p=f.readBits(1);if(m===0&&p===1){o=!0;break}}c+=d}while(c<a.length-1)}return o?"key":"delta"}case"hevc":return Wo(t,e).some(i=>{let s=Ie(i);return J.BLA_W_LP<=s&&s<=J.RSV_IRAP_VCL23})?"key":"delta";case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{let n=new N(t);if(n.readBits(2)!==2)return null;let o=n.readBits(1);return(n.readBits(1)<<1)+o===3&&n.skipBits(1),n.readBits(1)?null:n.readBits(1)===0?"key":"delta"}case"av1":{let n=!1;for(let{type:o,data:i}of hs(t))if(o===1){let s=new N(i);s.skipBits(4),n=!!s.readBits(1)}else if(o===3||o===6||o===7){if(n)return"key";let s=new N(i);return s.readBits(1)?null:s.readBits(2)===0?"key":"delta"}return null}default:se(r),h(!1)}},Ue;(function(r){r[r.STREAMINFO=0]="STREAMINFO",r[r.VORBIS_COMMENT=4]="VORBIS_COMMENT",r[r.PICTURE=6]="PICTURE"})(Ue||(Ue={}));var sr=(r,e)=>{let t=z(r),n=0,o=t.getUint32(n,!0);n+=4;let i=$.decode(r.subarray(n,n+o));n+=o,o>0&&(e.raw??={},e.raw.vendor??=i);let s=t.getUint32(n,!0);n+=4;for(let a=0;a<s;a++){let c=t.getUint32(n,!0);n+=4;let l=$.decode(r.subarray(n,n+c));n+=c;let d=l.indexOf("=");if(d===-1)continue;let u=l.slice(0,d).toUpperCase(),f=l.slice(d+1);switch(e.raw??={},e.raw[u]??=f,u){case"TITLE":e.title??=f;break;case"DESCRIPTION":e.description??=f;break;case"ARTIST":e.artist??=f;break;case"ALBUM":e.album??=f;break;case"ALBUMARTIST":e.albumArtist??=f;break;case"COMMENT":e.comment??=f;break;case"LYRICS":e.lyrics??=f;break;case"TRACKNUMBER":{let m=f.split("/"),p=Number.parseInt(m[0],10),g=m[1]&&Number.parseInt(m[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),g&&Number.isInteger(g)&&g>0&&(e.tracksTotal??=g)}break;case"TRACKTOTAL":{let m=Number.parseInt(f,10);Number.isInteger(m)&&m>0&&(e.tracksTotal??=m)}break;case"DISCNUMBER":{let m=f.split("/"),p=Number.parseInt(m[0],10),g=m[1]&&Number.parseInt(m[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),g&&Number.isInteger(g)&&g>0&&(e.discsTotal??=g)}break;case"DISCTOTAL":{let m=Number.parseInt(f,10);Number.isInteger(m)&&m>0&&(e.discsTotal??=m)}break;case"DATE":{let m=new Date(f);Number.isNaN(m.getTime())||(e.date??=m)}break;case"GENRE":e.genre??=f;break;case"METADATA_BLOCK_PICTURE":{let m=is(f),p=z(m),g=p.getUint32(0,!1),x=p.getUint32(4,!1),y=String.fromCharCode(...m.subarray(8,8+x)),b=p.getUint32(8+x,!1),w=$.decode(m.subarray(12+x,12+x+b)),k=p.getUint32(x+b+28),P=m.subarray(x+b+32,x+b+32+k);e.images??=[],e.images.push({data:P,mimeType:y,kind:g===3?"coverFront":g===4?"coverBack":"unknown",name:void 0,description:w||void 0})}break}}};var Q=class{constructor(e){this.input=e}};var fn=[],mn=[];var H=new Uint8Array(0),V=class r{constructor(e,t,n,o,i=-1,s,a){if(this.data=e,this.type=t,this.timestamp=n,this.duration=o,this.sequenceNumber=i,e===H&&s===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(s===void 0&&(s=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(n))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(o)||o<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(i))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");if(a!==void 0&&(typeof a!="object"||!a))throw new TypeError("sideData, when provided, must be an object.");if(a?.alpha!==void 0&&!(a.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(a?.alphaByteLength!==void 0&&(!Number.isInteger(a.alphaByteLength)||a.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=a??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===H}get microsecondTimestamp(){return Math.trunc(we*this.timestamp)}get microsecondDuration(){return Math.trunc(we*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let n=new Uint8Array(e.byteLength);return e.copyTo(n),new r(n,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");return new r(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}};var ys=r=>{let t=0,n=0,o=~r;o&128&&(o&=-129,t=-1),n=((o&240)>>4)+5;let i=(1<<n|(o&15)<<n-4|1<<n-5)-33;return t===0?i:-i};var Ts=r=>{let e=0,t=0,n=r^85;n&128&&(n&=-129,e=-1),t=((n&240)>>4)+4;let o=0;return t!==4?o=1<<t|(n&15)<<t-4|1<<t-5:o=n<<1|1,e===0?o:-o};tn();var ws=-1/0,ks=-1/0,lr=null;typeof FinalizationRegistry<"u"&&(lr=new FinalizationRegistry(r=>{let e=Date.now();r.type==="video"?(e-ws>=1e3&&(console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),ws=e),typeof VideoFrame<"u"&&r.data instanceof VideoFrame&&r.data.close()):(e-ks>=1e3&&(console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),ks=e),typeof AudioData<"u"&&r.data instanceof AudioData&&r.data.close())}));var vs=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Dc=new Set(vs),St=class r{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(we*this.timestamp)}get microsecondDuration(){return Math.trunc(we*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.format===void 0||!Dc.has(t.format))throw new TypeError("init.format must be one of: "+vs.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=le(e).slice(),this._layout=t.layout??Rc(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new cr(t.colorSpace)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(t?.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t?.timestamp!==void 0&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this._layout=null,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=t?.rotation??0,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new cr(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new r(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*we),duration:Math.trunc((t.duration??0)*we)||void 0}),t);let n=0,o=0;if("naturalWidth"in e?(n=e.naturalWidth,o=e.naturalHeight):"videoWidth"in e?(n=e.videoWidth,o=e.videoHeight):"width"in e&&(n=Number(e.width),o=Number(e.height)),!n||!o)throw new TypeError("Could not determine dimensions.");let i=new OffscreenCanvas(n,o),s=i.getContext("2d",{alpha:rr(),willReadFrequently:!0});h(s),s.drawImage(e,0,0),this._data=i,this._layout=null,this.format="RGBX",this.codedWidth=n,this.codedHeight=o,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new cr({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");lr?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return h(this._data!==null),ot(this._data)?new r(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(h(this._layout),new r(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})):new r(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){this._closed||(lr?.unregister(this),ot(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Ss(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)===null)throw new Error("Cannot get allocation size when format is null. Please manually provide an RGB pixel format in the options instead.");if(h(this._data!==null),!ot(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let t=this.toVideoFrame(),n=t.allocationSize(e);return t.close(),n}return ot(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,t={}){if(!Yr(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ss(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)===null)throw new Error("Cannot copy video sample data when format is null. Please manually provide an RGB pixel format in the options instead.");if(h(this._data!==null),!ot(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){let n=this.toVideoFrame(),o=await n.copyTo(e,t);return n.close(),o}if(ot(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array)return h(this._layout),le(e).set(this._data),this._layout;{let o=this._data.getContext("2d");h(o);let i=o.getImageData(0,0,this.codedWidth,this.codedHeight);return le(e).set(i.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return h(this._data!==null),ot(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,n,o,i,s,a,c,l){let d=0,u=0,f=this.displayWidth,m=this.displayHeight,p=0,g=0,x=this.displayWidth,y=this.displayHeight;if(s!==void 0?(d=t,u=n,f=o,m=i,p=s,g=a,c!==void 0?(x=c,y=l):(x=f,y=m)):(p=t,g=n,o!==void 0&&(x=o,y=i)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(d))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(m)||m<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(g))throw new TypeError("dy must be a number.");if(!Number.isFinite(x)||x<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:d,sy:u,sWidth:f,sHeight:m}=this._rotateSourceRegion(d,u,f,m,this.rotation));let b=this.toCanvasImageSource();e.save();let w=p+x/2,k=g+y/2;e.translate(w,k),e.rotate(this.rotation*Math.PI/180);let P=this.rotation%180===0?1:x/y;e.scale(1/P,P),e.drawImage(b,d,u,f,m,-x/2,-y/2,x,y),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");t.crop!==void 0&&Ko(t.crop,"options.");let n=e.canvas.width,o=e.canvas.height,i=t.rotation??this.rotation,[s,a]=i%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];t.crop&&$o(t.crop,s,a);let c,l,d,u,{sx:f,sy:m,sWidth:p,sHeight:g}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??s,t.crop?.height??a,i);if(t.fit==="fill")c=0,l=0,d=n,u=o;else{let[y,b]=t.crop?[t.crop.width,t.crop.height]:[s,a],w=t.fit==="contain"?Math.min(n/y,o/b):Math.max(n/y,o/b);d=y*w,u=b*w,c=(n-d)/2,l=(o-u)/2}e.save();let x=i%180===0?1:d/u;e.translate(n/2,o/2),e.rotate(i*Math.PI/180),e.scale(1/x,x),e.translate(-n/2,-o/2),e.drawImage(this.toCanvasImageSource(),f,m,p,g,c,l,d,u),e.restore()}_rotateSourceRegion(e,t,n,o,i){return i===90?[e,t,n,o]=[t,this.codedHeight-e-n,o,n]:i===180?[e,t]=[this.codedWidth-e-n,this.codedHeight-t-o]:i===270&&([e,t,n,o]=[this.codedWidth-t-o,e,o,n]),{sx:e,sy:t,sWidth:n,sHeight:o}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(h(this._data!==null),this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}},cr=class{constructor(e){this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},ot=r=>typeof VideoFrame<"u"&&r instanceof VideoFrame,$o=(r,e,t)=>{r.left=Math.min(r.left,e),r.top=Math.min(r.top,t),r.width=Math.min(r.width,e-r.left),r.height=Math.min(r.height,t-r.top),h(r.width>=0),h(r.height>=0)},Ko=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},Ss=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.colorSpace!==void 0&&!["display-p3","srgb"].includes(r.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(r.format!==void 0&&typeof r.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(r.layout!==void 0){if(!Array.isArray(r.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let e of r.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(r.rect!==void 0){if(!r.rect||typeof r.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(r.rect.x!==void 0&&(!Number.isInteger(r.rect.x)||r.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(r.rect.y!==void 0&&(!Number.isInteger(r.rect.y)||r.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(r.rect.width!==void 0&&(!Number.isInteger(r.rect.width)||r.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(r.rect.height!==void 0&&(!Number.isInteger(r.rect.height)||r.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},Rc=(r,e,t)=>{let n=Mc(r),o=[],i=0;for(let s of n){let a=Math.ceil(e/s.widthDivisor),c=Math.ceil(t/s.heightDivisor),l=a*s.sampleBytes,d=l*c;o.push({offset:i,stride:l}),i+=d}return o},Mc=r=>{let e=(t,n,o,i,s)=>{let a=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:n,widthDivisor:o,heightDivisor:i},{sampleBytes:n,widthDivisor:o,heightDivisor:i}];return s&&a.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),a};switch(r){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:se(r),h(!1)}},jo=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),vt=class r{get microsecondTimestamp(){return Math.trunc(we*this.timestamp)}get microsecondDuration(){return Math.trunc(we*this.duration)}constructor(e){if(this._closed=!1,ar(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!jo.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");let t=e.data.byteLength/(it(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let n;if(e.data instanceof ArrayBuffer)n=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))n=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let o=this.numberOfFrames*this.numberOfChannels*it(this.format);if(n.byteLength<o)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=n}lr?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!jo.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let t=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let o=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-n;if(o>this.numberOfFrames-n)throw new RangeError("frameCount out of range");let i=it(t),s=kt(t);if(s&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!s&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(s?o:o*this.numberOfChannels)*i}copyTo(e,t){if(!Yr(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!jo.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{planeIndex:n,format:o,frameCount:i,frameOffset:s}=t,a=this.format,c=o??this.format;if(!c)throw new Error("Destination format not determined");let l=this.numberOfFrames,d=this.numberOfChannels,u=s??0;if(u>=l)throw new RangeError("frameOffset out of range");let f=i!==void 0?i:l-u;if(f>l-u)throw new RangeError("frameCount out of range");let m=it(c),p=kt(c);if(p&&n>=d)throw new RangeError("planeIndex out of range");if(!p&&n!==0)throw new RangeError("planeIndex out of range");let x=(p?f:f*d)*m;if(e.byteLength<x)throw new RangeError("Destination buffer is too small");let y=z(e),b=Cs(c);if(ar(this._data))Be()&&d>2&&c!==a?Bc(this._data,y,a,c,d,n,u,f):this._data.copyTo(e,{planeIndex:n,frameOffset:u,frameCount:f,format:c});else{let w=this._data,k=z(w),P=Ps(a),S=it(a),_=kt(a);for(let C=0;C<f;C++)if(p){let F=C*m,O;_?O=(n*l+(C+u))*S:O=((C+u)*d+n)*S;let R=P(k,O);b(y,F,R)}else for(let F=0;F<d;F++){let R=(C*d+F)*m,j;_?j=(F*l+(C+u))*S:j=((C+u)*d+F)*S;let Ge=P(k,j);b(y,R,Ge)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(ar(this._data)){let e=new r(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new r({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(lr?.unregister(this),ar(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(ar(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(kt(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(t,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{let e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(t,{planeIndex:n,format:"f32-planar"}),e.copyToChannel(t,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,o=e.numberOfChannels,i=e.sampleRate,s=e.length,a=Math.floor(n/o),c=0,l=s;for(;l>0;){let d=Math.min(a,l),u=new Float32Array(o*d);for(let f=0;f<o;f++)e.copyFromChannel(u.subarray(f*d,(f+1)*d),f,c);yield new r({format:"f32-planar",sampleRate:i,numberOfFrames:d,numberOfChannels:o,timestamp:t+c/i,data:u}),c+=d,l-=d}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,o=e.numberOfChannels,i=e.sampleRate,s=e.length,a=Math.floor(n/o),c=0,l=s,d=[];for(;l>0;){let u=Math.min(a,l),f=new Float32Array(o*u);for(let p=0;p<o;p++)e.copyFromChannel(f.subarray(p*u,(p+1)*u),p,c);let m=new r({format:"f32-planar",sampleRate:i,numberOfFrames:u,numberOfChannels:o,timestamp:t+c/i,data:f});d.push(m),c+=u,l-=u}return d}},it=r=>{switch(r){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},kt=r=>{switch(r){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Ps=r=>{switch(r){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},Cs=r=>{switch(r){case"u8":case"u8-planar":return(e,t,n)=>e.setUint8(t,Ye((n+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,n)=>e.setInt16(t,Ye(Math.round(n*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,n)=>e.setInt32(t,Ye(Math.round(n*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,n)=>e.setFloat32(t,n,!0)}},ar=r=>typeof AudioData<"u"&&r instanceof AudioData,Bc=(r,e,t,n,o,i,s,a)=>{let c=Ps(t),l=Cs(n),d=it(t),u=it(n),f=kt(t);if(kt(n))if(f){let p=new ArrayBuffer(a*d),g=z(p);r.copyTo(p,{planeIndex:i,frameOffset:s,frameCount:a,format:t});for(let x=0;x<a;x++){let y=x*d,b=x*u,w=c(g,y);l(e,b,w)}}else{let p=new ArrayBuffer(a*o*d),g=z(p);r.copyTo(p,{planeIndex:0,frameOffset:s,frameCount:a,format:t});for(let x=0;x<a;x++){let y=(x*o+i)*d,b=x*u,w=c(g,y);l(e,b,w)}}else if(f){let p=a*d,g=new ArrayBuffer(p),x=z(g);for(let y=0;y<o;y++){r.copyTo(g,{planeIndex:y,frameOffset:s,frameCount:a,format:t});for(let b=0;b<a;b++){let w=b*d,k=(b*o+y)*u,P=c(x,w);l(e,k,P)}}}else{let p=new ArrayBuffer(a*o*d),g=z(p);r.copyTo(p,{planeIndex:0,frameOffset:s,frameCount:a,format:t});for(let x=0;x<a;x++)for(let y=0;y<o;y++){let b=x*o+y,w=b*d,k=b*u,P=c(g,w);l(e,k,P)}}};var Pt=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.metadataOnly!==void 0&&typeof r.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(r.verifyKeyPackets!==void 0&&typeof r.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(r.verifyKeyPackets&&r.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},Ne=r=>{if(!or(r))throw new TypeError("timestamp must be a number.")},Xo=(r,e,t)=>t.verifyKeyPackets?e.then(async n=>{if(!n||n.type==="delta")return n;let o=await r.determinePacketType(n);return o&&(n.type=o),n}):e,st=class{constructor(e){if(!(e instanceof It))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(Pt(e),this._track.input._disposed)throw new q;return Xo(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){if(Ne(e),Pt(t),this._track.input._disposed)throw new q;return Xo(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof V))throw new TypeError("packet must be an EncodedPacket.");if(Pt(t),this._track.input._disposed)throw new q;return Xo(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Ne(e),Pt(t),this._track.input._disposed)throw new q;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let n=await this._track._backing.getKeyPacket(e,t);return n&&(h(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getKeyPacket(n.timestamp-1/this._track.timeResolution,t):n)}async getNextKeyPacket(e,t={}){if(!(e instanceof V))throw new TypeError("packet must be an EncodedPacket.");if(Pt(t),this._track.input._disposed)throw new q;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let n=await this._track._backing.getNextKeyPacket(e,t);return n&&(h(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getNextKeyPacket(n,t):n)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof V))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof V))throw new TypeError("endPacket must be an EncodedPacket.");if(Pt(n),this._track.input._disposed)throw new q;let o=[],{promise:i,resolve:s}=Z(),{promise:a,resolve:c}=Z(),l=!1,d=!1,u=null,f=[],m=()=>Math.max(2,f.length);(async()=>{let g=e??await this.getFirstPacket(n);for(;g&&!d&&!this._track.input._disposed&&!(t&&g.sequenceNumber>=t?.sequenceNumber);){if(o.length>m()){({promise:a,resolve:c}=Z()),await a;continue}o.push(g),s(),{promise:i,resolve:s}=Z(),g=await this.getNextPacket(g,n)}l=!0,s()})().catch(g=>{u||(u=g,s())});let p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new q;if(d)return{value:void 0,done:!0};if(u)throw u;if(o.length>0){let g=o.shift(),x=performance.now();for(f.push(x);f.length>0&&x-f[0]>=1e3;)f.shift();return c(),{value:g,done:!1}}else{if(l)return{value:void 0,done:!0};await i}}},async return(){return d=!0,c(),s(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}},ur=class{constructor(e,t){this.onSample=e,this.onError=t}},dr=class{mediaSamplesInRange(e=0,t=1/0){Ne(e),Ne(t);let n=[],o=!1,i=null,{promise:s,resolve:a}=Z(),{promise:c,resolve:l}=Z(),d=!1,u=!1,f=!1,m=null;(async()=>{let x=await this._createDecoder(S=>{if(l(),S.timestamp>=t&&(u=!0),u){S.close();return}i&&(S.timestamp>e?(n.push(i),o=!0):i.close()),S.timestamp>=e&&(n.push(S),o=!0),i=o?null:S,n.length>0&&(a(),{promise:s,resolve:a}=Z())},S=>{m||(m=S,a())}),y=this._createPacketSink(),b=await y.getKeyPacket(e,{verifyKeyPackets:!0})??await y.getFirstPacket(),w=b,k;if(t<1/0){let S=await y.getPacket(t),_=S?S.type==="key"&&S.timestamp===t?S:await y.getNextKeyPacket(S,{verifyKeyPackets:!0}):null;_&&(k=_)}let P=y.packets(b??void 0,k);for(await P.next();w&&!u&&!this._track.input._disposed;){let S=Is(n.length);if(n.length+x.getDecodeQueueSize()>S){({promise:c,resolve:l}=Z()),await c;continue}x.decode(w);let _=await P.next();if(_.done)break;w=_.value}await P.return(),!f&&!this._track.input._disposed&&await x.flush(),x.close(),!o&&i&&n.push(i),d=!0,a()})().catch(x=>{m||(m=x,a())});let p=this._track,g=()=>{i?.close();for(let x of n)x.close()};return{async next(){for(;;){if(p.input._disposed)throw g(),new q;if(f)return{value:void 0,done:!0};if(m)throw g(),m;if(n.length>0){let x=n.shift();return l(),{value:x,done:!1}}else if(!d)await s;else return{value:void 0,done:!0}}},async return(){return f=!0,u=!0,l(),a(),g(),{value:void 0,done:!0}},async throw(x){throw x},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){Ji(e);let t=Zi(e),n=[],o=[],{promise:i,resolve:s}=Z(),{promise:a,resolve:c}=Z(),l=!1,d=!1,u=null,f=g=>{o.push(g),s(),{promise:i,resolve:s}=Z()};(async()=>{let g=await this._createDecoder(S=>{if(c(),d){S.close();return}let _=0;for(;n.length>0&&S.timestamp-n[0]>-1e-10;)_++,n.shift();if(_>0)for(let C=0;C<_;C++)f(C<_-1?S.clone():S);else S.close()},S=>{u||(u=S,s())}),x=this._createPacketSink(),y=null,b=null,w=-1,k=async()=>{h(b);let S=b;for(g.decode(S);S.sequenceNumber<w;){let _=Is(o.length);for(;o.length+g.getDecodeQueueSize()>_&&!d;)({promise:a,resolve:c}=Z()),await a;if(d)break;let C=await x.getNextPacket(S);h(C),g.decode(C),S=C}w=-1},P=async()=>{await g.flush();for(let S=0;S<n.length;S++)f(null);n.length=0};for await(let S of t){if(Ne(S),d||this._track.input._disposed)break;let _=await x.getPacket(S),C=_&&await x.getKeyPacket(S,{verifyKeyPackets:!0});if(!C){w!==-1&&(await k(),await P()),f(null),y=null;continue}y&&(C.sequenceNumber!==b.sequenceNumber||_.timestamp<y.timestamp)&&(await k(),await P()),n.push(_.timestamp),w=Math.max(_.sequenceNumber,w),y=_,b=C}!d&&!this._track.input._disposed&&(w!==-1&&await k(),await P()),g.close(),l=!0,s()})().catch(g=>{u||(u=g,s())});let m=this._track,p=()=>{for(let g of o)g?.close()};return{async next(){for(;;){if(m.input._disposed)throw p(),new q;if(d)return{value:void 0,done:!0};if(u)throw p(),u;if(o.length>0){let g=o.shift();return h(g!==void 0),c(),{value:g,done:!1}}else if(!l)await i;else return{value:void 0,done:!0}}},async return(){return d=!0,c(),s(),p(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}},Is=r=>r===0?40:8,Qo=class extends ur{constructor(e,t,n,o,i,s){super(e,t),this.codec=n,this.decoderConfig=o,this.rotation=i,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new tr,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;let a=fn.find(c=>c.supports(n,o));if(a)this.customDecoder=new a,this.customDecoder.codec=n,this.customDecoder.config=o,this.customDecoder.onSample=c=>{if(!(c instanceof St))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=d=>{if(this.alphaQueue.length>0){let u=this.alphaQueue.shift();h(u!==void 0),this.mergeAlpha(d,u)}else this.colorQueue.push(d)};if(n==="avc"&&this.decoderConfig.description&&nr()){let d=ms(le(this.decoderConfig.description));if(d&&d.sequenceParameterSets.length>0){let u=Go(d.sequenceParameterSets[0]);u&&u.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let l=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:d=>{try{c(d)}catch(u){this.onError(u)}},error:d=>{d.stack=l,this.onError(d)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(h(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(h(this.decoder),Be()||Bo(this.inputTimestamps,e.timestamp,t=>t),nr()&&this.currentPacketIndex===0&&this.codec==="avc"){let n=qo(e.data,this.decoderConfig).filter(i=>{let s=nt(i);return!(s>=20&&s<=31)}),o=ds(n,this.decoderConfig);e=new V(o,e.type,e.timestamp,e.duration)}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed){this.pushNullAlphaFrame();return}if(!this.merger)try{this.merger=new Yo}catch(n){console.error("Due to an error, only color data will be decoded.",n),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let n=i=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let s=this.colorQueue.shift();h(s!==void 0),this.mergeAlpha(s,i)}else this.alphaQueue.push(i);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let s=this.colorQueue.shift();h(s!==void 0),this.mergeAlpha(s,null)}else this.alphaQueue.push(null)},o=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:i=>{try{n(i)}catch(s){this.onError(s)}},error:i=>{i.stack=o,this.onError(i)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=dn(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=t==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){return Wo(e,this.decoderConfig).some(n=>{let o=Ie(n);return o===J.RASL_N||o===J.RASL_R})}sampleHandler(e){if(Be()){if(this.sampleQueue.length>0&&e.timestamp>=Y(this.sampleQueue).timestamp){for(let t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}Bo(this.sampleQueue,e,t=>t.timestamp)}else{let t=this.inputTimestamps.shift();h(t!==void 0),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,t){if(!t){let i=new St(e);this.sampleHandler(i);return}h(this.merger),this.merger.update(e,t),e.close(),t.close();let n=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),o=new St(n);this.sampleHandler(o)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(h(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Be()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(h(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},Yo=class{constructor(){typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");let e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
2340
|
+
`)}});var Nr=()=>({stdout:async r=>console.log(r),stderr:async r=>console.error(r)});var Vi=()=>wo()?zr():ko()?Ur():Nr();var Li=()=>({stdout:async()=>{},stderr:async()=>{}});function Hi(){return()=>({stdout:r=>r,stderr:r=>r})}var bt=class r{static writers={auto:Vi,void:Li,deno:zr,node:Ur,console:Nr};static colors={auto:So,colorful:()=>Yt,colorless:()=>Qt};static themes={auto:Oi,basic:Rr};static shapers={auto:Ni,none:Hi,errors:Br,timestamp:Or};writer=r.writers.auto();colors=r.colors.auto();theme=r.themes.auto();shaper=r.shapers.auto();async log(...e){await this.writer.stdout(this.shaper(this).stdout(e).join(" "))}async error(...e){await this.writer.stderr(this.shaper(this).stderr(e).join(" "))}setWriter(e){return this.writer=e,this}setColors(e){return this.colors=e,this}setTheme(e){return this.theme=e,this}setShaper(...e){return this.shaper=Zt(...e),this}};var Jt=class extends bt{static dummy(){return new this().setWriter(bt.writers.void())}rpcRequest=async({request:e,...t})=>{let n=this.colors.none;this.log(...this.#e(t),n(`${e.method}()`))};rpcError=async({request:e,error:t,...n})=>{this.error(...this.#e(n),`${e.method}()`,t)};#e({meta:e,label:t,remote:n}){let o=this.colors.mix(this.colors.blue,this.colors.dim),i=this.colors.mix(this.colors.cyan,this.colors.dim);return[e?this.#t(e):void 0,t||void 0,n===void 0?void 0:n?o("<-"):i("->")].filter(Boolean)}#t(e){let{headers:t}=e.request;return[this.colors.yellow(`[${e.ip}]`),this.colors.green(t.origin?t.origin:"(no-origin)")].join(" ")}};var be=class extends Jt{rpcRequest=async()=>{}};var Pe;(function(r){r.version="2.0";function e(t){return"id"in t?t.id:null}r.getId=e,r.errorCodes={serverError:-32e3,unexposedError:-32001}})(Pe||(Pe={}));var Vr=class extends Error{name=this.constructor.name},je=class extends Error{name=this.constructor.name};async function qi({tap:r,request:e,action:t}){let n=Pe.getId(e);try{let o=await t();return n===null?null:{id:n,result:o,jsonrpc:Pe.version}}catch(o){return r.rpcError({request:e,error:o}),n===null?null:{id:n,jsonrpc:Pe.version,error:o instanceof Vr?{code:Pe.errorCodes.serverError,message:o.message}:{code:Pe.errorCodes.unexposedError,message:"unexposed error"}}}}function Lr(r){let e=r.tap??new be;return async t=>{let n=t.method.split("."),o=Bi(r.fns,n),i=async()=>await o(...t.params);return e.rpcRequest({request:t}),await qi({tap:e,request:t,action:i})}}var yt=Symbol("tune"),mc=Symbol("query"),pc=Symbol("notify"),hc=Symbol("settings");function Gi(r){function e(t){let n={notify:void 0};return new Proxy((()=>{}),{apply:(o,i,s)=>r(t,s,n),get:(o,i)=>{if(i!=="then")return i===yt?s=>(...a)=>r(t,a,{...n,...s}):i===pc?(...s)=>r(t,s,{...n,notify:!0}):i===mc?(...s)=>r(t,s,{...n,notify:!1}):i===hc?n:(o[i]||(o[i]=e([...t,i])),o[i])},set:(o,i,s)=>(o[i]=s,!0)})}return e([])}function $e(r){let{endpoint:e,tap:t=new be}=r,n=1;return Gi(async(o,i,s)=>{let a=s.notify??r.notify??!1,c=s.transfer,l={jsonrpc:"2.0",method:o.join("."),params:i},d=a?l:{...l,id:n++};t.rpcRequest({request:d});let u=await e(d,{transfer:c});if(a&&!u)return null;if(!u)throw new je("response was null, but shouldn't be, because the request was not a notification");if("error"in u)throw new je(r.label?`${r.label}: ${u.error.message}`:u.error.message);return u.result})}function er(r){return $e({endpoint:Lr(r),tap:r.tap})}var Ke=class{recv=ve();sendRequest=ve();sendResponse=ve();static makeEntangledPair({origin:e="example.e280.org"}={}){let t=new this,n=new this,o=[t.sendRequest.sub(s=>n.recv(s,{origin:e})),t.sendResponse.sub(s=>n.recv(s,{origin:e})),n.sendRequest.sub(s=>t.recv(s,{origin:e})),n.sendResponse.sub(s=>t.recv(s,{origin:e}))];return[t,n,()=>o.forEach(s=>s())]}};function Hr(r,e){return r.addEventListener("message",e),()=>r.removeEventListener("message",e)}function Wi(r,e){return async(t,{transfer:n}={})=>{if("id"in t){let o=xe();return e(t,n,o.promise),r.wait(t.id,t.method).then(i=>(o.resolve(i),i))}else{let o=Promise.resolve(null);return e(t,n,o),o}}}function ji(r){let e=[],t=[];for(let n of Array.isArray(r)?r:[r])"method"in n?e.push(n):t.push(n);return{requests:e,responses:t}}async function $i(r,e){let t=(await Promise.all(e.map(async n=>r(n)))).filter(n=>n!==null);return t.length===0?null:t.length===1?t[0]:t}var Tt=class extends Ke{dispose=Dr();constructor(e){super(),this.dispose.schedule(this.sendRequest.sub((t,n)=>e.postMessage(t,n)),this.sendResponse.sub((t,n)=>e.postMessage(t,n)),Hr(e,t=>this.recv(t.data,t)))}};var qr=class{remote;transfer;constructor(e){this.remote=e}};var vo=Object.freeze({timeout:6e4,maxRequestBytes:1e7});var Gr=class{timeout;pending=new Map;constructor(e){this.timeout=e}async wait(e,t){let n=xe();return this.pending.set(e,{method:t,deferred:n}),await Mi(this.timeout,()=>n.promise).catch(o=>{throw o instanceof Xt&&(o.message=`request #${e} ${t}(), ${o.message}`),o})}deliverResponse(e){let t=this.pending.get(e.id);t&&("error"in e?t.deferred.reject(new je(e.error.message)):t.deferred.resolve(e))}};var Xe=class{options;remote;remoteEndpoint;dispose=Dr();#e;constructor(e){this.options=e;let{conduit:t,tap:n}=e;this.#e=new Gr(e.timeout??vo.timeout),this.remoteEndpoint=Wi(this.#e,t.sendRequest.pub.bind(t.sendRequest)),this.remote=$e({endpoint:this.remoteEndpoint,tap:n&&To(n,{remote:!0})}),this.dispose.schedule(t.recv.sub(o=>this.recv(o)))}async recv(e){let t=new qr(this.remote),{conduit:n,rpc:o,tap:i}=this.options,{requests:s,responses:a}=ji(e);for(let u of a)this.#e.deliverResponse(u);if(!o)return;let c=await o(t),l=Lr({fns:c,tap:i&&To(i,{remote:!1})}),d=await $i(l,s);d&&await n.sendResponse(d,t.transfer)}};var Ce={derive:{host:r=>({host:r.remote.host,get transfer(){return r.transfer},set transfer(e){r.transfer=e}}),work:r=>({work:r.remote,get transfer(){return r.transfer},set transfer(e){r.transfer=e}})},mock:{host:()=>({host:void 0,transfer:void 0}),work:()=>({work:void 0,transfer:void 0})}};var Ie=new be;async function Ki(r,e,t={}){let n=t.tap??Ie,o=new Xe({tap:n,timeout:t.timeout??1/0,conduit:new Tt(r.getSelf()),rpc:async i=>e(Ce.derive.host(i))});return await o.remote.infra.ready(),o.remote.host}var wt=class{worker;messenger;constructor(e,t){this.worker=e,this.messenger=t}static async make(e,t){let n=t.tap??Ie,o=t.label??"comrade",i=e.loadWorker(t.workerUrl,o),s=xe(),a={async ready(){s.resolve()}},c=new Xe({tap:n,timeout:t.timeout??1/0,conduit:new Tt(i),rpc:async l=>({infra:a,host:t.setupHost(Ce.derive.work(l))})});return await s.promise,new this(i,c)}get work(){return this.messenger.remote}terminate(){this.worker.terminate()}};var Wr=class{threads;static async make(e,t){let n=t.workerCount??e.guessOptimalThreadCount(),o=await Promise.all([...Array(n)].map(async(i,s)=>wt.make(e,{...t,label:t.label??`${t.label??"comrade"}_${s+1}`})));return new this(o,{tap:t.tap})}work;#e=new Set;#t=[];constructor(e,t={}){this.threads=e;let n=t.tap??Ie,o=async(i,s)=>this.#r({request:i,prom:xe(),transfer:s?.transfer});this.work=$e({tap:n,endpoint:o}),e.forEach(i=>this.#e.add(i))}get threadCount(){return this.threads.length}terminate(){for(let e of this.threads)e.terminate()}#r(e){return this.#t.push(e),this.#n(),e.prom.promise}#n(){for(;this.#e.size>0&&this.#t.length>0;){let e=[...this.#e].pop();this.#e.delete(e);let t=this.#t.shift();this.#e.delete(e);let n=e.messenger.remoteEndpoint(t.request,{transfer:t.transfer});t.prom.entangle(n).finally(()=>{this.#e.add(e),this.#n()})}}};var Xi=r=>({thread:e=>wt.make(r,e),cluster:e=>Wr.make(r,e),worker:(e,t={})=>Ki(r,e,t),work:e=>e,host:e=>e,mocks(e){let{setupWork:t,setupHost:n,tap:o=Ie}=e,i=Ce.mock.host(),s=Ce.mock.work();return s.work=er({tap:o,fns:t(i)}),i.host=er({tap:o,fns:n(s)}),{workShell:s,hostShell:i,work:s.work,host:i.host}},mockWork(e,t=Ie){let n=Ce.mock.host(),o=Ce.mock.work();return o.work=er({tap:t,fns:e(n)}),{workShell:o,hostShell:n,work:o.work,mockHost:i=>(n.host=er({tap:t,fns:i(o)}),{workShell:o,hostShell:n,work:o.work,host:n.host})}}});var Qi=()=>({getSelf(){return self},guessOptimalThreadCount(){let r=navigator.hardwareConcurrency??1;return Math.max(1,r-1)},loadWorker(r,e){return new window.Worker(r,{name:e,type:"module"})},async loadWasm(r){return WebAssembly.instantiateStreaming(fetch(r))}});var bc=Qi(),jr=Xi(bc);function h(r){if(!r)throw new Error("Assertion failed.")}var $r=r=>{let e=(r%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${r}.`)},Y=r=>r&&r[r.length-1];var N=class r{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),o=(t&1<<n)>>n;return this.pos++,o}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let o=this.pos;o<n;o++){let i=Math.floor(o/8),s=this.bytes[i],a=7-(o&7);s&=~(1<<a),s|=(t&1<<n-o-1)>>n-o-1<<a,this.bytes[i]=s}this.pos=n}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new r(this.bytes);return e.pos=this.pos,e}},I=r=>{let e=0;for(;r.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+r.readBits(e)},Te=r=>{let e=I(r);return(e&1)===0?-(e>>1):e+1>>1};var le=r=>r.constructor===Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),z=r=>r.constructor===DataView?r:ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r),$=new TextDecoder;var _o=r=>Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),Eo={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Kr=_o(Eo),Fo={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Xr=_o(Fo),Do={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Qr=_o(Do);var Yr=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r),ye=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e,t=new Promise(o=>{e=o}),n=this.currentPromise;return this.currentPromise=t,await n,e}},Ro=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),Mo=r=>(r=r>>1&1431655765|(r&1431655765)<<1,r=r>>2&858993459|(r&858993459)<<2,r=r>>4&252645135|(r&252645135)<<4,r=r>>8&16711935|(r&16711935)<<8,r=r>>16&65535|(r&65535)<<16,r>>>0),Qe=(r,e,t)=>{let n=0,o=r.length-1,i=-1;for(;n<=o;){let s=n+o>>1,a=t(r[s]);a===e?(i=s,o=s-1):a<e?n=s+1:o=s-1}return i},B=(r,e,t)=>{let n=0,o=r.length-1,i=-1;for(;n<=o;){let s=n+(o-n+1)/2|0;t(r[s])<=e?(i=s,n=s+1):o=s-1}return i},Bo=(r,e,t)=>{let n=B(r,t(e),t);r.splice(n+1,0,e)},Z=()=>{let r,e;return{promise:new Promise((n,o)=>{r=n,e=o}),resolve:r,reject:e}};var Oo=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return r[t]},Zr=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1},Zi=async function*(r){Symbol.iterator in r?yield*r[Symbol.iterator]():yield*r[Symbol.asyncIterator]()},Ji=r=>{if(!(Symbol.iterator in r)&&!(Symbol.asyncIterator in r))throw new TypeError("Argument must be an iterable or async iterable.")},se=r=>{throw new Error(`Unexpected value: ${r}`)},Ye=(r,e,t)=>{let n=r.getUint8(e),o=r.getUint8(e+1),i=r.getUint8(e+2);return t?n|o<<8|i<<16:n<<16|o<<8|i},es=(r,e,t)=>Ye(r,e,t)<<8>>8,ts=(r,e,t,n)=>{t=t>>>0,t=t&16777215,n?(r.setUint8(e,t&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t>>>16&255)):(r.setUint8(e,t>>>16&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t&255))};var zo=(r,e)=>({async next(){let t=await r.next();return t.done?{value:void 0,done:!0}:{value:e(t.value),done:!1}},return(){return r.return()},throw(t){return r.throw(t)},[Symbol.asyncIterator](){return this}}),Ze=(r,e,t)=>Math.max(e,Math.min(t,r)),K="und",Je=r=>{let e=Math.round(r);return Math.abs(r/e-1)<10*Number.EPSILON?e:r},rs=(r,e)=>Math.round(r/e)*e,ns=r=>{let e=0;for(;r;)e++,r>>=1;return e},yc=/^[a-z]{3}$/,Jr=r=>yc.test(r),we=1e6*(1+Number.EPSILON),Uo=(r,e)=>{let t={...r,...e};if(r.headers||e.headers){let n=r.headers?Yi(r.headers):{},o=e.headers?Yi(e.headers):{},i={...n};Object.entries(o).forEach(([s,a])=>{let c=Object.keys(i).find(l=>l.toLowerCase()===s.toLowerCase());c&&delete i[c],i[s]=a}),t.headers=i}return t},Yi=r=>{if(r instanceof Headers){let e={};return r.forEach((t,n)=>{e[n]=t}),e}if(Array.isArray(r)){let e={};return r.forEach(([t,n])=>{e[t]=n}),e}return r},No=async(r,e,t,n,o)=>{let i=0;for(;;)try{return await r(e,t)}catch(s){if(o())throw s;i++;let a=n(i,s,e);if(a===null)throw s;if(console.error("Retrying failed fetch. Error:",s),!Number.isFinite(a)||a<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(a>0&&await new Promise(c=>setTimeout(c,1e3*a)),o())throw s}};var tr=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},Po=null,Oe=()=>Po!==null?Po:Po=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),Co=null,rr=()=>Co!==null?Co:Co=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),Io=null,nr=()=>Io!==null?Io:Io=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),Ao=null,os=()=>{if(Ao!==null)return Ao;if(typeof navigator>"u")return null;let r=/\bChrome\/(\d+)/.exec(navigator.userAgent);return r?Ao=Number(r[1]):null},et=(r,e)=>r!==-1?r:e,en=(r,e,t,n)=>r<=n&&t<=e;var is=r=>{let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t};var tn=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},or=r=>typeof r=="number"&&!Number.isNaN(r);var ze=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof t!="string")throw new TypeError("mimeType must be a string.")}},rn=class{constructor(e,t,n,o){if(this.data=e,this.mimeType=t,this.name=n,this.description=o,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!==void 0&&typeof t!="string")throw new TypeError("mimeType, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("name, when provided, must be a string.");if(o!==void 0&&typeof o!="string")throw new TypeError("description, when provided, must be a string.")}};var te={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};var Ue=["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"],Tc=["aac","opus","mp3","vorbis","flac"],jm=[...Tc,...Ue];var tt=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}];var ss=".01.01.01.01.00",as=".0.110.01.01.01.0";var nn=r=>{let{codec:e,codecDescription:t,colorSpace:n,avcCodecInfo:o,hevcCodecInfo:i,vp9CodecInfo:s,av1CodecInfo:a}=r;if(e==="avc"){if(h(r.avcType!==null),o){let c=new Uint8Array([o.avcProfileIndication,o.profileCompatibility,o.avcLevelIndication]);return`avc${r.avcType}.${Ro(c)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${r.avcType}.${Ro(t.subarray(1,4))}`}else if(e==="hevc"){let c,l,d,u,f,m;if(i)c=i.generalProfileSpace,l=i.generalProfileIdc,d=Mo(i.generalProfileCompatibilityFlags),u=i.generalTierFlag,f=i.generalLevelIdc,m=[...i.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let g=z(t),x=g.getUint8(1);c=x>>6&3,l=x&31,d=Mo(g.getUint32(2)),u=x>>5&1,f=g.getUint8(12),m=[];for(let y=0;y<6;y++)m.push(g.getUint8(6+y))}let p="hev1.";for(p+=["","A","B","C"][c]+l,p+=".",p+=d.toString(16).toUpperCase(),p+=".",p+=u===0?"L":"H",p+=f;m.length>0&&m[m.length-1]===0;)m.pop();return m.length>0&&(p+=".",p+=m.map(g=>g.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!s){let y=r.width*r.height,b=Y(tt).level;for(let w of tt)if(y<=w.maxPictureSize){b=w.level;break}return`vp09.00.${b.toString().padStart(2,"0")}.08`}let c=s.profile.toString().padStart(2,"0"),l=s.level.toString().padStart(2,"0"),d=s.bitDepth.toString().padStart(2,"0"),u=s.chromaSubsampling.toString().padStart(2,"0"),f=s.colourPrimaries.toString().padStart(2,"0"),m=s.transferCharacteristics.toString().padStart(2,"0"),p=s.matrixCoefficients.toString().padStart(2,"0"),g=s.videoFullRangeFlag.toString().padStart(2,"0"),x=`vp09.${c}.${l}.${d}.${u}`;return x+=`.${f}.${m}.${p}.${g}`,x.endsWith(ss)&&(x=x.slice(0,-ss.length)),x}else if(e==="av1"){if(!a){let w=r.width*r.height,k=Y(tt).level;for(let P of tt)if(w<=P.maxPictureSize){k=P.level;break}return`av01.0.${k.toString().padStart(2,"0")}M.08`}let c=a.profile,l=a.level.toString().padStart(2,"0"),d=a.tier?"H":"M",u=a.bitDepth.toString().padStart(2,"0"),f=a.monochrome?"1":"0",m=100*a.chromaSubsamplingX+10*a.chromaSubsamplingY+1*(a.chromaSubsamplingX&&a.chromaSubsamplingY?a.chromaSamplePosition:0),p=n?.primaries?Eo[n.primaries]:1,g=n?.transfer?Fo[n.transfer]:1,x=n?.matrix?Do[n.matrix]:1,y=n?.fullRange?1:0,b=`av01.${c}.${l}${d}.${u}`;return b+=`.${f}.${m.toString().padStart(3,"0")}`,b+=`.${p.toString().padStart(2,"0")}`,b+=`.${g.toString().padStart(2,"0")}`,b+=`.${x.toString().padStart(2,"0")}`,b+=`.${y}`,b.endsWith(as)&&(b=b.slice(0,-as.length)),b}}throw new TypeError(`Unhandled codec '${e}'.`)};var on=r=>{let{codec:e,codecDescription:t,aacCodecInfo:n}=r;if(e==="aac"){if(!n)throw new TypeError("AAC codec info must be provided.");return n.isMpeg2?"mp4a.67":`mp4a.40.${Lo(t).objectType}`}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e&&Ue.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},ir=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Vo=[-1,1,2,3,4,5,6,8],Lo=r=>{if(!r||r.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new N(r),t=e.readBits(5);t===31&&(t=32+e.readBits(6));let n=e.readBits(4),o=null;n===15?o=e.readBits(24):n<ir.length&&(o=ir[n]);let i=e.readBits(4),s=null;return i>=1&&i<=7&&(s=Vo[i]),{objectType:t,frequencyIndex:n,sampleRate:o,channelConfiguration:i,numberOfChannels:s}};var rt=48e3,wc=/^pcm-([usf])(\d+)+(be)?$/,sn=r=>{if(h(Ue.includes(r)),r==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(r==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=wc.exec(r);h(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";let n=Number(e[2])/8,o=e[3]!=="be",i=r==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:n,littleEndian:o,silentValue:i}};var nt;(function(r){r[r.IDR=5]="IDR",r[r.SEI=6]="SEI",r[r.SPS=7]="SPS",r[r.PPS=8]="PPS",r[r.SPS_EXT=13]="SPS_EXT"})(nt||(nt={}));var J;(function(r){r[r.RASL_N=8]="RASL_N",r[r.RASL_R=9]="RASL_R",r[r.BLA_W_LP=16]="BLA_W_LP",r[r.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",r[r.VPS_NUT=32]="VPS_NUT",r[r.SPS_NUT=33]="SPS_NUT",r[r.PPS_NUT=34]="PPS_NUT",r[r.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",r[r.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(J||(J={}));var cn=r=>{let e=[],t=0;for(;t<r.length;){let n=-1,o=0;for(let i=t;i<r.length-3;i++){if(r[i]===0&&r[i+1]===0&&r[i+2]===1){n=i,o=3;break}if(i<r.length-4&&r[i]===0&&r[i+1]===0&&r[i+2]===0&&r[i+3]===1){n=i,o=4;break}}if(n===-1)break;if(t>0&&n>t){let i=r.subarray(t,n);i.length>0&&e.push(i)}t=n+o}if(t<r.length){let n=r.subarray(t);n.length>0&&e.push(n)}return e},us=(r,e)=>{let t=[],n=0,o=new DataView(r.buffer,r.byteOffset,r.byteLength);for(;n+e<=r.length;){let i;e===1?i=o.getUint8(n):e===2?i=o.getUint16(n,!1):e===3?i=Ye(o,n,!1):e===4?i=o.getUint32(n,!1):(se(e),h(!1)),n+=e;let s=r.subarray(n,n+i);t.push(s),n+=i}return t},an=r=>{let e=[],t=r.length;for(let n=0;n<t;n++)n+2<t&&r[n]===0&&r[n+1]===0&&r[n+2]===3?(e.push(0,0),n+=2):e.push(r[n]);return new Uint8Array(e)},Ho=new Uint8Array([0,0,0,1]),Sc=r=>{let e=r.reduce((o,i)=>o+Ho.byteLength+i.byteLength,0),t=new Uint8Array(e),n=0;for(let o of r)t.set(Ho,n),n+=Ho.byteLength,t.set(o,n),n+=o.byteLength;return t},vc=(r,e)=>{let t=r.reduce((i,s)=>i+e+s.byteLength,0),n=new Uint8Array(t),o=0;for(let i of r){let s=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(e){case 1:s.setUint8(o,i.byteLength);break;case 2:s.setUint16(o,i.byteLength,!1);break;case 3:ts(s,o,i.byteLength,!1);break;case 4:s.setUint32(o,i.byteLength,!1);break}o+=e,n.set(i,o),o+=i.byteLength}return n},qo=(r,e)=>{if(e.description){let o=(le(e.description)[4]&3)+1;return us(r,o)}else return cn(r)},ds=(r,e)=>{if(e.description){let o=(le(e.description)[4]&3)+1;return vc(r,o)}else return Sc(r)},ot=r=>r[0]&31,fs=r=>{try{let e=cn(r),t=e.filter(c=>ot(c)===nt.SPS),n=e.filter(c=>ot(c)===nt.PPS),o=e.filter(c=>ot(c)===nt.SPS_EXT);if(t.length===0||n.length===0)return null;let i=t[0],s=Go(i);h(s!==null);let a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:n,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?o:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}};var ms=r=>{try{let e=z(r),t=0,n=e.getUint8(t++),o=e.getUint8(t++),i=e.getUint8(t++),s=e.getUint8(t++),a=e.getUint8(t++)&3,c=e.getUint8(t++)&31,l=[];for(let m=0;m<c;m++){let p=e.getUint16(t,!1);t+=2,l.push(r.subarray(t,t+p)),t+=p}let d=e.getUint8(t++),u=[];for(let m=0;m<d;m++){let p=e.getUint16(t,!1);t+=2,u.push(r.subarray(t,t+p)),t+=p}let f={configurationVersion:n,avcProfileIndication:o,profileCompatibility:i,avcLevelIndication:s,lengthSizeMinusOne:a,sequenceParameterSets:l,pictureParameterSets:u,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((o===100||o===110||o===122||o===144)&&t+4<=r.length){let m=e.getUint8(t++)&3,p=e.getUint8(t++)&7,g=e.getUint8(t++)&7,x=e.getUint8(t++);f.chromaFormat=m,f.bitDepthLumaMinus8=p,f.bitDepthChromaMinus8=g;let y=[];for(let b=0;b<x;b++){let w=e.getUint16(t,!1);t+=2,y.push(r.subarray(t,t+w)),t+=w}f.sequenceParameterSetExt=y}return f}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}},Go=r=>{try{let e=new N(an(r));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let n=e.readAlignedByte(),o=e.readAlignedByte(),i=e.readAlignedByte();I(e);let s=null,a=null,c=null;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(s=I(e),s===3&&e.skipBits(1),a=I(e),c=I(e),e.skipBits(1),e.readBits(1))){for(let f=0;f<(s!==3?8:12);f++)if(e.readBits(1)){let p=f<6?16:64,g=8,x=8;for(let y=0;y<p;y++){if(x!==0){let b=Te(e);x=(g+b+256)%256}g=x===0?g:x}}}I(e);let l=I(e);if(l===0)I(e);else if(l===1){e.skipBits(1),Te(e),Te(e);let u=I(e);for(let f=0;f<u;f++)Te(e)}I(e),e.skipBits(1),I(e),I(e);let d=e.readBits(1);return{profileIdc:n,constraintFlags:o,levelIdc:i,frameMbsOnlyFlag:d,chromaFormatIdc:s,bitDepthLumaMinus8:a,bitDepthChromaMinus8:c}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},Wo=(r,e)=>{if(e.description){let o=(le(e.description)[21]&3)+1;return us(r,o)}else return cn(r)},Ae=r=>r[0]>>1&63,ps=r=>{try{let e=cn(r),t=e.filter(O=>Ae(O)===J.VPS_NUT),n=e.filter(O=>Ae(O)===J.SPS_NUT),o=e.filter(O=>Ae(O)===J.PPS_NUT),i=e.filter(O=>Ae(O)===J.PREFIX_SEI_NUT||Ae(O)===J.SUFFIX_SEI_NUT);if(n.length===0||o.length===0)return null;let s=n[0],a=new N(an(s));a.skipBits(16),a.readBits(4);let c=a.readBits(3),l=a.readBits(1),{general_profile_space:d,general_tier_flag:u,general_profile_idc:f,general_profile_compatibility_flags:m,general_constraint_indicator_flags:p,general_level_idc:g}=Pc(a,c);I(a);let x=I(a);x===3&&a.skipBits(1),I(a),I(a),a.readBits(1)&&(I(a),I(a),I(a),I(a));let y=I(a),b=I(a);I(a);let k=a.readBits(1)?0:c;for(let O=k;O<=c;O++)I(a),I(a),I(a);I(a),I(a),I(a),I(a),I(a),I(a),a.readBits(1)&&a.readBits(1)&&Cc(a),a.skipBits(1),a.skipBits(1),a.readBits(1)&&(a.skipBits(4),a.skipBits(4),I(a),I(a),a.skipBits(1));let P=I(a);if(Ic(a,P),a.readBits(1)){let O=I(a);for(let R=0;R<O;R++)I(a),a.skipBits(1)}a.skipBits(1),a.skipBits(1);let S=0;a.readBits(1)&&(S=_c(a,c));let _=0;if(o.length>0){let O=o[0],R=new N(an(O));R.skipBits(16),I(R),I(R),R.skipBits(1),R.skipBits(1),R.skipBits(3),R.skipBits(1),R.skipBits(1),I(R),I(R),Te(R),R.skipBits(1),R.skipBits(1),R.readBits(1)&&I(R),Te(R),Te(R),R.skipBits(1),R.skipBits(1),R.skipBits(1),R.skipBits(1);let j=R.readBits(1),We=R.readBits(1);!j&&!We?_=0:j&&!We?_=2:!j&&We?_=3:_=0}let C=[...t.length?[{arrayCompleteness:1,nalUnitType:J.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:J.SPS_NUT,nalUnits:n}]:[],...o.length?[{arrayCompleteness:1,nalUnitType:J.PPS_NUT,nalUnits:o}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ae(i[0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:d,generalTierFlag:u,generalProfileIdc:f,generalProfileCompatibilityFlags:m,generalConstraintIndicatorFlags:p,generalLevelIdc:g,minSpatialSegmentationIdc:S,parallelismType:_,chromaFormatIdc:x,bitDepthLumaMinus8:y,bitDepthChromaMinus8:b,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:l,lengthSizeMinusOne:3,arrays:C}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},Pc=(r,e)=>{let t=r.readBits(2),n=r.readBits(1),o=r.readBits(5),i=0;for(let d=0;d<32;d++)i=i<<1|r.readBits(1);let s=new Uint8Array(6);for(let d=0;d<6;d++)s[d]=r.readBits(8);let a=r.readBits(8),c=[],l=[];for(let d=0;d<e;d++)c.push(r.readBits(1)),l.push(r.readBits(1));if(e>0)for(let d=e;d<8;d++)r.skipBits(2);for(let d=0;d<e;d++)c[d]&&r.skipBits(88),l[d]&&r.skipBits(8);return{general_profile_space:t,general_tier_flag:n,general_profile_idc:o,general_profile_compatibility_flags:i,general_constraint_indicator_flags:s,general_level_idc:a}},Cc=r=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!r.readBits(1))I(r);else{let o=Math.min(64,1<<4+(e<<1));e>1&&Te(r);for(let i=0;i<o;i++)Te(r)}},Ic=(r,e)=>{let t=[];for(let n=0;n<e;n++)t[n]=Ac(r,n,e,t)},Ac=(r,e,t,n)=>{let o=0,i=0,s=0;if(e!==0&&(i=r.readBits(1)),i){if(e===t){let c=I(r);s=e-(c+1)}else s=e-1;r.readBits(1),I(r);let a=n[s]??0;for(let c=0;c<=a;c++)r.readBits(1)||r.readBits(1);o=n[s]}else{let a=I(r),c=I(r);for(let l=0;l<a;l++)I(r),r.readBits(1);for(let l=0;l<c;l++)I(r),r.readBits(1);o=a+c}return o},_c=(r,e)=>{if(r.readBits(1)&&r.readBits(8)===255&&(r.readBits(16),r.readBits(16)),r.readBits(1)&&r.readBits(1),r.readBits(1)&&(r.readBits(3),r.readBits(1),r.readBits(1)&&(r.readBits(8),r.readBits(8),r.readBits(8))),r.readBits(1)&&(I(r),I(r)),r.readBits(1),r.readBits(1),r.readBits(1),r.readBits(1)&&(I(r),I(r),I(r),I(r)),r.readBits(1)&&(r.readBits(32),r.readBits(32),r.readBits(1)&&I(r),r.readBits(1)&&Ec(r,!0,e)),r.readBits(1)){r.readBits(1),r.readBits(1),r.readBits(1);let t=I(r);return I(r),I(r),I(r),I(r),t}return 0},Ec=(r,e,t)=>{let n=!1,o=!1,i=!1;e&&(n=r.readBits(1)===1,o=r.readBits(1)===1,(n||o)&&(i=r.readBits(1)===1,i&&(r.readBits(8),r.readBits(5),r.readBits(1),r.readBits(5)),r.readBits(4),r.readBits(4),i&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5)));for(let s=0;s<=t;s++){let a=r.readBits(1)===1,c=!0;a||(c=r.readBits(1)===1);let l=!1;c?I(r):l=r.readBits(1)===1;let d=1;l||(d=I(r)+1),n&&cs(r,d,i),o&&cs(r,d,i)}},cs=(r,e,t)=>{for(let n=0;n<e;n++)I(r),I(r),t&&(I(r),I(r)),r.readBits(1)};var ln=r=>{let e=new N(r);if(e.readBits(2)!==2)return null;let n=e.readBits(1),i=(e.readBits(1)<<1)+n;if(i===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;i>=2&&(l=e.readBits(1)?12:10);let d=e.readBits(3),u=0,f=0;if(d!==7)if(f=e.readBits(1),i===1||i===3){let _=e.readBits(1),C=e.readBits(1);u=!_&&!C?3:_&&!C?2:1,e.skipBits(1)}else u=1;else u=3,f=1;let m=e.readBits(16),p=e.readBits(16),g=m+1,x=p+1,y=g*x,b=Y(tt).level;for(let S of tt)if(y<=S.maxPictureSize){b=S.level;break}return{profile:i,level:b,bitDepth:l,chromaSubsampling:u,videoFullRangeFlag:f,colourPrimaries:d===2?1:d===1?6:2,transferCharacteristics:d===2?1:d===1?6:2,matrixCoefficients:d===7?0:d===2?1:d===1?6:2}},hs=function*(r){let e=new N(r),t=()=>{let n=0;for(let o=0;o<8;o++){let i=e.readAlignedByte();if(n|=(i&127)<<o*7,!(i&128))break;if(o===7&&i&128)return null}return n>=2**32-1?null:n};for(;e.getBitsLeft()>=8;){e.skipBits(1);let n=e.readBits(4),o=e.readBits(1),i=e.readBits(1);e.skipBits(1),o&&e.skipBits(8);let s;if(i){let a=t();if(a===null)return;s=a}else s=Math.floor(e.getBitsLeft()/8);h(e.pos%8===0),yield{type:n,data:r.subarray(e.pos/8,e.pos/8+s)},e.skipBits(s*8)}},un=r=>{for(let{type:e,data:t}of hs(r)){if(e!==1)continue;let n=new N(t),o=n.readBits(3),i=n.readBits(1),s=n.readBits(1),a=0,c=0,l=0;if(s)a=n.readBits(5);else{if(n.readBits(1)&&(n.skipBits(32),n.skipBits(32),n.readBits(1)))return null;let S=n.readBits(1);S&&(l=n.readBits(5),n.skipBits(32),n.skipBits(5),n.skipBits(5));let _=n.readBits(5);for(let C=0;C<=_;C++){n.skipBits(12);let F=n.readBits(5);if(C===0&&(a=F),F>7){let R=n.readBits(1);C===0&&(c=R)}if(S&&n.readBits(1)){let j=l+1;n.skipBits(j),n.skipBits(j),n.skipBits(1)}n.readBits(1)&&n.skipBits(4)}}let d=n.readBits(4),u=n.readBits(4),f=d+1;n.skipBits(f);let m=u+1;n.skipBits(m);let p=0;if(s?p=0:p=n.readBits(1),p&&(n.skipBits(4),n.skipBits(3)),n.skipBits(1),n.skipBits(1),n.skipBits(1),!s){n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let P=n.readBits(1);P&&(n.skipBits(1),n.skipBits(1));let S=n.readBits(1),_=0;S?_=2:_=n.readBits(1),_>0&&(n.readBits(1)||n.skipBits(1)),P&&n.skipBits(3)}n.skipBits(1),n.skipBits(1),n.skipBits(1);let g=n.readBits(1),x=8;o===2&&g?x=n.readBits(1)?12:10:o<=2&&(x=g?10:8);let y=0;o!==1&&(y=n.readBits(1));let b=1,w=1,k=0;return y||(o===0?(b=1,w=1):o===1?(b=0,w=0):x===12&&(b=n.readBits(1),b&&(w=n.readBits(1))),b&&w&&(k=n.readBits(2))),{profile:o,level:a,tier:c,bitDepth:x,monochrome:y,chromaSubsamplingX:b,chromaSubsamplingY:w,chromaSamplePosition:k}}return null},gs=r=>{let e=z(r),t=e.getUint8(9),n=e.getUint16(10,!0),o=e.getUint32(12,!0),i=e.getInt16(16,!0),s=e.getUint8(18),a=null;return s&&(a=r.subarray(19,21+t)),{outputChannelCount:t,preSkip:n,inputSampleRate:o,outputGain:i,channelMappingFamily:s,channelMappingTable:a}},Fc=[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],xs=r=>{let e=r[0]>>3;return{durationInSamples:Fc[e]}},bs=r=>{if(r.length<7)throw new Error("Setup header is too short.");if(r[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...r.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let t=r.length,n=new Uint8Array(t);for(let u=0;u<t;u++)n[u]=r[t-1-u];let o=new N(n),i=0;for(;o.getBitsLeft()>97;)if(o.readBits(1)===1){i=o.pos;break}if(i===0)throw new Error("Invalid Setup header: framing bit not found.");let s=0,a=!1,c=0;for(;o.getBitsLeft()>=97;){let u=o.pos,f=o.readBits(8),m=o.readBits(16),p=o.readBits(16);if(f>63||m!==0||p!==0){o.pos=u;break}if(o.skipBits(1),s++,s>64)break;o.clone().readBits(6)+1===s&&(a=!0,c=s)}if(!a)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);let l=c;o.pos=0,o.skipBits(i);let d=Array(l).fill(0);for(let u=l-1;u>=0;u--)o.skipBits(40),d[u]=o.readBits(1);return{modeBlockflags:d}},dn=(r,e,t)=>{switch(r){case"avc":{let n=qo(t,e),o=n.some(i=>ot(i)===nt.IDR);if(!o&&(!nr()||os()>=144))for(let i of n){if(ot(i)!==nt.SEI)continue;let a=an(i),c=1;do{let l=0;for(;;){let f=a[c++];if(f===void 0||(l+=f,f<255))break}let d=0;for(;;){let f=a[c++];if(f===void 0||(d+=f,f<255))break}if(l===6){let f=new N(a);f.pos=8*c;let m=I(f),p=f.readBits(1);if(m===0&&p===1){o=!0;break}}c+=d}while(c<a.length-1)}return o?"key":"delta"}case"hevc":return Wo(t,e).some(i=>{let s=Ae(i);return J.BLA_W_LP<=s&&s<=J.RSV_IRAP_VCL23})?"key":"delta";case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{let n=new N(t);if(n.readBits(2)!==2)return null;let o=n.readBits(1);return(n.readBits(1)<<1)+o===3&&n.skipBits(1),n.readBits(1)?null:n.readBits(1)===0?"key":"delta"}case"av1":{let n=!1;for(let{type:o,data:i}of hs(t))if(o===1){let s=new N(i);s.skipBits(4),n=!!s.readBits(1)}else if(o===3||o===6||o===7){if(n)return"key";let s=new N(i);return s.readBits(1)?null:s.readBits(2)===0?"key":"delta"}return null}default:se(r),h(!1)}},Ne;(function(r){r[r.STREAMINFO=0]="STREAMINFO",r[r.VORBIS_COMMENT=4]="VORBIS_COMMENT",r[r.PICTURE=6]="PICTURE"})(Ne||(Ne={}));var sr=(r,e)=>{let t=z(r),n=0,o=t.getUint32(n,!0);n+=4;let i=$.decode(r.subarray(n,n+o));n+=o,o>0&&(e.raw??={},e.raw.vendor??=i);let s=t.getUint32(n,!0);n+=4;for(let a=0;a<s;a++){let c=t.getUint32(n,!0);n+=4;let l=$.decode(r.subarray(n,n+c));n+=c;let d=l.indexOf("=");if(d===-1)continue;let u=l.slice(0,d).toUpperCase(),f=l.slice(d+1);switch(e.raw??={},e.raw[u]??=f,u){case"TITLE":e.title??=f;break;case"DESCRIPTION":e.description??=f;break;case"ARTIST":e.artist??=f;break;case"ALBUM":e.album??=f;break;case"ALBUMARTIST":e.albumArtist??=f;break;case"COMMENT":e.comment??=f;break;case"LYRICS":e.lyrics??=f;break;case"TRACKNUMBER":{let m=f.split("/"),p=Number.parseInt(m[0],10),g=m[1]&&Number.parseInt(m[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),g&&Number.isInteger(g)&&g>0&&(e.tracksTotal??=g)}break;case"TRACKTOTAL":{let m=Number.parseInt(f,10);Number.isInteger(m)&&m>0&&(e.tracksTotal??=m)}break;case"DISCNUMBER":{let m=f.split("/"),p=Number.parseInt(m[0],10),g=m[1]&&Number.parseInt(m[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),g&&Number.isInteger(g)&&g>0&&(e.discsTotal??=g)}break;case"DISCTOTAL":{let m=Number.parseInt(f,10);Number.isInteger(m)&&m>0&&(e.discsTotal??=m)}break;case"DATE":{let m=new Date(f);Number.isNaN(m.getTime())||(e.date??=m)}break;case"GENRE":e.genre??=f;break;case"METADATA_BLOCK_PICTURE":{let m=is(f),p=z(m),g=p.getUint32(0,!1),x=p.getUint32(4,!1),y=String.fromCharCode(...m.subarray(8,8+x)),b=p.getUint32(8+x,!1),w=$.decode(m.subarray(12+x,12+x+b)),k=p.getUint32(x+b+28),P=m.subarray(x+b+32,x+b+32+k);e.images??=[],e.images.push({data:P,mimeType:y,kind:g===3?"coverFront":g===4?"coverBack":"unknown",name:void 0,description:w||void 0})}break}}};var Q=class{constructor(e){this.input=e}};var fn=[],mn=[];var H=new Uint8Array(0),V=class r{constructor(e,t,n,o,i=-1,s,a){if(this.data=e,this.type=t,this.timestamp=n,this.duration=o,this.sequenceNumber=i,e===H&&s===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(s===void 0&&(s=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(n))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(o)||o<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(i))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");if(a!==void 0&&(typeof a!="object"||!a))throw new TypeError("sideData, when provided, must be an object.");if(a?.alpha!==void 0&&!(a.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(a?.alphaByteLength!==void 0&&(!Number.isInteger(a.alphaByteLength)||a.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=a??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===H}get microsecondTimestamp(){return Math.trunc(we*this.timestamp)}get microsecondDuration(){return Math.trunc(we*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let n=new Uint8Array(e.byteLength);return e.copyTo(n),new r(n,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");return new r(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}};var ys=r=>{let t=0,n=0,o=~r;o&128&&(o&=-129,t=-1),n=((o&240)>>4)+5;let i=(1<<n|(o&15)<<n-4|1<<n-5)-33;return t===0?i:-i};var Ts=r=>{let e=0,t=0,n=r^85;n&128&&(n&=-129,e=-1),t=((n&240)>>4)+4;let o=0;return t!==4?o=1<<t|(n&15)<<t-4|1<<t-5:o=n<<1|1,e===0?o:-o};tn();var ws=-1/0,ks=-1/0,lr=null;typeof FinalizationRegistry<"u"&&(lr=new FinalizationRegistry(r=>{let e=Date.now();r.type==="video"?(e-ws>=1e3&&(console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),ws=e),typeof VideoFrame<"u"&&r.data instanceof VideoFrame&&r.data.close()):(e-ks>=1e3&&(console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),ks=e),typeof AudioData<"u"&&r.data instanceof AudioData&&r.data.close())}));var vs=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Dc=new Set(vs),St=class r{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(we*this.timestamp)}get microsecondDuration(){return Math.trunc(we*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.format===void 0||!Dc.has(t.format))throw new TypeError("init.format must be one of: "+vs.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=le(e).slice(),this._layout=t.layout??Rc(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new cr(t.colorSpace)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(t?.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t?.timestamp!==void 0&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this._layout=null,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=t?.rotation??0,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new cr(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new r(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*we),duration:Math.trunc((t.duration??0)*we)||void 0}),t);let n=0,o=0;if("naturalWidth"in e?(n=e.naturalWidth,o=e.naturalHeight):"videoWidth"in e?(n=e.videoWidth,o=e.videoHeight):"width"in e&&(n=Number(e.width),o=Number(e.height)),!n||!o)throw new TypeError("Could not determine dimensions.");let i=new OffscreenCanvas(n,o),s=i.getContext("2d",{alpha:rr(),willReadFrequently:!0});h(s),s.drawImage(e,0,0),this._data=i,this._layout=null,this.format="RGBX",this.codedWidth=n,this.codedHeight=o,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new cr({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");lr?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return h(this._data!==null),it(this._data)?new r(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(h(this._layout),new r(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})):new r(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){this._closed||(lr?.unregister(this),it(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Ss(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)===null)throw new Error("Cannot get allocation size when format is null. Please manually provide an RGB pixel format in the options instead.");if(h(this._data!==null),!it(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let t=this.toVideoFrame(),n=t.allocationSize(e);return t.close(),n}return it(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,t={}){if(!Yr(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ss(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)===null)throw new Error("Cannot copy video sample data when format is null. Please manually provide an RGB pixel format in the options instead.");if(h(this._data!==null),!it(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){let n=this.toVideoFrame(),o=await n.copyTo(e,t);return n.close(),o}if(it(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array)return h(this._layout),le(e).set(this._data),this._layout;{let o=this._data.getContext("2d");h(o);let i=o.getImageData(0,0,this.codedWidth,this.codedHeight);return le(e).set(i.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return h(this._data!==null),it(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,n,o,i,s,a,c,l){let d=0,u=0,f=this.displayWidth,m=this.displayHeight,p=0,g=0,x=this.displayWidth,y=this.displayHeight;if(s!==void 0?(d=t,u=n,f=o,m=i,p=s,g=a,c!==void 0?(x=c,y=l):(x=f,y=m)):(p=t,g=n,o!==void 0&&(x=o,y=i)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(d))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(m)||m<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(g))throw new TypeError("dy must be a number.");if(!Number.isFinite(x)||x<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:d,sy:u,sWidth:f,sHeight:m}=this._rotateSourceRegion(d,u,f,m,this.rotation));let b=this.toCanvasImageSource();e.save();let w=p+x/2,k=g+y/2;e.translate(w,k),e.rotate(this.rotation*Math.PI/180);let P=this.rotation%180===0?1:x/y;e.scale(1/P,P),e.drawImage(b,d,u,f,m,-x/2,-y/2,x,y),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");t.crop!==void 0&&Ko(t.crop,"options.");let n=e.canvas.width,o=e.canvas.height,i=t.rotation??this.rotation,[s,a]=i%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];t.crop&&$o(t.crop,s,a);let c,l,d,u,{sx:f,sy:m,sWidth:p,sHeight:g}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??s,t.crop?.height??a,i);if(t.fit==="fill")c=0,l=0,d=n,u=o;else{let[y,b]=t.crop?[t.crop.width,t.crop.height]:[s,a],w=t.fit==="contain"?Math.min(n/y,o/b):Math.max(n/y,o/b);d=y*w,u=b*w,c=(n-d)/2,l=(o-u)/2}e.save();let x=i%180===0?1:d/u;e.translate(n/2,o/2),e.rotate(i*Math.PI/180),e.scale(1/x,x),e.translate(-n/2,-o/2),e.drawImage(this.toCanvasImageSource(),f,m,p,g,c,l,d,u),e.restore()}_rotateSourceRegion(e,t,n,o,i){return i===90?[e,t,n,o]=[t,this.codedHeight-e-n,o,n]:i===180?[e,t]=[this.codedWidth-e-n,this.codedHeight-t-o]:i===270&&([e,t,n,o]=[this.codedWidth-t-o,e,o,n]),{sx:e,sy:t,sWidth:n,sHeight:o}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(h(this._data!==null),this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}},cr=class{constructor(e){this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},it=r=>typeof VideoFrame<"u"&&r instanceof VideoFrame,$o=(r,e,t)=>{r.left=Math.min(r.left,e),r.top=Math.min(r.top,t),r.width=Math.min(r.width,e-r.left),r.height=Math.min(r.height,t-r.top),h(r.width>=0),h(r.height>=0)},Ko=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},Ss=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.colorSpace!==void 0&&!["display-p3","srgb"].includes(r.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(r.format!==void 0&&typeof r.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(r.layout!==void 0){if(!Array.isArray(r.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let e of r.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(r.rect!==void 0){if(!r.rect||typeof r.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(r.rect.x!==void 0&&(!Number.isInteger(r.rect.x)||r.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(r.rect.y!==void 0&&(!Number.isInteger(r.rect.y)||r.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(r.rect.width!==void 0&&(!Number.isInteger(r.rect.width)||r.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(r.rect.height!==void 0&&(!Number.isInteger(r.rect.height)||r.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},Rc=(r,e,t)=>{let n=Mc(r),o=[],i=0;for(let s of n){let a=Math.ceil(e/s.widthDivisor),c=Math.ceil(t/s.heightDivisor),l=a*s.sampleBytes,d=l*c;o.push({offset:i,stride:l}),i+=d}return o},Mc=r=>{let e=(t,n,o,i,s)=>{let a=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:n,widthDivisor:o,heightDivisor:i},{sampleBytes:n,widthDivisor:o,heightDivisor:i}];return s&&a.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),a};switch(r){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:se(r),h(!1)}},jo=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),vt=class r{get microsecondTimestamp(){return Math.trunc(we*this.timestamp)}get microsecondDuration(){return Math.trunc(we*this.duration)}constructor(e){if(this._closed=!1,ar(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!jo.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");let t=e.data.byteLength/(st(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let n;if(e.data instanceof ArrayBuffer)n=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))n=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let o=this.numberOfFrames*this.numberOfChannels*st(this.format);if(n.byteLength<o)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=n}lr?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!jo.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let t=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let o=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-n;if(o>this.numberOfFrames-n)throw new RangeError("frameCount out of range");let i=st(t),s=kt(t);if(s&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!s&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(s?o:o*this.numberOfChannels)*i}copyTo(e,t){if(!Yr(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!jo.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{planeIndex:n,format:o,frameCount:i,frameOffset:s}=t,a=this.format,c=o??this.format;if(!c)throw new Error("Destination format not determined");let l=this.numberOfFrames,d=this.numberOfChannels,u=s??0;if(u>=l)throw new RangeError("frameOffset out of range");let f=i!==void 0?i:l-u;if(f>l-u)throw new RangeError("frameCount out of range");let m=st(c),p=kt(c);if(p&&n>=d)throw new RangeError("planeIndex out of range");if(!p&&n!==0)throw new RangeError("planeIndex out of range");let x=(p?f:f*d)*m;if(e.byteLength<x)throw new RangeError("Destination buffer is too small");let y=z(e),b=Cs(c);if(ar(this._data))Oe()&&d>2&&c!==a?Bc(this._data,y,a,c,d,n,u,f):this._data.copyTo(e,{planeIndex:n,frameOffset:u,frameCount:f,format:c});else{let w=this._data,k=z(w),P=Ps(a),S=st(a),_=kt(a);for(let C=0;C<f;C++)if(p){let F=C*m,O;_?O=(n*l+(C+u))*S:O=((C+u)*d+n)*S;let R=P(k,O);b(y,F,R)}else for(let F=0;F<d;F++){let R=(C*d+F)*m,j;_?j=(F*l+(C+u))*S:j=((C+u)*d+F)*S;let We=P(k,j);b(y,R,We)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(ar(this._data)){let e=new r(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new r({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(lr?.unregister(this),ar(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(ar(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(kt(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(t,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{let e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(t,{planeIndex:n,format:"f32-planar"}),e.copyToChannel(t,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,o=e.numberOfChannels,i=e.sampleRate,s=e.length,a=Math.floor(n/o),c=0,l=s;for(;l>0;){let d=Math.min(a,l),u=new Float32Array(o*d);for(let f=0;f<o;f++)e.copyFromChannel(u.subarray(f*d,(f+1)*d),f,c);yield new r({format:"f32-planar",sampleRate:i,numberOfFrames:d,numberOfChannels:o,timestamp:t+c/i,data:u}),c+=d,l-=d}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,o=e.numberOfChannels,i=e.sampleRate,s=e.length,a=Math.floor(n/o),c=0,l=s,d=[];for(;l>0;){let u=Math.min(a,l),f=new Float32Array(o*u);for(let p=0;p<o;p++)e.copyFromChannel(f.subarray(p*u,(p+1)*u),p,c);let m=new r({format:"f32-planar",sampleRate:i,numberOfFrames:u,numberOfChannels:o,timestamp:t+c/i,data:f});d.push(m),c+=u,l-=u}return d}},st=r=>{switch(r){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},kt=r=>{switch(r){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Ps=r=>{switch(r){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},Cs=r=>{switch(r){case"u8":case"u8-planar":return(e,t,n)=>e.setUint8(t,Ze((n+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,n)=>e.setInt16(t,Ze(Math.round(n*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,n)=>e.setInt32(t,Ze(Math.round(n*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,n)=>e.setFloat32(t,n,!0)}},ar=r=>typeof AudioData<"u"&&r instanceof AudioData,Bc=(r,e,t,n,o,i,s,a)=>{let c=Ps(t),l=Cs(n),d=st(t),u=st(n),f=kt(t);if(kt(n))if(f){let p=new ArrayBuffer(a*d),g=z(p);r.copyTo(p,{planeIndex:i,frameOffset:s,frameCount:a,format:t});for(let x=0;x<a;x++){let y=x*d,b=x*u,w=c(g,y);l(e,b,w)}}else{let p=new ArrayBuffer(a*o*d),g=z(p);r.copyTo(p,{planeIndex:0,frameOffset:s,frameCount:a,format:t});for(let x=0;x<a;x++){let y=(x*o+i)*d,b=x*u,w=c(g,y);l(e,b,w)}}else if(f){let p=a*d,g=new ArrayBuffer(p),x=z(g);for(let y=0;y<o;y++){r.copyTo(g,{planeIndex:y,frameOffset:s,frameCount:a,format:t});for(let b=0;b<a;b++){let w=b*d,k=(b*o+y)*u,P=c(x,w);l(e,k,P)}}}else{let p=new ArrayBuffer(a*o*d),g=z(p);r.copyTo(p,{planeIndex:0,frameOffset:s,frameCount:a,format:t});for(let x=0;x<a;x++)for(let y=0;y<o;y++){let b=x*o+y,w=b*d,k=b*u,P=c(g,w);l(e,k,P)}}};var Pt=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.metadataOnly!==void 0&&typeof r.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(r.verifyKeyPackets!==void 0&&typeof r.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(r.verifyKeyPackets&&r.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},Ve=r=>{if(!or(r))throw new TypeError("timestamp must be a number.")},Xo=(r,e,t)=>t.verifyKeyPackets?e.then(async n=>{if(!n||n.type==="delta")return n;let o=await r.determinePacketType(n);return o&&(n.type=o),n}):e,at=class{constructor(e){if(!(e instanceof It))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(Pt(e),this._track.input._disposed)throw new q;return Xo(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){if(Ve(e),Pt(t),this._track.input._disposed)throw new q;return Xo(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof V))throw new TypeError("packet must be an EncodedPacket.");if(Pt(t),this._track.input._disposed)throw new q;return Xo(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Ve(e),Pt(t),this._track.input._disposed)throw new q;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let n=await this._track._backing.getKeyPacket(e,t);return n&&(h(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getKeyPacket(n.timestamp-1/this._track.timeResolution,t):n)}async getNextKeyPacket(e,t={}){if(!(e instanceof V))throw new TypeError("packet must be an EncodedPacket.");if(Pt(t),this._track.input._disposed)throw new q;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let n=await this._track._backing.getNextKeyPacket(e,t);return n&&(h(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getNextKeyPacket(n,t):n)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof V))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof V))throw new TypeError("endPacket must be an EncodedPacket.");if(Pt(n),this._track.input._disposed)throw new q;let o=[],{promise:i,resolve:s}=Z(),{promise:a,resolve:c}=Z(),l=!1,d=!1,u=null,f=[],m=()=>Math.max(2,f.length);(async()=>{let g=e??await this.getFirstPacket(n);for(;g&&!d&&!this._track.input._disposed&&!(t&&g.sequenceNumber>=t?.sequenceNumber);){if(o.length>m()){({promise:a,resolve:c}=Z()),await a;continue}o.push(g),s(),{promise:i,resolve:s}=Z(),g=await this.getNextPacket(g,n)}l=!0,s()})().catch(g=>{u||(u=g,s())});let p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new q;if(d)return{value:void 0,done:!0};if(u)throw u;if(o.length>0){let g=o.shift(),x=performance.now();for(f.push(x);f.length>0&&x-f[0]>=1e3;)f.shift();return c(),{value:g,done:!1}}else{if(l)return{value:void 0,done:!0};await i}}},async return(){return d=!0,c(),s(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}},ur=class{constructor(e,t){this.onSample=e,this.onError=t}},dr=class{mediaSamplesInRange(e=0,t=1/0){Ve(e),Ve(t);let n=[],o=!1,i=null,{promise:s,resolve:a}=Z(),{promise:c,resolve:l}=Z(),d=!1,u=!1,f=!1,m=null;(async()=>{let x=await this._createDecoder(S=>{if(l(),S.timestamp>=t&&(u=!0),u){S.close();return}i&&(S.timestamp>e?(n.push(i),o=!0):i.close()),S.timestamp>=e&&(n.push(S),o=!0),i=o?null:S,n.length>0&&(a(),{promise:s,resolve:a}=Z())},S=>{m||(m=S,a())}),y=this._createPacketSink(),b=await y.getKeyPacket(e,{verifyKeyPackets:!0})??await y.getFirstPacket(),w=b,k;if(t<1/0){let S=await y.getPacket(t),_=S?S.type==="key"&&S.timestamp===t?S:await y.getNextKeyPacket(S,{verifyKeyPackets:!0}):null;_&&(k=_)}let P=y.packets(b??void 0,k);for(await P.next();w&&!u&&!this._track.input._disposed;){let S=Is(n.length);if(n.length+x.getDecodeQueueSize()>S){({promise:c,resolve:l}=Z()),await c;continue}x.decode(w);let _=await P.next();if(_.done)break;w=_.value}await P.return(),!f&&!this._track.input._disposed&&await x.flush(),x.close(),!o&&i&&n.push(i),d=!0,a()})().catch(x=>{m||(m=x,a())});let p=this._track,g=()=>{i?.close();for(let x of n)x.close()};return{async next(){for(;;){if(p.input._disposed)throw g(),new q;if(f)return{value:void 0,done:!0};if(m)throw g(),m;if(n.length>0){let x=n.shift();return l(),{value:x,done:!1}}else if(!d)await s;else return{value:void 0,done:!0}}},async return(){return f=!0,u=!0,l(),a(),g(),{value:void 0,done:!0}},async throw(x){throw x},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){Ji(e);let t=Zi(e),n=[],o=[],{promise:i,resolve:s}=Z(),{promise:a,resolve:c}=Z(),l=!1,d=!1,u=null,f=g=>{o.push(g),s(),{promise:i,resolve:s}=Z()};(async()=>{let g=await this._createDecoder(S=>{if(c(),d){S.close();return}let _=0;for(;n.length>0&&S.timestamp-n[0]>-1e-10;)_++,n.shift();if(_>0)for(let C=0;C<_;C++)f(C<_-1?S.clone():S);else S.close()},S=>{u||(u=S,s())}),x=this._createPacketSink(),y=null,b=null,w=-1,k=async()=>{h(b);let S=b;for(g.decode(S);S.sequenceNumber<w;){let _=Is(o.length);for(;o.length+g.getDecodeQueueSize()>_&&!d;)({promise:a,resolve:c}=Z()),await a;if(d)break;let C=await x.getNextPacket(S);h(C),g.decode(C),S=C}w=-1},P=async()=>{await g.flush();for(let S=0;S<n.length;S++)f(null);n.length=0};for await(let S of t){if(Ve(S),d||this._track.input._disposed)break;let _=await x.getPacket(S),C=_&&await x.getKeyPacket(S,{verifyKeyPackets:!0});if(!C){w!==-1&&(await k(),await P()),f(null),y=null;continue}y&&(C.sequenceNumber!==b.sequenceNumber||_.timestamp<y.timestamp)&&(await k(),await P()),n.push(_.timestamp),w=Math.max(_.sequenceNumber,w),y=_,b=C}!d&&!this._track.input._disposed&&(w!==-1&&await k(),await P()),g.close(),l=!0,s()})().catch(g=>{u||(u=g,s())});let m=this._track,p=()=>{for(let g of o)g?.close()};return{async next(){for(;;){if(m.input._disposed)throw p(),new q;if(d)return{value:void 0,done:!0};if(u)throw p(),u;if(o.length>0){let g=o.shift();return h(g!==void 0),c(),{value:g,done:!1}}else if(!l)await i;else return{value:void 0,done:!0}}},async return(){return d=!0,c(),s(),p(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}},Is=r=>r===0?40:8,Qo=class extends ur{constructor(e,t,n,o,i,s){super(e,t),this.codec=n,this.decoderConfig=o,this.rotation=i,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new tr,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;let a=fn.find(c=>c.supports(n,o));if(a)this.customDecoder=new a,this.customDecoder.codec=n,this.customDecoder.config=o,this.customDecoder.onSample=c=>{if(!(c instanceof St))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=d=>{if(this.alphaQueue.length>0){let u=this.alphaQueue.shift();h(u!==void 0),this.mergeAlpha(d,u)}else this.colorQueue.push(d)};if(n==="avc"&&this.decoderConfig.description&&nr()){let d=ms(le(this.decoderConfig.description));if(d&&d.sequenceParameterSets.length>0){let u=Go(d.sequenceParameterSets[0]);u&&u.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let l=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:d=>{try{c(d)}catch(u){this.onError(u)}},error:d=>{d.stack=l,this.onError(d)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(h(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(h(this.decoder),Oe()||Bo(this.inputTimestamps,e.timestamp,t=>t),nr()&&this.currentPacketIndex===0&&this.codec==="avc"){let n=qo(e.data,this.decoderConfig).filter(i=>{let s=ot(i);return!(s>=20&&s<=31)}),o=ds(n,this.decoderConfig);e=new V(o,e.type,e.timestamp,e.duration)}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed){this.pushNullAlphaFrame();return}if(!this.merger)try{this.merger=new Yo}catch(n){console.error("Due to an error, only color data will be decoded.",n),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let n=i=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let s=this.colorQueue.shift();h(s!==void 0),this.mergeAlpha(s,i)}else this.alphaQueue.push(i);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let s=this.colorQueue.shift();h(s!==void 0),this.mergeAlpha(s,null)}else this.alphaQueue.push(null)},o=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:i=>{try{n(i)}catch(s){this.onError(s)}},error:i=>{i.stack=o,this.onError(i)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=dn(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=t==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){return Wo(e,this.decoderConfig).some(n=>{let o=Ae(n);return o===J.RASL_N||o===J.RASL_R})}sampleHandler(e){if(Oe()){if(this.sampleQueue.length>0&&e.timestamp>=Y(this.sampleQueue).timestamp){for(let t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}Bo(this.sampleQueue,e,t=>t.timestamp)}else{let t=this.inputTimestamps.shift();h(t!==void 0),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,t){if(!t){let i=new St(e);this.sampleHandler(i);return}h(this.merger),this.merger.update(e,t),e.close(),t.close();let n=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),o=new St(n);this.sampleHandler(o)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(h(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Oe()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(h(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},Yo=class{constructor(){typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");let e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
2341
2341
|
in vec2 a_position;
|
|
2342
2342
|
in vec2 a_texCoord;
|
|
2343
2343
|
out vec2 v_texCoord;
|
|
@@ -2359,7 +2359,7 @@ vec4 transition(vec2 uv) {
|
|
|
2359
2359
|
float alpha = texture(u_alphaTexture, v_texCoord).r;
|
|
2360
2360
|
fragColor = vec4(color, alpha);
|
|
2361
2361
|
}
|
|
2362
|
-
`),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){let n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),n}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let o=this.gl.getAttribLocation(this.program,"a_position"),i=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(o),this.gl.vertexAttribPointer(o,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,t){(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}},Ct=class extends dr{constructor(e){if(!(e instanceof ke))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=this._track.codec,o=this._track.rotation,i=await this._track.getDecoderConfig(),s=this._track.timeResolution;return h(n&&i),new Qo(e,t,n,i,o,s)}_createPacketSink(){return new st(this._track)}async getSample(e){Ne(e);for await(let t of this.mediaSamplesAtTimestamps([e]))return t;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}},fr=class{constructor(e,t={}){if(this._nextCanvasIndex=0,!(e instanceof ke))throw new TypeError("videoTrack must be an InputVideoTrack.");if(t&&typeof t!="object")throw new TypeError("options must be an object.");if(t.alpha!==void 0&&typeof t.alpha!="boolean")throw new TypeError("options.alpha, when provided, must be a boolean.");if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(t.fit!==void 0&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(t.crop!==void 0&&Ko(t.crop,"options."),t.poolSize!==void 0&&(typeof t.poolSize!="number"||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");let n=t.rotation??e.rotation,[o,i]=n%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],s=t.crop;s&&$o(s,o,i);let[a,c]=s?[s.width,s.height]:[o,i],l=a/c;t.width!==void 0&&t.height===void 0?(a=t.width,c=Math.round(a/l)):t.width===void 0&&t.height!==void 0?(c=t.height,a=Math.round(c*l)):t.width!==void 0&&t.height!==void 0&&(a=t.width,c=t.height),this._videoTrack=e,this._alpha=t.alpha??!1,this._width=a,this._height=c,this._rotation=n,this._crop=s,this._fit=t.fit??"fill",this._videoSampleSink=new Ct(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let t=this._canvasPool[this._nextCanvasIndex],n=!1;t||(typeof document<"u"?(t=document.createElement("canvas"),t.width=this._width,t.height=this._height):t=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=t),n=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let o=t.getContext("2d",{alpha:this._alpha||rr()});h(o),o.resetTransform(),n||(!this._alpha&&rr()?(o.fillStyle="black",o.fillRect(0,0,this._width,this._height)):o.clearRect(0,0,this._width,this._height)),e.drawWithFit(o,{fit:this._fit,rotation:this._rotation,crop:this._crop});let i={canvas:t,timestamp:e.timestamp,duration:e.duration};return e.close(),i}async getCanvas(e){Ne(e);let t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return zo(this._videoSampleSink.samples(e,t),n=>this._videoSampleToWrappedCanvas(n))}canvasesAtTimestamps(e){return zo(this._videoSampleSink.samplesAtTimestamps(e),t=>t&&this._videoSampleToWrappedCanvas(t))}},Zo=class extends ur{constructor(e,t,n,o){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new tr,this.customDecoderQueueSize=0,this.currentTimestamp=null;let i=a=>{(this.currentTimestamp===null||Math.abs(a.timestamp-this.currentTimestamp)>=a.duration)&&(this.currentTimestamp=a.timestamp);let c=this.currentTimestamp;if(this.currentTimestamp+=a.duration,a.numberOfFrames===0){a.close();return}let l=o.sampleRate;a.setTimestamp(Math.round(c*l)/l),e(a)},s=mn.find(a=>a.supports(n,o));if(s)this.customDecoder=new s,this.customDecoder.codec=n,this.customDecoder.config=o,this.customDecoder.onSample=a=>{if(!(a instanceof vt))throw new TypeError("The argument passed to onSample must be an AudioSample.");i(a)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let a=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:c=>{try{i(new vt(c))}catch(l){this.onError(l)}},error:c=>{c.stack=a,this.onError(c)}}),this.decoder.configure(o)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(h(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(h(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(h(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(h(this.decoder),this.decoder.close())}},Jo=class extends ur{constructor(e,t,n){super(e,t),this.decoderConfig=n,this.currentTimestamp=null,h(ze.includes(n.codec)),this.codec=n.codec;let{dataType:o,sampleSize:i,littleEndian:s}=sn(this.codec);switch(this.inputSampleSize=i,i){case 1:o==="unsigned"?this.readInputValue=(a,c)=>a.getUint8(c)-2**7:o==="signed"?this.readInputValue=(a,c)=>a.getInt8(c):o==="ulaw"?this.readInputValue=(a,c)=>ys(a.getUint8(c)):o==="alaw"?this.readInputValue=(a,c)=>Ts(a.getUint8(c)):h(!1);break;case 2:o==="unsigned"?this.readInputValue=(a,c)=>a.getUint16(c,s)-2**15:o==="signed"?this.readInputValue=(a,c)=>a.getInt16(c,s):h(!1);break;case 3:o==="unsigned"?this.readInputValue=(a,c)=>Qe(a,c,s)-2**23:o==="signed"?this.readInputValue=(a,c)=>es(a,c,s):h(!1);break;case 4:o==="unsigned"?this.readInputValue=(a,c)=>a.getUint32(c,s)-2**31:o==="signed"?this.readInputValue=(a,c)=>a.getInt32(c,s):o==="float"?this.readInputValue=(a,c)=>a.getFloat32(c,s):h(!1);break;case 8:o==="float"?this.readInputValue=(a,c)=>a.getFloat64(c,s):h(!1);break;default:se(i),h(!1)}switch(i){case 1:o==="ulaw"||o==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(a,c,l)=>a.setInt16(c,l,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(a,c,l)=>a.setUint8(c,l+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(a,c,l)=>a.setInt16(c,l,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(a,c,l)=>a.setInt32(c,l<<8,!0);break;case 4:this.outputSampleSize=4,o==="float"?(this.outputFormat="f32",this.writeOutputValue=(a,c,l)=>a.setFloat32(c,l,!0)):(this.outputFormat="s32",this.writeOutputValue=(a,c,l)=>a.setInt32(c,l,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(a,c,l)=>a.setFloat32(c,l,!0);break;default:se(i),h(!1)}}getDecodeQueueSize(){return 0}decode(e){let t=z(e.data),n=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,o=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,i=new ArrayBuffer(o),s=new DataView(i);for(let d=0;d<n*this.decoderConfig.numberOfChannels;d++){let u=d*this.inputSampleSize,f=d*this.outputSampleSize,m=this.readInputValue(t,u);this.writeOutputValue(s,f,m)}let a=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=a)&&(this.currentTimestamp=e.timestamp);let c=this.currentTimestamp;this.currentTimestamp+=a;let l=new vt({format:this.outputFormat,data:i,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:c});this.onSample(l)}async flush(){}close(){}},mr=class extends dr{constructor(e){if(!(e instanceof G))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=this._track.codec,o=await this._track.getDecoderConfig();return h(n&&o),ze.includes(o.codec)?new Jo(e,t,o):new Zo(e,t,n,o)}_createPacketSink(){return new st(this._track)}async getSample(e){Ne(e);for await(let t of this.mediaSamplesAtTimestamps([e]))return t;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}};var It=class{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof ke}isAudioTrack(){return this instanceof G}get id(){return this._backing.getId()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){let t=new st(this),n=1/0,o=-1/0,i=0,s=0;for await(let a of t.packets(void 0,void 0,{metadataOnly:!0})){if(i>=e&&a.timestamp>=o)break;n=Math.min(n,a.timestamp),o=Math.max(o,a.timestamp+a.duration),i++,s+=a.byteLength}return{packetCount:i,averagePacketRate:i?Number((i/(o-n)).toPrecision(16)):0,averageBitrate:i?Number((8*s/(o-n)).toPrecision(16)):0}}},ke=class extends It{constructor(e,t){super(e,t),this._backing=t}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get displayWidth(){return this._backing.getRotation()%180===0?this._backing.getCodedWidth():this._backing.getCodedHeight()}get displayHeight(){return this._backing.getRotation()%180===0?this._backing.getCodedHeight():this._backing.getCodedWidth()}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pg"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=this._backing.getCodec();return h(t!==null),fn.some(o=>o.supports(t,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof V))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");if(this.codec===null)return null;let t=await this.getDecoderConfig();return h(t),dn(this.codec,t,e.data)}},G=class extends It{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=this._backing.getCodec();return h(t!==null),mn.some(n=>n.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof V))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}};var As=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isQuickTime?"quicktime":"mp4");if(r.codecStrings.length>0){let n=[...new Set(r.codecStrings)];t+=`; codecs="${n.join(", ")}"`}return t};var at=8,At=16,Ae=r=>{let e=v(r),t=L(r,4),n=8;e===1&&(e=ne(r),n=16);let i=e-n;return i<0?null:{name:t,totalSize:e,headerSize:n,contentSize:i}},Ve=r=>_e(r)/65536,pn=r=>_e(r)/1073741824,hn=r=>{let e=0;for(let t=0;t<4;t++){e<<=7;let n=A(r);if(e|=n&127,(n&128)===0)break}return e},ue=r=>{let e=W(r);return r.skip(2),e=Math.min(e,r.remainingLength),$.decode(E(r,e))},_s=r=>{let e=Ae(r);if(!e||e.name!=="data"||r.remainingLength<8)return null;let t=v(r);r.skip(4);let n=E(r,e.contentSize-8);switch(t){case 1:return $.decode(n);case 2:return new TextDecoder("utf-16be").decode(n);case 13:return new Oe(n,"image/jpeg");case 14:return new Oe(n,"image/png");case 27:return new Oe(n,"image/bmp");default:return n}};var gn=class extends Q{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(t=>t.inputTrack.getCodecParameterString()));return As({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(t=>t.info?.type==="video"),hasAudio:this.tracks.some(t=>t.info?.type==="audio"),codecStrings:e.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,at,At);if(t instanceof Promise&&(t=await t),!t)break;let n=e,o=Ae(t);if(!o)break;if(o.name==="ftyp"){let i=L(t,4);this.isQuickTime=i==="qt "}else if(o.name==="moov"){let i=this.reader.requestSlice(t.filePos,o.contentSize);if(i instanceof Promise&&(i=await i),!i)break;this.moovSlice=i,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((s,a)=>Number(a.disposition.default)-Number(s.disposition.default));for(let s of this.tracks){let a=s.editListPreviousSegmentDurations/this.movieTimescale;s.editListOffset-=Math.round(a*s.timescale)}break}e=n+o.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let t=this.reader.requestSlice(this.reader.fileSize-4,4);t instanceof Promise&&(t=await t),h(t);let n=v(t),o=this.reader.fileSize-n;if(o>=0&&o<=this.reader.fileSize-At){let i=this.reader.requestSliceRange(o,at,At);if(i instanceof Promise&&(i=await i),i){let s=Ae(i);if(s&&s.name==="mfra"){let a=this.reader.requestSlice(i.filePos,s.contentSize);a instanceof Promise&&(a=await a),a&&this.readContiguousBoxes(a)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=t,h(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&ze.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){h(e.info?.type==="audio");let i=sn(e.info.codec),s=[],a=[];for(let c=0;c<t.sampleToChunk.length;c++){let l=t.sampleToChunk[c],d=t.sampleToChunk[c+1],u=(d?d.startChunkIndex:t.chunkOffsets.length)-l.startChunkIndex;for(let f=0;f<u;f++){let m=l.startSampleIndex+f*l.samplesPerChunk,p=m+l.samplesPerChunk,g=B(t.sampleTimingEntries,m,C=>C.startIndex),x=t.sampleTimingEntries[g],y=B(t.sampleTimingEntries,p,C=>C.startIndex),b=t.sampleTimingEntries[y],w=x.startDecodeTimestamp+(m-x.startIndex)*x.delta,P=b.startDecodeTimestamp+(p-b.startIndex)*b.delta-w,S=Y(s);S&&S.delta===P?S.count++:s.push({startIndex:l.startChunkIndex+f,startDecodeTimestamp:w,count:1,delta:P});let _=l.samplesPerChunk*i.sampleSize*e.info.numberOfChannels;a.push(_)}l.startSampleIndex=l.startChunkIndex,l.samplesPerChunk=1}t.sampleTimingEntries=s,t.sampleSizes=a}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let i of t.sampleTimingEntries)for(let s=0;s<i.count;s++)t.presentationTimestamps.push({presentationTimestamp:i.startDecodeTimestamp+s*i.delta,sampleIndex:i.startIndex+s});for(let i of t.sampleCompositionTimeOffsets)for(let s=0;s<i.count;s++){let a=i.startIndex+s,c=t.presentationTimestamps[a];c&&(c.presentationTimestamp+=i.offset)}t.presentationTimestamps.sort((i,s)=>i.presentationTimestamp-s.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let i=0;i<t.presentationTimestamps.length;i++)t.presentationTimestampIndexMap[t.presentationTimestamps[i].sampleIndex]=i}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,at,At);t instanceof Promise&&(t=await t),h(t);let n=Ae(t);h(n?.name==="moof");let o=this.reader.requestSlice(e,n.totalSize);o instanceof Promise&&(o=await o),h(o),this.traverseBox(o);let i=this.lastReadFragment;h(i&&i.moofOffset===e);for(let[,s]of i.trackData){let a=s.track,{fragmentPositionCache:c}=a;if(!s.startTimestampIsFinal){let d=a.fragmentLookupTable.find(u=>u.moofOffset===i.moofOffset);if(d)ei(s,d.timestamp);else{let u=B(c,i.moofOffset-1,f=>f.moofOffset);if(u!==-1){let f=c[u];ei(s,f.endTimestamp)}}s.startTimestampIsFinal=!0}let l=B(c,s.startTimestamp,d=>d.startTimestamp);(l===-1||c[l].moofOffset!==i.moofOffset)&&c.splice(l+1,0,{moofOffset:i.moofOffset,startTimestamp:s.startTimestamp,endTimestamp:s.endTimestamp})}return i}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-at&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-at;){let n=e.filePos,o=Ae(e);if(!o)break;yield{boxInfo:o,slice:e},e.filePos=n+o.totalSize}}traverseBox(e){let t=e.filePos,n=Ae(e);if(!n)return!1;let o=e.filePos,i=t+n.totalSize;switch(n.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"mvhd":{let s=A(e);e.skip(3),s===1?(e.skip(16),this.movieTimescale=v(e),this.movieDurationInTimescale=ne(e)):(e.skip(8),this.movieTimescale=v(e),this.movieDurationInTimescale=v(e))}break;case"trak":{let s={id:-1,demuxer:this,inputTrack:null,disposition:{...te},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:K,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=s,this.readContiguousBoxes(e.slice(o,n.contentSize)),s.id!==-1&&s.timescale!==-1&&s.info!==null){if(s.info.type==="video"&&s.info.width!==-1){let a=s;s.inputTrack=new ke(this.input,new ti(a)),this.tracks.push(s)}else if(s.info.type==="audio"&&s.info.numberOfChannels!==-1){let a=s;s.inputTrack=new G(this.input,new ri(a)),this.tracks.push(s)}}this.currentTrack=null}break;case"tkhd":{let s=this.currentTrack;if(!s)break;let a=A(e),l=!!(Le(e)&1);if(s.disposition.default=l,a===0)e.skip(8),s.id=v(e),e.skip(4),s.durationInMovieTimescale=v(e);else if(a===1)e.skip(16),s.id=v(e),e.skip(4),s.durationInMovieTimescale=ne(e);else throw new Error(`Incorrect track header version ${a}.`);e.skip(16);let d=[Ve(e),Ve(e),pn(e),Ve(e),Ve(e),pn(e),Ve(e),Ve(e),pn(e)],u=$r(rs(Nc(d),90));h(u===0||u===90||u===180||u===270),s.rotation=u}break;case"elst":{let s=this.currentTrack;if(!s)break;let a=A(e);e.skip(3);let c=!1,l=0,d=v(e);for(let u=0;u<d;u++){let f=a===1?ne(e):v(e),m=a===1?Fs(e):_e(e),p=Ve(e);if(f!==0){if(c){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(m===-1){l+=f;continue}if(p!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}s.editListPreviousSegmentDurations=l,s.editListOffset=m,c=!0}}}break;case"mdhd":{let s=this.currentTrack;if(!s)break;let a=A(e);e.skip(3),a===0?(e.skip(8),s.timescale=v(e),s.durationInMediaTimescale=v(e)):a===1&&(e.skip(16),s.timescale=v(e),s.durationInMediaTimescale=ne(e));let c=W(e);if(c>0){s.languageCode="";for(let l=0;l<3;l++)s.languageCode=String.fromCharCode(96+(c&31))+s.languageCode,c>>=5;Jr(s.languageCode)||(s.languageCode=K)}}break;case"hdlr":{let s=this.currentTrack;if(!s)break;e.skip(8);let a=L(e,4);a==="vide"?s.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:a==="soun"&&(s.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{let s=this.currentTrack;if(!s)break;s.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(o,n.contentSize))}break;case"stsd":{let s=this.currentTrack;if(!s||s.info===null||s.sampleTable)break;let a=A(e);e.skip(3);let c=v(e);for(let l=0;l<c;l++){let d=e.filePos,u=Ae(e);if(!u)break;s.internalCodecId=u.name;let f=u.name.toLowerCase();if(s.info.type==="video")f==="avc1"||f==="avc3"?(s.info.codec="avc",s.info.avcType=f==="avc1"?1:3):f==="hvc1"||f==="hev1"?s.info.codec="hevc":f==="vp08"?s.info.codec="vp8":f==="vp09"?s.info.codec="vp9":f==="av01"?s.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${u.name}').`),e.skip(24),s.info.width=W(e),s.info.height=W(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,d+u.totalSize-e.filePos));else{f==="mp4a"||(f==="opus"?s.info.codec="opus":f==="flac"?s.info.codec="flac":f==="twos"||f==="sowt"||f==="raw "||f==="in24"||f==="in32"||f==="fl32"||f==="fl64"||f==="lpcm"||f==="ipcm"||f==="fpcm"||(f==="ulaw"?s.info.codec="ulaw":f==="alaw"?s.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${u.name}').`))),e.skip(8);let m=W(e);e.skip(6);let p=W(e),g=W(e);e.skip(4);let x=v(e)/65536;if(a===0&&m>0){if(m===1)e.skip(4),g=8*v(e),e.skip(8);else if(m===2){e.skip(4),x=bn(e),p=v(e),e.skip(4),g=v(e);let y=v(e);if(e.skip(8),f==="lpcm"){let b=g+7>>3,w=!!(y&1),k=!!(y&2),P=y&4?-1:0;g>0&&g<=64&&(w?g===32&&(s.info.codec=k?"pcm-f32be":"pcm-f32"):P&1<<b-1?b===1?s.info.codec="pcm-s8":b===2?s.info.codec=k?"pcm-s16be":"pcm-s16":b===3?s.info.codec=k?"pcm-s24be":"pcm-s24":b===4&&(s.info.codec=k?"pcm-s32be":"pcm-s32"):b===1&&(s.info.codec="pcm-u8")),s.info.codec===null&&console.warn("Unsupported PCM format.")}}}s.info.codec==="opus"&&(x=tt),s.info.numberOfChannels=p,s.info.sampleRate=x,f==="twos"?g===8?s.info.codec="pcm-s8":g===16?s.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${g} for codec 'twos'.`),s.info.codec=null):f==="sowt"?g===8?s.info.codec="pcm-s8":g===16?s.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${g} for codec 'sowt'.`),s.info.codec=null):f==="raw "?s.info.codec="pcm-u8":f==="in24"?s.info.codec="pcm-s24be":f==="in32"?s.info.codec="pcm-s32be":f==="fl32"?s.info.codec="pcm-f32be":f==="fl64"?s.info.codec="pcm-f64be":f==="ipcm"?s.info.codec="pcm-s16be":f==="fpcm"&&(s.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,d+u.totalSize-e.filePos))}}}break;case"avcC":{let s=this.currentTrack;if(!s)break;h(s.info),s.info.codecDescription=E(e,n.contentSize)}break;case"hvcC":{let s=this.currentTrack;if(!s)break;h(s.info),s.info.codecDescription=E(e,n.contentSize)}break;case"vpcC":{let s=this.currentTrack;if(!s)break;h(s.info?.type==="video"),e.skip(4);let a=A(e),c=A(e),l=A(e),d=l>>4,u=l>>1&7,f=l&1,m=A(e),p=A(e),g=A(e);s.info.vp9CodecInfo={profile:a,level:c,bitDepth:d,chromaSubsampling:u,videoFullRangeFlag:f,colourPrimaries:m,transferCharacteristics:p,matrixCoefficients:g}}break;case"av1C":{let s=this.currentTrack;if(!s)break;h(s.info?.type==="video"),e.skip(1);let a=A(e),c=a>>5,l=a&31,d=A(e),u=d>>7,f=d>>6&1,m=d>>5&1,p=d>>4&1,g=d>>3&1,x=d>>2&1,y=d&3,b=c===2&&f?m?12:10:f?10:8;s.info.av1CodecInfo={profile:c,level:l,tier:u,bitDepth:b,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:x,chromaSamplePosition:y}}break;case"colr":{let s=this.currentTrack;if(!s||(h(s.info?.type==="video"),L(e,4)!=="nclx"))break;let c=W(e),l=W(e),d=W(e),u=!!(A(e)&128);s.info.colorSpace={primaries:Kr[c],transfer:Xr[l],matrix:Qr[d],fullRange:u}}break;case"wave":this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"esds":{let s=this.currentTrack;if(!s)break;h(s.info?.type==="audio"),e.skip(4);let a=A(e);h(a===3),hn(e),e.skip(2);let c=A(e),l=(c&128)!==0,d=(c&64)!==0,u=(c&32)!==0;if(l&&e.skip(2),d){let x=A(e);e.skip(x)}u&&e.skip(2);let f=A(e);h(f===4);let m=hn(e),p=e.filePos,g=A(e);if(g===64||g===103?(s.info.codec="aac",s.info.aacCodecInfo={isMpeg2:g===103}):g===105||g===107?s.info.codec="mp3":g===221?s.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${g}) - discarding track.`),e.skip(12),m>e.filePos-p){let x=A(e);h(x===5);let y=hn(e);if(s.info.codecDescription=E(e,y),s.info.codec==="aac"){let b=Lo(s.info.codecDescription);b.numberOfChannels!==null&&(s.info.numberOfChannels=b.numberOfChannels),b.sampleRate!==null&&(s.info.sampleRate=b.sampleRate)}}}break;case"enda":{let s=this.currentTrack;if(!s)break;h(s.info?.type==="audio"),W(e)&255&&(s.info.codec==="pcm-s16be"?s.info.codec="pcm-s16":s.info.codec==="pcm-s24be"?s.info.codec="pcm-s24":s.info.codec==="pcm-s32be"?s.info.codec="pcm-s32":s.info.codec==="pcm-f32be"?s.info.codec="pcm-f32":s.info.codec==="pcm-f64be"&&(s.info.codec="pcm-f64"))}break;case"pcmC":{let s=this.currentTrack;if(!s)break;h(s.info?.type==="audio"),e.skip(4);let c=!!(A(e)&1),l=A(e);s.info.codec==="pcm-s16be"?c?l===16?s.info.codec="pcm-s16":l===24?s.info.codec="pcm-s24":l===32?s.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${l}.`),s.info.codec=null):l===16?s.info.codec="pcm-s16be":l===24?s.info.codec="pcm-s24be":l===32?s.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${l}.`),s.info.codec=null):s.info.codec==="pcm-f32be"&&(c?l===32?s.info.codec="pcm-f32":l===64?s.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${l}.`),s.info.codec=null):l===32?s.info.codec="pcm-f32be":l===64?s.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${l}.`),s.info.codec=null));break}case"dOps":{let s=this.currentTrack;if(!s)break;h(s.info?.type==="audio"),e.skip(1);let a=A(e),c=W(e),l=v(e),d=pr(e),u=A(e),f;u!==0?f=E(e,2+a):f=new Uint8Array(0);let m=new Uint8Array(19+f.byteLength),p=new DataView(m.buffer);p.setUint32(0,1332770163,!1),p.setUint32(4,1214603620,!1),p.setUint8(8,1),p.setUint8(9,a),p.setUint16(10,c,!0),p.setUint32(12,l,!0),p.setInt16(16,d,!0),p.setUint8(18,u),m.set(f,19),s.info.codecDescription=m,s.info.numberOfChannels=a}break;case"dfLa":{let s=this.currentTrack;if(!s)break;h(s.info?.type==="audio"),e.skip(4);let a=127,c=128,l=e.filePos;for(;e.filePos<i;){let p=A(e),g=Le(e);if((p&a)===Ue.STREAMINFO){e.skip(10);let y=v(e),b=y>>>12,w=(y>>9&7)+1;s.info.sampleRate=b,s.info.numberOfChannels=w,e.skip(20)}else e.skip(g);if(p&c)break}let d=e.filePos;e.filePos=l;let u=E(e,d-l),f=new Uint8Array(4+u.byteLength);new DataView(f.buffer).setUint32(0,1716281667,!1),f.set(u,4),s.info.codecDescription=f}break;case"stts":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=v(e),c=0,l=0;for(let d=0;d<a;d++){let u=v(e),f=v(e);s.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:l,count:u,delta:f}),c+=u,l+=u*f}}break;case"ctts":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=v(e),c=0;for(let l=0;l<a;l++){let d=v(e),u=_e(e);s.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:d,offset:u}),c+=d}}break;case"stsz":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=v(e),c=v(e);if(a===0)for(let l=0;l<c;l++){let d=v(e);s.sampleTable.sampleSizes.push(d)}else s.sampleTable.sampleSizes.push(a)}break;case"stz2":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4),e.skip(3);let a=A(e),c=v(e),l=E(e,Math.ceil(c*a/8)),d=new N(l);for(let u=0;u<c;u++){let f=d.readBits(a);s.sampleTable.sampleSizes.push(f)}}break;case"stss":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4),s.sampleTable.keySampleIndices=[];let a=v(e);for(let c=0;c<a;c++){let l=v(e)-1;s.sampleTable.keySampleIndices.push(l)}s.sampleTable.keySampleIndices[0]!==0&&s.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=v(e);for(let l=0;l<a;l++){let d=v(e)-1,u=v(e),f=v(e);s.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:d,samplesPerChunk:u,sampleDescriptionIndex:f})}let c=0;for(let l=0;l<s.sampleTable.sampleToChunk.length;l++)if(s.sampleTable.sampleToChunk[l].startSampleIndex=c,l<s.sampleTable.sampleToChunk.length-1){let u=s.sampleTable.sampleToChunk[l+1].startChunkIndex-s.sampleTable.sampleToChunk[l].startChunkIndex;c+=u*s.sampleTable.sampleToChunk[l].samplesPerChunk}}break;case"stco":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=v(e);for(let c=0;c<a;c++){let l=v(e);s.sampleTable.chunkOffsets.push(l)}}break;case"co64":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=v(e);for(let c=0;c<a;c++){let l=ne(e);s.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"mehd":{let s=A(e);e.skip(3);let a=s===1?ne(e):v(e);this.movieDurationInTimescale=a}break;case"trex":{e.skip(4);let s=v(e),a=v(e),c=v(e),l=v(e),d=v(e);this.fragmentTrackDefaults.push({trackId:s,defaultSampleDescriptionIndex:a,defaultSampleDuration:c,defaultSampleSize:l,defaultSampleFlags:d})}break;case"tfra":{let s=A(e);e.skip(3);let a=v(e),c=this.tracks.find(b=>b.id===a);if(!c)break;let l=v(e),d=(l&48)>>4,u=(l&12)>>2,f=l&3,m=[A,W,Le,v],p=m[d],g=m[u],x=m[f],y=v(e);for(let b=0;b<y;b++){let w=s===1?ne(e):v(e),k=s===1?ne(e):v(e);p(e),g(e),x(e),c.fragmentLookupTable.push({timestamp:w,moofOffset:k})}c.fragmentLookupTable.sort((b,w)=>b.timestamp-w.timestamp);for(let b=0;b<c.fragmentLookupTable.length-1;b++){let w=c.fragmentLookupTable[b],k=c.fragmentLookupTable[b+1];w.timestamp===k.timestamp&&(c.fragmentLookupTable.splice(b+1,1),b--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:n.totalSize,implicitBaseDataOffset:t,trackData:new Map},this.readContiguousBoxes(e.slice(o,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(h(this.currentFragment),this.readContiguousBoxes(e.slice(o,n.contentSize)),this.currentTrack){let s=this.currentFragment.trackData.get(this.currentTrack.id);if(s){let{currentFragmentState:a}=this.currentTrack;h(a),a.startTimestamp!==null&&(ei(s,a.startTimestamp),s.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{h(this.currentFragment),e.skip(1);let s=Le(e),a=!!(s&1),c=!!(s&2),l=!!(s&8),d=!!(s&16),u=!!(s&32),f=!!(s&65536),m=!!(s&131072),p=v(e),g=this.tracks.find(y=>y.id===p);if(!g)break;let x=this.fragmentTrackDefaults.find(y=>y.trackId===p);this.currentTrack=g,g.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:x?.defaultSampleDescriptionIndex??null,defaultSampleDuration:x?.defaultSampleDuration??null,defaultSampleSize:x?.defaultSampleSize??null,defaultSampleFlags:x?.defaultSampleFlags??null,startTimestamp:null},a?g.currentFragmentState.baseDataOffset=ne(e):m&&(g.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(g.currentFragmentState.sampleDescriptionIndex=v(e)),l&&(g.currentFragmentState.defaultSampleDuration=v(e)),d&&(g.currentFragmentState.defaultSampleSize=v(e)),u&&(g.currentFragmentState.defaultSampleFlags=v(e)),f&&(g.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let s=this.currentTrack;if(!s)break;h(s.currentFragmentState);let a=A(e);e.skip(3);let c=a===0?v(e):ne(e);s.currentFragmentState.startTimestamp=c}break;case"trun":{let s=this.currentTrack;if(!s)break;if(h(this.currentFragment),h(s.currentFragmentState),this.currentFragment.trackData.has(s.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}let a=A(e),c=Le(e),l=!!(c&1),d=!!(c&4),u=!!(c&256),f=!!(c&512),m=!!(c&1024),p=!!(c&2048),g=v(e),x=s.currentFragmentState.baseDataOffset;l&&(x+=_e(e));let y=null;d&&(y=v(e));let b=x;if(g===0){this.currentFragment.implicitBaseDataOffset=b;break}let w=0,k={track:s,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(s.id,k);for(let _=0;_<g;_++){let C;u?C=v(e):(h(s.currentFragmentState.defaultSampleDuration!==null),C=s.currentFragmentState.defaultSampleDuration);let F;f?F=v(e):(h(s.currentFragmentState.defaultSampleSize!==null),F=s.currentFragmentState.defaultSampleSize);let O;m?O=v(e):(h(s.currentFragmentState.defaultSampleFlags!==null),O=s.currentFragmentState.defaultSampleFlags),_===0&&y!==null&&(O=y);let R=0;p&&(a===0?R=v(e):R=_e(e));let j=!(O&65536);k.samples.push({presentationTimestamp:w+R,duration:C,byteOffset:b,byteSize:F,isKeyFrame:j}),b+=F,w+=C}k.presentationTimestamps=k.samples.map((_,C)=>({presentationTimestamp:_.presentationTimestamp,sampleIndex:C})).sort((_,C)=>_.presentationTimestamp-C.presentationTimestamp);for(let _=0;_<k.presentationTimestamps.length;_++){let C=k.presentationTimestamps[_],F=k.samples[C.sampleIndex];if(k.firstKeyFrameTimestamp===null&&F.isKeyFrame&&(k.firstKeyFrameTimestamp=F.presentationTimestamp),_<k.presentationTimestamps.length-1){let O=k.presentationTimestamps[_+1];F.duration=O.presentationTimestamp-C.presentationTimestamp}}let P=k.samples[k.presentationTimestamps[0].sampleIndex],S=k.samples[Y(k.presentationTimestamps).sampleIndex];k.startTimestamp=P.presentationTimestamp,k.endTimestamp=S.presentationTimestamp+S.duration,this.currentFragment.implicitBaseDataOffset=b}break;case"udta":{let s=this.iterateContiguousBoxes(e.slice(o,n.contentSize));for(let{boxInfo:a,slice:c}of s){if(a.name!=="meta"&&!this.currentTrack){let l=c.filePos;this.metadataTags.raw??={},a.name[0]==="\xA9"?this.metadataTags.raw[a.name]??=ue(c):this.metadataTags.raw[a.name]??=E(c,a.contentSize),c.filePos=l}switch(a.name){case"meta":c.skip(-a.headerSize),this.traverseBox(c);break;case"\xA9nam":case"name":this.currentTrack?this.currentTrack.name=$.decode(E(c,a.contentSize)):this.metadataTags.title??=ue(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=ue(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=ue(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=ue(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=ue(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=ue(c));break;case"\xA9day":if(!this.currentTrack){let l=new Date(ue(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=ue(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=ue(c));break}}}break;case"meta":{if(this.currentTrack)break;let a=v(e)!==0;this.currentMetadataKeys=new Map,a?this.readContiguousBoxes(e.slice(o,n.contentSize)):this.readContiguousBoxes(e.slice(o+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let s=v(e);for(let a=0;a<s;a++){let c=v(e);e.skip(4);let l=$.decode(E(e,c-8));this.currentMetadataKeys.set(a+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let s=this.iterateContiguousBoxes(e.slice(o,n.contentSize));for(let{boxInfo:a,slice:c}of s){let l=a.name,d=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(d)&&(l=this.currentMetadataKeys.get(d));let u=_s(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=u,l){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof u=="string"&&(this.metadataTags.title??=u);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof u=="string"&&(this.metadataTags.description??=u);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof u=="string"&&(this.metadataTags.artist??=u);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof u=="string"&&(this.metadataTags.album??=u);break;case"aART":case"album_artist":typeof u=="string"&&(this.metadataTags.albumArtist??=u);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof u=="string"&&(this.metadataTags.comment??=u);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof u=="string"&&(this.metadataTags.genre??=u);break;case"\xA9lyr":case"lyrics":typeof u=="string"&&(this.metadataTags.lyrics??=u);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof u=="string"){let f=new Date(u);Number.isNaN(f.getTime())||(this.metadataTags.date??=f)}break;case"covr":case"com.apple.quicktime.artwork":u instanceof Oe?(this.metadataTags.images??=[],this.metadataTags.images.push({data:u.data,kind:"coverFront",mimeType:u.mimeType})):u instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:u,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof u=="string"){let f=u.split("/"),m=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(m)&&m>0&&(this.metadataTags.trackNumber??=m),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(u instanceof Uint8Array&&u.length>=6){let f=z(u),m=f.getUint16(2,!1),p=f.getUint16(4,!1);m>0&&(this.metadataTags.trackNumber??=m),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(u instanceof Uint8Array&&u.length>=6){let f=z(u),m=f.getUint16(2,!1),p=f.getUint16(4,!1);m>0&&(this.metadataTags.discNumber??=m),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=i,!0}},xn=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,n=>n.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Ze(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),o=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=ni(o,n),s=await this.fetchPacketForSampleIndex(i,t);return!Es(o)||!this.internalTrack.demuxer.isFragmented?s:this.performFragmentedLookup(null,a=>{let c=a.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=B(c.presentationTimestamps,n,f=>f.presentationTimestamp),d=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,u=l!==-1&&n<c.endTimestamp;return{sampleIndex:d,correctSampleFound:u}},n,n,t)}async getNextPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,t);let o=this.packetToFragmentLocation.get(e);if(o===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(o.fragment,i=>{if(i===o.fragment){let s=i.trackData.get(this.internalTrack.id);if(o.sampleIndex+1<s.samples.length)return{sampleIndex:o.sampleIndex+1,correctSampleFound:!0}}else if(i.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.mapTimestampIntoTimescale(e),o=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=Oc(o,n),s=await this.fetchPacketForSampleIndex(i,t);return!Es(o)||!this.internalTrack.demuxer.isFragmented?s:this.performFragmentedLookup(null,a=>{let c=a.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=Zr(c.presentationTimestamps,f=>c.samples[f.sampleIndex].isKeyFrame&&f.presentationTimestamp<=n),d=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,u=l!==-1&&n<c.endTimestamp;return{sampleIndex:d,correctSampleFound:u}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Uc(i,n);return this.fetchPacketForSampleIndex(s,t)}let o=this.packetToFragmentLocation.get(e);if(o===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(o.fragment,i=>{if(i===o.fragment){let a=i.trackData.get(this.internalTrack.id).samples.findIndex((c,l)=>c.isKeyFrame&&l>o.sampleIndex);if(a!==-1)return{sampleIndex:a,correctSampleFound:!0}}else{let s=i.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){let a=s.samples.findIndex(c=>c.isKeyFrame);return h(a!==-1),{sampleIndex:a,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),o=zc(n,e);if(!o)return null;let i;if(t.metadataOnly)i=H;else{let l=this.internalTrack.demuxer.reader.requestSlice(o.sampleOffset,o.sampleSize);l instanceof Promise&&(l=await l),h(l),i=E(l,o.sampleSize)}let s=(o.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=o.duration/this.internalTrack.timescale,c=new V(i,o.isKeyFrame?"key":"delta",s,a,e,o.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,n){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).samples[t];h(i);let s;if(n.metadataOnly)s=H;else{let d=this.internalTrack.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);d instanceof Promise&&(d=await d),h(d),s=E(d,i.byteSize)}let a=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=i.duration/this.internalTrack.timescale,l=new V(s,i.isKeyFrame?"key":"delta",a,c,e.moofOffset+t,i.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:t}),l}async performFragmentedLookup(e,t,n,o,i){let s=this.internalTrack.demuxer,a=null,c=null,l=-1;if(e){let{sampleIndex:x,correctSampleFound:y}=t(e);if(y)return this.fetchPacketInFragment(e,x,i);x!==-1&&(c=e,l=x)}let d=B(this.internalTrack.fragmentLookupTable,n,x=>x.timestamp),u=d!==-1?this.internalTrack.fragmentLookupTable[d]:null,f=B(this.internalTrack.fragmentPositionCache,n,x=>x.startTimestamp),m=f!==-1?this.internalTrack.fragmentPositionCache[f]:null,p=Math.max(u?.moofOffset??0,m?.moofOffset??0)||null,g;for(e?p===null||e.moofOffset>=p?(g=e.moofOffset+e.moofSize,a=e):g=p:g=p??0;;){if(a){let w=a.trackData.get(this.internalTrack.id);if(w&&w.startTimestamp>o)break}let x=s.reader.requestSliceRange(g,at,At);if(x instanceof Promise&&(x=await x),!x)break;let y=g,b=Ae(x);if(!b)break;if(b.name==="moof"){a=await s.readFragment(y);let{sampleIndex:w,correctSampleFound:k}=t(a);if(k)return this.fetchPacketInFragment(a,w,i);w!==-1&&(c=a,l=w)}g=y+b.totalSize}if(u&&(!c||c.moofOffset<u.moofOffset)){let x=this.internalTrack.fragmentLookupTable[d-1];h(!x||x.timestamp<u.timestamp);let y=x?.timestamp??-1/0;return this.performFragmentedLookup(null,t,y,o,i)}return c?this.fetchPacketInFragment(c,l,i):null}},ti=class extends xn{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&ln(e.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&un(e.data)}return{codec:nn(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}})():null}},ri=class extends xn{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:on(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},ni=(r,e)=>{if(r.presentationTimestamps){let t=B(r.presentationTimestamps,e,n=>n.presentationTimestamp);return t===-1?-1:r.presentationTimestamps[t].sampleIndex}else{let t=B(r.sampleTimingEntries,e,o=>o.startDecodeTimestamp);if(t===-1)return-1;let n=r.sampleTimingEntries[t];return n.startIndex+Math.min(Math.floor((e-n.startDecodeTimestamp)/n.delta),n.count-1)}},Oc=(r,e)=>{if(!r.keySampleIndices)return ni(r,e);if(r.presentationTimestamps){let t=B(r.presentationTimestamps,e,n=>n.presentationTimestamp);if(t===-1)return-1;for(let n=t;n>=0;n--){let o=r.presentationTimestamps[n].sampleIndex;if(Xe(r.keySampleIndices,o,s=>s)!==-1)return o}return-1}else{let t=ni(r,e),n=B(r.keySampleIndices,t,o=>o);return r.keySampleIndices[n]??-1}},zc=(r,e)=>{let t=B(r.sampleTimingEntries,e,y=>y.startIndex),n=r.sampleTimingEntries[t];if(!n||n.startIndex+n.count<=e)return null;let i=n.startDecodeTimestamp+(e-n.startIndex)*n.delta,s=B(r.sampleCompositionTimeOffsets,e,y=>y.startIndex),a=r.sampleCompositionTimeOffsets[s];a&&e-a.startIndex<a.count&&(i+=a.offset);let c=r.sampleSizes[Math.min(e,r.sampleSizes.length-1)],l=B(r.sampleToChunk,e,y=>y.startSampleIndex),d=r.sampleToChunk[l];h(d);let u=d.startChunkIndex+Math.floor((e-d.startSampleIndex)/d.samplesPerChunk),f=r.chunkOffsets[u],m=d.startSampleIndex+(u-d.startChunkIndex)*d.samplesPerChunk,p=0,g=f;if(r.sampleSizes.length===1)g+=c*(e-m),p+=c*d.samplesPerChunk;else for(let y=m;y<m+d.samplesPerChunk;y++){let b=r.sampleSizes[y];y<e&&(g+=b),p+=b}let x=n.delta;if(r.presentationTimestamps){let y=r.presentationTimestampIndexMap[e];h(y!==void 0),y<r.presentationTimestamps.length-1&&(x=r.presentationTimestamps[y+1].presentationTimestamp-i)}return{presentationTimestamp:i,duration:x,sampleOffset:g,sampleSize:c,chunkOffset:f,chunkSize:p,isKeyFrame:r.keySampleIndices?Xe(r.keySampleIndices,e,y=>y)!==-1:!0}},Uc=(r,e)=>{if(!r.keySampleIndices)return e+1;let t=B(r.keySampleIndices,e,n=>n);return r.keySampleIndices[t+1]??-1},ei=(r,e)=>{r.startTimestamp+=e,r.endTimestamp+=e;for(let t of r.samples)t.presentationTimestamp+=e;for(let t of r.presentationTimestamps)t.presentationTimestamp+=e},Nc=r=>{let[e,,,t]=r,n=Math.hypot(e,t),o=e/n,i=t/n,s=-Math.atan2(i,o)*(180/Math.PI);return Number.isFinite(s)?s:0},Es=r=>r.sampleSizes.length===0;var T;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Duration=17545]="Duration",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.MuxingApp=19840]="MuxingApp",r[r.WritingApp=22337]="WritingApp",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.TrackNumber=215]="TrackNumber",r[r.TrackUID=29637]="TrackUID",r[r.TrackType=131]="TrackType",r[r.FlagEnabled=185]="FlagEnabled",r[r.FlagDefault=136]="FlagDefault",r[r.FlagForced=21930]="FlagForced",r[r.FlagOriginal=21934]="FlagOriginal",r[r.FlagHearingImpaired=21931]="FlagHearingImpaired",r[r.FlagVisualImpaired=21932]="FlagVisualImpaired",r[r.FlagCommentary=21935]="FlagCommentary",r[r.FlagLacing=156]="FlagLacing",r[r.Name=21358]="Name",r[r.Language=2274716]="Language",r[r.LanguageBCP47=2274717]="LanguageBCP47",r[r.CodecID=134]="CodecID",r[r.CodecPrivate=25506]="CodecPrivate",r[r.CodecDelay=22186]="CodecDelay",r[r.SeekPreRoll=22203]="SeekPreRoll",r[r.DefaultDuration=2352003]="DefaultDuration",r[r.Video=224]="Video",r[r.PixelWidth=176]="PixelWidth",r[r.PixelHeight=186]="PixelHeight",r[r.AlphaMode=21440]="AlphaMode",r[r.Audio=225]="Audio",r[r.SamplingFrequency=181]="SamplingFrequency",r[r.Channels=159]="Channels",r[r.BitDepth=25188]="BitDepth",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.Block=161]="Block",r[r.BlockAdditions=30113]="BlockAdditions",r[r.BlockMore=166]="BlockMore",r[r.BlockAdditional=165]="BlockAdditional",r[r.BlockAddID=238]="BlockAddID",r[r.BlockDuration=155]="BlockDuration",r[r.ReferenceBlock=251]="ReferenceBlock",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.Colour=21936]="Colour",r[r.MatrixCoefficients=21937]="MatrixCoefficients",r[r.TransferCharacteristics=21946]="TransferCharacteristics",r[r.Primaries=21947]="Primaries",r[r.Range=21945]="Range",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPoseRoll=30325]="ProjectionPoseRoll",r[r.Attachments=423732329]="Attachments",r[r.AttachedFile=24999]="AttachedFile",r[r.FileDescription=18046]="FileDescription",r[r.FileName=18030]="FileName",r[r.FileMediaType=18016]="FileMediaType",r[r.FileData=18012]="FileData",r[r.FileUID=18094]="FileUID",r[r.Chapters=272869232]="Chapters",r[r.Tags=307544935]="Tags",r[r.Tag=29555]="Tag",r[r.Targets=25536]="Targets",r[r.TargetTypeValue=26826]="TargetTypeValue",r[r.TargetType=25546]="TargetType",r[r.TagTrackUID=25541]="TagTrackUID",r[r.TagEditionUID=25545]="TagEditionUID",r[r.TagChapterUID=25540]="TagChapterUID",r[r.TagAttachmentUID=25542]="TagAttachmentUID",r[r.SimpleTag=26568]="SimpleTag",r[r.TagName=17827]="TagName",r[r.TagLanguage=17530]="TagLanguage",r[r.TagString=17543]="TagString",r[r.TagBinary=17541]="TagBinary",r[r.ContentEncodings=28032]="ContentEncodings",r[r.ContentEncoding=25152]="ContentEncoding",r[r.ContentEncodingOrder=20529]="ContentEncodingOrder",r[r.ContentEncodingScope=20530]="ContentEncodingScope",r[r.ContentCompression=20532]="ContentCompression",r[r.ContentCompAlgo=16980]="ContentCompAlgo",r[r.ContentCompSettings=16981]="ContentCompSettings",r[r.ContentEncryption=20533]="ContentEncryption"})(T||(T={}));var Vc=[T.EBML,T.Segment],_t=[T.SeekHead,T.Info,T.Cluster,T.Tracks,T.Cues,T.Attachments,T.Chapters,T.Tags],hr=[...Vc,..._t];var oi=8,oe=2,de=2*oi,ii=r=>{let e=A(r);if(r.skip(-1),e===0)return null;let t=1,n=128;for(;(e&n)===0;)t++,n>>=1;return t},Et=r=>{let e=A(r);if(e===0)return null;let t=1,n=128;for(;(e&n)===0;)t++,n>>=1;let o=e&n-1;for(let i=1;i<t;i++)o*=256,o+=A(r);return o},D=(r,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let n=0;n<e;n++)t*=256,t+=A(r);return t},Ds=(r,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let t=0n;for(let n=0;n<e;n++)t<<=8n,t+=BigInt(A(r));return t};var yn=r=>{let e=ii(r);return e===null?null:D(r,e)},si=r=>{let e=A(r);return e===255?e=null:(r.skip(-1),e=Et(r),e===72057594037927940&&(e=null)),e},fe=r=>{let e=yn(r);if(e===null)return null;let t=si(r);return{id:e,size:t}},He=(r,e)=>{let t=E(r,e),n=0;for(;n<e&&t[n]!==0;)n+=1;return String.fromCharCode(...t.subarray(0,n))},Ft=(r,e)=>{let t=E(r,e),n=0;for(;n<e&&t[n]!==0;)n+=1;return $.decode(t.subarray(0,n))},Tn=(r,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?Rs(r):bn(r)},wn=async(r,e,t,n)=>{let o=new Set(t),i=e;for(;n===null||i<n;){let s=r.requestSliceRange(i,oe,de);if(s instanceof Promise&&(s=await s),!s)break;let a=fe(s);if(!a)break;if(o.has(a.id))return{pos:i,found:!0};Ee(a.size),i=s.filePos+a.size}return{pos:n!==null&&n>i?n:i,found:!1}},ai=async(r,e,t,n)=>{let i=new Set(t),s=e;for(;s<n;){let a=r.requestSliceRange(s,0,Math.min(65536,n-s));if(a instanceof Promise&&(a=await a),!a||a.length<oi)break;for(let c=0;c<a.length-oi;c++){a.filePos=s;let l=yn(a);if(l!==null&&i.has(l))return s;s++}}return null},me={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function Ee(r){if(r===null)throw new Error("Undefined element size is used in a place where it is not supported.")}var Ms=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isWebM?"webm":"x-matroska");if(r.codecStrings.length>0){let n=[...new Set(r.codecStrings.filter(Boolean))];t+=`; codecs="${n.join(", ")}"`}return t};var Fe;(function(r){r[r.None=0]="None",r[r.Xiph=1]="Xiph",r[r.FixedSize=2]="FixedSize",r[r.Ebml=3]="Ebml"})(Fe||(Fe={}));var kn;(function(r){r[r.Block=1]="Block",r[r.Private=2]="Private",r[r.Next=4]="Next"})(kn||(kn={}));var gr;(function(r){r[r.Zlib=0]="Zlib",r[r.Bzlib=1]="Bzlib",r[r.lzo1x=2]="lzo1x",r[r.HeaderStripping=3]="HeaderStripping"})(gr||(gr={}));var ci=[{id:T.SeekHead,flag:"seekHeadSeen"},{id:T.Info,flag:"infoSeen"},{id:T.Tracks,flag:"tracksSeen"},{id:T.Cues,flag:"cuesSeen"}],Bs=10*2**20,Sn=class extends Q{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(t=>t.inputTrack))}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),t=await Promise.all(e.map(n=>n.getCodecParameterString()));return Ms({isWebM:this.isWebM,hasVideo:this.segments.some(n=>n.tracks.some(o=>o.info?.type==="video")),hasAudio:this.segments.some(n=>n.tracks.some(o=>o.info?.type==="audio")),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let t of this.segments)t.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(let t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,oe,de);if(t instanceof Promise&&(t=await t),!t)break;let n=fe(t);if(!n)break;let o=n.id,i=n.size,s=t.filePos;if(o===T.EBML){Ee(i);let a=this.reader.requestSlice(s,i);if(a instanceof Promise&&(a=await a),!a)break;this.readContiguousElements(a)}else if(o===T.Segment){if(await this.readSegment(s,i),i===null||this.reader.fileSize===null)break}else if(o===T.Cluster){if(this.reader.fileSize===null)break;i===null&&(i=(await wn(this.reader,s,hr,this.reader.fileSize)).pos-s);let a=Y(this.segments);a&&(a.elementEndPos=s+i)}Ee(i),e=s+i}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===null?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let a=this.reader.requestSliceRange(n,oe,de);if(a instanceof Promise&&(a=await a),!a)break;let c=n,l=fe(a);if(!l||!_t.includes(l.id)&&l.id!==T.Void){let p=await ai(this.reader,c,_t,Math.min(this.currentSegment.elementEndPos??1/0,c+Bs));if(p){n=p;continue}else break}let{id:d,size:u}=l,f=a.filePos,m=ci.findIndex(p=>p.id===d);if(m!==-1){let p=ci[m].flag;this.currentSegment[p]=!0,Ee(u);let g=this.reader.requestSlice(f,u);g instanceof Promise&&(g=await g),g&&this.readContiguousElements(g)}else if(d===T.Tags||d===T.Attachments){d===T.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Ee(u);let p=this.reader.requestSlice(f,u);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(d===T.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(u===null)break;n=f+u}if(this.currentSegment.seekEntries.sort((a,c)=>a.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(let a of this.currentSegment.seekEntries){let c=ci.find(p=>p.id===a.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+a.segmentPosition,oe,de);if(l instanceof Promise&&(l=await l),!l)continue;let d=fe(l);if(!d)continue;let{id:u,size:f}=d;if(u!==c.id)continue;Ee(f),this.currentSegment[c.flag]=!0;let m=this.reader.requestSlice(l.filePos,f);m instanceof Promise&&(m=await m),m&&this.readContiguousElements(m)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6),this.currentSegment.tracks.sort((a,c)=>Number(c.disposition.default)-Number(a.disposition.default));let o=new Map(this.currentSegment.tracks.map(a=>[a.id,a]));for(let a of this.currentSegment.cuePoints){let c=o.get(a.trackId);c&&c.cuePoints.push(a)}for(let a of this.currentSegment.tracks){a.cuePoints.sort((c,l)=>c.time-l.time);for(let c=0;c<a.cuePoints.length-1;c++){let l=a.cuePoints[c],d=a.cuePoints[c+1];l.time===d.time&&(a.cuePoints.splice(c+1,1),c--)}}let i=null,s=-1/0;for(let a of this.currentSegment.tracks)a.cuePoints.length>s&&(s=a.cuePoints.length,i=a);for(let a of this.currentSegment.tracks)a.cuePoints.length===0&&(a.cuePoints=i.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let n=this.reader.requestSliceRange(e,oe,de);n instanceof Promise&&(n=await n),h(n);let o=e,i=fe(n);h(i);let s=i.id;h(s===T.Cluster);let a=i.size,c=n.filePos;a===null&&(a=(await wn(this.reader,c,hr,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,a);l instanceof Promise&&(l=await l);let d={segment:t,elementStartPos:o,elementEndPos:c+a,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=d,l){let u=this.readContiguousElements(l,hr);d.elementEndPos=u}for(let[,u]of d.trackData){let f=u.track;h(u.blocks.length>0);let m=!1;for(let y=0;y<u.blocks.length;y++){let b=u.blocks[y];b.timestamp+=d.timestamp,m||=b.lacing!==Fe.None}u.presentationTimestamps=u.blocks.map((y,b)=>({timestamp:y.timestamp,blockIndex:b})).sort((y,b)=>y.timestamp-b.timestamp);for(let y=0;y<u.presentationTimestamps.length;y++){let b=u.presentationTimestamps[y],w=u.blocks[b.blockIndex];if(u.firstKeyFrameTimestamp===null&&w.isKeyFrame&&(u.firstKeyFrameTimestamp=w.timestamp),y<u.presentationTimestamps.length-1){let k=u.presentationTimestamps[y+1];w.duration=k.timestamp-w.timestamp}else w.duration===0&&f.defaultDuration!=null&&w.lacing===Fe.None&&(w.duration=f.defaultDuration)}m&&(this.expandLacedBlocks(u.blocks,f),u.presentationTimestamps=u.blocks.map((y,b)=>({timestamp:y.timestamp,blockIndex:b})).sort((y,b)=>y.timestamp-b.timestamp));let p=u.blocks[u.presentationTimestamps[0].blockIndex],g=u.blocks[Y(u.presentationTimestamps).blockIndex];u.startTimestamp=p.timestamp,u.endTimestamp=g.timestamp+g.duration;let x=B(f.clusterPositionCache,u.startTimestamp,y=>y.startTimestamp);(x===-1||f.clusterPositionCache[x].elementStartPos!==o)&&f.clusterPositionCache.splice(x+1,0,{elementStartPos:d.elementStartPos,startTimestamp:u.startTimestamp})}return t.lastReadCluster=d,d}getTrackDataInCluster(e,t){let n=e.trackData.get(t);if(!n){let o=e.segment.tracks.find(i=>i.id===t);if(!o)return null;n={track:o,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,n)}return n}expandLacedBlocks(e,t){for(let n=0;n<e.length;n++){let o=e[n];if(o.lacing===Fe.None)continue;o.decoded||(o.data=this.decodeBlockData(t,o.data),o.decoded=!0);let i=Dt.tempFromBytes(o.data),s=[],a=A(i)+1;switch(o.lacing){case Fe.Xiph:{let l=0;for(let d=0;d<a-1;d++){let u=0;for(;i.bufferPos<i.length;){let f=A(i);if(u+=f,f<255){s.push(u),l+=u;break}}}s.push(i.length-(i.bufferPos+l))}break;case Fe.FixedSize:{let l=i.length-1,d=Math.floor(l/a);for(let u=0;u<a;u++)s.push(d)}break;case Fe.Ebml:{let l=Et(i);h(l!==null);let d=l;s.push(d);let u=d;for(let f=1;f<a-1;f++){let m=i.bufferPos,p=Et(i);h(p!==null);let g=p,y=(1<<(i.bufferPos-m)*7-1)-1,b=g-y;d+=b,s.push(d),u+=d}s.push(i.length-(i.bufferPos+u))}break;default:h(!1)}h(s.length===a),e.splice(n,1);let c=o.duration||a*(t.defaultDuration??0);for(let l=0;l<a;l++){let d=s[l],u=E(i,d),f=o.timestamp+c*l/a,m=c/a;e.splice(n+l,0,{timestamp:f,duration:m,isKeyFrame:o.isKeyFrame,data:u,lacing:Fe.None,decoded:!0,mainAdditional:o.mainAdditional})}n+=a,n--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if(!(t.id===T.Tags&&!e.tagsSeen)){if(!(t.id===T.Attachments&&!e.attachmentsSeen))continue}let n=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,oe,de);if(n instanceof Promise&&(n=await n),!n)continue;let o=fe(n);if(!o||o.id!==t.id)continue;let{size:i}=o;Ee(i),h(!this.currentSegment),this.currentSegment=e;let s=this.reader.requestSlice(n.filePos,i);s instanceof Promise&&(s=await s),s&&this.readContiguousElements(s),this.currentSegment=null,t.id===T.Tags?e.tagsSeen=!0:t.id===T.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){let n=e.filePos;for(;e.filePos-n<=e.length-oe;){let o=e.filePos;if(!this.traverseElement(e,t))return o}return e.filePos}traverseElement(e,t){let n=fe(e);if(!n||t&&t.includes(n.id))return!1;let{id:o,size:i}=n,s=e.filePos;switch(Ee(i),o){case T.DocType:this.isWebM=He(e,i)==="webm";break;case T.Seek:{if(!this.currentSegment)break;let a={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(a),this.readContiguousElements(e.slice(s,i)),(a.id===-1||a.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case T.SeekID:{let a=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!a)break;a.id=D(e,i)}break;case T.SeekPosition:{let a=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!a)break;a.segmentPosition=D(e,i)}break;case T.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=D(e,i),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case T.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Tn(e,i)}break;case T.TrackEntry:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...te},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:K,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(s,i)),this.currentTrack.decodingInstructions.some(a=>a.data?.type!=="decompress"||a.scope!==kn.Block||a.data.algorithm!==gr.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let a=this.currentTrack.codecId.indexOf("/"),c=a===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,a);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){this.currentTrack.codecId===me.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===me.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===me.vp8?this.currentTrack.info.codec="vp8":c===me.vp9?this.currentTrack.info.codec="vp9":c===me.av1&&(this.currentTrack.info.codec="av1");let l=this.currentTrack,d=new ke(this.input,new li(l));this.currentTrack.inputTrack=d,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){c===me.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2")},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===me.mp3?this.currentTrack.info.codec="mp3":c===me.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=tt):c===me.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===me.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));let l=this.currentTrack,d=new G(this.input,new ui(l));this.currentTrack.inputTrack=d,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case T.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=D(e,i)}break;case T.TrackType:{if(!this.currentTrack)break;let a=D(e,i);a===1?this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:a===2&&(this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case T.FlagEnabled:{if(!this.currentTrack)break;D(e,i)||(this.currentSegment.tracks.pop(),this.currentTrack=null)}break;case T.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!D(e,i)}break;case T.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!D(e,i)}break;case T.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!D(e,i)}break;case T.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!D(e,i)}break;case T.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!D(e,i)}break;case T.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!D(e,i)}break;case T.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=He(e,i)}break;case T.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=E(e,i)}break;case T.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*D(e,i)/1e9}break;case T.Name:{if(!this.currentTrack)break;this.currentTrack.name=Ft(e,i)}break;case T.Language:{if(!this.currentTrack||this.currentTrack.languageCode!==K)break;this.currentTrack.languageCode=He(e,i),Jr(this.currentTrack.languageCode)||(this.currentTrack.languageCode=K)}break;case T.LanguageBCP47:{if(!this.currentTrack)break;let c=He(e,i).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=K}break;case T.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(s,i))}break;case T.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=D(e,i)}break;case T.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=D(e,i)}break;case T.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=D(e,i)===1}break;case T.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(s,i))}break;case T.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=D(e,i),c=Qr[a]??null;this.currentTrack.info.colorSpace.matrix=c}break;case T.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=D(e,i)===2}break;case T.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=D(e,i),c=Xr[a]??null;this.currentTrack.info.colorSpace.transfer=c}break;case T.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=D(e,i),c=Kr[a]??null;this.currentTrack.info.colorSpace.primaries=c}break;case T.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(s,i))}break;case T.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let c=-Tn(e,i);try{this.currentTrack.info.rotation=$r(c)}catch{}}break;case T.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(s,i))}break;case T.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=Tn(e,i)}break;case T.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=D(e,i)}break;case T.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=D(e,i)}break;case T.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(s,i)),this.currentCueTime=null}break;case T.CueTime:this.currentCueTime=D(e,i);break;case T.CueTrackPositions:{if(this.currentCueTime===null)break;h(this.currentSegment);let a={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(a),this.readContiguousElements(e.slice(s,i)),(a.trackId===-1||a.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case T.CueTrack:{let a=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!a)break;a.trackId=D(e,i)}break;case T.CueClusterPosition:{let a=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!a)break;h(this.currentSegment),a.clusterPosition=this.currentSegment.dataStartPos+D(e,i)}break;case T.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=D(e,i)}break;case T.SimpleBlock:{if(!this.currentCluster)break;let a=Et(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let l=pr(e),d=A(e),u=d>>1&3,f=!!(d&128);c.track.info?.type==="audio"&&c.track.info.codec&&(f=!0);let m=E(e,i-(e.filePos-s)),p=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:f,data:m,lacing:u,decoded:!p,mainAdditional:null})}break;case T.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(s,i)),this.currentBlock=null}break;case T.Block:{if(!this.currentCluster)break;let a=Et(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let l=pr(e),u=A(e)>>1&3,f=E(e,i-(e.filePos-s)),m=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:f,lacing:u,decoded:!m,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case T.BlockAdditions:this.readContiguousElements(e.slice(s,i));break;case T.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(s,i)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case T.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=E(e,i)}break;case T.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=D(e,i)}break;case T.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=D(e,i)}break;case T.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case T.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(s,i));break;case T.Targets:this.readContiguousElements(e.slice(s,i));break;case T.TargetTypeValue:D(e,i)!==50&&(this.currentTagTargetIsMovie=!1);break;case T.TagTrackUID:case T.TagEditionUID:case T.TagChapterUID:case T.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case T.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(s,i))}break;case T.TagName:this.currentSimpleTagName=Ft(e,i);break;case T.TagString:{if(!this.currentSimpleTagName)break;let a=Ft(e,i);this.processTagValue(this.currentSimpleTagName,a)}break;case T.TagBinary:{if(!this.currentSimpleTagName)break;let a=E(e,i);this.processTagValue(this.currentSimpleTagName,a)}break;case T.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(s,i));let a=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(a.raw??={},a.raw[this.currentAttachedFile.fileUid.toString()]=new rn(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let c=this.currentAttachedFile.fileName,l="unknown";if(c){let d=c.toLowerCase();d.startsWith("cover.")?l="coverFront":d.startsWith("back.")&&(l="coverBack")}a.images??=[],a.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:l,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case T.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=Ds(e,i)}break;case T.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Ft(e,i)}break;case T.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=He(e,i)}break;case T.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=E(e,i)}break;case T.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Ft(e,i)}break;case T.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(s,i)),this.currentTrack.decodingInstructions.sort((a,c)=>c.order-a.order)}break;case T.ContentEncoding:this.currentDecodingInstruction={order:0,scope:kn.Block,data:null},this.readContiguousElements(e.slice(s,i)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case T.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=D(e,i)}break;case T.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=D(e,i)}break;case T.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:gr.Zlib,settings:null},this.readContiguousElements(e.slice(s,i))}break;case T.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=D(e,i)}break;case T.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=E(e,i)}break;case T.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=s+i,!0}decodeBlockData(e,t){h(e.decodingInstructions.length>0);let n=t;for(let o of e.decodingInstructions)switch(h(o.data),o.data.type){case"decompress":switch(o.data.algorithm){case gr.HeaderStripping:if(o.data.settings&&o.data.settings.length>0){let i=o.data.settings,s=new Uint8Array(i.length+n.length);s.set(i,0),s.set(n,i.length),n=s}break;default:}break;default:}return n}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=t,typeof t=="string")switch(e.toLowerCase()){case"title":n.title??=t;break;case"description":n.description??=t;break;case"artist":n.artist??=t;break;case"album":n.album??=t;break;case"album_artist":n.albumArtist??=t;break;case"genre":n.genre??=t;break;case"comment":n.comment??=t;break;case"lyrics":n.lyrics??=t;break;case"date":{let o=new Date(t);Number.isNaN(o.getTime())||(n.date??=o)}break;case"track_number":case"part_number":{let o=t.split("/"),i=Number.parseInt(o[0],10),s=o[1]&&Number.parseInt(o[1],10);Number.isInteger(i)&&i>0&&(n.trackNumber??=i),s&&Number.isInteger(s)&&s>0&&(n.tracksTotal??=s)}break;case"disc_number":case"disc":{let o=t.split("/"),i=Number.parseInt(o[0],10),s=o[1]&&Number.parseInt(o[1],10);Number.isInteger(i)&&i>0&&(n.discNumber??=i),s&&Number.isInteger(s)&&s>0&&(n.discsTotal??=s)}break}}},vn=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket(e){return this.performClusterLookup(null,t=>t.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Ze(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,o=>{let i=o.trackData.get(this.internalTrack.id);if(!i)return{blockIndex:-1,correctBlockFound:!1};let s=B(i.presentationTimestamps,n,l=>l.timestamp),a=s!==-1?i.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&n<i.endTimestamp;return{blockIndex:a,correctBlockFound:c}},n,n,t)}async getNextPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,o=>{if(o===n.cluster){let i=o.trackData.get(this.internalTrack.id);if(n.blockIndex+1<i.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(o.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,o=>{let i=o.trackData.get(this.internalTrack.id);if(!i)return{blockIndex:-1,correctBlockFound:!1};let s=Zr(i.presentationTimestamps,l=>i.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=n),a=s!==-1?i.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&n<i.endTimestamp;return{blockIndex:a,correctBlockFound:c}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,o=>{if(o===n.cluster){let s=o.trackData.get(this.internalTrack.id).blocks.findIndex((a,c)=>a.isKeyFrame&&c>n.blockIndex);if(s!==-1)return{blockIndex:s,correctBlockFound:!0}}else{let i=o.trackData.get(this.internalTrack.id);if(i&&i.firstKeyFrameTimestamp!==null){let s=i.blocks.findIndex(a=>a.isKeyFrame);return h(s!==-1),{blockIndex:s,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,n){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).blocks[t];h(i),i.decoded||(i.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,i.data),i.decoded=!0);let s=n.metadataOnly?H:i.data,a=i.timestamp/this.internalTrack.segment.timestampFactor,c=i.duration/this.internalTrack.segment.timestampFactor,l={};i.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=n.metadataOnly?H:i.mainAdditional,l.alphaByteLength=i.mainAdditional.byteLength);let d=new V(s,i.isKeyFrame?"key":"delta",a,c,e.dataStartPos+t,i.data.byteLength,l);return this.packetToClusterLocation.set(d,{cluster:e,blockIndex:t}),d}async performClusterLookup(e,t,n,o,i){let{demuxer:s,segment:a}=this.internalTrack,c=null,l=null,d=-1;if(e){let{blockIndex:y,correctBlockFound:b}=t(e);if(b)return this.fetchPacketInCluster(e,y,i);y!==-1&&(l=e,d=y)}let u=B(this.internalTrack.cuePoints,n,y=>y.time),f=u!==-1?this.internalTrack.cuePoints[u]:null,m=B(this.internalTrack.clusterPositionCache,n,y=>y.startTimestamp),p=m!==-1?this.internalTrack.clusterPositionCache[m]:null,g=Math.max(f?.clusterPosition??0,p?.elementStartPos??0)||null,x;for(e?g===null||e.elementStartPos>=g?(x=e.elementEndPos,c=e):x=g:x=g??a.clusterSeekStartPos;a.elementEndPos===null||x<=a.elementEndPos-oe;){if(c){let C=c.trackData.get(this.internalTrack.id);if(C&&C.startTimestamp>o)break}let y=s.reader.requestSliceRange(x,oe,de);if(y instanceof Promise&&(y=await y),!y)break;let b=x,w=fe(y);if(!w||!_t.includes(w.id)&&w.id!==T.Void){let C=await ai(s.reader,b,_t,Math.min(a.elementEndPos??1/0,b+Bs));if(C){x=C;continue}else break}let k=w.id,P=w.size,S=y.filePos;if(k===T.Cluster){c=await s.readCluster(b,a),P=c.elementEndPos-S;let{blockIndex:C,correctBlockFound:F}=t(c);if(F)return this.fetchPacketInCluster(c,C,i);C!==-1&&(l=c,d=C)}P===null&&(h(k!==T.Cluster),P=(await wn(s.reader,S,hr,a.elementEndPos)).pos-S);let _=S+P;if(a.elementEndPos===null){let C=s.reader.requestSliceRange(_,oe,de);if(C instanceof Promise&&(C=await C),!C)break;if(yn(C)===T.Segment){a.elementEndPos=_;break}}x=_}if(f&&(!l||l.elementStartPos<f.clusterPosition)){let y=this.internalTrack.cuePoints[u-1];h(!y||y.time<f.time);let b=y?.time??-1/0;return this.performClusterLookup(null,t,b,o,i)}return l?this.fetchPacketInCluster(l,d,i):null}},li=class extends vn{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;return(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({})),{codec:nn({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?fs(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?ps(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?ln(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?un(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}},ui=class extends vn{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:on({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}};var Lc=[44100,48e3,32e3],Hc=[-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],Os=1483304551,zs=1231971951,qc=(r,e,t,n,o)=>e===0?0:e===1?Math.floor(144*t/(n<<r))+o:e===2?Math.floor(144*t/n)+o:(Math.floor(12*t/n)+o)*4,Us=(r,e)=>r===3?e===3?21:36:e===3?13:21,Ns=(r,e)=>{let t=r>>>24,n=r>>>16&255,o=r>>>8&255,i=r&255;if(t!==255&&n!==255&&o!==255&&i!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((n&224)!==224)return{header:null,bytesAdvanced:1};let s=0,a=0;n&16?s=n&8?0:1:(s=1,a=1);let c=n>>3&3,l=n>>1&3,d=o>>4&15,u=(o>>2&3)%3,f=o>>1&1,m=i>>6&3,p=i>>4&3,g=i>>3&1,x=i>>2&1,y=i&3,b=Hc[s*16*4+l*16+d];if(b===-1)return{header:null,bytesAdvanced:1};let w=b*1e3,k=Lc[u]>>s+a,P=qc(s,l,w,k,f);if(e!==null&&e<P)return{header:null,bytesAdvanced:1};let S;return c===3?S=l===3?384:1152:l===3?S=384:l===2?S=1152:S=576,{header:{totalSize:P,mpegVersionId:c,layer:l,bitrate:w,frequencyIndex:u,sampleRate:k,channel:m,modeExtension:p,copyright:g,original:x,emphasis:y,audioSamplesInFrame:S},bytesAdvanced:1}};var Pn=r=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=r&e,e>>=8;return t};var Mt;(function(r){r[r.Unsynchronisation=128]="Unsynchronisation",r[r.ExtendedHeader=64]="ExtendedHeader",r[r.ExperimentalIndicator=32]="ExperimentalIndicator",r[r.Footer=16]="Footer"})(Mt||(Mt={}));var Bt;(function(r){r[r.ISO_8859_1=0]="ISO_8859_1",r[r.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",r[r.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",r[r.UTF_8=3]="UTF_8"})(Bt||(Bt={}));var xr=128,zt=10,Ot=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],Vs=(r,e)=>{let t=r.filePos;e.raw??={},e.raw.TAG??=E(r,xr-3),r.filePos=t;let n=Rt(r,30);n&&(e.title??=n);let o=Rt(r,30);o&&(e.artist??=o);let i=Rt(r,30);i&&(e.album??=i);let s=Rt(r,4),a=Number.parseInt(s,10);Number.isInteger(a)&&a>0&&(e.date??=new Date(a,0,1));let c=E(r,30),l;if(c[28]===0&&c[29]!==0){let u=c[29];u>0&&(e.trackNumber??=u),r.skip(-30),l=Rt(r,28),r.skip(2)}else r.skip(-30),l=Rt(r,30);l&&(e.comment??=l);let d=A(r);d<Ot.length&&(e.genre??=Ot[d])},Rt=(r,e)=>{let t=E(r,e),n=Je(t.indexOf(0),t.length),o=t.subarray(0,n),i="";for(let s=0;s<o.length;s++)i+=String.fromCharCode(o[s]);return i.trimEnd()},ct=r=>{let e=r.filePos,t=L(r,3),n=A(r),o=A(r),i=A(r),s=v(r);if(t!=="ID3"||n===255||o===255||(s&2155905152)!==0)return r.filePos=e,null;let a=Pn(s);return{majorVersion:n,revision:o,flags:i,size:a}},Cn=(r,e,t)=>{if(![2,3,4].includes(e.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let n=E(r,e.size),o=new di(e,n);if(e.flags&Mt.Footer&&o.removeFooter(),e.flags&Mt.Unsynchronisation&&e.majorVersion===3&&o.ununsynchronizeAll(),e.flags&Mt.ExtendedHeader){let i=o.readU32();e.majorVersion===3?o.pos+=i:o.pos+=i-4}for(;o.pos<=o.bytes.length-o.frameHeaderSize();){let i=o.readId3V2Frame();if(!i)break;let s=o.pos,a=o.pos+i.size,c=!1,l=!1,d=!1;if(e.majorVersion===3?(c=!!(i.flags&64),l=!!(i.flags&128)):e.majorVersion===4&&(c=!!(i.flags&4),l=!!(i.flags&8),d=!!(i.flags&2)||!!(e.flags&Mt.Unsynchronisation)),c){console.warn(`Skipping encrypted ID3v2 frame ${i.id}`),o.pos=a;continue}if(l){console.warn(`Skipping compressed ID3v2 frame ${i.id}`),o.pos=a;continue}switch(d&&o.ununsynchronizeRegion(o.pos,a),t.raw??={},i.id[0]==="T"?t.raw[i.id]??=o.readId3V2EncodingAndText(a):t.raw[i.id]??=o.readBytes(i.size),o.pos=s,i.id){case"TIT2":case"TT2":t.title??=o.readId3V2EncodingAndText(a);break;case"TIT3":case"TT3":t.description??=o.readId3V2EncodingAndText(a);break;case"TPE1":case"TP1":t.artist??=o.readId3V2EncodingAndText(a);break;case"TALB":case"TAL":t.album??=o.readId3V2EncodingAndText(a);break;case"TPE2":case"TP2":t.albumArtist??=o.readId3V2EncodingAndText(a);break;case"TRCK":case"TRK":{let f=o.readId3V2EncodingAndText(a).split("/"),m=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(m)&&m>0&&(t.trackNumber??=m),p&&Number.isInteger(p)&&p>0&&(t.tracksTotal??=p)}break;case"TPOS":case"TPA":{let f=o.readId3V2EncodingAndText(a).split("/"),m=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(m)&&m>0&&(t.discNumber??=m),p&&Number.isInteger(p)&&p>0&&(t.discsTotal??=p)}break;case"TCON":case"TCO":{let u=o.readId3V2EncodingAndText(a),f=/^\((\d+)\)/.exec(u);if(f){let m=Number.parseInt(f[1]);if(Ot[m]!==void 0){t.genre??=Ot[m];break}}if(f=/^\d+$/.exec(u),f){let m=Number.parseInt(f[0]);if(Ot[m]!==void 0){t.genre??=Ot[m];break}}t.genre??=u}break;case"TDRC":case"TDAT":{let u=o.readId3V2EncodingAndText(a),f=new Date(u);Number.isNaN(f.getTime())||(t.date??=f)}break;case"TYER":case"TYE":{let u=o.readId3V2EncodingAndText(a),f=Number.parseInt(u,10);Number.isInteger(f)&&(t.date??=new Date(f,0,1))}break;case"USLT":case"ULT":{let u=o.readU8();o.pos+=3,o.readId3V2Text(u,a),t.lyrics??=o.readId3V2Text(u,a)}break;case"COMM":case"COM":{let u=o.readU8();o.pos+=3,o.readId3V2Text(u,a),t.comment??=o.readId3V2Text(u,a)}break;case"APIC":case"PIC":{let u=o.readId3V2TextEncoding(),f;if(e.majorVersion===2){let x=o.readAscii(3);f=x==="PNG"?"image/png":x==="JPG"?"image/jpeg":"image/*"}else f=o.readId3V2Text(u,a);let m=o.readU8(),p=o.readId3V2Text(u,a).trimEnd(),g=a-o.pos;if(g>=0){let x=o.readBytes(g);t.images||(t.images=[]),t.images.push({data:x,mimeType:f,kind:m===3?"coverFront":m===4?"coverBack":"unknown",description:p})}}break;default:o.pos+=i.size;break}o.pos=a}},di=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t<this.bytes.length;t++){let n=this.bytes[t];e.push(n),n===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let n=[];for(let s=e;s<t;s++){let a=this.bytes[s];n.push(a),a===255&&s!==t-1&&this.bytes[s+1]===0&&s++}let o=this.bytes.subarray(0,e),i=this.bytes.subarray(t);this.bytes=new Uint8Array(o.length+n.length+i.length),this.bytes.set(o,0),this.bytes.set(n,o.length),this.bytes.set(i,o.length+n.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-zt),this.view=new DataView(this.bytes.buffer)}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+1);return this.pos+=3,e*256+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let n=0;n<e;n++)t+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);if(e==="\0\0\0")return null;let t=this.readU24();return{id:e,size:t,flags:0}}else{let e=this.readAscii(4);if(e==="\0\0\0\0")return null;let t=this.readU32(),n=this.header.majorVersion===4?Pn(t):t,o=this.readU16(),i=this.pos,s=a=>{let c=this.pos+a;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=a;let l=this.readAscii(4);if(l!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(l))return!1}return!0};if(!s(n)){let a=this.header.majorVersion===4?t:Pn(t);s(a)&&(n=a)}return this.pos=i,{id:e,size:n,flags:o}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let n=this.pos,o=this.readBytes(t-this.pos);switch(e){case Bt.ISO_8859_1:{let i="";for(let s=0;s<o.length;s++){let a=o[s];if(a===0){this.pos=n+s+1;break}i+=String.fromCharCode(a)}return i}case Bt.UTF_16_WITH_BOM:if(o[0]===255&&o[1]===254){let i=new TextDecoder("utf-16le"),s=Je(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=n+Math.min(s+2,o.length),i.decode(o.subarray(2,s))}else if(o[0]===254&&o[1]===255){let i=new TextDecoder("utf-16be"),s=Je(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=n+Math.min(s+2,o.length),i.decode(o.subarray(2,s))}else{let i=Je(o.findIndex(s=>s===0),o.length);return this.pos=n+Math.min(i+1,o.length),$.decode(o.subarray(0,i))}case Bt.UTF_16_BE_NO_BOM:{let i=new TextDecoder("utf-16be"),s=Je(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=n+Math.min(s+2,o.length),i.decode(o.subarray(0,s))}case Bt.UTF_8:{let i=Je(o.findIndex(s=>s===0),o.length);return this.pos=n+Math.min(i+1,o.length),$.decode(o.subarray(0,i))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}};var br=async(r,e,t)=>{let n=e;for(;t===null||n<t;){let o=r.requestSlice(n,4);if(o instanceof Promise&&(o=await o),!o)break;let i=v(o),s=Ns(i,r.fileSize!==null?r.fileSize-n:null);if(s.header)return{header:s.header,startPos:n};n+=s.bytesAdvanced}return null};var In=class extends Q{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new ye,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.tracks=[new G(this.input,new fi(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,zt);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}let c=ct(a);if(!c)break;this.lastLoadedPos=a.filePos+c.size}let e=await br(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let n=Us(t.mpegVersionId,t.channel),o=this.reader.requestSlice(e.startPos+n,4);if(o instanceof Promise&&(o=await o),o){let a=v(o);if(a===Os||a===zs)return}this.firstFrameHeader||(this.firstFrameHeader=t),t.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${t.sampleRate} Hz. Might be a bug, so please report this file.`);let i=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,s={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:i,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(s),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return h(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0,n=!1;for(;;){let o=this.reader.requestSlice(t,zt);if(o instanceof Promise&&(o=await o),!o)break;let i=ct(o);if(!i)break;n=!0;let s=this.reader.requestSlice(o.filePos,i.size);if(s instanceof Promise&&(s=await s),!s)break;Cn(s,i,this.metadataTags),t=o.filePos+i.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=xr){let o=this.reader.requestSlice(this.reader.fileSize-xr,xr);o instanceof Promise&&(o=await o),h(o),L(o,3)==="TAG"&&Vs(o,this.metadataTags)}return this.metadataTags}finally{e()}}},fi=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return K}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...te}}async getDecoderConfig(){return h(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let o;if(t.metadataOnly)o=H;else{let i=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(i instanceof Promise&&(i=await i),!i)return null;o=E(i,n.dataSize)}return new V(o,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let o=Xe(this.demuxer.loadedSamples,e.timestamp,s=>s.timestamp);if(o===-1)throw new Error("Packet was not created from this track.");let i=o+1;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let o=B(this.demuxer.loadedSamples,e,i=>i.timestamp);if(o===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(o,t);if(o>=0&&o+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(o,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var mi=1399285583,Gc=79764919,Hs=new Uint32Array(256);for(let r=0;r<256;r++){let e=r<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^Gc:e<<1;Hs[r]=e>>>0&4294967295}var qs=r=>{let e=z(r),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let n=0;for(let o=0;o<r.length;o++){let i=r[o];n=(n<<8^Hs[n>>>24^i])>>>0}return e.setUint32(22,t,!0),n},Gs=(r,e,t)=>{let n=0,o=null;if(r.length>0)if(e.codec==="vorbis"){h(e.vorbisInfo);let i=e.vorbisInfo.modeBlockflags.length,a=(1<<ns(i-1))-1<<1,c=(r[0]&a)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=t,d=e.vorbisInfo.modeBlockflags[c];if(o=e.vorbisInfo.blocksizes[d],d===1){let u=(a|1)+1,f=r[0]&u?1:0;l=e.vorbisInfo.blocksizes[f]}n=l!==null?l+o>>2:0}else e.codec==="opus"&&(n=xs(r).durationInSamples);return{durationInSamples:n,vorbisBlockSize:o}},Ws=r=>{let e="audio/ogg";if(r.codecStrings){let t=[...new Set(r.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};var qe=27,ut=282,js=ut+65025,Ut=r=>{let e=r.filePos;if(lt(r)!==mi)return null;r.skip(1);let n=A(r),o=Ks(r),i=lt(r),s=lt(r),a=lt(r),c=A(r),l=new Uint8Array(c);for(let m=0;m<c;m++)l[m]=A(r);let d=27+c,u=l.reduce((m,p)=>m+p,0),f=d+u;return{headerStartPos:e,totalSize:f,dataStartPos:e+d,dataSize:u,headerType:n,granulePosition:o,serialNumber:i,sequenceNumber:s,checksum:a,lacingValues:l}},$s=(r,e)=>{for(;r.filePos<e-3;){let t=lt(r),n=t&255,o=t>>>8&255,i=t>>>16&255,s=t>>>24&255,a=79;if(!(n!==a&&o!==a&&i!==a&&s!==a)){if(r.skip(-4),t===mi)return!0;r.skip(1)}}return!1};var An=class extends Q{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.tracks=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,qe,ut);if(t instanceof Promise&&(t=await t),!t)break;let n=Ut(t);if(!n||!!!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let t of this.bitstreams){let n=await this.readPacket(t.bosPage,0);n&&(n.data.byteLength>=7&&n.data[0]===1&&n.data[1]===118&&n.data[2]===111&&n.data[3]===114&&n.data[4]===98&&n.data[5]===105&&n.data[6]===115?await this.readVorbisMetadata(n,t):n.data.byteLength>=8&&n.data[0]===79&&n.data[1]===112&&n.data[2]===117&&n.data[3]===115&&n.data[4]===72&&n.data[5]===101&&n.data[6]===97&&n.data[7]===100&&await this.readOpusMetadata(n,t),t.codecInfo.codec!==null&&this.tracks.push(new G(this.input,new pi(t,this))))}})()}async readVorbisMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let o=await this.readPacket(n.startPage,n.startSegmentIndex);if(!o||(n=await this.findNextPacketStart(o),!n))return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i||o.data[0]!==3||i.data[0]!==5)return;let s=[],a=u=>{for(;s.push(Math.min(255,u)),!(u<255);)u-=255};a(e.data.length),a(o.data.length);let c=new Uint8Array(1+s.length+e.data.length+o.data.length+i.data.length);c[0]=2,c.set(s,1),c.set(e.data,1+s.length),c.set(o.data,1+s.length+e.data.length),c.set(i.data,1+s.length+e.data.length+o.data.length),t.codecInfo.codec="vorbis",t.description=c,t.lastMetadataPacket=i;let l=z(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);let d=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(d&15),1<<(d>>4)],modeBlockflags:bs(i.data).modeBlockflags},sr(o.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let o=await this.readPacket(n.startPage,n.startSegmentIndex);if(!o)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=o;let i=gs(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=tt,t.codecInfo.opusInfo={preSkip:i.preSkip},sr(o.data.subarray(8),this.metadataTags)}async readPacket(e,t){h(t<e.lacingValues.length);let n=0;for(let u=0;u<t;u++)n+=e.lacingValues[u];let o=e,i=n,s=t,a=[];e:for(;;){let u=this.reader.requestSlice(o.dataStartPos,o.dataSize);u instanceof Promise&&(u=await u),h(u);let f=E(u,o.dataSize);for(;;){if(s===o.lacingValues.length){a.push(f.subarray(n,i));break}let p=o.lacingValues[s];if(i+=p,p<255){a.push(f.subarray(n,i));break e}s++}let m=o.headerStartPos+o.totalSize;for(;;){let p=this.reader.requestSliceRange(m,qe,ut);if(p instanceof Promise&&(p=await p),!p)return null;let g=Ut(p);if(!g)return null;if(o=g,o.serialNumber===e.serialNumber)break;m=o.headerStartPos+o.totalSize}n=0,i=0,s=0}let c=a.reduce((u,f)=>u+f.length,0),l=new Uint8Array(c),d=0;for(let u=0;u<a.length;u++){let f=a[u];l.set(f,d),d+=f.length}return{data:l,endPage:o,endSegmentIndex:s}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let n=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let o=this.reader.requestSliceRange(n,qe,ut);if(o instanceof Promise&&(o=await o),!o)return null;let i=Ut(o);if(!i)return null;if(i.serialNumber===e.endPage.serialNumber)return{startPage:i,startSegmentIndex:0};n=i.headerStartPos+i.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(t=>t.getCodecParameterString()));return Ws({codecStrings:e.filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...t)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},pi=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new ye,this.internalSampleRate=e.codecInfo.codec==="opus"?tt:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return h(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return K}getDisposition(){return{...te}}async getFirstTimestamp(){return 0}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(h(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,n){if(!e)return null;let{durationInSamples:o,vorbisBlockSize:i}=Gs(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new V(n.metadataOnly?H:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,o/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:o,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:i}),s}async getFirstPacket(e){h(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let n=0;this.bitstream.codecInfo.codec==="opus"&&(h(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let o=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(o,{timestampInSamples:n,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let n=this.encodedPacketToMetadata.get(e);if(!n)throw new Error("Packet was not created from this track.");let o=await this.demuxer.findNextPacketStart(n.packet);if(!o)return null;let i=n.timestampInSamples+n.durationInSamples,s=await this.demuxer.readPacket(o.startPage,o.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:i,vorbisLastBlocksize:n.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let n=Ze(e*this.internalSampleRate);if(n===0)return this.getFirstPacket(t);if(n<0)return null;h(this.bitstream.lastMetadataPacket);let o=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!o)return null;let i=o.startPage,s=this.demuxer.reader.fileSize,a=[i];e:for(;i.headerStartPos+i.totalSize<s;){let b=i.headerStartPos,w=Math.floor((b+s)/2),k=w;for(;;){let P=Math.min(k+js,s-qe),S=this.demuxer.reader.requestSlice(k,P-k);if(S instanceof Promise&&(S=await S),h(S),!$s(S,P)){s=w+qe;continue e}let C=this.demuxer.reader.requestSliceRange(S.filePos,qe,ut);C instanceof Promise&&(C=await C),h(C);let F=Ut(C);h(F);let O=!1;if(F.serialNumber===this.bitstream.serialNumber)O=!0;else{let j=this.demuxer.reader.requestSlice(F.headerStartPos,F.totalSize);j instanceof Promise&&(j=await j),h(j);let Ge=E(j,F.totalSize);O=qs(Ge)===F.checksum}if(!O){k=F.headerStartPos+4;continue}if(O&&F.serialNumber!==this.bitstream.serialNumber){k=F.headerStartPos+F.totalSize;continue}if(F.granulePosition===-1){k=F.headerStartPos+F.totalSize;continue}this.granulePositionToTimestampInSamples(F.granulePosition)>n?s=F.headerStartPos:(i=F,a.push(F));continue e}}let c=o.startPage;for(let b of a){if(b.granulePosition===i.granulePosition)break;(!c||b.headerStartPos>c.headerStartPos)&&(c=b)}let l=c,d=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===i.granulePosition);){let b=l.headerStartPos+l.totalSize,w=this.demuxer.reader.requestSliceRange(b,qe,ut);w instanceof Promise&&(w=await w),h(w);let k=Ut(w);h(k),l=k,l.serialNumber===this.bitstream.serialNumber&&d.push(l)}h(l.granulePosition!==-1);let u=null,f,m,p=l,g=0;if(l.headerStartPos===o.startPage.headerStartPos)f=this.granulePositionToTimestampInSamples(0),m=!0,u=0;else{f=0,m=!1;for(let k=l.lacingValues.length-1;k>=0;k--)if(l.lacingValues[k]<255){u=k+1;break}if(u===null)throw new Error("Invalid page with granule position: no packets end on this page.");g=u-1;let b={data:H,endPage:p,endSegmentIndex:g};if(await this.demuxer.findNextPacketStart(b)){let k=Qs(d,l,u);h(k);let P=Xs(d,k.page,k.segmentIndex);P&&(l=P.page,u=P.segmentIndex)}else for(;;){let k=Qs(d,l,u);if(!k)break;let P=Xs(d,k.page,k.segmentIndex);if(!P)break;if(l=P.page,u=P.segmentIndex,k.page.headerStartPos!==p.headerStartPos){p=k.page,g=k.segmentIndex;break}}}let x=null,y=null;for(;l!==null;){h(u!==null);let b=await this.demuxer.readPacket(l,u);if(!b)break;if(!(l.headerStartPos===o.startPage.headerStartPos&&u<o.startSegmentIndex)){let P=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:f,vorbisLastBlocksize:y?.vorbisBlockSize??null},t);h(P);let S=this.encodedPacketToMetadata.get(P);if(h(S),!m&&b.endPage.headerStartPos===p.headerStartPos&&b.endSegmentIndex===g?(f=this.granulePositionToTimestampInSamples(l.granulePosition),m=!0,P=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:f-S.durationInSamples,vorbisLastBlocksize:y?.vorbisBlockSize??null},t),h(P),S=this.encodedPacketToMetadata.get(P),h(S)):f+=S.durationInSamples,x=P,y=S,m&&(Math.max(f,0)>n||Math.max(S.timestampInSamples,0)===n))break}let k=await this.demuxer.findNextPacketStart(b);if(!k)break;l=k.startPage,u=k.startSegmentIndex}return x}async getPacketSequential(e,t){let n=await this.sequentialScanMutex.acquire();try{let o=Ze(e*this.internalSampleRate);e=o/this.internalSampleRate;let i=B(this.sequentialScanCache,o,c=>c.timestampInSamples),s;if(i!==-1){let c=this.sequentialScanCache[i];s=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},t)}else s=await this.getFirstPacket(t);let a=0;for(;s&&s.timestamp<e;){let c=await this.getNextPacket(s,t);if(!c||c.timestamp>e)break;if(s=c,a++,a===100){a=0;let l=this.encodedPacketToMetadata.get(s);h(l),this.sequentialScanCache.length>0&&h(Y(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return s}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},Xs=(r,e,t)=>{let n=e,o=t;e:for(;;){for(o--,o;o>=0;o--)if(n.lacingValues[o]<255){o++;break e}if(h(o===-1),!(n.headerType&1)){o=0;break}let s=Oo(r,a=>a.headerStartPos<n.headerStartPos);if(!s)return null;n=s,o=n.lacingValues.length}if(h(o!==-1),o===n.lacingValues.length){let i=r[r.indexOf(n)+1];h(i),n=i,o=0}return{page:n,segmentIndex:o}},Qs=(r,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};let n=Oo(r,o=>o.headerStartPos<e.headerStartPos);return n?{page:n,segmentIndex:n.lacingValues.length-1}:null};var De;(function(r){r[r.PCM=1]="PCM",r[r.IEEE_FLOAT=3]="IEEE_FLOAT",r[r.ALAW=6]="ALAW",r[r.MULAW=7]="MULAW",r[r.EXTENSIBLE=65534]="EXTENSIBLE"})(De||(De={}));var _n=class extends Q{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.tracks=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),h(e);let t=L(e,4),n=t!=="RIFX",o=t==="RF64",i=Re(e,n),s=o?this.reader.fileSize:Math.min(i+8,this.reader.fileSize??1/0);if(L(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,d=e.filePos;for(;s===null||d<s;){let f=this.reader.requestSlice(d,8);if(f instanceof Promise&&(f=await f),!f)break;let m=L(f,4),p=Re(f,n),g=f.filePos;if(o&&c===0&&m!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(m==="fmt ")await this.parseFmtChunk(g,p,n);else if(m==="data"){if(l??=p,this.dataStart=f.filePos,this.dataSize=Math.min(l,(s??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(m==="ds64"){let x=this.reader.requestSlice(g,p);if(x instanceof Promise&&(x=await x),!x)break;let y=gi(x,n);l=gi(x,n),s=Math.min(y+8,this.reader.fileSize??1/0)}else m==="LIST"?await this.parseListChunk(g,p,n):(m==="ID3 "||m==="id3 ")&&await this.parseId3Chunk(g,p);d=g+p+(p&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');let u=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/u)*u,this.tracks.push(new G(this.input,new hi(this)))})()}async parseFmtChunk(e,t,n){let o=this.reader.requestSlice(e,t);if(o instanceof Promise&&(o=await o),!o)return;let i=Vt(o,n),s=Vt(o,n),a=Re(o,n);o.skip(4);let c=Vt(o,n),l;if(t===14?l=8:l=Vt(o,n),t>=18&&i!==357){let d=Vt(o,n),u=t-18;if(Math.min(u,d)>=22&&i===De.EXTENSIBLE){o.skip(6);let m=E(o,16);i=m[0]|m[1]<<8}}(i===De.MULAW||i===De.ALAW)&&(l=8),this.audioInfo={format:i,numberOfChannels:s,sampleRate:a,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}}async parseListChunk(e,t,n){let o=this.reader.requestSlice(e,t);if(o instanceof Promise&&(o=await o),!o)return;let i=L(o,4);if(i!=="INFO"&&i!=="INF0")return;let s=o.filePos;for(;s<=e+t-8;){o.filePos=s;let a=L(o,4),c=Re(o,n),l=E(o,c),d=0;for(let f=0;f<l.length&&l[f]!==0;f++)d++;let u=String.fromCharCode(...l.subarray(0,d));switch(this.metadataTags.raw??={},this.metadataTags.raw[a]=u,a){case"INAM":case"TITL":this.metadataTags.title??=u;break;case"TIT3":this.metadataTags.description??=u;break;case"IART":this.metadataTags.artist??=u;break;case"IPRD":this.metadataTags.album??=u;break;case"IPRT":case"ITRK":case"TRCK":{let f=u.split("/"),m=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(m)&&m>0&&(this.metadataTags.trackNumber??=m),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{let f=new Date(u);Number.isNaN(f.getTime())||(this.metadataTags.date??=f)}break;case"YEAR":{let f=Number.parseInt(u,10);Number.isInteger(f)&&f>0&&(this.metadataTags.date??=new Date(f,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=u;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=u;break}s+=8+c+(c&1)}}async parseId3Chunk(e,t){let n=this.reader.requestSlice(e,t);if(n instanceof Promise&&(n=await n),!n)return;let o=ct(n);if(o){let i=n.slice(e+10,o.size);Cn(i,o,this.metadataTags)}}getCodec(){if(h(this.audioInfo),this.audioInfo.format===De.MULAW)return"ulaw";if(this.audioInfo.format===De.ALAW)return"alaw";if(this.audioInfo.format===De.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}return this.audioInfo.format===De.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return h(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Nt=2048,hi=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(h(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getNumberOfChannels(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return K}getDisposition(){return{...te}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){h(this.demuxer.audioInfo);let n=e*Nt*this.demuxer.audioInfo.blockSizeInBytes;if(n>=this.demuxer.dataSize)return null;let o=Math.min(Nt*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-n);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,o);if(c instanceof Promise&&(c=await c),!c)return null}let i;if(t.metadataOnly)i=H;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,o);c instanceof Promise&&(c=await c),h(c),i=E(c,o)}let s=e*Nt/this.demuxer.audioInfo.sampleRate,a=o/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,s),new V(i,"key",s,a,e,o)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){h(this.demuxer.audioInfo);let n=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Nt,(this.demuxer.dataSize-1)/(Nt*this.demuxer.audioInfo.blockSizeInBytes))),o=await this.getPacketAtIndex(n,t);if(o)return o;if(n===0)return null;h(this.demuxer.reader.fileSize===null);let i=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;i;){let s=await this.getNextPacket(i,t);if(!s)break;i=s}return i}getNextPacket(e,t){h(this.demuxer.audioInfo);let n=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Nt);return this.getPacketAtIndex(n+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Lt=7,Ht=9,yr=r=>{let e=r.filePos,t=E(r,9),n=new N(t);if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let s=n.readBits(1),a=n.readBits(2)+1,c=n.readBits(4);if(c===15)return null;n.skipBits(1);let l=n.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let d=n.readBits(13);n.skipBits(11);let u=n.readBits(2)+1;if(u!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let f=null;return s===1?r.filePos-=2:f=n.readBits(16),{objectType:a,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:d,numberOfAacFrames:u,crcCheck:f,startPos:e}};var xi=1024,En=class extends Q{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new ye,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();h(this.firstFrameHeader),this.tracks=[new G(this.input,new bi(this))]})()}async advanceReader(){let e=this.reader.requestSliceRange(this.lastLoadedPos,Lt,Ht);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=yr(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);let n=ir[t.samplingFrequencyIndex];h(n!==void 0);let o=xi/n,i=t.crcCheck?Ht:Lt,s={timestamp:this.nextTimestampInSamples/n,duration:o,dataStart:t.startPos+i,dataSize:t.frameLength-i};this.loadedSamples.push(s),this.nextTimestampInSamples+=xi,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return h(e),e.computeDuration()}async getMetadataTags(){return{}}},bi=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/xi}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return K}getCodec(){return"aac"}getInternalCodecId(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){h(this.demuxer.firstFrameHeader);let e=Vo[this.demuxer.firstFrameHeader.channelConfiguration];return h(e!==void 0),e}getSampleRate(){h(this.demuxer.firstFrameHeader);let e=ir[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return h(e!==void 0),e}getDisposition(){return{...te}}async getDecoderConfig(){h(this.demuxer.firstFrameHeader);let e=new Uint8Array(3),t=new N(e),{objectType:n,samplingFrequencyIndex:o,channelConfiguration:i}=this.demuxer.firstFrameHeader;return n>31?(t.writeBits(5,31),t.writeBits(6,n-32)):t.writeBits(5,n),t.writeBits(4,o),t.writeBits(4,i),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:e.subarray(0,Math.ceil((t.pos-1)/8))}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let o;if(t.metadataOnly)o=H;else{let i=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(i instanceof Promise&&(i=await i),!i)return null;o=E(i,n.dataSize)}return new V(o,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let o=Xe(this.demuxer.loadedSamples,e.timestamp,s=>s.timestamp);if(o===-1)throw new Error("Packet was not created from this track.");let i=o+1;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let o=B(this.demuxer.loadedSamples,e,i=>i.timestamp);if(o===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(o,t);if(o>=0&&o+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(o,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Ys=r=>r===0?null:r===1?192:r>=2&&r<=5?144*2**r:r===6?"uncommon-u8":r===7?"uncommon-u16":r>=8&&r<=15?2**r:null,Zs=(r,e)=>{switch(r){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},Js=r=>{let e=0,t=new N(E(r,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);let n=[],o=e-1,i=new N(E(r,o)),s=8-e-1;for(let c=0;c<s;c++)n.unshift(t.readBits(1));for(let c=0;c<o;c++)for(let l=0;l<8;l++){let d=i.readBits(1);l<2||n.unshift(d)}return n.reduce((c,l,d)=>c|l<<d,0)},ea=(r,e)=>{if(e==="uncommon-u16")return W(r)+1;if(e==="uncommon-u8")return A(r)+1;if(typeof e=="number")return e;se(e),h(!1)},ta=(r,e)=>e==="uncommon-u16"?W(r):e==="uncommon-u16-10"?W(r)*10:e==="uncommon-u8"?A(r):typeof e=="number"?e:null,ra=r=>{let t=0;for(let n of r){t^=n;for(let o=0;o<8;o++)(t&128)!==0?t=t<<1^7:t<<=1,t&=255}return t};var Fn=class extends Q{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.track=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new ye,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),h(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),h(this.track),[this.track]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;this.reader.fileSize===null||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),e+=4,t===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);h(t);let n=A(t),o=Le(t),i=(n&128)!==0;switch(n&127){case Ue.STREAMINFO:{let a=this.reader.requestSlice(e,o);if(a instanceof Promise&&(a=await a),h(a),a===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let c=E(a,34),l=new N(c),d=l.readBits(16),u=l.readBits(16),f=l.readBits(24),m=l.readBits(24),p=l.readBits(20),g=l.readBits(3)+1;l.readBits(5);let x=l.readBits(36);l.skipBits(128);let y=new Uint8Array(42);y.set(new Uint8Array([102,76,97,67]),0),y.set(new Uint8Array([128,0,0,34]),4),y.set(c,8),this.audioInfo={numberOfChannels:g,sampleRate:p,totalSamples:x,minimumBlockSize:d,maximumBlockSize:u,minimumFrameSize:f,maximumFrameSize:m,description:y},this.track=new G(this.input,new yi(this));break}case Ue.VORBIS_COMMENT:{let a=this.reader.requestSlice(e,o);a instanceof Promise&&(a=await a),h(a),sr(E(a,o),this.metadataTags);break}case Ue.PICTURE:{let a=this.reader.requestSlice(e,o);a instanceof Promise&&(a=await a),h(a);let c=v(a),l=v(a),d=$.decode(E(a,l)),u=v(a),f=$.decode(E(a,u));a.skip(16);let m=v(a),p=E(a,m);this.metadataTags.images??=[],this.metadataTags.images.push({data:p,mimeType:d,kind:c===3?"coverFront":c===4?"coverBack":"unknown",description:f});break}default:break}if(e+=o,i){this.lastLoadedPos=e;break}}})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){h(this.audioInfo);let n=6,i=this.audioInfo.maximumFrameSize+16,s=await this.reader.requestSliceRange(e,this.audioInfo.minimumFrameSize,i);if(!s)return null;let a=this.readFlacFrameHeader({slice:s,isFirstPacket:t});if(!a)return null;for(s.filePos=e+this.audioInfo.minimumFrameSize;;){if(s.filePos>s.end-n)return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:s.end-e,isLastFrame:!0};if(A(s)===255){let l=s.filePos,d=A(s),u=this.blockingBit===1?249:248;if(d!==u){s.filePos=l;continue}s.skip(-2);let f=s.filePos-e,m=this.readFlacFrameHeader({slice:s,isFirstPacket:!1});if(!m){s.filePos=l;continue}if(this.blockingBit===0){if(m.num-a.num!==1){s.filePos=l;continue}}else if(m.num-a.num!==a.blockSize){s.filePos=l;continue}return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:f,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){let n=e.filePos,o=E(e,4),i=new N(o);if(i.readBits(15)!==32764)return null;if(this.blockingBit===null){h(t);let x=i.readBits(1);this.blockingBit=x}else if(this.blockingBit===1){if(h(!t),i.readBits(1)!==1)return null}else if(this.blockingBit===0){if(h(!t),i.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");let a=Ys(i.readBits(4));if(!a)return null;h(this.audioInfo);let c=Zs(i.readBits(4),this.audioInfo.sampleRate);if(!c||(i.readBits(4),i.readBits(3),i.readBits(1)!==0))return null;let d=Js(e),u=ea(e,a),f=ta(e,c);if(f===null||f!==this.audioInfo.sampleRate)return null;let m=e.filePos-n,p=A(e);e.skip(-m),e.skip(-1);let g=ra(E(e,m));return p!==g?null:{num:d,blockSize:u,sampleRate:f}}async advanceReader(){await this.readMetadata(),h(this.lastLoadedPos!==null),h(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],i={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(i),t.isLastFrame){this.lastSampleLoaded=!0;return}}},yi=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getSampleRate(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return K}getTimeResolution(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...te}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return h(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(h(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");let n=await this.demuxer.readingMutex.acquire();try{for(;;){let o=B(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(o===-1){await this.demuxer.advanceReader();continue}let i=this.demuxer.loadedSamples[o],s=i.blockOffset/this.demuxer.audioInfo.sampleRate,a=i.blockSize/this.demuxer.audioInfo.sampleRate;if(s+a<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(o,t)}}finally{n()}}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let o=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&o>=this.demuxer.loadedSamples.length)return null;for(;o>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(o,t)}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let n=this.demuxer.loadedSamples[e];if(!n)return null;let o;if(t.metadataOnly)o=H;else{let a=this.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(a instanceof Promise&&(a=await a),!a)return null;o=E(a,n.byteSize)}h(this.demuxer.audioInfo);let i=n.blockOffset/this.demuxer.audioInfo.sampleRate,s=n.blockSize/this.demuxer.audioInfo.sampleRate;return new V(o,"key",i,s,e,n.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}};var ae=class{},Tr=class extends ae{async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);return t instanceof Promise&&(t=await t),!t||(t.skip(4),L(t,4)!=="ftyp")?null:L(t,4)}_createDemuxer(e){return new gn(e)}},Dn=class extends Tr{async _canReadInput(e){let t=await this._getMajorBrand(e);return!!t&&t!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},Rn=class extends Tr{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},wr=class extends ae{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,de);if(n instanceof Promise&&(n=await n),!n)return!1;let o=ii(n);if(o===null||o<1||o>8||D(n,o)!==T.EBML)return!1;let s=si(n);if(s===null)return!1;let a=e._reader.requestSlice(n.filePos,s);if(a instanceof Promise&&(a=await a),!a)return!1;let c=n.filePos;for(;a.filePos<=c+s-oe;){let l=fe(a);if(!l)break;let{id:d,size:u}=l,f=a.filePos;if(u===null)return!1;switch(d){case T.EBMLVersion:if(D(a,u)!==1)return!1;break;case T.EBMLReadVersion:if(D(a,u)!==1)return!1;break;case T.DocType:if(He(a,u)!==t)return!1;break;case T.DocTypeVersion:if(D(a,u)>4)return!1;break}a.filePos=f+u}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Sn(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},Mn=class extends wr{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},Bn=class extends ae{async _canReadInput(e){let t=e._reader.requestSlice(0,10);if(t instanceof Promise&&(t=await t),!t)return!1;let n=0,o=!1;for(;;){let l=e._reader.requestSlice(n,zt);if(l instanceof Promise&&(l=await l),!l)break;let d=ct(l);if(!d)break;o=!0,n=l.filePos+d.size}let i=await br(e._reader,n,n+4096);if(!i)return!1;if(o)return!0;n=i.startPos+i.header.totalSize;let s=await br(e._reader,n,n+4);if(!s)return!1;let a=i.header,c=s.header;return!(a.channel!==c.channel||a.sampleRate!==c.sampleRate)}_createDemuxer(e){return new In(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},On=class extends ae{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let n=L(t,4);return n!=="RIFF"&&n!=="RIFX"&&n!=="RF64"?!1:(t.skip(4),L(t,4)==="WAVE")}_createDemuxer(e){return new _n(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},zn=class extends ae{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?L(t,4)==="OggS":!1}_createDemuxer(e){return new An(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},Un=class extends ae{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?L(t,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Fn(e)}},Nn=class extends ae{async _canReadInput(e){let t=e._reader.requestSliceRange(0,Lt,Ht);if(t instanceof Promise&&(t=await t),!t)return!1;let n=yr(t);if(!n||(t=e._reader.requestSliceRange(n.frameLength,Lt,Ht),t instanceof Promise&&(t=await t),!t))return!1;let o=yr(t);return o?n.objectType===o.objectType&&n.samplingFrequencyIndex===o.samplingFrequencyIndex&&n.channelConfiguration===o.channelConfiguration:!1}_createDemuxer(e){return new En(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},na=new Dn,oa=new Rn,ia=new wr,sa=new Mn,aa=new Bn,ca=new On,la=new zn,ua=new Nn,da=new Un,ie=[na,oa,ia,sa,ca,la,da,aa,ua];var dt=class{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new q;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new q;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}};var kr=class extends dt{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!or(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new Vn({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:ma.fileSystem})}_retrieveSize(){let e=this._blob.size;return this._orchestrator.fileSize=e,e}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){let t=this._readers.get(e);for(t===void 0&&("stream"in this._blob&&!Be()?t=this._blob.slice(e.currentPos).stream().getReader():t=null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){let{done:n,value:o}=await t.read();if(n)throw this._orchestrator.forgetWorker(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}else{let n=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+n.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(n))}e.running=!1,e.aborted&&await t?.cancel()}_dispose(){this._orchestrator.dispose()}},fa=.5*2**20,Wc=((r,e,t)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))){let o=null;try{typeof window<"u"&&typeof window.location<"u"&&(o=new URL(t instanceof Request?t.url:t,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&o!==null&&o!==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**(r-2),16)}),Sr=class extends dt{constructor(e,t={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.requestInit!==void 0&&(!t.requestInit||typeof t.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(t.getRetryDelay!==void 0&&typeof t.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(t.maxCacheSize!==void 0&&(!or(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.fetchFn!==void 0&&typeof t.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");super(),this._existingResponses=new WeakMap,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??Wc,this._orchestrator=new Vn({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:ma.network})}async _retrieveSize(){let e=new AbortController,t=await No(this._options.fetchFn??fetch,this._url,Uo(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:e.signal}),this._getRetryDelay,()=>this._disposed);if(!t.ok)throw new Error(`Error fetching ${String(this._url)}: ${t.status} ${t.statusText}`);let n,o;if(t.status===206)o=this._getTotalLengthFromRangeResponse(t),n=this._orchestrator.createWorker(0,Math.min(o,fa));else{let i=t.headers.get("Content-Length");if(i)o=Number(i),n=this._orchestrator.createWorker(0,o),this._orchestrator.options.maxCacheSize=1/0,console.warn("HTTP server did not respond with 206 Partial Content, meaning the entire remote resource now has to be downloaded. For efficient media file streaming across a network, please make sure your server supports range requests.");else throw new Error(`HTTP response (status ${t.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=o,this._existingResponses.set(n,{response:t,abortController:e}),this._orchestrator.runWorker(n),o}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;;){let t=this._existingResponses.get(e);this._existingResponses.delete(e);let n=t?.abortController,o=t?.response;if(n||(n=new AbortController,o=await No(this._options.fetchFn??fetch,this._url,Uo(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:n.signal}),this._getRetryDelay,()=>this._disposed)),h(o),!o.ok)throw new Error(`Error fetching ${String(this._url)}: ${o.status} ${o.statusText}`);if(e.currentPos>0&&o.status!==206)throw new Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!o.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let i=o.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){n.abort(),e.running=!1;return}let s;try{s=await i.read()}catch(l){if(this._disposed)throw l;let d=this._getRetryDelay(1,l,this._url);if(d!==null){console.error("Error while reading response stream. Attempting to resume.",l),await new Promise(u=>setTimeout(u,1e3*d));break}else throw l}if(e.aborted)continue;let{done:a,value:c}=s;if(a){if(e.currentPos>=e.targetPos){this._orchestrator.forgetWorker(e),e.running=!1;return}break}this.onread?.(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}}}_getTotalLengthFromRangeResponse(e){let t=e.headers.get("Content-Range");if(t){let o=/\/(\d+)/.exec(t);if(o)return Number(o[1])}let n=e.headers.get("Content-Length");if(n)return Number(n);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}};var ma={none:(r,e)=>({start:r,end:e}),fileSystem:(r,e)=>(r=Math.floor((r-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:r,end:e}),network:(r,e,t)=>{r=Math.max(0,Math.floor((r-65536)/65536)*65536);for(let o of t){let s=Math.max((o.startPos+o.targetPos)/2,o.targetPos-8388608);if(en(r,e,s,o.targetPos)){let a=o.targetPos-o.startPos,c=Math.ceil((a+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(a+1)),d=Math.min(l,c);e=Math.max(e,o.startPos+d)}}return e=Math.max(e,r+fa),{start:r,end:e}}},Vn=class{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,t){h(this.fileSize!==null);let n=this.options.prefetchProfile(e,t,this.workers),o=Math.max(n.start,0),i=Math.min(n.end,this.fileSize);h(o<=e&&t<=i);let s=null,a=B(this.cache,e,b=>b.start),c=a!==-1?this.cache[a]:null;c&&c.start<=e&&t<=c.end&&(c.age=this.nextAge++,s={bytes:c.bytes,view:c.view,offset:c.start});let l=B(this.cache,o,b=>b.start),d=s?null:new Uint8Array(t-e),u=0,f=o,m=[];if(l!==-1){for(let b=l;b<this.cache.length;b++){let w=this.cache[b];if(w.start>=i)break;if(w.end<=o)continue;let k=Math.max(o,w.start),P=Math.min(i,w.end);if(h(k<=P),f<k&&m.push({start:f,end:k}),f=P,d){let S=Math.max(e,w.start),_=Math.min(t,w.end);if(S<_){let C=S-e;d.set(w.bytes.subarray(S-w.start,_-w.start),C),C===u&&(u=_-e)}}w.age=this.nextAge++}f<i&&m.push({start:f,end:i})}else m.push({start:o,end:i});if(d&&u>=d.length&&(s={bytes:d,view:z(d),offset:e}),m.length===0)return h(s),s;let{promise:p,resolve:g,reject:x}=Z(),y=[];for(let b of m){let w=Math.max(e,b.start),k=Math.min(t,b.end);w===b.start&&k===b.end?y.push(b):w<k&&y.push({start:w,end:k})}for(let b of m){let w=d&&{start:e,bytes:d,holes:y,resolve:g,reject:x},k=!1;for(let P of this.workers)if(en(b.start-131072,b.start,P.currentPos,P.targetPos)){P.targetPos=Math.max(P.targetPos,b.end),k=!0,w&&!P.pendingSlices.includes(w)&&P.pendingSlices.push(w),P.running||this.runWorker(P);break}if(!k){let P=this.createWorker(b.start,b.end);w&&(P.pendingSlices=[w]),this.runWorker(P)}}return s||(h(d),s=p.then(b=>({bytes:b,view:z(b),offset:e}))),s}createWorker(e,t){let n={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(n);this.workers.length>this.options.maxWorkerCount;){let o=0,i=this.workers[0];for(let s=1;s<this.workers.length;s++){let a=this.workers[s];a.age<i.age&&(o=s,i=a)}if(i.running&&i.pendingSlices.length>0)break;i.aborted=!0,this.workers.splice(o,1)}return n}runWorker(e){h(!e.running),h(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(n=>n.reject(t)),e.pendingSlices.length=0;else throw t})}supplyWorkerData(e,t){h(!e.aborted);let n=e.currentPos,o=n+t.length;this.insertIntoCache({start:n,end:o,bytes:t,view:z(t),age:this.nextAge++}),e.currentPos+=t.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let i=0;i<e.pendingSlices.length;i++){let s=e.pendingSlices[i],a=Math.max(n,s.start),c=Math.min(o,s.start+s.bytes.length);a<c&&s.bytes.set(t.subarray(a-n,c-n),a-s.start);for(let l=0;l<s.holes.length;l++){let d=s.holes[l];n<=d.start&&o>d.start&&(d.start=o),d.end<=d.start&&(s.holes.splice(l,1),l--)}s.holes.length===0&&(s.resolve(s.bytes),e.pendingSlices.splice(i,1),i--)}for(let i=0;i<this.workers.length;i++){let s=this.workers[i];e===s||s.running||en(n,o,s.currentPos,s.targetPos)&&(this.workers.splice(i,1),i--)}}forgetWorker(e){let t=this.workers.indexOf(e);h(t!==-1),this.workers.splice(t,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=B(this.cache,e.start,n=>n.start)+1;if(t>0){let n=this.cache[t-1];if(n.end>=e.end)return;if(n.end>e.start){let o=new Uint8Array(e.end-n.start);o.set(n.bytes,0),o.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=o,n.view=z(o),n.end=e.end,t--,e=n}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let n=t+1;n<this.cache.length;n++){let o=this.cache[n];if(e.end<=o.start)break;if(e.end>=o.end){this.cache.splice(n,1),this.currentCacheSize-=o.bytes.length,n--;continue}let i=new Uint8Array(o.end-e.start);i.set(e.bytes,0),i.set(o.bytes,o.start-e.start),this.currentCacheSize-=e.end-o.start,e.bytes=i,e.view=z(i),e.end=o.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let n=0,o=this.cache[0];for(let i=1;i<this.cache.length;i++){let s=this.cache[i];s.age<o.age&&(n=i,o=s)}if(this.currentCacheSize-o.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(n,1),this.currentCacheSize-=o.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}};tn();var ee=class{get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(t=>!(t instanceof ae)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof dt))throw new TypeError("options.source must be a Source.");if(e.source._disposed)throw new Error("options.source must not be disposed.");this._formats=e.formats,this._source=e.source,this._reader=new Ln(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw new Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),h(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(t=>t.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(t=>t.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(t=>t.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(t=>t.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){this._disposed||(this._disposed=!0,this._source._disposed=!0,this._source._dispose())}[Symbol.dispose](){this.dispose()}},q=class extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}};var Ln=class{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new q;if(this.fileSize!==null&&e+t>this.fileSize)return null;let n=e+t,o=this.source._read(e,n);return o instanceof Promise?o.then(i=>i?new Dt(i.bytes,i.view,i.offset,e,n):null):o?new Dt(o.bytes,o.view,o.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new q;if(this.fileSize!==null)return this.requestSlice(e,Ye(this.fileSize-e,t,n));{let o=this.requestSlice(e,n),i=s=>{if(s)return s;let a=l=>(h(l!==null),this.requestSlice(e,Ye(l-e,t,n))),c=this.source._retrieveSize();return c instanceof Promise?c.then(a):a(c)};return o instanceof Promise?o.then(i):i(o)}}},Dt=class r{constructor(e,t,n,o,i){this.bytes=e,this.view=t,this.offset=n,this.start=o,this.end=i,this.bufferPos=o-n}static tempFromBytes(e){return new r(e,z(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new r(this.bytes,this.view,this.offset,e,e+t)}},re=(r,e)=>{if(r.filePos<r.start||r.filePos+e>r.end)throw new RangeError(`Tried reading [${r.filePos}, ${r.filePos+e}), but slice is [${r.start}, ${r.end}). This is likely an internal error, please report it alongside the file that caused it.`)},E=(r,e)=>{re(r,e);let t=r.bytes.subarray(r.bufferPos,r.bufferPos+e);return r.bufferPos+=e,t},A=r=>(re(r,1),r.view.getUint8(r.bufferPos++)),Vt=(r,e)=>{re(r,2);let t=r.view.getUint16(r.bufferPos,e);return r.bufferPos+=2,t},W=r=>{re(r,2);let e=r.view.getUint16(r.bufferPos,!1);return r.bufferPos+=2,e},Le=r=>{re(r,3);let e=Qe(r.view,r.bufferPos,!1);return r.bufferPos+=3,e},pr=r=>{re(r,2);let e=r.view.getInt16(r.bufferPos,!1);return r.bufferPos+=2,e},Re=(r,e)=>{re(r,4);let t=r.view.getUint32(r.bufferPos,e);return r.bufferPos+=4,t},v=r=>{re(r,4);let e=r.view.getUint32(r.bufferPos,!1);return r.bufferPos+=4,e},lt=r=>{re(r,4);let e=r.view.getUint32(r.bufferPos,!0);return r.bufferPos+=4,e},_e=r=>{re(r,4);let e=r.view.getInt32(r.bufferPos,!1);return r.bufferPos+=4,e},jc=r=>{re(r,4);let e=r.view.getInt32(r.bufferPos,!0);return r.bufferPos+=4,e},gi=(r,e)=>{let t,n;return e?(t=Re(r,!0),n=Re(r,!0)):(n=Re(r,!1),t=Re(r,!1)),n*4294967296+t},ne=r=>{let e=v(r),t=v(r);return e*4294967296+t},Fs=r=>{let e=_e(r),t=v(r);return e*4294967296+t},Ks=r=>{let e=lt(r);return jc(r)*4294967296+e},Rs=r=>{re(r,4);let e=r.view.getFloat32(r.bufferPos,!1);return r.bufferPos+=4,e},bn=r=>{re(r,8);let e=r.view.getFloat64(r.bufferPos,!1);return r.bufferPos+=8,e},L=(r,e)=>{re(r,e);let t="";for(let n=0;n<e;n++)t+=String.fromCharCode(r.bytes[r.bufferPos++]);return t};var Hn=class{count=0};var pa={extension:{type:Cr.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await import("./browserAll-5AZHDDG6.js")}};var ha={extension:{type:Cr.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await import("./webworkerAll-QKIC5O27.js")}};var qn;function ga(r){return qn!==void 0||(qn=(()=>{let e={stencil:!0,failIfMajorPerformanceCaveat:r??Ar.defaultOptions.failIfMajorPerformanceCaveat};try{if(!Kt.get().getWebGLRenderingContext())return!1;let n=Kt.get().createCanvas().getContext("webgl",e),o=!!n?.getContextAttributes()?.stencil;if(n){let i=n.getExtension("WEBGL_lose_context");i&&i.loseContext()}return n=null,o}catch{return!1}})()),qn}var Gn;async function xa(r={}){return Gn!==void 0||(Gn=await(async()=>{let e=Kt.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(r)).requestDevice(),!0}catch{return!1}})()),Gn}var ba=["webgl","webgpu","canvas"];async function Ti(r){let e=[];r.preference?(e.push(r.preference),ba.forEach(i=>{i!==r.preference&&e.push(i)})):e=ba.slice();let t,n={};for(let i=0;i<e.length;i++){let s=e[i];if(s==="webgpu"&&await xa()){let{WebGPURenderer:a}=await import("./WebGPURenderer-RBOFXPL5.js");t=a,n={...r,...r.webgpu};break}else if(s==="webgl"&&ga(r.failIfMajorPerformanceCaveat??Ar.defaultOptions.failIfMajorPerformanceCaveat)){let{WebGLRenderer:a}=await import("./WebGLRenderer-NLGJGAXK.js");t=a,n={...r,...r.webgl};break}else if(s==="canvas")throw n={...r},new Error("CanvasRenderer is not yet implemented")}if(delete n.webgpu,delete n.webgl,!t)throw new Error("No available renderer for the current environment");let o=new t;return await o.init(n),o}var Wn=class extends Ei{constructor(e,t){let{text:n,resolution:o,style:i,anchor:s,width:a,height:c,roundPixels:l,...d}=e;super({...d}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=t,this.text=n??"",this.style=i,this.resolution=o??null,this.allowChildren=!1,this._anchor=new Ii({_onUpdate:()=>{this.onViewUpdate()}}),s&&(this.anchor=s),this.roundPixels=l??!1,a!==void 0&&(this.width=a),c!==void 0&&(this.height=c)}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}set text(e){e=e.toString(),this._text!==e&&(this._text=e,this.onViewUpdate())}get text(){return this._text}set resolution(e){this._autoResolution=e===null,this._resolution=e,this.onViewUpdate()}get resolution(){return this._resolution}get style(){return this._style}set style(e){e||(e={}),this._style?.off("update",this.onViewUpdate,this),e instanceof this._styleClass?this._style=e:this._style=new this._styleClass(e),this._style.on("update",this.onViewUpdate,this),this.onViewUpdate()}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(e){this._setWidth(e,this.bounds.width)}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(e){this._setHeight(e,this.bounds.height)}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this.bounds.width,e.height=Math.abs(this.scale.y)*this.bounds.height,e}setSize(e,t){typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,this.bounds.width),t!==void 0&&this._setHeight(t,this.bounds.height)}containsPoint(e){let t=this.bounds.width,n=this.bounds.height,o=-t*this.anchor.x,i=0;return e.x>=o&&e.x<=o+t&&(i=-n*this.anchor.y,e.y>=i&&e.y<=i+n)}onViewUpdate(){this.didViewUpdate||(this._didTextUpdate=!0),super.onViewUpdate()}destroy(e=!1){super.destroy(e),this.owner=null,this._bounds=null,this._anchor=null,(typeof e=="boolean"?e:e?.style)&&this._style.destroy(e),this._style=null,this._text=null}get styleKey(){return`${this._text}:${this._style.styleKey}:${this._resolution}`}};function ya(r,e){let t=r[0]??{};return(typeof t=="string"||r[1])&&(_i(Ai,`use new ${e}({ text: "hi!", style }) instead`),t={text:t,style:r[1]}),t}var vr=class extends Wn{constructor(...e){let t=ya(e,"Text");super(t,Fi),this.renderPipeId="text",t.textureStyle&&(this.textureStyle=t.textureStyle instanceof fo?t.textureStyle:new fo(t.textureStyle))}updateBounds(){let e=this._bounds,t=this._anchor,n=0,o=0;if(this._style.trim){let{frame:i,canvasAndContext:s}=ho.getCanvasAndContext({text:this.text,style:this._style,resolution:1});ho.returnCanvasAndContext(s),n=i.width,o=i.height}else{let i=Di.measureText(this._text,this._style);n=i.width,o=i.height}e.minX=-t._x*n,e.maxX=e.minX+n,e.minY=-t._y*o,e.maxY=e.minY+o}};Ci.add(pa,ha);var Ta=r=>{let[e,t,n]=r,[o,i]=e,[s,a]=t,c=n*Math.PI/180,l=Math.cos(c),d=Math.sin(c);return[l*s,d*s,-d*a,l*a,o,i]},wa=([r,e,t,n,o,i])=>new uo(r,e,t,n,o,i);var ka=(r,e)=>{let[t,n,o,i,s,a]=r,[c,l,d,u,f,m]=e;return[t*c+o*l,n*c+i*l,t*d+o*u,n*d+i*u,t*f+o*m+s,n*f+i*m+a]},Sa=[1,0,0,1,0,0];var Aa=ic(Pa(),1);var Ca=`
|
|
2362
|
+
`),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){let n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),n}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let o=this.gl.getAttribLocation(this.program,"a_position"),i=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(o),this.gl.vertexAttribPointer(o,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,t){(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}},Ct=class extends dr{constructor(e){if(!(e instanceof ke))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=this._track.codec,o=this._track.rotation,i=await this._track.getDecoderConfig(),s=this._track.timeResolution;return h(n&&i),new Qo(e,t,n,i,o,s)}_createPacketSink(){return new at(this._track)}async getSample(e){Ve(e);for await(let t of this.mediaSamplesAtTimestamps([e]))return t;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}},fr=class{constructor(e,t={}){if(this._nextCanvasIndex=0,!(e instanceof ke))throw new TypeError("videoTrack must be an InputVideoTrack.");if(t&&typeof t!="object")throw new TypeError("options must be an object.");if(t.alpha!==void 0&&typeof t.alpha!="boolean")throw new TypeError("options.alpha, when provided, must be a boolean.");if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(t.fit!==void 0&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(t.crop!==void 0&&Ko(t.crop,"options."),t.poolSize!==void 0&&(typeof t.poolSize!="number"||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");let n=t.rotation??e.rotation,[o,i]=n%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],s=t.crop;s&&$o(s,o,i);let[a,c]=s?[s.width,s.height]:[o,i],l=a/c;t.width!==void 0&&t.height===void 0?(a=t.width,c=Math.round(a/l)):t.width===void 0&&t.height!==void 0?(c=t.height,a=Math.round(c*l)):t.width!==void 0&&t.height!==void 0&&(a=t.width,c=t.height),this._videoTrack=e,this._alpha=t.alpha??!1,this._width=a,this._height=c,this._rotation=n,this._crop=s,this._fit=t.fit??"fill",this._videoSampleSink=new Ct(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let t=this._canvasPool[this._nextCanvasIndex],n=!1;t||(typeof document<"u"?(t=document.createElement("canvas"),t.width=this._width,t.height=this._height):t=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=t),n=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let o=t.getContext("2d",{alpha:this._alpha||rr()});h(o),o.resetTransform(),n||(!this._alpha&&rr()?(o.fillStyle="black",o.fillRect(0,0,this._width,this._height)):o.clearRect(0,0,this._width,this._height)),e.drawWithFit(o,{fit:this._fit,rotation:this._rotation,crop:this._crop});let i={canvas:t,timestamp:e.timestamp,duration:e.duration};return e.close(),i}async getCanvas(e){Ve(e);let t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return zo(this._videoSampleSink.samples(e,t),n=>this._videoSampleToWrappedCanvas(n))}canvasesAtTimestamps(e){return zo(this._videoSampleSink.samplesAtTimestamps(e),t=>t&&this._videoSampleToWrappedCanvas(t))}},Zo=class extends ur{constructor(e,t,n,o){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new tr,this.customDecoderQueueSize=0,this.currentTimestamp=null;let i=a=>{(this.currentTimestamp===null||Math.abs(a.timestamp-this.currentTimestamp)>=a.duration)&&(this.currentTimestamp=a.timestamp);let c=this.currentTimestamp;if(this.currentTimestamp+=a.duration,a.numberOfFrames===0){a.close();return}let l=o.sampleRate;a.setTimestamp(Math.round(c*l)/l),e(a)},s=mn.find(a=>a.supports(n,o));if(s)this.customDecoder=new s,this.customDecoder.codec=n,this.customDecoder.config=o,this.customDecoder.onSample=a=>{if(!(a instanceof vt))throw new TypeError("The argument passed to onSample must be an AudioSample.");i(a)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let a=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:c=>{try{i(new vt(c))}catch(l){this.onError(l)}},error:c=>{c.stack=a,this.onError(c)}}),this.decoder.configure(o)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(h(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(h(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(h(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(h(this.decoder),this.decoder.close())}},Jo=class extends ur{constructor(e,t,n){super(e,t),this.decoderConfig=n,this.currentTimestamp=null,h(Ue.includes(n.codec)),this.codec=n.codec;let{dataType:o,sampleSize:i,littleEndian:s}=sn(this.codec);switch(this.inputSampleSize=i,i){case 1:o==="unsigned"?this.readInputValue=(a,c)=>a.getUint8(c)-2**7:o==="signed"?this.readInputValue=(a,c)=>a.getInt8(c):o==="ulaw"?this.readInputValue=(a,c)=>ys(a.getUint8(c)):o==="alaw"?this.readInputValue=(a,c)=>Ts(a.getUint8(c)):h(!1);break;case 2:o==="unsigned"?this.readInputValue=(a,c)=>a.getUint16(c,s)-2**15:o==="signed"?this.readInputValue=(a,c)=>a.getInt16(c,s):h(!1);break;case 3:o==="unsigned"?this.readInputValue=(a,c)=>Ye(a,c,s)-2**23:o==="signed"?this.readInputValue=(a,c)=>es(a,c,s):h(!1);break;case 4:o==="unsigned"?this.readInputValue=(a,c)=>a.getUint32(c,s)-2**31:o==="signed"?this.readInputValue=(a,c)=>a.getInt32(c,s):o==="float"?this.readInputValue=(a,c)=>a.getFloat32(c,s):h(!1);break;case 8:o==="float"?this.readInputValue=(a,c)=>a.getFloat64(c,s):h(!1);break;default:se(i),h(!1)}switch(i){case 1:o==="ulaw"||o==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(a,c,l)=>a.setInt16(c,l,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(a,c,l)=>a.setUint8(c,l+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(a,c,l)=>a.setInt16(c,l,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(a,c,l)=>a.setInt32(c,l<<8,!0);break;case 4:this.outputSampleSize=4,o==="float"?(this.outputFormat="f32",this.writeOutputValue=(a,c,l)=>a.setFloat32(c,l,!0)):(this.outputFormat="s32",this.writeOutputValue=(a,c,l)=>a.setInt32(c,l,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(a,c,l)=>a.setFloat32(c,l,!0);break;default:se(i),h(!1)}}getDecodeQueueSize(){return 0}decode(e){let t=z(e.data),n=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,o=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,i=new ArrayBuffer(o),s=new DataView(i);for(let d=0;d<n*this.decoderConfig.numberOfChannels;d++){let u=d*this.inputSampleSize,f=d*this.outputSampleSize,m=this.readInputValue(t,u);this.writeOutputValue(s,f,m)}let a=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=a)&&(this.currentTimestamp=e.timestamp);let c=this.currentTimestamp;this.currentTimestamp+=a;let l=new vt({format:this.outputFormat,data:i,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:c});this.onSample(l)}async flush(){}close(){}},mr=class extends dr{constructor(e){if(!(e instanceof G))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=this._track.codec,o=await this._track.getDecoderConfig();return h(n&&o),Ue.includes(o.codec)?new Jo(e,t,o):new Zo(e,t,n,o)}_createPacketSink(){return new at(this._track)}async getSample(e){Ve(e);for await(let t of this.mediaSamplesAtTimestamps([e]))return t;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}};var It=class{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof ke}isAudioTrack(){return this instanceof G}get id(){return this._backing.getId()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){let t=new at(this),n=1/0,o=-1/0,i=0,s=0;for await(let a of t.packets(void 0,void 0,{metadataOnly:!0})){if(i>=e&&a.timestamp>=o)break;n=Math.min(n,a.timestamp),o=Math.max(o,a.timestamp+a.duration),i++,s+=a.byteLength}return{packetCount:i,averagePacketRate:i?Number((i/(o-n)).toPrecision(16)):0,averageBitrate:i?Number((8*s/(o-n)).toPrecision(16)):0}}},ke=class extends It{constructor(e,t){super(e,t),this._backing=t}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get displayWidth(){return this._backing.getRotation()%180===0?this._backing.getCodedWidth():this._backing.getCodedHeight()}get displayHeight(){return this._backing.getRotation()%180===0?this._backing.getCodedHeight():this._backing.getCodedWidth()}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pg"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=this._backing.getCodec();return h(t!==null),fn.some(o=>o.supports(t,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof V))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");if(this.codec===null)return null;let t=await this.getDecoderConfig();return h(t),dn(this.codec,t,e.data)}},G=class extends It{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=this._backing.getCodec();return h(t!==null),mn.some(n=>n.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof V))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}};var As=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isQuickTime?"quicktime":"mp4");if(r.codecStrings.length>0){let n=[...new Set(r.codecStrings)];t+=`; codecs="${n.join(", ")}"`}return t};var ct=8,At=16,_e=r=>{let e=v(r),t=L(r,4),n=8;e===1&&(e=ne(r),n=16);let i=e-n;return i<0?null:{name:t,totalSize:e,headerSize:n,contentSize:i}},Le=r=>Ee(r)/65536,pn=r=>Ee(r)/1073741824,hn=r=>{let e=0;for(let t=0;t<4;t++){e<<=7;let n=A(r);if(e|=n&127,(n&128)===0)break}return e},ue=r=>{let e=W(r);return r.skip(2),e=Math.min(e,r.remainingLength),$.decode(E(r,e))},_s=r=>{let e=_e(r);if(!e||e.name!=="data"||r.remainingLength<8)return null;let t=v(r);r.skip(4);let n=E(r,e.contentSize-8);switch(t){case 1:return $.decode(n);case 2:return new TextDecoder("utf-16be").decode(n);case 13:return new ze(n,"image/jpeg");case 14:return new ze(n,"image/png");case 27:return new ze(n,"image/bmp");default:return n}};var gn=class extends Q{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(t=>t.inputTrack.getCodecParameterString()));return As({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(t=>t.info?.type==="video"),hasAudio:this.tracks.some(t=>t.info?.type==="audio"),codecStrings:e.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,ct,At);if(t instanceof Promise&&(t=await t),!t)break;let n=e,o=_e(t);if(!o)break;if(o.name==="ftyp"){let i=L(t,4);this.isQuickTime=i==="qt "}else if(o.name==="moov"){let i=this.reader.requestSlice(t.filePos,o.contentSize);if(i instanceof Promise&&(i=await i),!i)break;this.moovSlice=i,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((s,a)=>Number(a.disposition.default)-Number(s.disposition.default));for(let s of this.tracks){let a=s.editListPreviousSegmentDurations/this.movieTimescale;s.editListOffset-=Math.round(a*s.timescale)}break}e=n+o.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let t=this.reader.requestSlice(this.reader.fileSize-4,4);t instanceof Promise&&(t=await t),h(t);let n=v(t),o=this.reader.fileSize-n;if(o>=0&&o<=this.reader.fileSize-At){let i=this.reader.requestSliceRange(o,ct,At);if(i instanceof Promise&&(i=await i),i){let s=_e(i);if(s&&s.name==="mfra"){let a=this.reader.requestSlice(i.filePos,s.contentSize);a instanceof Promise&&(a=await a),a&&this.readContiguousBoxes(a)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=t,h(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&Ue.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){h(e.info?.type==="audio");let i=sn(e.info.codec),s=[],a=[];for(let c=0;c<t.sampleToChunk.length;c++){let l=t.sampleToChunk[c],d=t.sampleToChunk[c+1],u=(d?d.startChunkIndex:t.chunkOffsets.length)-l.startChunkIndex;for(let f=0;f<u;f++){let m=l.startSampleIndex+f*l.samplesPerChunk,p=m+l.samplesPerChunk,g=B(t.sampleTimingEntries,m,C=>C.startIndex),x=t.sampleTimingEntries[g],y=B(t.sampleTimingEntries,p,C=>C.startIndex),b=t.sampleTimingEntries[y],w=x.startDecodeTimestamp+(m-x.startIndex)*x.delta,P=b.startDecodeTimestamp+(p-b.startIndex)*b.delta-w,S=Y(s);S&&S.delta===P?S.count++:s.push({startIndex:l.startChunkIndex+f,startDecodeTimestamp:w,count:1,delta:P});let _=l.samplesPerChunk*i.sampleSize*e.info.numberOfChannels;a.push(_)}l.startSampleIndex=l.startChunkIndex,l.samplesPerChunk=1}t.sampleTimingEntries=s,t.sampleSizes=a}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let i of t.sampleTimingEntries)for(let s=0;s<i.count;s++)t.presentationTimestamps.push({presentationTimestamp:i.startDecodeTimestamp+s*i.delta,sampleIndex:i.startIndex+s});for(let i of t.sampleCompositionTimeOffsets)for(let s=0;s<i.count;s++){let a=i.startIndex+s,c=t.presentationTimestamps[a];c&&(c.presentationTimestamp+=i.offset)}t.presentationTimestamps.sort((i,s)=>i.presentationTimestamp-s.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let i=0;i<t.presentationTimestamps.length;i++)t.presentationTimestampIndexMap[t.presentationTimestamps[i].sampleIndex]=i}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,ct,At);t instanceof Promise&&(t=await t),h(t);let n=_e(t);h(n?.name==="moof");let o=this.reader.requestSlice(e,n.totalSize);o instanceof Promise&&(o=await o),h(o),this.traverseBox(o);let i=this.lastReadFragment;h(i&&i.moofOffset===e);for(let[,s]of i.trackData){let a=s.track,{fragmentPositionCache:c}=a;if(!s.startTimestampIsFinal){let d=a.fragmentLookupTable.find(u=>u.moofOffset===i.moofOffset);if(d)ei(s,d.timestamp);else{let u=B(c,i.moofOffset-1,f=>f.moofOffset);if(u!==-1){let f=c[u];ei(s,f.endTimestamp)}}s.startTimestampIsFinal=!0}let l=B(c,s.startTimestamp,d=>d.startTimestamp);(l===-1||c[l].moofOffset!==i.moofOffset)&&c.splice(l+1,0,{moofOffset:i.moofOffset,startTimestamp:s.startTimestamp,endTimestamp:s.endTimestamp})}return i}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-ct&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-ct;){let n=e.filePos,o=_e(e);if(!o)break;yield{boxInfo:o,slice:e},e.filePos=n+o.totalSize}}traverseBox(e){let t=e.filePos,n=_e(e);if(!n)return!1;let o=e.filePos,i=t+n.totalSize;switch(n.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"mvhd":{let s=A(e);e.skip(3),s===1?(e.skip(16),this.movieTimescale=v(e),this.movieDurationInTimescale=ne(e)):(e.skip(8),this.movieTimescale=v(e),this.movieDurationInTimescale=v(e))}break;case"trak":{let s={id:-1,demuxer:this,inputTrack:null,disposition:{...te},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:K,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=s,this.readContiguousBoxes(e.slice(o,n.contentSize)),s.id!==-1&&s.timescale!==-1&&s.info!==null){if(s.info.type==="video"&&s.info.width!==-1){let a=s;s.inputTrack=new ke(this.input,new ti(a)),this.tracks.push(s)}else if(s.info.type==="audio"&&s.info.numberOfChannels!==-1){let a=s;s.inputTrack=new G(this.input,new ri(a)),this.tracks.push(s)}}this.currentTrack=null}break;case"tkhd":{let s=this.currentTrack;if(!s)break;let a=A(e),l=!!(He(e)&1);if(s.disposition.default=l,a===0)e.skip(8),s.id=v(e),e.skip(4),s.durationInMovieTimescale=v(e);else if(a===1)e.skip(16),s.id=v(e),e.skip(4),s.durationInMovieTimescale=ne(e);else throw new Error(`Incorrect track header version ${a}.`);e.skip(16);let d=[Le(e),Le(e),pn(e),Le(e),Le(e),pn(e),Le(e),Le(e),pn(e)],u=$r(rs(Nc(d),90));h(u===0||u===90||u===180||u===270),s.rotation=u}break;case"elst":{let s=this.currentTrack;if(!s)break;let a=A(e);e.skip(3);let c=!1,l=0,d=v(e);for(let u=0;u<d;u++){let f=a===1?ne(e):v(e),m=a===1?Fs(e):Ee(e),p=Le(e);if(f!==0){if(c){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(m===-1){l+=f;continue}if(p!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}s.editListPreviousSegmentDurations=l,s.editListOffset=m,c=!0}}}break;case"mdhd":{let s=this.currentTrack;if(!s)break;let a=A(e);e.skip(3),a===0?(e.skip(8),s.timescale=v(e),s.durationInMediaTimescale=v(e)):a===1&&(e.skip(16),s.timescale=v(e),s.durationInMediaTimescale=ne(e));let c=W(e);if(c>0){s.languageCode="";for(let l=0;l<3;l++)s.languageCode=String.fromCharCode(96+(c&31))+s.languageCode,c>>=5;Jr(s.languageCode)||(s.languageCode=K)}}break;case"hdlr":{let s=this.currentTrack;if(!s)break;e.skip(8);let a=L(e,4);a==="vide"?s.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:a==="soun"&&(s.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{let s=this.currentTrack;if(!s)break;s.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(o,n.contentSize))}break;case"stsd":{let s=this.currentTrack;if(!s||s.info===null||s.sampleTable)break;let a=A(e);e.skip(3);let c=v(e);for(let l=0;l<c;l++){let d=e.filePos,u=_e(e);if(!u)break;s.internalCodecId=u.name;let f=u.name.toLowerCase();if(s.info.type==="video")f==="avc1"||f==="avc3"?(s.info.codec="avc",s.info.avcType=f==="avc1"?1:3):f==="hvc1"||f==="hev1"?s.info.codec="hevc":f==="vp08"?s.info.codec="vp8":f==="vp09"?s.info.codec="vp9":f==="av01"?s.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${u.name}').`),e.skip(24),s.info.width=W(e),s.info.height=W(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,d+u.totalSize-e.filePos));else{f==="mp4a"||(f==="opus"?s.info.codec="opus":f==="flac"?s.info.codec="flac":f==="twos"||f==="sowt"||f==="raw "||f==="in24"||f==="in32"||f==="fl32"||f==="fl64"||f==="lpcm"||f==="ipcm"||f==="fpcm"||(f==="ulaw"?s.info.codec="ulaw":f==="alaw"?s.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${u.name}').`))),e.skip(8);let m=W(e);e.skip(6);let p=W(e),g=W(e);e.skip(4);let x=v(e)/65536;if(a===0&&m>0){if(m===1)e.skip(4),g=8*v(e),e.skip(8);else if(m===2){e.skip(4),x=bn(e),p=v(e),e.skip(4),g=v(e);let y=v(e);if(e.skip(8),f==="lpcm"){let b=g+7>>3,w=!!(y&1),k=!!(y&2),P=y&4?-1:0;g>0&&g<=64&&(w?g===32&&(s.info.codec=k?"pcm-f32be":"pcm-f32"):P&1<<b-1?b===1?s.info.codec="pcm-s8":b===2?s.info.codec=k?"pcm-s16be":"pcm-s16":b===3?s.info.codec=k?"pcm-s24be":"pcm-s24":b===4&&(s.info.codec=k?"pcm-s32be":"pcm-s32"):b===1&&(s.info.codec="pcm-u8")),s.info.codec===null&&console.warn("Unsupported PCM format.")}}}s.info.codec==="opus"&&(x=rt),s.info.numberOfChannels=p,s.info.sampleRate=x,f==="twos"?g===8?s.info.codec="pcm-s8":g===16?s.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${g} for codec 'twos'.`),s.info.codec=null):f==="sowt"?g===8?s.info.codec="pcm-s8":g===16?s.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${g} for codec 'sowt'.`),s.info.codec=null):f==="raw "?s.info.codec="pcm-u8":f==="in24"?s.info.codec="pcm-s24be":f==="in32"?s.info.codec="pcm-s32be":f==="fl32"?s.info.codec="pcm-f32be":f==="fl64"?s.info.codec="pcm-f64be":f==="ipcm"?s.info.codec="pcm-s16be":f==="fpcm"&&(s.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,d+u.totalSize-e.filePos))}}}break;case"avcC":{let s=this.currentTrack;if(!s)break;h(s.info),s.info.codecDescription=E(e,n.contentSize)}break;case"hvcC":{let s=this.currentTrack;if(!s)break;h(s.info),s.info.codecDescription=E(e,n.contentSize)}break;case"vpcC":{let s=this.currentTrack;if(!s)break;h(s.info?.type==="video"),e.skip(4);let a=A(e),c=A(e),l=A(e),d=l>>4,u=l>>1&7,f=l&1,m=A(e),p=A(e),g=A(e);s.info.vp9CodecInfo={profile:a,level:c,bitDepth:d,chromaSubsampling:u,videoFullRangeFlag:f,colourPrimaries:m,transferCharacteristics:p,matrixCoefficients:g}}break;case"av1C":{let s=this.currentTrack;if(!s)break;h(s.info?.type==="video"),e.skip(1);let a=A(e),c=a>>5,l=a&31,d=A(e),u=d>>7,f=d>>6&1,m=d>>5&1,p=d>>4&1,g=d>>3&1,x=d>>2&1,y=d&3,b=c===2&&f?m?12:10:f?10:8;s.info.av1CodecInfo={profile:c,level:l,tier:u,bitDepth:b,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:x,chromaSamplePosition:y}}break;case"colr":{let s=this.currentTrack;if(!s||(h(s.info?.type==="video"),L(e,4)!=="nclx"))break;let c=W(e),l=W(e),d=W(e),u=!!(A(e)&128);s.info.colorSpace={primaries:Kr[c],transfer:Xr[l],matrix:Qr[d],fullRange:u}}break;case"wave":this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"esds":{let s=this.currentTrack;if(!s)break;h(s.info?.type==="audio"),e.skip(4);let a=A(e);h(a===3),hn(e),e.skip(2);let c=A(e),l=(c&128)!==0,d=(c&64)!==0,u=(c&32)!==0;if(l&&e.skip(2),d){let x=A(e);e.skip(x)}u&&e.skip(2);let f=A(e);h(f===4);let m=hn(e),p=e.filePos,g=A(e);if(g===64||g===103?(s.info.codec="aac",s.info.aacCodecInfo={isMpeg2:g===103}):g===105||g===107?s.info.codec="mp3":g===221?s.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${g}) - discarding track.`),e.skip(12),m>e.filePos-p){let x=A(e);h(x===5);let y=hn(e);if(s.info.codecDescription=E(e,y),s.info.codec==="aac"){let b=Lo(s.info.codecDescription);b.numberOfChannels!==null&&(s.info.numberOfChannels=b.numberOfChannels),b.sampleRate!==null&&(s.info.sampleRate=b.sampleRate)}}}break;case"enda":{let s=this.currentTrack;if(!s)break;h(s.info?.type==="audio"),W(e)&255&&(s.info.codec==="pcm-s16be"?s.info.codec="pcm-s16":s.info.codec==="pcm-s24be"?s.info.codec="pcm-s24":s.info.codec==="pcm-s32be"?s.info.codec="pcm-s32":s.info.codec==="pcm-f32be"?s.info.codec="pcm-f32":s.info.codec==="pcm-f64be"&&(s.info.codec="pcm-f64"))}break;case"pcmC":{let s=this.currentTrack;if(!s)break;h(s.info?.type==="audio"),e.skip(4);let c=!!(A(e)&1),l=A(e);s.info.codec==="pcm-s16be"?c?l===16?s.info.codec="pcm-s16":l===24?s.info.codec="pcm-s24":l===32?s.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${l}.`),s.info.codec=null):l===16?s.info.codec="pcm-s16be":l===24?s.info.codec="pcm-s24be":l===32?s.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${l}.`),s.info.codec=null):s.info.codec==="pcm-f32be"&&(c?l===32?s.info.codec="pcm-f32":l===64?s.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${l}.`),s.info.codec=null):l===32?s.info.codec="pcm-f32be":l===64?s.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${l}.`),s.info.codec=null));break}case"dOps":{let s=this.currentTrack;if(!s)break;h(s.info?.type==="audio"),e.skip(1);let a=A(e),c=W(e),l=v(e),d=pr(e),u=A(e),f;u!==0?f=E(e,2+a):f=new Uint8Array(0);let m=new Uint8Array(19+f.byteLength),p=new DataView(m.buffer);p.setUint32(0,1332770163,!1),p.setUint32(4,1214603620,!1),p.setUint8(8,1),p.setUint8(9,a),p.setUint16(10,c,!0),p.setUint32(12,l,!0),p.setInt16(16,d,!0),p.setUint8(18,u),m.set(f,19),s.info.codecDescription=m,s.info.numberOfChannels=a}break;case"dfLa":{let s=this.currentTrack;if(!s)break;h(s.info?.type==="audio"),e.skip(4);let a=127,c=128,l=e.filePos;for(;e.filePos<i;){let p=A(e),g=He(e);if((p&a)===Ne.STREAMINFO){e.skip(10);let y=v(e),b=y>>>12,w=(y>>9&7)+1;s.info.sampleRate=b,s.info.numberOfChannels=w,e.skip(20)}else e.skip(g);if(p&c)break}let d=e.filePos;e.filePos=l;let u=E(e,d-l),f=new Uint8Array(4+u.byteLength);new DataView(f.buffer).setUint32(0,1716281667,!1),f.set(u,4),s.info.codecDescription=f}break;case"stts":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=v(e),c=0,l=0;for(let d=0;d<a;d++){let u=v(e),f=v(e);s.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:l,count:u,delta:f}),c+=u,l+=u*f}}break;case"ctts":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=v(e),c=0;for(let l=0;l<a;l++){let d=v(e),u=Ee(e);s.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:d,offset:u}),c+=d}}break;case"stsz":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=v(e),c=v(e);if(a===0)for(let l=0;l<c;l++){let d=v(e);s.sampleTable.sampleSizes.push(d)}else s.sampleTable.sampleSizes.push(a)}break;case"stz2":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4),e.skip(3);let a=A(e),c=v(e),l=E(e,Math.ceil(c*a/8)),d=new N(l);for(let u=0;u<c;u++){let f=d.readBits(a);s.sampleTable.sampleSizes.push(f)}}break;case"stss":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4),s.sampleTable.keySampleIndices=[];let a=v(e);for(let c=0;c<a;c++){let l=v(e)-1;s.sampleTable.keySampleIndices.push(l)}s.sampleTable.keySampleIndices[0]!==0&&s.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=v(e);for(let l=0;l<a;l++){let d=v(e)-1,u=v(e),f=v(e);s.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:d,samplesPerChunk:u,sampleDescriptionIndex:f})}let c=0;for(let l=0;l<s.sampleTable.sampleToChunk.length;l++)if(s.sampleTable.sampleToChunk[l].startSampleIndex=c,l<s.sampleTable.sampleToChunk.length-1){let u=s.sampleTable.sampleToChunk[l+1].startChunkIndex-s.sampleTable.sampleToChunk[l].startChunkIndex;c+=u*s.sampleTable.sampleToChunk[l].samplesPerChunk}}break;case"stco":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=v(e);for(let c=0;c<a;c++){let l=v(e);s.sampleTable.chunkOffsets.push(l)}}break;case"co64":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=v(e);for(let c=0;c<a;c++){let l=ne(e);s.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"mehd":{let s=A(e);e.skip(3);let a=s===1?ne(e):v(e);this.movieDurationInTimescale=a}break;case"trex":{e.skip(4);let s=v(e),a=v(e),c=v(e),l=v(e),d=v(e);this.fragmentTrackDefaults.push({trackId:s,defaultSampleDescriptionIndex:a,defaultSampleDuration:c,defaultSampleSize:l,defaultSampleFlags:d})}break;case"tfra":{let s=A(e);e.skip(3);let a=v(e),c=this.tracks.find(b=>b.id===a);if(!c)break;let l=v(e),d=(l&48)>>4,u=(l&12)>>2,f=l&3,m=[A,W,He,v],p=m[d],g=m[u],x=m[f],y=v(e);for(let b=0;b<y;b++){let w=s===1?ne(e):v(e),k=s===1?ne(e):v(e);p(e),g(e),x(e),c.fragmentLookupTable.push({timestamp:w,moofOffset:k})}c.fragmentLookupTable.sort((b,w)=>b.timestamp-w.timestamp);for(let b=0;b<c.fragmentLookupTable.length-1;b++){let w=c.fragmentLookupTable[b],k=c.fragmentLookupTable[b+1];w.timestamp===k.timestamp&&(c.fragmentLookupTable.splice(b+1,1),b--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:n.totalSize,implicitBaseDataOffset:t,trackData:new Map},this.readContiguousBoxes(e.slice(o,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(h(this.currentFragment),this.readContiguousBoxes(e.slice(o,n.contentSize)),this.currentTrack){let s=this.currentFragment.trackData.get(this.currentTrack.id);if(s){let{currentFragmentState:a}=this.currentTrack;h(a),a.startTimestamp!==null&&(ei(s,a.startTimestamp),s.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{h(this.currentFragment),e.skip(1);let s=He(e),a=!!(s&1),c=!!(s&2),l=!!(s&8),d=!!(s&16),u=!!(s&32),f=!!(s&65536),m=!!(s&131072),p=v(e),g=this.tracks.find(y=>y.id===p);if(!g)break;let x=this.fragmentTrackDefaults.find(y=>y.trackId===p);this.currentTrack=g,g.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:x?.defaultSampleDescriptionIndex??null,defaultSampleDuration:x?.defaultSampleDuration??null,defaultSampleSize:x?.defaultSampleSize??null,defaultSampleFlags:x?.defaultSampleFlags??null,startTimestamp:null},a?g.currentFragmentState.baseDataOffset=ne(e):m&&(g.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(g.currentFragmentState.sampleDescriptionIndex=v(e)),l&&(g.currentFragmentState.defaultSampleDuration=v(e)),d&&(g.currentFragmentState.defaultSampleSize=v(e)),u&&(g.currentFragmentState.defaultSampleFlags=v(e)),f&&(g.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let s=this.currentTrack;if(!s)break;h(s.currentFragmentState);let a=A(e);e.skip(3);let c=a===0?v(e):ne(e);s.currentFragmentState.startTimestamp=c}break;case"trun":{let s=this.currentTrack;if(!s)break;if(h(this.currentFragment),h(s.currentFragmentState),this.currentFragment.trackData.has(s.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}let a=A(e),c=He(e),l=!!(c&1),d=!!(c&4),u=!!(c&256),f=!!(c&512),m=!!(c&1024),p=!!(c&2048),g=v(e),x=s.currentFragmentState.baseDataOffset;l&&(x+=Ee(e));let y=null;d&&(y=v(e));let b=x;if(g===0){this.currentFragment.implicitBaseDataOffset=b;break}let w=0,k={track:s,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(s.id,k);for(let _=0;_<g;_++){let C;u?C=v(e):(h(s.currentFragmentState.defaultSampleDuration!==null),C=s.currentFragmentState.defaultSampleDuration);let F;f?F=v(e):(h(s.currentFragmentState.defaultSampleSize!==null),F=s.currentFragmentState.defaultSampleSize);let O;m?O=v(e):(h(s.currentFragmentState.defaultSampleFlags!==null),O=s.currentFragmentState.defaultSampleFlags),_===0&&y!==null&&(O=y);let R=0;p&&(a===0?R=v(e):R=Ee(e));let j=!(O&65536);k.samples.push({presentationTimestamp:w+R,duration:C,byteOffset:b,byteSize:F,isKeyFrame:j}),b+=F,w+=C}k.presentationTimestamps=k.samples.map((_,C)=>({presentationTimestamp:_.presentationTimestamp,sampleIndex:C})).sort((_,C)=>_.presentationTimestamp-C.presentationTimestamp);for(let _=0;_<k.presentationTimestamps.length;_++){let C=k.presentationTimestamps[_],F=k.samples[C.sampleIndex];if(k.firstKeyFrameTimestamp===null&&F.isKeyFrame&&(k.firstKeyFrameTimestamp=F.presentationTimestamp),_<k.presentationTimestamps.length-1){let O=k.presentationTimestamps[_+1];F.duration=O.presentationTimestamp-C.presentationTimestamp}}let P=k.samples[k.presentationTimestamps[0].sampleIndex],S=k.samples[Y(k.presentationTimestamps).sampleIndex];k.startTimestamp=P.presentationTimestamp,k.endTimestamp=S.presentationTimestamp+S.duration,this.currentFragment.implicitBaseDataOffset=b}break;case"udta":{let s=this.iterateContiguousBoxes(e.slice(o,n.contentSize));for(let{boxInfo:a,slice:c}of s){if(a.name!=="meta"&&!this.currentTrack){let l=c.filePos;this.metadataTags.raw??={},a.name[0]==="\xA9"?this.metadataTags.raw[a.name]??=ue(c):this.metadataTags.raw[a.name]??=E(c,a.contentSize),c.filePos=l}switch(a.name){case"meta":c.skip(-a.headerSize),this.traverseBox(c);break;case"\xA9nam":case"name":this.currentTrack?this.currentTrack.name=$.decode(E(c,a.contentSize)):this.metadataTags.title??=ue(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=ue(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=ue(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=ue(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=ue(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=ue(c));break;case"\xA9day":if(!this.currentTrack){let l=new Date(ue(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=ue(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=ue(c));break}}}break;case"meta":{if(this.currentTrack)break;let a=v(e)!==0;this.currentMetadataKeys=new Map,a?this.readContiguousBoxes(e.slice(o,n.contentSize)):this.readContiguousBoxes(e.slice(o+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let s=v(e);for(let a=0;a<s;a++){let c=v(e);e.skip(4);let l=$.decode(E(e,c-8));this.currentMetadataKeys.set(a+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let s=this.iterateContiguousBoxes(e.slice(o,n.contentSize));for(let{boxInfo:a,slice:c}of s){let l=a.name,d=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(d)&&(l=this.currentMetadataKeys.get(d));let u=_s(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=u,l){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof u=="string"&&(this.metadataTags.title??=u);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof u=="string"&&(this.metadataTags.description??=u);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof u=="string"&&(this.metadataTags.artist??=u);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof u=="string"&&(this.metadataTags.album??=u);break;case"aART":case"album_artist":typeof u=="string"&&(this.metadataTags.albumArtist??=u);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof u=="string"&&(this.metadataTags.comment??=u);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof u=="string"&&(this.metadataTags.genre??=u);break;case"\xA9lyr":case"lyrics":typeof u=="string"&&(this.metadataTags.lyrics??=u);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof u=="string"){let f=new Date(u);Number.isNaN(f.getTime())||(this.metadataTags.date??=f)}break;case"covr":case"com.apple.quicktime.artwork":u instanceof ze?(this.metadataTags.images??=[],this.metadataTags.images.push({data:u.data,kind:"coverFront",mimeType:u.mimeType})):u instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:u,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof u=="string"){let f=u.split("/"),m=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(m)&&m>0&&(this.metadataTags.trackNumber??=m),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(u instanceof Uint8Array&&u.length>=6){let f=z(u),m=f.getUint16(2,!1),p=f.getUint16(4,!1);m>0&&(this.metadataTags.trackNumber??=m),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(u instanceof Uint8Array&&u.length>=6){let f=z(u),m=f.getUint16(2,!1),p=f.getUint16(4,!1);m>0&&(this.metadataTags.discNumber??=m),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=i,!0}},xn=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,n=>n.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Je(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),o=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=ni(o,n),s=await this.fetchPacketForSampleIndex(i,t);return!Es(o)||!this.internalTrack.demuxer.isFragmented?s:this.performFragmentedLookup(null,a=>{let c=a.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=B(c.presentationTimestamps,n,f=>f.presentationTimestamp),d=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,u=l!==-1&&n<c.endTimestamp;return{sampleIndex:d,correctSampleFound:u}},n,n,t)}async getNextPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,t);let o=this.packetToFragmentLocation.get(e);if(o===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(o.fragment,i=>{if(i===o.fragment){let s=i.trackData.get(this.internalTrack.id);if(o.sampleIndex+1<s.samples.length)return{sampleIndex:o.sampleIndex+1,correctSampleFound:!0}}else if(i.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.mapTimestampIntoTimescale(e),o=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=Oc(o,n),s=await this.fetchPacketForSampleIndex(i,t);return!Es(o)||!this.internalTrack.demuxer.isFragmented?s:this.performFragmentedLookup(null,a=>{let c=a.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=Zr(c.presentationTimestamps,f=>c.samples[f.sampleIndex].isKeyFrame&&f.presentationTimestamp<=n),d=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,u=l!==-1&&n<c.endTimestamp;return{sampleIndex:d,correctSampleFound:u}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Uc(i,n);return this.fetchPacketForSampleIndex(s,t)}let o=this.packetToFragmentLocation.get(e);if(o===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(o.fragment,i=>{if(i===o.fragment){let a=i.trackData.get(this.internalTrack.id).samples.findIndex((c,l)=>c.isKeyFrame&&l>o.sampleIndex);if(a!==-1)return{sampleIndex:a,correctSampleFound:!0}}else{let s=i.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){let a=s.samples.findIndex(c=>c.isKeyFrame);return h(a!==-1),{sampleIndex:a,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),o=zc(n,e);if(!o)return null;let i;if(t.metadataOnly)i=H;else{let l=this.internalTrack.demuxer.reader.requestSlice(o.sampleOffset,o.sampleSize);l instanceof Promise&&(l=await l),h(l),i=E(l,o.sampleSize)}let s=(o.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=o.duration/this.internalTrack.timescale,c=new V(i,o.isKeyFrame?"key":"delta",s,a,e,o.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,n){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).samples[t];h(i);let s;if(n.metadataOnly)s=H;else{let d=this.internalTrack.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);d instanceof Promise&&(d=await d),h(d),s=E(d,i.byteSize)}let a=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=i.duration/this.internalTrack.timescale,l=new V(s,i.isKeyFrame?"key":"delta",a,c,e.moofOffset+t,i.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:t}),l}async performFragmentedLookup(e,t,n,o,i){let s=this.internalTrack.demuxer,a=null,c=null,l=-1;if(e){let{sampleIndex:x,correctSampleFound:y}=t(e);if(y)return this.fetchPacketInFragment(e,x,i);x!==-1&&(c=e,l=x)}let d=B(this.internalTrack.fragmentLookupTable,n,x=>x.timestamp),u=d!==-1?this.internalTrack.fragmentLookupTable[d]:null,f=B(this.internalTrack.fragmentPositionCache,n,x=>x.startTimestamp),m=f!==-1?this.internalTrack.fragmentPositionCache[f]:null,p=Math.max(u?.moofOffset??0,m?.moofOffset??0)||null,g;for(e?p===null||e.moofOffset>=p?(g=e.moofOffset+e.moofSize,a=e):g=p:g=p??0;;){if(a){let w=a.trackData.get(this.internalTrack.id);if(w&&w.startTimestamp>o)break}let x=s.reader.requestSliceRange(g,ct,At);if(x instanceof Promise&&(x=await x),!x)break;let y=g,b=_e(x);if(!b)break;if(b.name==="moof"){a=await s.readFragment(y);let{sampleIndex:w,correctSampleFound:k}=t(a);if(k)return this.fetchPacketInFragment(a,w,i);w!==-1&&(c=a,l=w)}g=y+b.totalSize}if(u&&(!c||c.moofOffset<u.moofOffset)){let x=this.internalTrack.fragmentLookupTable[d-1];h(!x||x.timestamp<u.timestamp);let y=x?.timestamp??-1/0;return this.performFragmentedLookup(null,t,y,o,i)}return c?this.fetchPacketInFragment(c,l,i):null}},ti=class extends xn{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&ln(e.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&un(e.data)}return{codec:nn(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}})():null}},ri=class extends xn{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:on(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},ni=(r,e)=>{if(r.presentationTimestamps){let t=B(r.presentationTimestamps,e,n=>n.presentationTimestamp);return t===-1?-1:r.presentationTimestamps[t].sampleIndex}else{let t=B(r.sampleTimingEntries,e,o=>o.startDecodeTimestamp);if(t===-1)return-1;let n=r.sampleTimingEntries[t];return n.startIndex+Math.min(Math.floor((e-n.startDecodeTimestamp)/n.delta),n.count-1)}},Oc=(r,e)=>{if(!r.keySampleIndices)return ni(r,e);if(r.presentationTimestamps){let t=B(r.presentationTimestamps,e,n=>n.presentationTimestamp);if(t===-1)return-1;for(let n=t;n>=0;n--){let o=r.presentationTimestamps[n].sampleIndex;if(Qe(r.keySampleIndices,o,s=>s)!==-1)return o}return-1}else{let t=ni(r,e),n=B(r.keySampleIndices,t,o=>o);return r.keySampleIndices[n]??-1}},zc=(r,e)=>{let t=B(r.sampleTimingEntries,e,y=>y.startIndex),n=r.sampleTimingEntries[t];if(!n||n.startIndex+n.count<=e)return null;let i=n.startDecodeTimestamp+(e-n.startIndex)*n.delta,s=B(r.sampleCompositionTimeOffsets,e,y=>y.startIndex),a=r.sampleCompositionTimeOffsets[s];a&&e-a.startIndex<a.count&&(i+=a.offset);let c=r.sampleSizes[Math.min(e,r.sampleSizes.length-1)],l=B(r.sampleToChunk,e,y=>y.startSampleIndex),d=r.sampleToChunk[l];h(d);let u=d.startChunkIndex+Math.floor((e-d.startSampleIndex)/d.samplesPerChunk),f=r.chunkOffsets[u],m=d.startSampleIndex+(u-d.startChunkIndex)*d.samplesPerChunk,p=0,g=f;if(r.sampleSizes.length===1)g+=c*(e-m),p+=c*d.samplesPerChunk;else for(let y=m;y<m+d.samplesPerChunk;y++){let b=r.sampleSizes[y];y<e&&(g+=b),p+=b}let x=n.delta;if(r.presentationTimestamps){let y=r.presentationTimestampIndexMap[e];h(y!==void 0),y<r.presentationTimestamps.length-1&&(x=r.presentationTimestamps[y+1].presentationTimestamp-i)}return{presentationTimestamp:i,duration:x,sampleOffset:g,sampleSize:c,chunkOffset:f,chunkSize:p,isKeyFrame:r.keySampleIndices?Qe(r.keySampleIndices,e,y=>y)!==-1:!0}},Uc=(r,e)=>{if(!r.keySampleIndices)return e+1;let t=B(r.keySampleIndices,e,n=>n);return r.keySampleIndices[t+1]??-1},ei=(r,e)=>{r.startTimestamp+=e,r.endTimestamp+=e;for(let t of r.samples)t.presentationTimestamp+=e;for(let t of r.presentationTimestamps)t.presentationTimestamp+=e},Nc=r=>{let[e,,,t]=r,n=Math.hypot(e,t),o=e/n,i=t/n,s=-Math.atan2(i,o)*(180/Math.PI);return Number.isFinite(s)?s:0},Es=r=>r.sampleSizes.length===0;var T;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Duration=17545]="Duration",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.MuxingApp=19840]="MuxingApp",r[r.WritingApp=22337]="WritingApp",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.TrackNumber=215]="TrackNumber",r[r.TrackUID=29637]="TrackUID",r[r.TrackType=131]="TrackType",r[r.FlagEnabled=185]="FlagEnabled",r[r.FlagDefault=136]="FlagDefault",r[r.FlagForced=21930]="FlagForced",r[r.FlagOriginal=21934]="FlagOriginal",r[r.FlagHearingImpaired=21931]="FlagHearingImpaired",r[r.FlagVisualImpaired=21932]="FlagVisualImpaired",r[r.FlagCommentary=21935]="FlagCommentary",r[r.FlagLacing=156]="FlagLacing",r[r.Name=21358]="Name",r[r.Language=2274716]="Language",r[r.LanguageBCP47=2274717]="LanguageBCP47",r[r.CodecID=134]="CodecID",r[r.CodecPrivate=25506]="CodecPrivate",r[r.CodecDelay=22186]="CodecDelay",r[r.SeekPreRoll=22203]="SeekPreRoll",r[r.DefaultDuration=2352003]="DefaultDuration",r[r.Video=224]="Video",r[r.PixelWidth=176]="PixelWidth",r[r.PixelHeight=186]="PixelHeight",r[r.AlphaMode=21440]="AlphaMode",r[r.Audio=225]="Audio",r[r.SamplingFrequency=181]="SamplingFrequency",r[r.Channels=159]="Channels",r[r.BitDepth=25188]="BitDepth",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.Block=161]="Block",r[r.BlockAdditions=30113]="BlockAdditions",r[r.BlockMore=166]="BlockMore",r[r.BlockAdditional=165]="BlockAdditional",r[r.BlockAddID=238]="BlockAddID",r[r.BlockDuration=155]="BlockDuration",r[r.ReferenceBlock=251]="ReferenceBlock",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.Colour=21936]="Colour",r[r.MatrixCoefficients=21937]="MatrixCoefficients",r[r.TransferCharacteristics=21946]="TransferCharacteristics",r[r.Primaries=21947]="Primaries",r[r.Range=21945]="Range",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPoseRoll=30325]="ProjectionPoseRoll",r[r.Attachments=423732329]="Attachments",r[r.AttachedFile=24999]="AttachedFile",r[r.FileDescription=18046]="FileDescription",r[r.FileName=18030]="FileName",r[r.FileMediaType=18016]="FileMediaType",r[r.FileData=18012]="FileData",r[r.FileUID=18094]="FileUID",r[r.Chapters=272869232]="Chapters",r[r.Tags=307544935]="Tags",r[r.Tag=29555]="Tag",r[r.Targets=25536]="Targets",r[r.TargetTypeValue=26826]="TargetTypeValue",r[r.TargetType=25546]="TargetType",r[r.TagTrackUID=25541]="TagTrackUID",r[r.TagEditionUID=25545]="TagEditionUID",r[r.TagChapterUID=25540]="TagChapterUID",r[r.TagAttachmentUID=25542]="TagAttachmentUID",r[r.SimpleTag=26568]="SimpleTag",r[r.TagName=17827]="TagName",r[r.TagLanguage=17530]="TagLanguage",r[r.TagString=17543]="TagString",r[r.TagBinary=17541]="TagBinary",r[r.ContentEncodings=28032]="ContentEncodings",r[r.ContentEncoding=25152]="ContentEncoding",r[r.ContentEncodingOrder=20529]="ContentEncodingOrder",r[r.ContentEncodingScope=20530]="ContentEncodingScope",r[r.ContentCompression=20532]="ContentCompression",r[r.ContentCompAlgo=16980]="ContentCompAlgo",r[r.ContentCompSettings=16981]="ContentCompSettings",r[r.ContentEncryption=20533]="ContentEncryption"})(T||(T={}));var Vc=[T.EBML,T.Segment],_t=[T.SeekHead,T.Info,T.Cluster,T.Tracks,T.Cues,T.Attachments,T.Chapters,T.Tags],hr=[...Vc,..._t];var oi=8,oe=2,de=2*oi,ii=r=>{let e=A(r);if(r.skip(-1),e===0)return null;let t=1,n=128;for(;(e&n)===0;)t++,n>>=1;return t},Et=r=>{let e=A(r);if(e===0)return null;let t=1,n=128;for(;(e&n)===0;)t++,n>>=1;let o=e&n-1;for(let i=1;i<t;i++)o*=256,o+=A(r);return o},D=(r,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let n=0;n<e;n++)t*=256,t+=A(r);return t},Ds=(r,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let t=0n;for(let n=0;n<e;n++)t<<=8n,t+=BigInt(A(r));return t};var yn=r=>{let e=ii(r);return e===null?null:D(r,e)},si=r=>{let e=A(r);return e===255?e=null:(r.skip(-1),e=Et(r),e===72057594037927940&&(e=null)),e},fe=r=>{let e=yn(r);if(e===null)return null;let t=si(r);return{id:e,size:t}},qe=(r,e)=>{let t=E(r,e),n=0;for(;n<e&&t[n]!==0;)n+=1;return String.fromCharCode(...t.subarray(0,n))},Ft=(r,e)=>{let t=E(r,e),n=0;for(;n<e&&t[n]!==0;)n+=1;return $.decode(t.subarray(0,n))},Tn=(r,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?Rs(r):bn(r)},wn=async(r,e,t,n)=>{let o=new Set(t),i=e;for(;n===null||i<n;){let s=r.requestSliceRange(i,oe,de);if(s instanceof Promise&&(s=await s),!s)break;let a=fe(s);if(!a)break;if(o.has(a.id))return{pos:i,found:!0};Fe(a.size),i=s.filePos+a.size}return{pos:n!==null&&n>i?n:i,found:!1}},ai=async(r,e,t,n)=>{let i=new Set(t),s=e;for(;s<n;){let a=r.requestSliceRange(s,0,Math.min(65536,n-s));if(a instanceof Promise&&(a=await a),!a||a.length<oi)break;for(let c=0;c<a.length-oi;c++){a.filePos=s;let l=yn(a);if(l!==null&&i.has(l))return s;s++}}return null},me={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function Fe(r){if(r===null)throw new Error("Undefined element size is used in a place where it is not supported.")}var Ms=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isWebM?"webm":"x-matroska");if(r.codecStrings.length>0){let n=[...new Set(r.codecStrings.filter(Boolean))];t+=`; codecs="${n.join(", ")}"`}return t};var De;(function(r){r[r.None=0]="None",r[r.Xiph=1]="Xiph",r[r.FixedSize=2]="FixedSize",r[r.Ebml=3]="Ebml"})(De||(De={}));var kn;(function(r){r[r.Block=1]="Block",r[r.Private=2]="Private",r[r.Next=4]="Next"})(kn||(kn={}));var gr;(function(r){r[r.Zlib=0]="Zlib",r[r.Bzlib=1]="Bzlib",r[r.lzo1x=2]="lzo1x",r[r.HeaderStripping=3]="HeaderStripping"})(gr||(gr={}));var ci=[{id:T.SeekHead,flag:"seekHeadSeen"},{id:T.Info,flag:"infoSeen"},{id:T.Tracks,flag:"tracksSeen"},{id:T.Cues,flag:"cuesSeen"}],Bs=10*2**20,Sn=class extends Q{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(t=>t.inputTrack))}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),t=await Promise.all(e.map(n=>n.getCodecParameterString()));return Ms({isWebM:this.isWebM,hasVideo:this.segments.some(n=>n.tracks.some(o=>o.info?.type==="video")),hasAudio:this.segments.some(n=>n.tracks.some(o=>o.info?.type==="audio")),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let t of this.segments)t.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(let t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,oe,de);if(t instanceof Promise&&(t=await t),!t)break;let n=fe(t);if(!n)break;let o=n.id,i=n.size,s=t.filePos;if(o===T.EBML){Fe(i);let a=this.reader.requestSlice(s,i);if(a instanceof Promise&&(a=await a),!a)break;this.readContiguousElements(a)}else if(o===T.Segment){if(await this.readSegment(s,i),i===null||this.reader.fileSize===null)break}else if(o===T.Cluster){if(this.reader.fileSize===null)break;i===null&&(i=(await wn(this.reader,s,hr,this.reader.fileSize)).pos-s);let a=Y(this.segments);a&&(a.elementEndPos=s+i)}Fe(i),e=s+i}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===null?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let a=this.reader.requestSliceRange(n,oe,de);if(a instanceof Promise&&(a=await a),!a)break;let c=n,l=fe(a);if(!l||!_t.includes(l.id)&&l.id!==T.Void){let p=await ai(this.reader,c,_t,Math.min(this.currentSegment.elementEndPos??1/0,c+Bs));if(p){n=p;continue}else break}let{id:d,size:u}=l,f=a.filePos,m=ci.findIndex(p=>p.id===d);if(m!==-1){let p=ci[m].flag;this.currentSegment[p]=!0,Fe(u);let g=this.reader.requestSlice(f,u);g instanceof Promise&&(g=await g),g&&this.readContiguousElements(g)}else if(d===T.Tags||d===T.Attachments){d===T.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Fe(u);let p=this.reader.requestSlice(f,u);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(d===T.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(u===null)break;n=f+u}if(this.currentSegment.seekEntries.sort((a,c)=>a.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(let a of this.currentSegment.seekEntries){let c=ci.find(p=>p.id===a.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+a.segmentPosition,oe,de);if(l instanceof Promise&&(l=await l),!l)continue;let d=fe(l);if(!d)continue;let{id:u,size:f}=d;if(u!==c.id)continue;Fe(f),this.currentSegment[c.flag]=!0;let m=this.reader.requestSlice(l.filePos,f);m instanceof Promise&&(m=await m),m&&this.readContiguousElements(m)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6),this.currentSegment.tracks.sort((a,c)=>Number(c.disposition.default)-Number(a.disposition.default));let o=new Map(this.currentSegment.tracks.map(a=>[a.id,a]));for(let a of this.currentSegment.cuePoints){let c=o.get(a.trackId);c&&c.cuePoints.push(a)}for(let a of this.currentSegment.tracks){a.cuePoints.sort((c,l)=>c.time-l.time);for(let c=0;c<a.cuePoints.length-1;c++){let l=a.cuePoints[c],d=a.cuePoints[c+1];l.time===d.time&&(a.cuePoints.splice(c+1,1),c--)}}let i=null,s=-1/0;for(let a of this.currentSegment.tracks)a.cuePoints.length>s&&(s=a.cuePoints.length,i=a);for(let a of this.currentSegment.tracks)a.cuePoints.length===0&&(a.cuePoints=i.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let n=this.reader.requestSliceRange(e,oe,de);n instanceof Promise&&(n=await n),h(n);let o=e,i=fe(n);h(i);let s=i.id;h(s===T.Cluster);let a=i.size,c=n.filePos;a===null&&(a=(await wn(this.reader,c,hr,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,a);l instanceof Promise&&(l=await l);let d={segment:t,elementStartPos:o,elementEndPos:c+a,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=d,l){let u=this.readContiguousElements(l,hr);d.elementEndPos=u}for(let[,u]of d.trackData){let f=u.track;h(u.blocks.length>0);let m=!1;for(let y=0;y<u.blocks.length;y++){let b=u.blocks[y];b.timestamp+=d.timestamp,m||=b.lacing!==De.None}u.presentationTimestamps=u.blocks.map((y,b)=>({timestamp:y.timestamp,blockIndex:b})).sort((y,b)=>y.timestamp-b.timestamp);for(let y=0;y<u.presentationTimestamps.length;y++){let b=u.presentationTimestamps[y],w=u.blocks[b.blockIndex];if(u.firstKeyFrameTimestamp===null&&w.isKeyFrame&&(u.firstKeyFrameTimestamp=w.timestamp),y<u.presentationTimestamps.length-1){let k=u.presentationTimestamps[y+1];w.duration=k.timestamp-w.timestamp}else w.duration===0&&f.defaultDuration!=null&&w.lacing===De.None&&(w.duration=f.defaultDuration)}m&&(this.expandLacedBlocks(u.blocks,f),u.presentationTimestamps=u.blocks.map((y,b)=>({timestamp:y.timestamp,blockIndex:b})).sort((y,b)=>y.timestamp-b.timestamp));let p=u.blocks[u.presentationTimestamps[0].blockIndex],g=u.blocks[Y(u.presentationTimestamps).blockIndex];u.startTimestamp=p.timestamp,u.endTimestamp=g.timestamp+g.duration;let x=B(f.clusterPositionCache,u.startTimestamp,y=>y.startTimestamp);(x===-1||f.clusterPositionCache[x].elementStartPos!==o)&&f.clusterPositionCache.splice(x+1,0,{elementStartPos:d.elementStartPos,startTimestamp:u.startTimestamp})}return t.lastReadCluster=d,d}getTrackDataInCluster(e,t){let n=e.trackData.get(t);if(!n){let o=e.segment.tracks.find(i=>i.id===t);if(!o)return null;n={track:o,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,n)}return n}expandLacedBlocks(e,t){for(let n=0;n<e.length;n++){let o=e[n];if(o.lacing===De.None)continue;o.decoded||(o.data=this.decodeBlockData(t,o.data),o.decoded=!0);let i=Dt.tempFromBytes(o.data),s=[],a=A(i)+1;switch(o.lacing){case De.Xiph:{let l=0;for(let d=0;d<a-1;d++){let u=0;for(;i.bufferPos<i.length;){let f=A(i);if(u+=f,f<255){s.push(u),l+=u;break}}}s.push(i.length-(i.bufferPos+l))}break;case De.FixedSize:{let l=i.length-1,d=Math.floor(l/a);for(let u=0;u<a;u++)s.push(d)}break;case De.Ebml:{let l=Et(i);h(l!==null);let d=l;s.push(d);let u=d;for(let f=1;f<a-1;f++){let m=i.bufferPos,p=Et(i);h(p!==null);let g=p,y=(1<<(i.bufferPos-m)*7-1)-1,b=g-y;d+=b,s.push(d),u+=d}s.push(i.length-(i.bufferPos+u))}break;default:h(!1)}h(s.length===a),e.splice(n,1);let c=o.duration||a*(t.defaultDuration??0);for(let l=0;l<a;l++){let d=s[l],u=E(i,d),f=o.timestamp+c*l/a,m=c/a;e.splice(n+l,0,{timestamp:f,duration:m,isKeyFrame:o.isKeyFrame,data:u,lacing:De.None,decoded:!0,mainAdditional:o.mainAdditional})}n+=a,n--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if(!(t.id===T.Tags&&!e.tagsSeen)){if(!(t.id===T.Attachments&&!e.attachmentsSeen))continue}let n=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,oe,de);if(n instanceof Promise&&(n=await n),!n)continue;let o=fe(n);if(!o||o.id!==t.id)continue;let{size:i}=o;Fe(i),h(!this.currentSegment),this.currentSegment=e;let s=this.reader.requestSlice(n.filePos,i);s instanceof Promise&&(s=await s),s&&this.readContiguousElements(s),this.currentSegment=null,t.id===T.Tags?e.tagsSeen=!0:t.id===T.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){let n=e.filePos;for(;e.filePos-n<=e.length-oe;){let o=e.filePos;if(!this.traverseElement(e,t))return o}return e.filePos}traverseElement(e,t){let n=fe(e);if(!n||t&&t.includes(n.id))return!1;let{id:o,size:i}=n,s=e.filePos;switch(Fe(i),o){case T.DocType:this.isWebM=qe(e,i)==="webm";break;case T.Seek:{if(!this.currentSegment)break;let a={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(a),this.readContiguousElements(e.slice(s,i)),(a.id===-1||a.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case T.SeekID:{let a=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!a)break;a.id=D(e,i)}break;case T.SeekPosition:{let a=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!a)break;a.segmentPosition=D(e,i)}break;case T.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=D(e,i),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case T.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Tn(e,i)}break;case T.TrackEntry:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...te},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:K,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(s,i)),this.currentTrack.decodingInstructions.some(a=>a.data?.type!=="decompress"||a.scope!==kn.Block||a.data.algorithm!==gr.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let a=this.currentTrack.codecId.indexOf("/"),c=a===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,a);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){this.currentTrack.codecId===me.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===me.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===me.vp8?this.currentTrack.info.codec="vp8":c===me.vp9?this.currentTrack.info.codec="vp9":c===me.av1&&(this.currentTrack.info.codec="av1");let l=this.currentTrack,d=new ke(this.input,new li(l));this.currentTrack.inputTrack=d,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){c===me.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2")},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===me.mp3?this.currentTrack.info.codec="mp3":c===me.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=rt):c===me.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===me.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));let l=this.currentTrack,d=new G(this.input,new ui(l));this.currentTrack.inputTrack=d,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case T.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=D(e,i)}break;case T.TrackType:{if(!this.currentTrack)break;let a=D(e,i);a===1?this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:a===2&&(this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case T.FlagEnabled:{if(!this.currentTrack)break;D(e,i)||(this.currentSegment.tracks.pop(),this.currentTrack=null)}break;case T.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!D(e,i)}break;case T.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!D(e,i)}break;case T.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!D(e,i)}break;case T.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!D(e,i)}break;case T.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!D(e,i)}break;case T.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!D(e,i)}break;case T.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=qe(e,i)}break;case T.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=E(e,i)}break;case T.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*D(e,i)/1e9}break;case T.Name:{if(!this.currentTrack)break;this.currentTrack.name=Ft(e,i)}break;case T.Language:{if(!this.currentTrack||this.currentTrack.languageCode!==K)break;this.currentTrack.languageCode=qe(e,i),Jr(this.currentTrack.languageCode)||(this.currentTrack.languageCode=K)}break;case T.LanguageBCP47:{if(!this.currentTrack)break;let c=qe(e,i).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=K}break;case T.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(s,i))}break;case T.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=D(e,i)}break;case T.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=D(e,i)}break;case T.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=D(e,i)===1}break;case T.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(s,i))}break;case T.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=D(e,i),c=Qr[a]??null;this.currentTrack.info.colorSpace.matrix=c}break;case T.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=D(e,i)===2}break;case T.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=D(e,i),c=Xr[a]??null;this.currentTrack.info.colorSpace.transfer=c}break;case T.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=D(e,i),c=Kr[a]??null;this.currentTrack.info.colorSpace.primaries=c}break;case T.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(s,i))}break;case T.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let c=-Tn(e,i);try{this.currentTrack.info.rotation=$r(c)}catch{}}break;case T.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(s,i))}break;case T.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=Tn(e,i)}break;case T.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=D(e,i)}break;case T.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=D(e,i)}break;case T.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(s,i)),this.currentCueTime=null}break;case T.CueTime:this.currentCueTime=D(e,i);break;case T.CueTrackPositions:{if(this.currentCueTime===null)break;h(this.currentSegment);let a={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(a),this.readContiguousElements(e.slice(s,i)),(a.trackId===-1||a.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case T.CueTrack:{let a=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!a)break;a.trackId=D(e,i)}break;case T.CueClusterPosition:{let a=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!a)break;h(this.currentSegment),a.clusterPosition=this.currentSegment.dataStartPos+D(e,i)}break;case T.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=D(e,i)}break;case T.SimpleBlock:{if(!this.currentCluster)break;let a=Et(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let l=pr(e),d=A(e),u=d>>1&3,f=!!(d&128);c.track.info?.type==="audio"&&c.track.info.codec&&(f=!0);let m=E(e,i-(e.filePos-s)),p=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:f,data:m,lacing:u,decoded:!p,mainAdditional:null})}break;case T.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(s,i)),this.currentBlock=null}break;case T.Block:{if(!this.currentCluster)break;let a=Et(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let l=pr(e),u=A(e)>>1&3,f=E(e,i-(e.filePos-s)),m=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:f,lacing:u,decoded:!m,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case T.BlockAdditions:this.readContiguousElements(e.slice(s,i));break;case T.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(s,i)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case T.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=E(e,i)}break;case T.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=D(e,i)}break;case T.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=D(e,i)}break;case T.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case T.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(s,i));break;case T.Targets:this.readContiguousElements(e.slice(s,i));break;case T.TargetTypeValue:D(e,i)!==50&&(this.currentTagTargetIsMovie=!1);break;case T.TagTrackUID:case T.TagEditionUID:case T.TagChapterUID:case T.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case T.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(s,i))}break;case T.TagName:this.currentSimpleTagName=Ft(e,i);break;case T.TagString:{if(!this.currentSimpleTagName)break;let a=Ft(e,i);this.processTagValue(this.currentSimpleTagName,a)}break;case T.TagBinary:{if(!this.currentSimpleTagName)break;let a=E(e,i);this.processTagValue(this.currentSimpleTagName,a)}break;case T.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(s,i));let a=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(a.raw??={},a.raw[this.currentAttachedFile.fileUid.toString()]=new rn(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let c=this.currentAttachedFile.fileName,l="unknown";if(c){let d=c.toLowerCase();d.startsWith("cover.")?l="coverFront":d.startsWith("back.")&&(l="coverBack")}a.images??=[],a.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:l,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case T.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=Ds(e,i)}break;case T.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Ft(e,i)}break;case T.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=qe(e,i)}break;case T.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=E(e,i)}break;case T.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Ft(e,i)}break;case T.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(s,i)),this.currentTrack.decodingInstructions.sort((a,c)=>c.order-a.order)}break;case T.ContentEncoding:this.currentDecodingInstruction={order:0,scope:kn.Block,data:null},this.readContiguousElements(e.slice(s,i)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case T.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=D(e,i)}break;case T.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=D(e,i)}break;case T.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:gr.Zlib,settings:null},this.readContiguousElements(e.slice(s,i))}break;case T.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=D(e,i)}break;case T.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=E(e,i)}break;case T.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=s+i,!0}decodeBlockData(e,t){h(e.decodingInstructions.length>0);let n=t;for(let o of e.decodingInstructions)switch(h(o.data),o.data.type){case"decompress":switch(o.data.algorithm){case gr.HeaderStripping:if(o.data.settings&&o.data.settings.length>0){let i=o.data.settings,s=new Uint8Array(i.length+n.length);s.set(i,0),s.set(n,i.length),n=s}break;default:}break;default:}return n}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=t,typeof t=="string")switch(e.toLowerCase()){case"title":n.title??=t;break;case"description":n.description??=t;break;case"artist":n.artist??=t;break;case"album":n.album??=t;break;case"album_artist":n.albumArtist??=t;break;case"genre":n.genre??=t;break;case"comment":n.comment??=t;break;case"lyrics":n.lyrics??=t;break;case"date":{let o=new Date(t);Number.isNaN(o.getTime())||(n.date??=o)}break;case"track_number":case"part_number":{let o=t.split("/"),i=Number.parseInt(o[0],10),s=o[1]&&Number.parseInt(o[1],10);Number.isInteger(i)&&i>0&&(n.trackNumber??=i),s&&Number.isInteger(s)&&s>0&&(n.tracksTotal??=s)}break;case"disc_number":case"disc":{let o=t.split("/"),i=Number.parseInt(o[0],10),s=o[1]&&Number.parseInt(o[1],10);Number.isInteger(i)&&i>0&&(n.discNumber??=i),s&&Number.isInteger(s)&&s>0&&(n.discsTotal??=s)}break}}},vn=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket(e){return this.performClusterLookup(null,t=>t.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Je(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,o=>{let i=o.trackData.get(this.internalTrack.id);if(!i)return{blockIndex:-1,correctBlockFound:!1};let s=B(i.presentationTimestamps,n,l=>l.timestamp),a=s!==-1?i.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&n<i.endTimestamp;return{blockIndex:a,correctBlockFound:c}},n,n,t)}async getNextPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,o=>{if(o===n.cluster){let i=o.trackData.get(this.internalTrack.id);if(n.blockIndex+1<i.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(o.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,o=>{let i=o.trackData.get(this.internalTrack.id);if(!i)return{blockIndex:-1,correctBlockFound:!1};let s=Zr(i.presentationTimestamps,l=>i.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=n),a=s!==-1?i.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&n<i.endTimestamp;return{blockIndex:a,correctBlockFound:c}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,o=>{if(o===n.cluster){let s=o.trackData.get(this.internalTrack.id).blocks.findIndex((a,c)=>a.isKeyFrame&&c>n.blockIndex);if(s!==-1)return{blockIndex:s,correctBlockFound:!0}}else{let i=o.trackData.get(this.internalTrack.id);if(i&&i.firstKeyFrameTimestamp!==null){let s=i.blocks.findIndex(a=>a.isKeyFrame);return h(s!==-1),{blockIndex:s,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,n){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).blocks[t];h(i),i.decoded||(i.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,i.data),i.decoded=!0);let s=n.metadataOnly?H:i.data,a=i.timestamp/this.internalTrack.segment.timestampFactor,c=i.duration/this.internalTrack.segment.timestampFactor,l={};i.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=n.metadataOnly?H:i.mainAdditional,l.alphaByteLength=i.mainAdditional.byteLength);let d=new V(s,i.isKeyFrame?"key":"delta",a,c,e.dataStartPos+t,i.data.byteLength,l);return this.packetToClusterLocation.set(d,{cluster:e,blockIndex:t}),d}async performClusterLookup(e,t,n,o,i){let{demuxer:s,segment:a}=this.internalTrack,c=null,l=null,d=-1;if(e){let{blockIndex:y,correctBlockFound:b}=t(e);if(b)return this.fetchPacketInCluster(e,y,i);y!==-1&&(l=e,d=y)}let u=B(this.internalTrack.cuePoints,n,y=>y.time),f=u!==-1?this.internalTrack.cuePoints[u]:null,m=B(this.internalTrack.clusterPositionCache,n,y=>y.startTimestamp),p=m!==-1?this.internalTrack.clusterPositionCache[m]:null,g=Math.max(f?.clusterPosition??0,p?.elementStartPos??0)||null,x;for(e?g===null||e.elementStartPos>=g?(x=e.elementEndPos,c=e):x=g:x=g??a.clusterSeekStartPos;a.elementEndPos===null||x<=a.elementEndPos-oe;){if(c){let C=c.trackData.get(this.internalTrack.id);if(C&&C.startTimestamp>o)break}let y=s.reader.requestSliceRange(x,oe,de);if(y instanceof Promise&&(y=await y),!y)break;let b=x,w=fe(y);if(!w||!_t.includes(w.id)&&w.id!==T.Void){let C=await ai(s.reader,b,_t,Math.min(a.elementEndPos??1/0,b+Bs));if(C){x=C;continue}else break}let k=w.id,P=w.size,S=y.filePos;if(k===T.Cluster){c=await s.readCluster(b,a),P=c.elementEndPos-S;let{blockIndex:C,correctBlockFound:F}=t(c);if(F)return this.fetchPacketInCluster(c,C,i);C!==-1&&(l=c,d=C)}P===null&&(h(k!==T.Cluster),P=(await wn(s.reader,S,hr,a.elementEndPos)).pos-S);let _=S+P;if(a.elementEndPos===null){let C=s.reader.requestSliceRange(_,oe,de);if(C instanceof Promise&&(C=await C),!C)break;if(yn(C)===T.Segment){a.elementEndPos=_;break}}x=_}if(f&&(!l||l.elementStartPos<f.clusterPosition)){let y=this.internalTrack.cuePoints[u-1];h(!y||y.time<f.time);let b=y?.time??-1/0;return this.performClusterLookup(null,t,b,o,i)}return l?this.fetchPacketInCluster(l,d,i):null}},li=class extends vn{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;return(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({})),{codec:nn({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?fs(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?ps(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?ln(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?un(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}},ui=class extends vn{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:on({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}};var Lc=[44100,48e3,32e3],Hc=[-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],Os=1483304551,zs=1231971951,qc=(r,e,t,n,o)=>e===0?0:e===1?Math.floor(144*t/(n<<r))+o:e===2?Math.floor(144*t/n)+o:(Math.floor(12*t/n)+o)*4,Us=(r,e)=>r===3?e===3?21:36:e===3?13:21,Ns=(r,e)=>{let t=r>>>24,n=r>>>16&255,o=r>>>8&255,i=r&255;if(t!==255&&n!==255&&o!==255&&i!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((n&224)!==224)return{header:null,bytesAdvanced:1};let s=0,a=0;n&16?s=n&8?0:1:(s=1,a=1);let c=n>>3&3,l=n>>1&3,d=o>>4&15,u=(o>>2&3)%3,f=o>>1&1,m=i>>6&3,p=i>>4&3,g=i>>3&1,x=i>>2&1,y=i&3,b=Hc[s*16*4+l*16+d];if(b===-1)return{header:null,bytesAdvanced:1};let w=b*1e3,k=Lc[u]>>s+a,P=qc(s,l,w,k,f);if(e!==null&&e<P)return{header:null,bytesAdvanced:1};let S;return c===3?S=l===3?384:1152:l===3?S=384:l===2?S=1152:S=576,{header:{totalSize:P,mpegVersionId:c,layer:l,bitrate:w,frequencyIndex:u,sampleRate:k,channel:m,modeExtension:p,copyright:g,original:x,emphasis:y,audioSamplesInFrame:S},bytesAdvanced:1}};var Pn=r=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=r&e,e>>=8;return t};var Mt;(function(r){r[r.Unsynchronisation=128]="Unsynchronisation",r[r.ExtendedHeader=64]="ExtendedHeader",r[r.ExperimentalIndicator=32]="ExperimentalIndicator",r[r.Footer=16]="Footer"})(Mt||(Mt={}));var Bt;(function(r){r[r.ISO_8859_1=0]="ISO_8859_1",r[r.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",r[r.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",r[r.UTF_8=3]="UTF_8"})(Bt||(Bt={}));var xr=128,zt=10,Ot=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],Vs=(r,e)=>{let t=r.filePos;e.raw??={},e.raw.TAG??=E(r,xr-3),r.filePos=t;let n=Rt(r,30);n&&(e.title??=n);let o=Rt(r,30);o&&(e.artist??=o);let i=Rt(r,30);i&&(e.album??=i);let s=Rt(r,4),a=Number.parseInt(s,10);Number.isInteger(a)&&a>0&&(e.date??=new Date(a,0,1));let c=E(r,30),l;if(c[28]===0&&c[29]!==0){let u=c[29];u>0&&(e.trackNumber??=u),r.skip(-30),l=Rt(r,28),r.skip(2)}else r.skip(-30),l=Rt(r,30);l&&(e.comment??=l);let d=A(r);d<Ot.length&&(e.genre??=Ot[d])},Rt=(r,e)=>{let t=E(r,e),n=et(t.indexOf(0),t.length),o=t.subarray(0,n),i="";for(let s=0;s<o.length;s++)i+=String.fromCharCode(o[s]);return i.trimEnd()},lt=r=>{let e=r.filePos,t=L(r,3),n=A(r),o=A(r),i=A(r),s=v(r);if(t!=="ID3"||n===255||o===255||(s&2155905152)!==0)return r.filePos=e,null;let a=Pn(s);return{majorVersion:n,revision:o,flags:i,size:a}},Cn=(r,e,t)=>{if(![2,3,4].includes(e.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let n=E(r,e.size),o=new di(e,n);if(e.flags&Mt.Footer&&o.removeFooter(),e.flags&Mt.Unsynchronisation&&e.majorVersion===3&&o.ununsynchronizeAll(),e.flags&Mt.ExtendedHeader){let i=o.readU32();e.majorVersion===3?o.pos+=i:o.pos+=i-4}for(;o.pos<=o.bytes.length-o.frameHeaderSize();){let i=o.readId3V2Frame();if(!i)break;let s=o.pos,a=o.pos+i.size,c=!1,l=!1,d=!1;if(e.majorVersion===3?(c=!!(i.flags&64),l=!!(i.flags&128)):e.majorVersion===4&&(c=!!(i.flags&4),l=!!(i.flags&8),d=!!(i.flags&2)||!!(e.flags&Mt.Unsynchronisation)),c){console.warn(`Skipping encrypted ID3v2 frame ${i.id}`),o.pos=a;continue}if(l){console.warn(`Skipping compressed ID3v2 frame ${i.id}`),o.pos=a;continue}switch(d&&o.ununsynchronizeRegion(o.pos,a),t.raw??={},i.id[0]==="T"?t.raw[i.id]??=o.readId3V2EncodingAndText(a):t.raw[i.id]??=o.readBytes(i.size),o.pos=s,i.id){case"TIT2":case"TT2":t.title??=o.readId3V2EncodingAndText(a);break;case"TIT3":case"TT3":t.description??=o.readId3V2EncodingAndText(a);break;case"TPE1":case"TP1":t.artist??=o.readId3V2EncodingAndText(a);break;case"TALB":case"TAL":t.album??=o.readId3V2EncodingAndText(a);break;case"TPE2":case"TP2":t.albumArtist??=o.readId3V2EncodingAndText(a);break;case"TRCK":case"TRK":{let f=o.readId3V2EncodingAndText(a).split("/"),m=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(m)&&m>0&&(t.trackNumber??=m),p&&Number.isInteger(p)&&p>0&&(t.tracksTotal??=p)}break;case"TPOS":case"TPA":{let f=o.readId3V2EncodingAndText(a).split("/"),m=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(m)&&m>0&&(t.discNumber??=m),p&&Number.isInteger(p)&&p>0&&(t.discsTotal??=p)}break;case"TCON":case"TCO":{let u=o.readId3V2EncodingAndText(a),f=/^\((\d+)\)/.exec(u);if(f){let m=Number.parseInt(f[1]);if(Ot[m]!==void 0){t.genre??=Ot[m];break}}if(f=/^\d+$/.exec(u),f){let m=Number.parseInt(f[0]);if(Ot[m]!==void 0){t.genre??=Ot[m];break}}t.genre??=u}break;case"TDRC":case"TDAT":{let u=o.readId3V2EncodingAndText(a),f=new Date(u);Number.isNaN(f.getTime())||(t.date??=f)}break;case"TYER":case"TYE":{let u=o.readId3V2EncodingAndText(a),f=Number.parseInt(u,10);Number.isInteger(f)&&(t.date??=new Date(f,0,1))}break;case"USLT":case"ULT":{let u=o.readU8();o.pos+=3,o.readId3V2Text(u,a),t.lyrics??=o.readId3V2Text(u,a)}break;case"COMM":case"COM":{let u=o.readU8();o.pos+=3,o.readId3V2Text(u,a),t.comment??=o.readId3V2Text(u,a)}break;case"APIC":case"PIC":{let u=o.readId3V2TextEncoding(),f;if(e.majorVersion===2){let x=o.readAscii(3);f=x==="PNG"?"image/png":x==="JPG"?"image/jpeg":"image/*"}else f=o.readId3V2Text(u,a);let m=o.readU8(),p=o.readId3V2Text(u,a).trimEnd(),g=a-o.pos;if(g>=0){let x=o.readBytes(g);t.images||(t.images=[]),t.images.push({data:x,mimeType:f,kind:m===3?"coverFront":m===4?"coverBack":"unknown",description:p})}}break;default:o.pos+=i.size;break}o.pos=a}},di=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t<this.bytes.length;t++){let n=this.bytes[t];e.push(n),n===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let n=[];for(let s=e;s<t;s++){let a=this.bytes[s];n.push(a),a===255&&s!==t-1&&this.bytes[s+1]===0&&s++}let o=this.bytes.subarray(0,e),i=this.bytes.subarray(t);this.bytes=new Uint8Array(o.length+n.length+i.length),this.bytes.set(o,0),this.bytes.set(n,o.length),this.bytes.set(i,o.length+n.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-zt),this.view=new DataView(this.bytes.buffer)}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+1);return this.pos+=3,e*256+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let n=0;n<e;n++)t+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);if(e==="\0\0\0")return null;let t=this.readU24();return{id:e,size:t,flags:0}}else{let e=this.readAscii(4);if(e==="\0\0\0\0")return null;let t=this.readU32(),n=this.header.majorVersion===4?Pn(t):t,o=this.readU16(),i=this.pos,s=a=>{let c=this.pos+a;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=a;let l=this.readAscii(4);if(l!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(l))return!1}return!0};if(!s(n)){let a=this.header.majorVersion===4?t:Pn(t);s(a)&&(n=a)}return this.pos=i,{id:e,size:n,flags:o}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let n=this.pos,o=this.readBytes(t-this.pos);switch(e){case Bt.ISO_8859_1:{let i="";for(let s=0;s<o.length;s++){let a=o[s];if(a===0){this.pos=n+s+1;break}i+=String.fromCharCode(a)}return i}case Bt.UTF_16_WITH_BOM:if(o[0]===255&&o[1]===254){let i=new TextDecoder("utf-16le"),s=et(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=n+Math.min(s+2,o.length),i.decode(o.subarray(2,s))}else if(o[0]===254&&o[1]===255){let i=new TextDecoder("utf-16be"),s=et(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=n+Math.min(s+2,o.length),i.decode(o.subarray(2,s))}else{let i=et(o.findIndex(s=>s===0),o.length);return this.pos=n+Math.min(i+1,o.length),$.decode(o.subarray(0,i))}case Bt.UTF_16_BE_NO_BOM:{let i=new TextDecoder("utf-16be"),s=et(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=n+Math.min(s+2,o.length),i.decode(o.subarray(0,s))}case Bt.UTF_8:{let i=et(o.findIndex(s=>s===0),o.length);return this.pos=n+Math.min(i+1,o.length),$.decode(o.subarray(0,i))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}};var br=async(r,e,t)=>{let n=e;for(;t===null||n<t;){let o=r.requestSlice(n,4);if(o instanceof Promise&&(o=await o),!o)break;let i=v(o),s=Ns(i,r.fileSize!==null?r.fileSize-n:null);if(s.header)return{header:s.header,startPos:n};n+=s.bytesAdvanced}return null};var In=class extends Q{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new ye,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.tracks=[new G(this.input,new fi(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,zt);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}let c=lt(a);if(!c)break;this.lastLoadedPos=a.filePos+c.size}let e=await br(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let n=Us(t.mpegVersionId,t.channel),o=this.reader.requestSlice(e.startPos+n,4);if(o instanceof Promise&&(o=await o),o){let a=v(o);if(a===Os||a===zs)return}this.firstFrameHeader||(this.firstFrameHeader=t),t.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${t.sampleRate} Hz. Might be a bug, so please report this file.`);let i=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,s={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:i,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(s),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return h(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0,n=!1;for(;;){let o=this.reader.requestSlice(t,zt);if(o instanceof Promise&&(o=await o),!o)break;let i=lt(o);if(!i)break;n=!0;let s=this.reader.requestSlice(o.filePos,i.size);if(s instanceof Promise&&(s=await s),!s)break;Cn(s,i,this.metadataTags),t=o.filePos+i.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=xr){let o=this.reader.requestSlice(this.reader.fileSize-xr,xr);o instanceof Promise&&(o=await o),h(o),L(o,3)==="TAG"&&Vs(o,this.metadataTags)}return this.metadataTags}finally{e()}}},fi=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return K}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...te}}async getDecoderConfig(){return h(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let o;if(t.metadataOnly)o=H;else{let i=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(i instanceof Promise&&(i=await i),!i)return null;o=E(i,n.dataSize)}return new V(o,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let o=Qe(this.demuxer.loadedSamples,e.timestamp,s=>s.timestamp);if(o===-1)throw new Error("Packet was not created from this track.");let i=o+1;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let o=B(this.demuxer.loadedSamples,e,i=>i.timestamp);if(o===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(o,t);if(o>=0&&o+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(o,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var mi=1399285583,Gc=79764919,Hs=new Uint32Array(256);for(let r=0;r<256;r++){let e=r<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^Gc:e<<1;Hs[r]=e>>>0&4294967295}var qs=r=>{let e=z(r),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let n=0;for(let o=0;o<r.length;o++){let i=r[o];n=(n<<8^Hs[n>>>24^i])>>>0}return e.setUint32(22,t,!0),n},Gs=(r,e,t)=>{let n=0,o=null;if(r.length>0)if(e.codec==="vorbis"){h(e.vorbisInfo);let i=e.vorbisInfo.modeBlockflags.length,a=(1<<ns(i-1))-1<<1,c=(r[0]&a)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=t,d=e.vorbisInfo.modeBlockflags[c];if(o=e.vorbisInfo.blocksizes[d],d===1){let u=(a|1)+1,f=r[0]&u?1:0;l=e.vorbisInfo.blocksizes[f]}n=l!==null?l+o>>2:0}else e.codec==="opus"&&(n=xs(r).durationInSamples);return{durationInSamples:n,vorbisBlockSize:o}},Ws=r=>{let e="audio/ogg";if(r.codecStrings){let t=[...new Set(r.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};var Ge=27,dt=282,js=dt+65025,Ut=r=>{let e=r.filePos;if(ut(r)!==mi)return null;r.skip(1);let n=A(r),o=Ks(r),i=ut(r),s=ut(r),a=ut(r),c=A(r),l=new Uint8Array(c);for(let m=0;m<c;m++)l[m]=A(r);let d=27+c,u=l.reduce((m,p)=>m+p,0),f=d+u;return{headerStartPos:e,totalSize:f,dataStartPos:e+d,dataSize:u,headerType:n,granulePosition:o,serialNumber:i,sequenceNumber:s,checksum:a,lacingValues:l}},$s=(r,e)=>{for(;r.filePos<e-3;){let t=ut(r),n=t&255,o=t>>>8&255,i=t>>>16&255,s=t>>>24&255,a=79;if(!(n!==a&&o!==a&&i!==a&&s!==a)){if(r.skip(-4),t===mi)return!0;r.skip(1)}}return!1};var An=class extends Q{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.tracks=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,Ge,dt);if(t instanceof Promise&&(t=await t),!t)break;let n=Ut(t);if(!n||!!!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let t of this.bitstreams){let n=await this.readPacket(t.bosPage,0);n&&(n.data.byteLength>=7&&n.data[0]===1&&n.data[1]===118&&n.data[2]===111&&n.data[3]===114&&n.data[4]===98&&n.data[5]===105&&n.data[6]===115?await this.readVorbisMetadata(n,t):n.data.byteLength>=8&&n.data[0]===79&&n.data[1]===112&&n.data[2]===117&&n.data[3]===115&&n.data[4]===72&&n.data[5]===101&&n.data[6]===97&&n.data[7]===100&&await this.readOpusMetadata(n,t),t.codecInfo.codec!==null&&this.tracks.push(new G(this.input,new pi(t,this))))}})()}async readVorbisMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let o=await this.readPacket(n.startPage,n.startSegmentIndex);if(!o||(n=await this.findNextPacketStart(o),!n))return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i||o.data[0]!==3||i.data[0]!==5)return;let s=[],a=u=>{for(;s.push(Math.min(255,u)),!(u<255);)u-=255};a(e.data.length),a(o.data.length);let c=new Uint8Array(1+s.length+e.data.length+o.data.length+i.data.length);c[0]=2,c.set(s,1),c.set(e.data,1+s.length),c.set(o.data,1+s.length+e.data.length),c.set(i.data,1+s.length+e.data.length+o.data.length),t.codecInfo.codec="vorbis",t.description=c,t.lastMetadataPacket=i;let l=z(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);let d=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(d&15),1<<(d>>4)],modeBlockflags:bs(i.data).modeBlockflags},sr(o.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let o=await this.readPacket(n.startPage,n.startSegmentIndex);if(!o)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=o;let i=gs(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=rt,t.codecInfo.opusInfo={preSkip:i.preSkip},sr(o.data.subarray(8),this.metadataTags)}async readPacket(e,t){h(t<e.lacingValues.length);let n=0;for(let u=0;u<t;u++)n+=e.lacingValues[u];let o=e,i=n,s=t,a=[];e:for(;;){let u=this.reader.requestSlice(o.dataStartPos,o.dataSize);u instanceof Promise&&(u=await u),h(u);let f=E(u,o.dataSize);for(;;){if(s===o.lacingValues.length){a.push(f.subarray(n,i));break}let p=o.lacingValues[s];if(i+=p,p<255){a.push(f.subarray(n,i));break e}s++}let m=o.headerStartPos+o.totalSize;for(;;){let p=this.reader.requestSliceRange(m,Ge,dt);if(p instanceof Promise&&(p=await p),!p)return null;let g=Ut(p);if(!g)return null;if(o=g,o.serialNumber===e.serialNumber)break;m=o.headerStartPos+o.totalSize}n=0,i=0,s=0}let c=a.reduce((u,f)=>u+f.length,0),l=new Uint8Array(c),d=0;for(let u=0;u<a.length;u++){let f=a[u];l.set(f,d),d+=f.length}return{data:l,endPage:o,endSegmentIndex:s}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let n=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let o=this.reader.requestSliceRange(n,Ge,dt);if(o instanceof Promise&&(o=await o),!o)return null;let i=Ut(o);if(!i)return null;if(i.serialNumber===e.endPage.serialNumber)return{startPage:i,startSegmentIndex:0};n=i.headerStartPos+i.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(t=>t.getCodecParameterString()));return Ws({codecStrings:e.filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...t)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},pi=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new ye,this.internalSampleRate=e.codecInfo.codec==="opus"?rt:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return h(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return K}getDisposition(){return{...te}}async getFirstTimestamp(){return 0}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(h(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,n){if(!e)return null;let{durationInSamples:o,vorbisBlockSize:i}=Gs(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new V(n.metadataOnly?H:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,o/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:o,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:i}),s}async getFirstPacket(e){h(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let n=0;this.bitstream.codecInfo.codec==="opus"&&(h(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let o=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(o,{timestampInSamples:n,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let n=this.encodedPacketToMetadata.get(e);if(!n)throw new Error("Packet was not created from this track.");let o=await this.demuxer.findNextPacketStart(n.packet);if(!o)return null;let i=n.timestampInSamples+n.durationInSamples,s=await this.demuxer.readPacket(o.startPage,o.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:i,vorbisLastBlocksize:n.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let n=Je(e*this.internalSampleRate);if(n===0)return this.getFirstPacket(t);if(n<0)return null;h(this.bitstream.lastMetadataPacket);let o=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!o)return null;let i=o.startPage,s=this.demuxer.reader.fileSize,a=[i];e:for(;i.headerStartPos+i.totalSize<s;){let b=i.headerStartPos,w=Math.floor((b+s)/2),k=w;for(;;){let P=Math.min(k+js,s-Ge),S=this.demuxer.reader.requestSlice(k,P-k);if(S instanceof Promise&&(S=await S),h(S),!$s(S,P)){s=w+Ge;continue e}let C=this.demuxer.reader.requestSliceRange(S.filePos,Ge,dt);C instanceof Promise&&(C=await C),h(C);let F=Ut(C);h(F);let O=!1;if(F.serialNumber===this.bitstream.serialNumber)O=!0;else{let j=this.demuxer.reader.requestSlice(F.headerStartPos,F.totalSize);j instanceof Promise&&(j=await j),h(j);let We=E(j,F.totalSize);O=qs(We)===F.checksum}if(!O){k=F.headerStartPos+4;continue}if(O&&F.serialNumber!==this.bitstream.serialNumber){k=F.headerStartPos+F.totalSize;continue}if(F.granulePosition===-1){k=F.headerStartPos+F.totalSize;continue}this.granulePositionToTimestampInSamples(F.granulePosition)>n?s=F.headerStartPos:(i=F,a.push(F));continue e}}let c=o.startPage;for(let b of a){if(b.granulePosition===i.granulePosition)break;(!c||b.headerStartPos>c.headerStartPos)&&(c=b)}let l=c,d=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===i.granulePosition);){let b=l.headerStartPos+l.totalSize,w=this.demuxer.reader.requestSliceRange(b,Ge,dt);w instanceof Promise&&(w=await w),h(w);let k=Ut(w);h(k),l=k,l.serialNumber===this.bitstream.serialNumber&&d.push(l)}h(l.granulePosition!==-1);let u=null,f,m,p=l,g=0;if(l.headerStartPos===o.startPage.headerStartPos)f=this.granulePositionToTimestampInSamples(0),m=!0,u=0;else{f=0,m=!1;for(let k=l.lacingValues.length-1;k>=0;k--)if(l.lacingValues[k]<255){u=k+1;break}if(u===null)throw new Error("Invalid page with granule position: no packets end on this page.");g=u-1;let b={data:H,endPage:p,endSegmentIndex:g};if(await this.demuxer.findNextPacketStart(b)){let k=Qs(d,l,u);h(k);let P=Xs(d,k.page,k.segmentIndex);P&&(l=P.page,u=P.segmentIndex)}else for(;;){let k=Qs(d,l,u);if(!k)break;let P=Xs(d,k.page,k.segmentIndex);if(!P)break;if(l=P.page,u=P.segmentIndex,k.page.headerStartPos!==p.headerStartPos){p=k.page,g=k.segmentIndex;break}}}let x=null,y=null;for(;l!==null;){h(u!==null);let b=await this.demuxer.readPacket(l,u);if(!b)break;if(!(l.headerStartPos===o.startPage.headerStartPos&&u<o.startSegmentIndex)){let P=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:f,vorbisLastBlocksize:y?.vorbisBlockSize??null},t);h(P);let S=this.encodedPacketToMetadata.get(P);if(h(S),!m&&b.endPage.headerStartPos===p.headerStartPos&&b.endSegmentIndex===g?(f=this.granulePositionToTimestampInSamples(l.granulePosition),m=!0,P=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:f-S.durationInSamples,vorbisLastBlocksize:y?.vorbisBlockSize??null},t),h(P),S=this.encodedPacketToMetadata.get(P),h(S)):f+=S.durationInSamples,x=P,y=S,m&&(Math.max(f,0)>n||Math.max(S.timestampInSamples,0)===n))break}let k=await this.demuxer.findNextPacketStart(b);if(!k)break;l=k.startPage,u=k.startSegmentIndex}return x}async getPacketSequential(e,t){let n=await this.sequentialScanMutex.acquire();try{let o=Je(e*this.internalSampleRate);e=o/this.internalSampleRate;let i=B(this.sequentialScanCache,o,c=>c.timestampInSamples),s;if(i!==-1){let c=this.sequentialScanCache[i];s=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},t)}else s=await this.getFirstPacket(t);let a=0;for(;s&&s.timestamp<e;){let c=await this.getNextPacket(s,t);if(!c||c.timestamp>e)break;if(s=c,a++,a===100){a=0;let l=this.encodedPacketToMetadata.get(s);h(l),this.sequentialScanCache.length>0&&h(Y(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return s}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},Xs=(r,e,t)=>{let n=e,o=t;e:for(;;){for(o--,o;o>=0;o--)if(n.lacingValues[o]<255){o++;break e}if(h(o===-1),!(n.headerType&1)){o=0;break}let s=Oo(r,a=>a.headerStartPos<n.headerStartPos);if(!s)return null;n=s,o=n.lacingValues.length}if(h(o!==-1),o===n.lacingValues.length){let i=r[r.indexOf(n)+1];h(i),n=i,o=0}return{page:n,segmentIndex:o}},Qs=(r,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};let n=Oo(r,o=>o.headerStartPos<e.headerStartPos);return n?{page:n,segmentIndex:n.lacingValues.length-1}:null};var Re;(function(r){r[r.PCM=1]="PCM",r[r.IEEE_FLOAT=3]="IEEE_FLOAT",r[r.ALAW=6]="ALAW",r[r.MULAW=7]="MULAW",r[r.EXTENSIBLE=65534]="EXTENSIBLE"})(Re||(Re={}));var _n=class extends Q{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.tracks=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),h(e);let t=L(e,4),n=t!=="RIFX",o=t==="RF64",i=Me(e,n),s=o?this.reader.fileSize:Math.min(i+8,this.reader.fileSize??1/0);if(L(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,d=e.filePos;for(;s===null||d<s;){let f=this.reader.requestSlice(d,8);if(f instanceof Promise&&(f=await f),!f)break;let m=L(f,4),p=Me(f,n),g=f.filePos;if(o&&c===0&&m!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(m==="fmt ")await this.parseFmtChunk(g,p,n);else if(m==="data"){if(l??=p,this.dataStart=f.filePos,this.dataSize=Math.min(l,(s??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(m==="ds64"){let x=this.reader.requestSlice(g,p);if(x instanceof Promise&&(x=await x),!x)break;let y=gi(x,n);l=gi(x,n),s=Math.min(y+8,this.reader.fileSize??1/0)}else m==="LIST"?await this.parseListChunk(g,p,n):(m==="ID3 "||m==="id3 ")&&await this.parseId3Chunk(g,p);d=g+p+(p&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');let u=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/u)*u,this.tracks.push(new G(this.input,new hi(this)))})()}async parseFmtChunk(e,t,n){let o=this.reader.requestSlice(e,t);if(o instanceof Promise&&(o=await o),!o)return;let i=Vt(o,n),s=Vt(o,n),a=Me(o,n);o.skip(4);let c=Vt(o,n),l;if(t===14?l=8:l=Vt(o,n),t>=18&&i!==357){let d=Vt(o,n),u=t-18;if(Math.min(u,d)>=22&&i===Re.EXTENSIBLE){o.skip(6);let m=E(o,16);i=m[0]|m[1]<<8}}(i===Re.MULAW||i===Re.ALAW)&&(l=8),this.audioInfo={format:i,numberOfChannels:s,sampleRate:a,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}}async parseListChunk(e,t,n){let o=this.reader.requestSlice(e,t);if(o instanceof Promise&&(o=await o),!o)return;let i=L(o,4);if(i!=="INFO"&&i!=="INF0")return;let s=o.filePos;for(;s<=e+t-8;){o.filePos=s;let a=L(o,4),c=Me(o,n),l=E(o,c),d=0;for(let f=0;f<l.length&&l[f]!==0;f++)d++;let u=String.fromCharCode(...l.subarray(0,d));switch(this.metadataTags.raw??={},this.metadataTags.raw[a]=u,a){case"INAM":case"TITL":this.metadataTags.title??=u;break;case"TIT3":this.metadataTags.description??=u;break;case"IART":this.metadataTags.artist??=u;break;case"IPRD":this.metadataTags.album??=u;break;case"IPRT":case"ITRK":case"TRCK":{let f=u.split("/"),m=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(m)&&m>0&&(this.metadataTags.trackNumber??=m),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{let f=new Date(u);Number.isNaN(f.getTime())||(this.metadataTags.date??=f)}break;case"YEAR":{let f=Number.parseInt(u,10);Number.isInteger(f)&&f>0&&(this.metadataTags.date??=new Date(f,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=u;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=u;break}s+=8+c+(c&1)}}async parseId3Chunk(e,t){let n=this.reader.requestSlice(e,t);if(n instanceof Promise&&(n=await n),!n)return;let o=lt(n);if(o){let i=n.slice(e+10,o.size);Cn(i,o,this.metadataTags)}}getCodec(){if(h(this.audioInfo),this.audioInfo.format===Re.MULAW)return"ulaw";if(this.audioInfo.format===Re.ALAW)return"alaw";if(this.audioInfo.format===Re.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}return this.audioInfo.format===Re.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return h(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Nt=2048,hi=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(h(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getNumberOfChannels(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return K}getDisposition(){return{...te}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){h(this.demuxer.audioInfo);let n=e*Nt*this.demuxer.audioInfo.blockSizeInBytes;if(n>=this.demuxer.dataSize)return null;let o=Math.min(Nt*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-n);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,o);if(c instanceof Promise&&(c=await c),!c)return null}let i;if(t.metadataOnly)i=H;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,o);c instanceof Promise&&(c=await c),h(c),i=E(c,o)}let s=e*Nt/this.demuxer.audioInfo.sampleRate,a=o/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,s),new V(i,"key",s,a,e,o)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){h(this.demuxer.audioInfo);let n=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Nt,(this.demuxer.dataSize-1)/(Nt*this.demuxer.audioInfo.blockSizeInBytes))),o=await this.getPacketAtIndex(n,t);if(o)return o;if(n===0)return null;h(this.demuxer.reader.fileSize===null);let i=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;i;){let s=await this.getNextPacket(i,t);if(!s)break;i=s}return i}getNextPacket(e,t){h(this.demuxer.audioInfo);let n=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Nt);return this.getPacketAtIndex(n+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Lt=7,Ht=9,yr=r=>{let e=r.filePos,t=E(r,9),n=new N(t);if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let s=n.readBits(1),a=n.readBits(2)+1,c=n.readBits(4);if(c===15)return null;n.skipBits(1);let l=n.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let d=n.readBits(13);n.skipBits(11);let u=n.readBits(2)+1;if(u!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let f=null;return s===1?r.filePos-=2:f=n.readBits(16),{objectType:a,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:d,numberOfAacFrames:u,crcCheck:f,startPos:e}};var xi=1024,En=class extends Q{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new ye,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();h(this.firstFrameHeader),this.tracks=[new G(this.input,new bi(this))]})()}async advanceReader(){let e=this.reader.requestSliceRange(this.lastLoadedPos,Lt,Ht);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=yr(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);let n=ir[t.samplingFrequencyIndex];h(n!==void 0);let o=xi/n,i=t.crcCheck?Ht:Lt,s={timestamp:this.nextTimestampInSamples/n,duration:o,dataStart:t.startPos+i,dataSize:t.frameLength-i};this.loadedSamples.push(s),this.nextTimestampInSamples+=xi,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return h(e),e.computeDuration()}async getMetadataTags(){return{}}},bi=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/xi}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return K}getCodec(){return"aac"}getInternalCodecId(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){h(this.demuxer.firstFrameHeader);let e=Vo[this.demuxer.firstFrameHeader.channelConfiguration];return h(e!==void 0),e}getSampleRate(){h(this.demuxer.firstFrameHeader);let e=ir[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return h(e!==void 0),e}getDisposition(){return{...te}}async getDecoderConfig(){h(this.demuxer.firstFrameHeader);let e=new Uint8Array(3),t=new N(e),{objectType:n,samplingFrequencyIndex:o,channelConfiguration:i}=this.demuxer.firstFrameHeader;return n>31?(t.writeBits(5,31),t.writeBits(6,n-32)):t.writeBits(5,n),t.writeBits(4,o),t.writeBits(4,i),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:e.subarray(0,Math.ceil((t.pos-1)/8))}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let o;if(t.metadataOnly)o=H;else{let i=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(i instanceof Promise&&(i=await i),!i)return null;o=E(i,n.dataSize)}return new V(o,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let o=Qe(this.demuxer.loadedSamples,e.timestamp,s=>s.timestamp);if(o===-1)throw new Error("Packet was not created from this track.");let i=o+1;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let o=B(this.demuxer.loadedSamples,e,i=>i.timestamp);if(o===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(o,t);if(o>=0&&o+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(o,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Ys=r=>r===0?null:r===1?192:r>=2&&r<=5?144*2**r:r===6?"uncommon-u8":r===7?"uncommon-u16":r>=8&&r<=15?2**r:null,Zs=(r,e)=>{switch(r){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},Js=r=>{let e=0,t=new N(E(r,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);let n=[],o=e-1,i=new N(E(r,o)),s=8-e-1;for(let c=0;c<s;c++)n.unshift(t.readBits(1));for(let c=0;c<o;c++)for(let l=0;l<8;l++){let d=i.readBits(1);l<2||n.unshift(d)}return n.reduce((c,l,d)=>c|l<<d,0)},ea=(r,e)=>{if(e==="uncommon-u16")return W(r)+1;if(e==="uncommon-u8")return A(r)+1;if(typeof e=="number")return e;se(e),h(!1)},ta=(r,e)=>e==="uncommon-u16"?W(r):e==="uncommon-u16-10"?W(r)*10:e==="uncommon-u8"?A(r):typeof e=="number"?e:null,ra=r=>{let t=0;for(let n of r){t^=n;for(let o=0;o<8;o++)(t&128)!==0?t=t<<1^7:t<<=1,t&=255}return t};var Fn=class extends Q{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.track=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new ye,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),h(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),h(this.track),[this.track]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;this.reader.fileSize===null||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),e+=4,t===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);h(t);let n=A(t),o=He(t),i=(n&128)!==0;switch(n&127){case Ne.STREAMINFO:{let a=this.reader.requestSlice(e,o);if(a instanceof Promise&&(a=await a),h(a),a===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let c=E(a,34),l=new N(c),d=l.readBits(16),u=l.readBits(16),f=l.readBits(24),m=l.readBits(24),p=l.readBits(20),g=l.readBits(3)+1;l.readBits(5);let x=l.readBits(36);l.skipBits(128);let y=new Uint8Array(42);y.set(new Uint8Array([102,76,97,67]),0),y.set(new Uint8Array([128,0,0,34]),4),y.set(c,8),this.audioInfo={numberOfChannels:g,sampleRate:p,totalSamples:x,minimumBlockSize:d,maximumBlockSize:u,minimumFrameSize:f,maximumFrameSize:m,description:y},this.track=new G(this.input,new yi(this));break}case Ne.VORBIS_COMMENT:{let a=this.reader.requestSlice(e,o);a instanceof Promise&&(a=await a),h(a),sr(E(a,o),this.metadataTags);break}case Ne.PICTURE:{let a=this.reader.requestSlice(e,o);a instanceof Promise&&(a=await a),h(a);let c=v(a),l=v(a),d=$.decode(E(a,l)),u=v(a),f=$.decode(E(a,u));a.skip(16);let m=v(a),p=E(a,m);this.metadataTags.images??=[],this.metadataTags.images.push({data:p,mimeType:d,kind:c===3?"coverFront":c===4?"coverBack":"unknown",description:f});break}default:break}if(e+=o,i){this.lastLoadedPos=e;break}}})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){h(this.audioInfo);let n=6,i=this.audioInfo.maximumFrameSize+16,s=await this.reader.requestSliceRange(e,this.audioInfo.minimumFrameSize,i);if(!s)return null;let a=this.readFlacFrameHeader({slice:s,isFirstPacket:t});if(!a)return null;for(s.filePos=e+this.audioInfo.minimumFrameSize;;){if(s.filePos>s.end-n)return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:s.end-e,isLastFrame:!0};if(A(s)===255){let l=s.filePos,d=A(s),u=this.blockingBit===1?249:248;if(d!==u){s.filePos=l;continue}s.skip(-2);let f=s.filePos-e,m=this.readFlacFrameHeader({slice:s,isFirstPacket:!1});if(!m){s.filePos=l;continue}if(this.blockingBit===0){if(m.num-a.num!==1){s.filePos=l;continue}}else if(m.num-a.num!==a.blockSize){s.filePos=l;continue}return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:f,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){let n=e.filePos,o=E(e,4),i=new N(o);if(i.readBits(15)!==32764)return null;if(this.blockingBit===null){h(t);let x=i.readBits(1);this.blockingBit=x}else if(this.blockingBit===1){if(h(!t),i.readBits(1)!==1)return null}else if(this.blockingBit===0){if(h(!t),i.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");let a=Ys(i.readBits(4));if(!a)return null;h(this.audioInfo);let c=Zs(i.readBits(4),this.audioInfo.sampleRate);if(!c||(i.readBits(4),i.readBits(3),i.readBits(1)!==0))return null;let d=Js(e),u=ea(e,a),f=ta(e,c);if(f===null||f!==this.audioInfo.sampleRate)return null;let m=e.filePos-n,p=A(e);e.skip(-m),e.skip(-1);let g=ra(E(e,m));return p!==g?null:{num:d,blockSize:u,sampleRate:f}}async advanceReader(){await this.readMetadata(),h(this.lastLoadedPos!==null),h(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],i={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(i),t.isLastFrame){this.lastSampleLoaded=!0;return}}},yi=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getSampleRate(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return K}getTimeResolution(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...te}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return h(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(h(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");let n=await this.demuxer.readingMutex.acquire();try{for(;;){let o=B(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(o===-1){await this.demuxer.advanceReader();continue}let i=this.demuxer.loadedSamples[o],s=i.blockOffset/this.demuxer.audioInfo.sampleRate,a=i.blockSize/this.demuxer.audioInfo.sampleRate;if(s+a<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(o,t)}}finally{n()}}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let o=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&o>=this.demuxer.loadedSamples.length)return null;for(;o>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(o,t)}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let n=this.demuxer.loadedSamples[e];if(!n)return null;let o;if(t.metadataOnly)o=H;else{let a=this.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(a instanceof Promise&&(a=await a),!a)return null;o=E(a,n.byteSize)}h(this.demuxer.audioInfo);let i=n.blockOffset/this.demuxer.audioInfo.sampleRate,s=n.blockSize/this.demuxer.audioInfo.sampleRate;return new V(o,"key",i,s,e,n.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}};var ae=class{},Tr=class extends ae{async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);return t instanceof Promise&&(t=await t),!t||(t.skip(4),L(t,4)!=="ftyp")?null:L(t,4)}_createDemuxer(e){return new gn(e)}},Dn=class extends Tr{async _canReadInput(e){let t=await this._getMajorBrand(e);return!!t&&t!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},Rn=class extends Tr{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},wr=class extends ae{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,de);if(n instanceof Promise&&(n=await n),!n)return!1;let o=ii(n);if(o===null||o<1||o>8||D(n,o)!==T.EBML)return!1;let s=si(n);if(s===null)return!1;let a=e._reader.requestSlice(n.filePos,s);if(a instanceof Promise&&(a=await a),!a)return!1;let c=n.filePos;for(;a.filePos<=c+s-oe;){let l=fe(a);if(!l)break;let{id:d,size:u}=l,f=a.filePos;if(u===null)return!1;switch(d){case T.EBMLVersion:if(D(a,u)!==1)return!1;break;case T.EBMLReadVersion:if(D(a,u)!==1)return!1;break;case T.DocType:if(qe(a,u)!==t)return!1;break;case T.DocTypeVersion:if(D(a,u)>4)return!1;break}a.filePos=f+u}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Sn(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},Mn=class extends wr{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},Bn=class extends ae{async _canReadInput(e){let t=e._reader.requestSlice(0,10);if(t instanceof Promise&&(t=await t),!t)return!1;let n=0,o=!1;for(;;){let l=e._reader.requestSlice(n,zt);if(l instanceof Promise&&(l=await l),!l)break;let d=lt(l);if(!d)break;o=!0,n=l.filePos+d.size}let i=await br(e._reader,n,n+4096);if(!i)return!1;if(o)return!0;n=i.startPos+i.header.totalSize;let s=await br(e._reader,n,n+4);if(!s)return!1;let a=i.header,c=s.header;return!(a.channel!==c.channel||a.sampleRate!==c.sampleRate)}_createDemuxer(e){return new In(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},On=class extends ae{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let n=L(t,4);return n!=="RIFF"&&n!=="RIFX"&&n!=="RF64"?!1:(t.skip(4),L(t,4)==="WAVE")}_createDemuxer(e){return new _n(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},zn=class extends ae{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?L(t,4)==="OggS":!1}_createDemuxer(e){return new An(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},Un=class extends ae{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?L(t,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Fn(e)}},Nn=class extends ae{async _canReadInput(e){let t=e._reader.requestSliceRange(0,Lt,Ht);if(t instanceof Promise&&(t=await t),!t)return!1;let n=yr(t);if(!n||(t=e._reader.requestSliceRange(n.frameLength,Lt,Ht),t instanceof Promise&&(t=await t),!t))return!1;let o=yr(t);return o?n.objectType===o.objectType&&n.samplingFrequencyIndex===o.samplingFrequencyIndex&&n.channelConfiguration===o.channelConfiguration:!1}_createDemuxer(e){return new En(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},na=new Dn,oa=new Rn,ia=new wr,sa=new Mn,aa=new Bn,ca=new On,la=new zn,ua=new Nn,da=new Un,ie=[na,oa,ia,sa,ca,la,da,aa,ua];var ft=class{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new q;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new q;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}};var kr=class extends ft{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!or(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new Vn({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:ma.fileSystem})}_retrieveSize(){let e=this._blob.size;return this._orchestrator.fileSize=e,e}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){let t=this._readers.get(e);for(t===void 0&&("stream"in this._blob&&!Oe()?t=this._blob.slice(e.currentPos).stream().getReader():t=null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){let{done:n,value:o}=await t.read();if(n)throw this._orchestrator.forgetWorker(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}else{let n=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+n.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(n))}e.running=!1,e.aborted&&await t?.cancel()}_dispose(){this._orchestrator.dispose()}},fa=.5*2**20,Wc=((r,e,t)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))){let o=null;try{typeof window<"u"&&typeof window.location<"u"&&(o=new URL(t instanceof Request?t.url:t,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&o!==null&&o!==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**(r-2),16)}),Sr=class extends ft{constructor(e,t={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.requestInit!==void 0&&(!t.requestInit||typeof t.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(t.getRetryDelay!==void 0&&typeof t.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(t.maxCacheSize!==void 0&&(!or(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.fetchFn!==void 0&&typeof t.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");super(),this._existingResponses=new WeakMap,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??Wc,this._orchestrator=new Vn({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:ma.network})}async _retrieveSize(){let e=new AbortController,t=await No(this._options.fetchFn??fetch,this._url,Uo(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:e.signal}),this._getRetryDelay,()=>this._disposed);if(!t.ok)throw new Error(`Error fetching ${String(this._url)}: ${t.status} ${t.statusText}`);let n,o;if(t.status===206)o=this._getTotalLengthFromRangeResponse(t),n=this._orchestrator.createWorker(0,Math.min(o,fa));else{let i=t.headers.get("Content-Length");if(i)o=Number(i),n=this._orchestrator.createWorker(0,o),this._orchestrator.options.maxCacheSize=1/0,console.warn("HTTP server did not respond with 206 Partial Content, meaning the entire remote resource now has to be downloaded. For efficient media file streaming across a network, please make sure your server supports range requests.");else throw new Error(`HTTP response (status ${t.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=o,this._existingResponses.set(n,{response:t,abortController:e}),this._orchestrator.runWorker(n),o}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;;){let t=this._existingResponses.get(e);this._existingResponses.delete(e);let n=t?.abortController,o=t?.response;if(n||(n=new AbortController,o=await No(this._options.fetchFn??fetch,this._url,Uo(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:n.signal}),this._getRetryDelay,()=>this._disposed)),h(o),!o.ok)throw new Error(`Error fetching ${String(this._url)}: ${o.status} ${o.statusText}`);if(e.currentPos>0&&o.status!==206)throw new Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!o.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let i=o.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){n.abort(),e.running=!1;return}let s;try{s=await i.read()}catch(l){if(this._disposed)throw l;let d=this._getRetryDelay(1,l,this._url);if(d!==null){console.error("Error while reading response stream. Attempting to resume.",l),await new Promise(u=>setTimeout(u,1e3*d));break}else throw l}if(e.aborted)continue;let{done:a,value:c}=s;if(a){if(e.currentPos>=e.targetPos){this._orchestrator.forgetWorker(e),e.running=!1;return}break}this.onread?.(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}}}_getTotalLengthFromRangeResponse(e){let t=e.headers.get("Content-Range");if(t){let o=/\/(\d+)/.exec(t);if(o)return Number(o[1])}let n=e.headers.get("Content-Length");if(n)return Number(n);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}};var ma={none:(r,e)=>({start:r,end:e}),fileSystem:(r,e)=>(r=Math.floor((r-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:r,end:e}),network:(r,e,t)=>{r=Math.max(0,Math.floor((r-65536)/65536)*65536);for(let o of t){let s=Math.max((o.startPos+o.targetPos)/2,o.targetPos-8388608);if(en(r,e,s,o.targetPos)){let a=o.targetPos-o.startPos,c=Math.ceil((a+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(a+1)),d=Math.min(l,c);e=Math.max(e,o.startPos+d)}}return e=Math.max(e,r+fa),{start:r,end:e}}},Vn=class{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,t){h(this.fileSize!==null);let n=this.options.prefetchProfile(e,t,this.workers),o=Math.max(n.start,0),i=Math.min(n.end,this.fileSize);h(o<=e&&t<=i);let s=null,a=B(this.cache,e,b=>b.start),c=a!==-1?this.cache[a]:null;c&&c.start<=e&&t<=c.end&&(c.age=this.nextAge++,s={bytes:c.bytes,view:c.view,offset:c.start});let l=B(this.cache,o,b=>b.start),d=s?null:new Uint8Array(t-e),u=0,f=o,m=[];if(l!==-1){for(let b=l;b<this.cache.length;b++){let w=this.cache[b];if(w.start>=i)break;if(w.end<=o)continue;let k=Math.max(o,w.start),P=Math.min(i,w.end);if(h(k<=P),f<k&&m.push({start:f,end:k}),f=P,d){let S=Math.max(e,w.start),_=Math.min(t,w.end);if(S<_){let C=S-e;d.set(w.bytes.subarray(S-w.start,_-w.start),C),C===u&&(u=_-e)}}w.age=this.nextAge++}f<i&&m.push({start:f,end:i})}else m.push({start:o,end:i});if(d&&u>=d.length&&(s={bytes:d,view:z(d),offset:e}),m.length===0)return h(s),s;let{promise:p,resolve:g,reject:x}=Z(),y=[];for(let b of m){let w=Math.max(e,b.start),k=Math.min(t,b.end);w===b.start&&k===b.end?y.push(b):w<k&&y.push({start:w,end:k})}for(let b of m){let w=d&&{start:e,bytes:d,holes:y,resolve:g,reject:x},k=!1;for(let P of this.workers)if(en(b.start-131072,b.start,P.currentPos,P.targetPos)){P.targetPos=Math.max(P.targetPos,b.end),k=!0,w&&!P.pendingSlices.includes(w)&&P.pendingSlices.push(w),P.running||this.runWorker(P);break}if(!k){let P=this.createWorker(b.start,b.end);w&&(P.pendingSlices=[w]),this.runWorker(P)}}return s||(h(d),s=p.then(b=>({bytes:b,view:z(b),offset:e}))),s}createWorker(e,t){let n={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(n);this.workers.length>this.options.maxWorkerCount;){let o=0,i=this.workers[0];for(let s=1;s<this.workers.length;s++){let a=this.workers[s];a.age<i.age&&(o=s,i=a)}if(i.running&&i.pendingSlices.length>0)break;i.aborted=!0,this.workers.splice(o,1)}return n}runWorker(e){h(!e.running),h(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(n=>n.reject(t)),e.pendingSlices.length=0;else throw t})}supplyWorkerData(e,t){h(!e.aborted);let n=e.currentPos,o=n+t.length;this.insertIntoCache({start:n,end:o,bytes:t,view:z(t),age:this.nextAge++}),e.currentPos+=t.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let i=0;i<e.pendingSlices.length;i++){let s=e.pendingSlices[i],a=Math.max(n,s.start),c=Math.min(o,s.start+s.bytes.length);a<c&&s.bytes.set(t.subarray(a-n,c-n),a-s.start);for(let l=0;l<s.holes.length;l++){let d=s.holes[l];n<=d.start&&o>d.start&&(d.start=o),d.end<=d.start&&(s.holes.splice(l,1),l--)}s.holes.length===0&&(s.resolve(s.bytes),e.pendingSlices.splice(i,1),i--)}for(let i=0;i<this.workers.length;i++){let s=this.workers[i];e===s||s.running||en(n,o,s.currentPos,s.targetPos)&&(this.workers.splice(i,1),i--)}}forgetWorker(e){let t=this.workers.indexOf(e);h(t!==-1),this.workers.splice(t,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=B(this.cache,e.start,n=>n.start)+1;if(t>0){let n=this.cache[t-1];if(n.end>=e.end)return;if(n.end>e.start){let o=new Uint8Array(e.end-n.start);o.set(n.bytes,0),o.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=o,n.view=z(o),n.end=e.end,t--,e=n}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let n=t+1;n<this.cache.length;n++){let o=this.cache[n];if(e.end<=o.start)break;if(e.end>=o.end){this.cache.splice(n,1),this.currentCacheSize-=o.bytes.length,n--;continue}let i=new Uint8Array(o.end-e.start);i.set(e.bytes,0),i.set(o.bytes,o.start-e.start),this.currentCacheSize-=e.end-o.start,e.bytes=i,e.view=z(i),e.end=o.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let n=0,o=this.cache[0];for(let i=1;i<this.cache.length;i++){let s=this.cache[i];s.age<o.age&&(n=i,o=s)}if(this.currentCacheSize-o.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(n,1),this.currentCacheSize-=o.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}};tn();var ee=class{get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(t=>!(t instanceof ae)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof ft))throw new TypeError("options.source must be a Source.");if(e.source._disposed)throw new Error("options.source must not be disposed.");this._formats=e.formats,this._source=e.source,this._reader=new Ln(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw new Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),h(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(t=>t.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(t=>t.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(t=>t.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(t=>t.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){this._disposed||(this._disposed=!0,this._source._disposed=!0,this._source._dispose())}[Symbol.dispose](){this.dispose()}},q=class extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}};var Ln=class{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new q;if(this.fileSize!==null&&e+t>this.fileSize)return null;let n=e+t,o=this.source._read(e,n);return o instanceof Promise?o.then(i=>i?new Dt(i.bytes,i.view,i.offset,e,n):null):o?new Dt(o.bytes,o.view,o.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new q;if(this.fileSize!==null)return this.requestSlice(e,Ze(this.fileSize-e,t,n));{let o=this.requestSlice(e,n),i=s=>{if(s)return s;let a=l=>(h(l!==null),this.requestSlice(e,Ze(l-e,t,n))),c=this.source._retrieveSize();return c instanceof Promise?c.then(a):a(c)};return o instanceof Promise?o.then(i):i(o)}}},Dt=class r{constructor(e,t,n,o,i){this.bytes=e,this.view=t,this.offset=n,this.start=o,this.end=i,this.bufferPos=o-n}static tempFromBytes(e){return new r(e,z(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new r(this.bytes,this.view,this.offset,e,e+t)}},re=(r,e)=>{if(r.filePos<r.start||r.filePos+e>r.end)throw new RangeError(`Tried reading [${r.filePos}, ${r.filePos+e}), but slice is [${r.start}, ${r.end}). This is likely an internal error, please report it alongside the file that caused it.`)},E=(r,e)=>{re(r,e);let t=r.bytes.subarray(r.bufferPos,r.bufferPos+e);return r.bufferPos+=e,t},A=r=>(re(r,1),r.view.getUint8(r.bufferPos++)),Vt=(r,e)=>{re(r,2);let t=r.view.getUint16(r.bufferPos,e);return r.bufferPos+=2,t},W=r=>{re(r,2);let e=r.view.getUint16(r.bufferPos,!1);return r.bufferPos+=2,e},He=r=>{re(r,3);let e=Ye(r.view,r.bufferPos,!1);return r.bufferPos+=3,e},pr=r=>{re(r,2);let e=r.view.getInt16(r.bufferPos,!1);return r.bufferPos+=2,e},Me=(r,e)=>{re(r,4);let t=r.view.getUint32(r.bufferPos,e);return r.bufferPos+=4,t},v=r=>{re(r,4);let e=r.view.getUint32(r.bufferPos,!1);return r.bufferPos+=4,e},ut=r=>{re(r,4);let e=r.view.getUint32(r.bufferPos,!0);return r.bufferPos+=4,e},Ee=r=>{re(r,4);let e=r.view.getInt32(r.bufferPos,!1);return r.bufferPos+=4,e},jc=r=>{re(r,4);let e=r.view.getInt32(r.bufferPos,!0);return r.bufferPos+=4,e},gi=(r,e)=>{let t,n;return e?(t=Me(r,!0),n=Me(r,!0)):(n=Me(r,!1),t=Me(r,!1)),n*4294967296+t},ne=r=>{let e=v(r),t=v(r);return e*4294967296+t},Fs=r=>{let e=Ee(r),t=v(r);return e*4294967296+t},Ks=r=>{let e=ut(r);return jc(r)*4294967296+e},Rs=r=>{re(r,4);let e=r.view.getFloat32(r.bufferPos,!1);return r.bufferPos+=4,e},bn=r=>{re(r,8);let e=r.view.getFloat64(r.bufferPos,!1);return r.bufferPos+=8,e},L=(r,e)=>{re(r,e);let t="";for(let n=0;n<e;n++)t+=String.fromCharCode(r.bytes[r.bufferPos++]);return t};var Hn=class{count=0};var pa={extension:{type:Cr.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await import("./browserAll-5AZHDDG6.js")}};var ha={extension:{type:Cr.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await import("./webworkerAll-QKIC5O27.js")}};var qn;function ga(r){return qn!==void 0||(qn=(()=>{let e={stencil:!0,failIfMajorPerformanceCaveat:r??Ar.defaultOptions.failIfMajorPerformanceCaveat};try{if(!Kt.get().getWebGLRenderingContext())return!1;let n=Kt.get().createCanvas().getContext("webgl",e),o=!!n?.getContextAttributes()?.stencil;if(n){let i=n.getExtension("WEBGL_lose_context");i&&i.loseContext()}return n=null,o}catch{return!1}})()),qn}var Gn;async function xa(r={}){return Gn!==void 0||(Gn=await(async()=>{let e=Kt.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(r)).requestDevice(),!0}catch{return!1}})()),Gn}var ba=["webgl","webgpu","canvas"];async function Ti(r){let e=[];r.preference?(e.push(r.preference),ba.forEach(i=>{i!==r.preference&&e.push(i)})):e=ba.slice();let t,n={};for(let i=0;i<e.length;i++){let s=e[i];if(s==="webgpu"&&await xa()){let{WebGPURenderer:a}=await import("./WebGPURenderer-RBOFXPL5.js");t=a,n={...r,...r.webgpu};break}else if(s==="webgl"&&ga(r.failIfMajorPerformanceCaveat??Ar.defaultOptions.failIfMajorPerformanceCaveat)){let{WebGLRenderer:a}=await import("./WebGLRenderer-NLGJGAXK.js");t=a,n={...r,...r.webgl};break}else if(s==="canvas")throw n={...r},new Error("CanvasRenderer is not yet implemented")}if(delete n.webgpu,delete n.webgl,!t)throw new Error("No available renderer for the current environment");let o=new t;return await o.init(n),o}var Wn=class extends Ei{constructor(e,t){let{text:n,resolution:o,style:i,anchor:s,width:a,height:c,roundPixels:l,...d}=e;super({...d}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=t,this.text=n??"",this.style=i,this.resolution=o??null,this.allowChildren=!1,this._anchor=new Ii({_onUpdate:()=>{this.onViewUpdate()}}),s&&(this.anchor=s),this.roundPixels=l??!1,a!==void 0&&(this.width=a),c!==void 0&&(this.height=c)}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}set text(e){e=e.toString(),this._text!==e&&(this._text=e,this.onViewUpdate())}get text(){return this._text}set resolution(e){this._autoResolution=e===null,this._resolution=e,this.onViewUpdate()}get resolution(){return this._resolution}get style(){return this._style}set style(e){e||(e={}),this._style?.off("update",this.onViewUpdate,this),e instanceof this._styleClass?this._style=e:this._style=new this._styleClass(e),this._style.on("update",this.onViewUpdate,this),this.onViewUpdate()}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(e){this._setWidth(e,this.bounds.width)}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(e){this._setHeight(e,this.bounds.height)}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this.bounds.width,e.height=Math.abs(this.scale.y)*this.bounds.height,e}setSize(e,t){typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,this.bounds.width),t!==void 0&&this._setHeight(t,this.bounds.height)}containsPoint(e){let t=this.bounds.width,n=this.bounds.height,o=-t*this.anchor.x,i=0;return e.x>=o&&e.x<=o+t&&(i=-n*this.anchor.y,e.y>=i&&e.y<=i+n)}onViewUpdate(){this.didViewUpdate||(this._didTextUpdate=!0),super.onViewUpdate()}destroy(e=!1){super.destroy(e),this.owner=null,this._bounds=null,this._anchor=null,(typeof e=="boolean"?e:e?.style)&&this._style.destroy(e),this._style=null,this._text=null}get styleKey(){return`${this._text}:${this._style.styleKey}:${this._resolution}`}};function ya(r,e){let t=r[0]??{};return(typeof t=="string"||r[1])&&(_i(Ai,`use new ${e}({ text: "hi!", style }) instead`),t={text:t,style:r[1]}),t}var vr=class extends Wn{constructor(...e){let t=ya(e,"Text");super(t,Fi),this.renderPipeId="text",t.textureStyle&&(this.textureStyle=t.textureStyle instanceof fo?t.textureStyle:new fo(t.textureStyle))}updateBounds(){let e=this._bounds,t=this._anchor,n=0,o=0;if(this._style.trim){let{frame:i,canvasAndContext:s}=ho.getCanvasAndContext({text:this.text,style:this._style,resolution:1});ho.returnCanvasAndContext(s),n=i.width,o=i.height}else{let i=Di.measureText(this._text,this._style);n=i.width,o=i.height}e.minX=-t._x*n,e.maxX=e.minX+n,e.minY=-t._y*o,e.maxY=e.minY+o}};Ci.add(pa,ha);var Ta=r=>{let[e,t,n]=r,[o,i]=e,[s,a]=t,c=n*Math.PI/180,l=Math.cos(c),d=Math.sin(c);return[l*s,d*s,-d*a,l*a,o,i]},wa=([r,e,t,n,o,i])=>new uo(r,e,t,n,o,i);var ka=(r,e)=>{let[t,n,o,i,s,a]=r,[c,l,d,u,f,m]=e;return[t*c+o*l,n*c+i*l,t*d+o*u,n*d+i*u,t*f+o*m+s,n*f+i*m+a]},Sa=[1,0,0,1,0,0];var Aa=ic(Pa(),1);var Ca=`
|
|
2363
2363
|
in vec2 aPosition;
|
|
2364
2364
|
varying vec2 _uv; // gl-transition
|
|
2365
2365
|
uniform mat3 projectionMatrix;
|
|
@@ -2412,7 +2412,7 @@ vec4 transition(vec2 uv) {
|
|
|
2412
2412
|
vec2 uv = vTextureCoord.xy;
|
|
2413
2413
|
gl_FragColor = transition(vTextureCoord);
|
|
2414
2414
|
}
|
|
2415
|
-
`;function _a({name:r,renderer:e}){let t=Aa.default.find(c=>c.name===r),n=new ht,o=new $t,i=new Ir({}),s=new Ir({}),a=new go({glProgram:new po({vertex:Ca,fragment:Ia(t.glsl)}),resources:{from:i,to:s,uniforms:{...wi.basics,...wi.custom(t)}}});return n.filters=[a],{render({width:c,height:l,from:d,to:u,progress:f}){return(n.width!==c||n.height!==l)&&(n.setSize({width:c,height:l}),o.source.resize(c,l)),i.resource=d,s.resource=u,i.update(),s.update(),a.resources.uniforms.uniforms.progress=f,e.render({container:n,target:o,clear:!1,width:c,height:l}),o}}}var jn=class{pixi;static async setup(){let e=await Ti({width:1920,height:1080,preference:"webgl",background:"black",preferWebGLVersion:2}),t=new mo;return t.interactive=!0,new this({renderer:e,stage:t})}constructor(e){this.pixi=e}#e=new Map;#t=new Map;async composite(e){let{stage:t,renderer:n}=this.pixi;this.#l(this.#c(e));let{dispose:o}=await this.#r(e,t);n.render(t);let i=new VideoFrame(n.canvas,{timestamp:0,duration:0});return o(),i}getActiveObject(e){return this.#t.get(e)}async#r(e,t){if(Array.isArray(e)){e.reverse();let n=[];for(let o of e){let i=await this.#r(o,t);n.push(i.dispose)}return{dispose:()=>n.forEach(o=>o())}}switch(e.kind){case"text":return this.#n(e,t);case"image":return this.#i(e,t);case"transition":return this.#s(e,t);case"gap":return this.pixi?.renderer.clear(),{dispose:()=>{}};default:return console.warn("Unknown layer kind",e.kind),{dispose:()=>{}}}}#n(e,t){let n=this.#a(e);return this.#o(n,e.matrix),t.addChild(n),{dispose:()=>{}}}#i(e,t){let n=$t.from(e.frame),o=this.#a(e);return o.texture=n,this.#o(o,e.matrix),t.addChild(o),{dispose:()=>{n.destroy(!0),e.frame.close()}}}#s({from:e,to:t,progress:n,name:o},i){let a=(this.#e.get(o)??(this.#e.set(o,_a({name:"circle",renderer:this.pixi.renderer})),this.#e.get(o))).render({from:e,to:t,progress:n,width:e.displayWidth,height:e.displayHeight}),c=new ht(a);return i.addChild(c),{dispose:()=>c.destroy(!1)}}#o(e,t){if(!t)return;let n=wa(t);e.setFromMatrix(n)}#a(e){let t=this.#t.get(e.id);if(t)return t;switch(e.kind){case"text":{let n=new vr({text:e.content,style:e.style});return n.onmouseenter=()=>console.log("enter text"),this.#t.set(e.id,n).get(e.id)}case"image":{let n=new ht;return n.onmouseenter=()=>console.log("enter"),this.#t.set(e.id,n).get(e.id)}}}#c(e){let t=new Set,n=o=>{if(Array.isArray(o))for(let i of o)n(i);else t.add(o.id)};return n(e),t}#l(e){for(let t of this.#t.keys())e.has(t)||(this.#t.get(t).destroy(!0),this.#t.delete(t))}};var Ea=r=>jr.host(e=>({async world(){r.count++}}));async function ce(r){return r instanceof Blob?new kr(r):new Sr(r)}var $n=class{machina;thread;compositor;static async setup(e){let t=new Hn,n=await jr.thread({label:"OmnitoolDriver",workerUrl:e?.workerUrl??"/node_modules/@omnimedia/omnitool/x/driver/driver.worker.bundle.min.js",setupHost:Ea(t)}),o=await jn.setup();return new this(t,n,o)}constructor(e,t,n){this.machina=e,this.thread=t,this.compositor=n}async hello(){return this.thread.work.hello()}async getAudioDuration(e){let n=await new ee({source:await ce(e),formats:ie}).getPrimaryAudioTrack();if(!n)throw new Error("primary audio track not found");return await n.computeDuration()}async getVideoDuration(e){return await(await new ee({source:await ce(e),formats:ie}).getPrimaryVideoTrack())?.computeDuration()}decodeVideo(e){let t=null,{port1:n,port2:o}=new MessageChannel,i=new TransformStream({async transform(s,a){let c=await e.onFrame?.(s)??s;t?.close(),a.enqueue(c),t=c}});return this.thread.work.decodeVideo[yt]({transfer:[i.writable,o]})({source:e.source,cancel:o,video:i.writable,start:e.start,end:e.end}),{readable:i.readable,cancel(){n.postMessage("close"),n.close()}}}decodeAudio(e){let t=new TransformStream,{port1:n,port2:o}=new MessageChannel;return this.thread.work.decodeAudio[yt]({transfer:[t.writable,o]})({source:e.source,cancel:o,audio:t.writable,start:e.start,end:e.end}),{readable:t.readable,cancel(){n.postMessage("close"),n.close()}}}encode({audio:e,video:t,config:n}){let{readable:o,writable:i}=new TransformStream,s=[e,t,i].filter(Er.happy),a=this.thread.work.encode[yt]({transfer:s})({audio:e,video:t,config:n,writable:i});return{readable:o,done:a}}async composite(e){return await this.compositor.composite(e)}};var M;(function(r){r[r.Sequence=0]="Sequence",r[r.Stack=1]="Stack",r[r.Video=2]="Video",r[r.Audio=3]="Audio",r[r.Text=4]="Text",r[r.Gap=5]="Gap",r[r.Spatial=6]="Spatial",r[r.Transition=7]="Transition",r[r.TextStyle=8]="TextStyle"})(M||(M={}));var Kn;(function(r){r[r.Crossfade=0]="Crossfade"})(Kn||(Kn={}));var Xn=class{datafile;duration=0;hasVideo=!1;hasAudio=!1;constructor(e){this.datafile=e}static async analyze(e){let t=new this(e),n=await this.duration(e.url)*1e3;t.duration=n;let{video:o,audio:i}=await this.#e(e.url);return t.hasAudio=i,t.hasVideo=o,t}static async duration(e){let n=await new ee({formats:ie,source:await ce(e)}).computeDuration();return Number(n.toFixed(5))}static async#e(e){let t=new ee({formats:ie,source:await ce(e)});return{audio:!!await t.getPrimaryAudioTrack(),video:!!await t.getPrimaryVideoTrack()}}};var Qn=class{#e=new Fr;async store(e){let t=await Xn.analyze(e),{hash:n}=t.datafile.checksum,{filename:o,bytes:i,url:s,blob:a}=t.datafile;if(this.#e.has(n)){let c=this.#e.require(n);c.filename=o}else this.#e.set(n,{kind:"media",filename:o,bytes:i,url:s,blob:a,duration:t.duration});return t}require(e){return this.#e.require(e)}};var Yn=class r{videoTrack;options;#e;#t=new Map;#r=[0,0];constructor(e,t){this.videoTrack=e,this.options=t,this.#e=new fr(e,t.canvasSinkOptions)}static async init(e,t){let o=await new ee({formats:ie,source:await ce(e)}).getPrimaryVideoTrack();if(o)return new r(o,{frequency:t.frequency??1,canvasSinkOptions:t.canvasSinkOptions??{width:80,height:50,fit:"fill"},onChange:t.onChange,onPlaceholders:t.onPlaceholders});throw new Error("Source has no video track")}set frequency(e){e!==this.options.frequency&&(this.options.frequency=e,this.#c())}get frequency(){return this.options.frequency}#n([e,t],n=1){let o=t-e;return[e-o*n,t+o*n]}async#i(){let[e,t]=this.#r,n=new Set,o=await this.videoTrack.computeDuration();for(let i=Math.max(0,e);i<=t;i+=this.options.frequency)i>=0&&i<=o&&n.add(i);this.options.onPlaceholders?.([...n])}async#s(){let[e,t]=this.#r,n=new Set,o=await this.videoTrack.computeDuration();for(let c=Math.max(0,e);c<=t;c+=this.options.frequency)c>=0&&c<=o&&n.add(c);let i=[...n].filter(c=>!this.#t.has(c)),s=0;for await(let c of this.#e.canvasesAtTimestamps(i))if(c){let l=i[s++];this.#t.set(l,c)}for(let c of this.#t.keys())n.has(c)||this.#t.delete(c);let a=[...this.#t.entries()].map(([c,l])=>({time:c,canvas:l}));this.options.onChange(a)}set range(e){let[t,n]=e,o=n-t,[i,s]=this.#r,a=i+o,c=s-o,l=t<a,d=n>c;!l&&!d||(this.#r=this.#n(e,2),this.#c())}#o=null;#a=!1;async#c(){if(this.#i(),this.#o){this.#a=!0;return}this.#o=this.#s(),await this.#o,this.#o=null,this.#a&&(this.#a=!1,await this.#c())}getThumbnail(e){return this.#t.get(e)}};function Fa(r,e){let t=typeof window<"u"&&window.devicePixelRatio||1,n=document.createElement("canvas");n.width=e.width*t,n.height=e.height*t,n.style.width=`${e.width}px`,n.style.height=`${e.height}px`;let o=n.getContext("2d");if(!o)return n;o.scale(t,t),o.fillStyle=e.color;let i=e.height/2,s=Math.max(1,e.width),a=r.length/s;for(let c=0;c<s;c++){let l=Math.floor(c*a),d=Math.max(l+1,Math.floor((c+1)*a)),u=0;for(let m=l;m<d&&m<r.length;m++)r[m]>u&&(u=r[m]);let f=u*e.height;o.fillRect(c,i-f/2,1,f)}return n}var ki=[2048,1024,512,256,128,64,32];async function Da(r,e){let t=await r.getAudioDuration(e)??0,n=r.decodeAudio({source:e}).readable,o=ki[ki.length-1],i=[],s=0,a=0,c=0;for await(let u of n){c||=u.sampleRate;let f=u.numberOfFrames,m=new Float32Array(f);u.copyTo(m,{planeIndex:0});for(let p=0;p<m.length;p++){let g=Math.abs(m[p]);g>s&&(s=g),a++,a>=o&&(i.push(s),s=0,a=0)}u.close()}a>0&&i.push(s);let l=new Float32Array(i),d=ki.map(u=>{let f=Math.max(1,Math.round(u/o)),m=f===1?l:Kc(l,f);return{samplesPerPeak:u,peaks:m,peaksPerSecond:c>0?c/u:0}});return{duration:t,levels:d}}function Kc(r,e){let t=new Float32Array(Math.ceil(r.length/e));for(let n=0;n<t.length;n++){let o=0,i=n*e,s=Math.min(i+e,r.length);for(let a=i;a<s;a++)r[a]>o&&(o=r[a]);t[n]=o}return t}var Xc=4096,Zn=class r{#e=new Map;#t=[0,0];#r=[0,0];#n;#i;#s;#o=!1;color;duration;tileSize;tileHeight;preloadMargin;constructor(e,t,n){this.#i=e,this.duration=t,this.tileSize=n.tileSize??1,this.#n=n.zoom??(n.tileWidth??256)/this.tileSize,this.tileHeight=n.tileHeight??96,this.preloadMargin=n.preloadMargin??2,this.color=n.color??"rgb(3, 148, 129)",this.#s=n.onChange}static async init(e,t,n={}){let{duration:o,levels:i}=await Da(e,t);return new r(i,o,n)}set zoom(e){let t=Math.max(1,e);t!==this.#n&&(this.#n=t,this.#e.clear(),this.#c())}get zoom(){return this.#n}get range(){return this.#r}#a([e,t],n=1){let o=t-e;return[Math.max(0,e-o*n),Math.min(this.duration,t+o*n)]}set range(e){this.#r=e;let[t,n]=e,o=n-t,[i,s]=this.#t,a=i>0,c=s<this.duration,l=!a||t>=i+o,d=!c||n<=s-o;l&&d||(this.#t=this.#a(e,this.preloadMargin),this.#c())}#c(){this.#o||(this.#o=!0,queueMicrotask(()=>{this.#o=!1,this.#l()}))}#l(){let[e,t]=this.#t,n=new Set,o=this.#d(),i=Math.max(0,Math.floor(e/this.tileSize)*this.tileSize),s=Math.min(this.duration,t);for(let a=i;a<=s;a+=this.tileSize)n.add(a);for(let a of n)if(!this.#e.has(a)){let c=Math.min(a+this.tileSize,this.duration);this.#e.set(a,this.#u(a,c,o))}for(let a of this.#e.keys())n.has(a)||this.#e.delete(a);this.#p()}#u(e,t,n){let o=this.#f(n,e,t);return{startTime:e,endTime:t,peaks:o,canvas:Fa(o,{width:this.#m(e,t),height:this.tileHeight,color:this.color})}}#d(){return this.#i.find(e=>e.peaksPerSecond>=this.#n)??this.#i[this.#i.length-1]}#f(e,t,n){if(!e.peaksPerSecond)return new Float32Array;let o=Math.max(0,Math.floor(t*e.peaksPerSecond)),i=Math.max(o+1,Math.min(e.peaks.length,Math.ceil(n*e.peaksPerSecond)));return e.peaks.slice(o,i)}#m(e,t){return Math.min(Xc,Math.max(1,Math.ceil((t-e)*this.#n)))}#p(){this.#s&&this.#s([...this.#e.values()].sort((e,t)=>e.startTime-t.startTime))}getTiles(){return this.#e}};var U=r=>r;var qt=r=>r;var Ra=()=>{let r=!1,e=qt(60),t=1e3/e,n=0,o=0,i=xt(),s=null,a=l=>{if(requestAnimationFrame(a),!!r)for(n=l;l-o>=t;)o+=t,s?.(),s=null,i()};async function*c(){for(n=performance.now(),o=n,requestAnimationFrame(a);;)await new Promise(l=>s=l),yield}return{play(){r||(r=!0,n=performance.now(),o=n)},pause(){r=!1},setFPS(l){e=l,t=1e3/e},isPlaying(){return r},ticks:c,onTick:i}},Ma=async(r,e)=>{let t=U(1e3/r.fps),n=r.duration/1e3,o=Math.ceil(n*r.fps);for(let i=0;i<o;i++){let s=U(i*t);await e(s,i)}};function Oa(r){return"duration"in r}function za(r){let e=[],t=new Map(r.timeline.items.map(n=>[n.id,n]));return Si(r.timeline.rootId,t,r.from,{sequence:()=>{},stack:()=>{},video:(n,o,i)=>e.push({item:n,localTime:o,ancestors:i}),text:(n,o,i)=>e.push({item:n,localTime:o,ancestors:i}),audio:(n,o,i)=>e.push({item:n,localTime:o,ancestors:i})}),e}function Ua(r,e,t){let n=Sa;for(let o of e)n=Ba(r,o,n);return Ba(r,t,n)}function Ba(r,e,t){if("spatialId"in e&&e.spatialId){let n=r.get(e.spatialId);if(n?.enabled){let o=Ta(n.transform);return ka(o,t)}}return t}function Si(r,e,t,n,o=[]){let i=e.get(r);if(i)switch(i.kind){case M.Stack:n.stack(i,t,o);for(let s of i.childrenIds)Si(s,e,t,n,[...o,i]);break;case M.Sequence:{n.sequence(i,t,o);let s=U(0);for(let a of i.childrenIds){let c=e.get(a);if(!c||!Oa(c))continue;let l=U(s+c.duration);if(t>=l){s=l;continue}let d=U(Math.max(0,t-s));Si(a,e,d,n,[...o,i]),s=l}break}case M.Video:n.video(i,t,o);break;case M.Text:n.text(i,t,o);break;case M.Audio:n.audio(i,t,o);break}}function pe(r,e){let t=e.items.find(n=>n.id===r);if(!t)return U(0);switch(t.kind){case M.Sequence:{let n=t.childrenIds.map(i=>e.items.find(s=>s.id===i)).filter(Boolean),o=U(0);for(let i=0;i<n.length;i++){let s=n[i];if(s.kind===M.Transition){let a=n[i-1],c=n[i+1];if(a&&c&&a.kind!==M.Transition&&c.kind!==M.Transition){let l=pe(a.id,e),d=pe(c.id,e),u=Math.max(0,Math.min(s.duration,l,d));o=U(o-u)}continue}o=U(o+pe(s.id,e))}return o}case M.Stack:{let n=U(0);for(let o of t.childrenIds){let i=pe(o,e);i>n&&(n=i)}return n}default:return Oa(t)?t.duration:U(0)}}var Pr=r=>r;var Jn=class{resolveMedia;#e=new Map;constructor(e){this.resolveMedia=e}async getSink(e){let t=this.#e.get(e);if(t)return t.sink;let n=new ee({formats:ie,source:await ce(this.resolveMedia(e))}),o=await n.getPrimaryVideoTrack(),s=!!o&&await o.canDecode()&&o?new Ct(o):null;return this.#e.set(e,{input:n,sink:s}),s}};async function Na(r,e,t,n){let[o,i]=await Promise.all([t,n]),s=o.find(l=>l.kind==="image")?.frame,a=i.find(l=>l.kind==="image")?.frame,c=[...o.filter(l=>l.kind!=="image"),...i.filter(l=>l.kind!=="image")];return s&&a?[{id:r.id,kind:"transition",name:"circle",progress:e,from:s,to:a},...c]:c}async function Va(r,e,t,n){let o=Qc(r,e,t);if(!o)return[];let i=[...n,e];return o.isTransitioning?Na(o.transition,o.progress,ft(r,o.outgoing,o.outgoingTime,i),ft(r,o.incoming,o.incomingTime,i)):ft(r,o.item,o.localTime,i)}function Qc(r,e,t){let n=e.childrenIds.map(i=>r.items.get(i)).filter(i=>!!i),o=U(0);for(let i=0;i<n.length;i++){let s=n[i];if(s.kind===M.Transition)continue;let a=o,c=pe(s.id,r.timeline),l=U(a+c),d=n[i+1];if(!(d?.kind===M.Transition)){if(t<l)return{isTransitioning:!1,item:s,localTime:U(t-a)};o=l;continue}let f=d,m=n[i+2];if(!m||m.kind===M.Transition){o=l;continue}let p=pe(m.id,r.timeline),g=Math.max(0,Math.min(f.duration,c,p)),x=U(l-g);if(t<x)return{isTransitioning:!1,item:s,localTime:U(t-a)};if(t<l){let y=U(t-x),b=U(t-a);return{isTransitioning:!0,incoming:m,outgoing:s,outgoingTime:b,incomingTime:y,progress:g>0?y/g:1,transition:f}}o=x,i++}return null}async function ft(r,e,t,n){let o=Ua(r.items,n,e);switch(e.kind){case M.Stack:{let i=[...n,e];return(await Promise.all(e.childrenIds.map(a=>r.items.get(a)).filter(a=>!!a).map(a=>ft(r,a,t,i)))).flat()}case M.Sequence:return Va(r,e,t,n);case M.Video:{if(t<0||t>=e.duration)return[];let i=await r.videoSampler(e,t);return i?[{kind:"image",frame:i,matrix:o,id:e.id}]:[]}case M.Text:{if(t<0||t>=e.duration)return[];let i=e.styleId?r.items.get(e.styleId)?.style:void 0;return[{id:e.id,kind:"text",content:e.content,style:i,matrix:o}]}case M.Gap:return[{id:e.id,kind:"gap"}];default:return[]}}function La(r){return async(e,t)=>{let o=await(await r.getSink(e.mediaHash))?.getSample(t/1e3),i=o?.toVideoFrame();return o?.close(),i??void 0}}function eo(r,e){let t=new Jn(r),n=e??La(t);return{async sample(o,i){let s=new Map(o.items.map(c=>[c.id,c])),a=s.get(o.rootId);return a?ft({videoSampler:n,timeline:o,items:s},a,i,[]):[]}}}var Gt=class{driver;resolveMedia;timeline;#e=-1/0;#t=new Map;#r;constructor(e,t,n){this.driver=e,this.resolveMedia=t,this.timeline=n,this.#r=eo(this.resolveMedia,(o,i)=>{let s=Ha(i),a=this.#t.get(o.id);if(!a){let c=this.resolveMedia(o.mediaHash),l=Ha(U(o.start+o.duration));a=this.#n(c,s,l),this.#t.set(o.id,a)}return a.next(s)})}next(e){if(e<this.#e)throw new Error(`Forward-only cursor regression: ${e}ms < ${this.#e}ms`);return this.#e=e,this.#r.sample(this.timeline,e)}async cancel(){await Promise.all([...this.#t.values()].map(e=>e.cancel())),this.#t.clear()}#n(e,t,n){let o=this.driver.decodeVideo({source:e,start:t/1e6,end:n/1e6}),i=o.readable.getReader(),s=null,a=null,c=!1,l=async()=>{if(c)return null;let{done:d,value:u}=await i.read();if(d)return c=!0,null;let f=new VideoFrame(u);return u.close(),f};return{async next(d){if(s??=await l(),!!s)for(;;){a??=l();let u=await a;if(!u)return new VideoFrame(s);let f=s.timestamp??-1/0,m=u.timestamp??f;if(m<d){s.close(),s=u,a=null;continue}if(Math.abs(m-d)<Math.abs(f-d)){s.close(),s=u,a=null;continue}return new VideoFrame(s)}},async cancel(){let d=a;a=null,c=!0,(await d?.catch(()=>null))?.close(),s?.close(),s=null,o.cancel()}}}},Ha=r=>Math.round(r*1e3);async function qa(r,e,t){return(await Promise.all(e.map(async({item:o,localTime:i})=>{if(o.kind!==M.Audio)return;let s=await r.getSink(o.mediaHash);if(!s)return;let a=o.start+i,c=Pr((t-a)/1e3),l=s.samples(a/1e3),d=await l.next();if(d.done)return;let u=d.value,f=l.next();return{offset:c,gain:o.gain??1,get currentSample(){return u},timelineTime:()=>Pr(c+u.timestamp),output:()=>({sample:u,timestamp:c+u.timestamp,gain:o.gain??1}),advance:async()=>{let m=await f;return m.done?!1:(u=m.value,f=l.next(),!0)}}}))).filter(o=>!!o)}var to=class{resolveMedia;#e=new Map;constructor(e){this.resolveMedia=e}async getSink(e){let t=this.#e.get(e);if(t)return t.sink;let n=new ee({formats:ie,source:await ce(this.resolveMedia(e))}),o=await n.getPrimaryAudioTrack(),s=!!o&&await o.canDecode()&&o?new mr(o):null;return this.#e.set(e,{input:n,sink:s}),s}};function Ga(r){let e={index:0,stream:r[0],time:r[0].timelineTime()};for(let[t,n]of r.entries()){let o=n.timelineTime();o<e.time&&(e={time:o,stream:n,index:t})}return e}function ro(r){let e=new to(r);return{async*sampleAudio(t,n){let o=za({timeline:t,from:n}),i=await qa(e,o,n);for(;i.length>0;){let{stream:s,index:a}=Ga(i);yield s.output(),await s.advance()||i.splice(a,1)}}}}var no=class{driver;timeline;resolveMedia;audioSampler;seekVisualSampler;playVisualSampler=null;#e=U(0);#t=null;#r=Ra();onTick=this.#r.onTick;audioContext=new AudioContext({sampleRate:48e3});audioGain=this.audioContext.createGain();audioNodes=new Set;#n=null;constructor(e,t,n){this.driver=e,this.timeline=t,this.resolveMedia=n,this.audioGain.connect(this.audioContext.destination),this.audioGain.gain.value=.7**2,this.seekVisualSampler=eo(this.resolveMedia),this.audioSampler=ro(this.resolveMedia),this.#i()}update(e){this.timeline=e}get isPlaying(){return this.#r.isPlaying()}async#i(){for await(let e of this.#r.ticks()){let t=await this.playVisualSampler?.next(this.currentTime)??[];(await this.driver.composite(t)).close(),this.currentTime>=this.duration&&this.pause()}}async seek(e){return this.pause(),this.#e=e,await this.seekVisualSampler.sample(this.timeline,e)}async start(){if(!this.#r.isPlaying()){await this.audioContext.resume(),this.#e=this.currentTime,this.#t=this.audioContext.currentTime,this.#n?.abort(),this.#n=new AbortController;for(let e of this.audioNodes)e.stop();this.audioNodes.clear(),this.playVisualSampler=new Gt(this.driver,this.resolveMedia,this.timeline),this.#r.play(),this.#s(this.#n.signal,Pr(this.#e/1e3))}}pause(){this.#e=this.currentTime,this.#r.pause(),this.#n?.abort();for(let e of this.audioNodes)e.stop();this.audioNodes.clear(),this.playVisualSampler&&(this.playVisualSampler.cancel(),this.playVisualSampler=null)}get duration(){return pe(this.timeline.rootId,this.timeline)}get currentTime(){if(!this.#r.isPlaying()||this.#t===null)return this.#e;let e=(this.audioContext.currentTime-this.#t)*1e3;return U(this.#e+e)}setFps(e){this.#r.setFPS(e)}async#s(e,t){let n=this.audioContext;if(this.#t!==null)for await(let{sample:o,timestamp:i}of this.audioSampler.sampleAudio(this.timeline,U(t*1e3))){if(e.aborted||!this.#r.isPlaying())return;for(;i-(n.currentTime-this.#t+t)>.75;)await new Promise(c=>setTimeout(c,25));let s=n.createBufferSource();s.buffer=o.toAudioBuffer(),s.connect(this.audioGain),s.onended=()=>this.audioNodes.delete(s),this.audioNodes.add(s);let a=this.#t+i-t;a>=n.currentTime?s.start(a):s.start(n.currentTime,n.currentTime-a)}}};var oo=class{driver;canvas;playback;#e=null;#t=null;constructor(e,t,n){this.driver=e,this.playback=new no(e,n,t),this.canvas=e.compositor.pixi.renderer.canvas}async play(){await this.playback.start()}pause(){this.playback.pause()}seek(e){return this.#e=e,this.#t??=this.#r().finally(()=>this.#t=null)}setFPS(e){this.playback.setFps(qt(e))}get isSeeking(){return this.#t!==null}get isPlaying(){return this.playback.isPlaying}get duration(){return this.playback.duration}get currentTime(){return this.playback.currentTime}update(e){this.playback.update(e)}async#r(){for(;this.#e!==null;){let e=this.#e;this.#e=null;let t=await this.playback.seek(U(e));(await this.driver.composite(t)).close()}}};var mt=class{state;constructor(e){this.state=e}require(e){return e===void 0?void 0:this.state.timeline.items.find(n=>n.id===e)}get timeline(){return this.state.timeline}getId(){return he.toInteger(he.random())}#e(e){this.state.timeline=e(this.state.timeline)}register(e){this.#e(t=>({...t,items:[...t.items,e]}))}textStyle=e=>{let t={id:this.getId(),kind:M.TextStyle,style:e};return this.register(t),t};spatial=e=>{let t={id:this.getId(),kind:M.Spatial,transform:e,enabled:!0};return this.register(t),t};sequence=(...e)=>{let t={id:this.getId(),kind:M.Sequence,childrenIds:e.map(n=>n.id)};return this.register(t),t};stack=(...e)=>{let t={kind:M.Stack,id:this.getId(),childrenIds:e.map(n=>n.id)};return this.register(t),t};video=(e,t)=>{if(!e.hasVideo)throw new Error(`Video clip error: media "${e.datafile.filename}" has no video track.`);let n={kind:M.Video,id:this.getId(),mediaHash:e.datafile.checksum.hash,start:t?.start??0,duration:t?.duration??e.duration};return this.register(n),n};audio=(e,t)=>{if(!e.hasAudio)throw new Error(`Audio clip error: media "${e.datafile.filename}" has no audio track.`);let n={kind:M.Audio,id:this.getId(),mediaHash:e.datafile.checksum.hash,start:t?.start??0,duration:t?.duration??e.duration,gain:t?.gain??1};return this.register(n),n};text=(e,t)=>{let n={id:this.getId(),content:e,kind:M.Text,duration:t?.duration??2e3};return t?.styles&&(n.styleId=this.textStyle(t.styles).id),this.register(n),n};gap=e=>{let t={id:this.getId(),kind:M.Gap,duration:e};return this.register(t),t};transition={crossfade:e=>{let t={id:this.getId(),kind:M.Transition,effect:Kn.Crossfade,duration:e};return this.register(t),t}};transform=e=>{let t=[e?.position?.[0]??0,e?.position?.[1]??0],n=[e?.scale?.[0]??1,e?.scale?.[1]??1],o=e?.rotation??0;return[t,n,o]};addChildren(e,...t){this.#e(n=>(n.items.find(({id:i})=>i===e.id).childrenIds.push(...t.map(i=>i.id)),n))}set=(e,t)=>{this.#e(n=>({...n,items:n.items.map(o=>o.id===e?{...o,...t}:o)}))}};var io=class{#e;#t;constructor(e={}){this.#e=e.chunkFrames??1024,this.#t=e.clamp??!0}async*mix(e){let t=this.#e,n=null,o=null,i=[],s=0,a=0;for await(let c of e){if(o===null)o=c.planes.length,n=c.sampleRate;else{if(c.planes.length!==o)throw new Error("Channel count changed");if(c.sampleRate!==n)throw new Error("Sample rate changed")}let l=Math.round(c.timestamp*n),d=c.planes[0]?.length??0;for(;s+t<=l;)yield this.#r(i,s,o,n),s+=t;i.push({startFrame:l,endFrame:l+d,data:c.planes}),a=Math.max(a,l+d)}if(o!==null&&n!==null)for(;s<a;)yield this.#r(i,s,o,n),s+=t}#r(e,t,n,o){let i=this.#e,s=new Float32Array(n*i),a=t+i;for(let c=0;c<n;c++){let l=c*i,d=s.subarray(l,l+i);for(let u of e){let f=u.data[c];if(!f)continue;let m=Math.max(t,u.startFrame),p=Math.min(a,u.endFrame);if(m>=p)continue;let g=m-t,x=m-u.startFrame,y=p-m;for(let b=0;b<y;b++)d[g+b]+=f[x+b]}if(this.#t)for(let u=0;u<i;u++){let f=d[u];d[u]=f<-1?-1:f>1?1:f}}for(let c=e.length-1;c>=0;c--)e[c].endFrame<=a&&e.splice(c,1);return{planar:s,sampleRate:o,channels:n,frames:i,startFrame:t}}};var Yc=(r,e,t)=>{if(e===t)return r;let n=t/e,o=Math.max(1,Math.round(r.length*n)),i=new Float32Array(o);for(let s=0;s<o;s++){let a=s/n,c=Math.floor(a),l=Math.min(c+1,r.length-1),d=a-c;i[s]=r[c]*(1-d)+r[l]*d}return i},Wa=(r,e)=>{let t=r.numberOfChannels,n=new Array(t),o=0;for(let i=0;i<t;i++){let s=new Float32Array(r.numberOfFrames);r.copyTo(s,{planeIndex:i,format:"f32-planar"});let a=Yc(s,r.sampleRate,e);n[i]=a,o=a.length}return{data:n,frames:o}};var ja=(r,e)=>{if(e!==1)for(let t of r)for(let n=0;n<t.length;n++)t[n]*=e};function $a({timeline:r,resolveMedia:e}){let t=new io,n=Zc(r,e),o=new TransformStream,i=o.writable.getWriter();async function s(){for await(let a of t.mix(n)){let c=new AudioData({format:"f32-planar",sampleRate:a.sampleRate,numberOfFrames:a.frames,numberOfChannels:a.channels,timestamp:Math.round(a.startFrame/a.sampleRate*1e6),data:new Float32Array(a.planar)});await i.write(c)}await i.close()}return s(),o.readable}async function*Zc(r,e){let t=ro(e);for await(let{sample:n,timestamp:o,gain:i}of t.sampleAudio(r,U(0))){let{data:s}=Wa(n,48e3);ja(s,i),yield{planes:s,sampleRate:48e3,timestamp:o},n.close()}}function Ka({timeline:r,fps:e,driver:t,resolveMedia:n}){let o=new TransformStream,i=o.writable.getWriter(),s=new Gt(t,n,r),a=1/e,c=pe(r.rootId,r);async function l(){await Ma({fps:e,duration:c},async(d,u)=>{let f=await s.next(d),m=await t.composite(f),p=new VideoFrame(m,{timestamp:Math.round(u*a*1e6),duration:Math.round(a*1e6)});await i.write(p),m.close()}),await i.close()}return l(),o.readable}function Xa(r){let e=$a({...r}),t=Ka({...r});return r.driver.encode({video:t,audio:e,config:{audio:{codec:"opus",bitrate:128e3},video:{codec:"vp9",bitrate:1e6}}})}var so=class{driver;resources=new Qn;constructor(e){this.driver=e}load=async e=>Object.fromEntries(await Promise.all(Object.entries(e).map(async([t,n])=>[t,await this.resources.store(await n)])));timeline=e=>{let t=new mt({timeline:{format:"timeline",info:"https://omniclip.app/",version:0,items:[],rootId:0}}),n=e(t);return t.timeline.rootId=n.id,t.timeline};playback=async e=>new oo(this.driver,t=>this.resources.require(t).url,e);render=async(e,t=30)=>Xa({timeline:e,fps:qt(t),driver:this.driver,resolveMedia:n=>this.resources.require(n).url})};var ao=class{data;bytes;hash;nickname;constructor(e,t,n,o){this.data=e,this.bytes=t,this.hash=n,this.nickname=o}static async make(e){let t=new Uint8Array(e),n=new Uint8Array(await crypto.subtle.digest("SHA-256",t)),o=_r.fromBytes(n),i=Ri.sigil.fromBytes(n);return new this(e,n,o,i)}};var co=class{url;bytes;blob;filename;checksum;constructor(e,t,n,o,i){this.url=e,this.bytes=t,this.blob=n,this.filename=o,this.checksum=i}static async make(e,t){let n=await e.arrayBuffer(),o=new Uint8Array(n),i=await ao.make(o),s=t??i.nickname,a=URL.createObjectURL(e);return new this(a,o,e,s,i)}static async load(e){}};async function Ya(r,e,t){let n=t.querySelector(".play"),o=t.querySelector(".stop"),i=t.querySelector(".scrub"),s=t.querySelector(".playhead"),a=t.querySelector(".timecode"),c=t.querySelector(".player-canvas"),l=new mt({timeline:r}),d=await e.playback(r);c.replaceChildren(d.canvas),n.disabled=!1,o.disabled=!1,n.addEventListener("click",()=>d.play()),o.addEventListener("click",()=>d.pause()),i.max=String(Math.ceil(d.duration));let u=!1;d.playback.onTick.on(()=>m(d.currentTime,d.duration));let f=(p,g)=>{a.textContent=`${Qa(p)} / ${Qa(g)}`};i.addEventListener("input",async()=>{u=!0;let p=Math.max(0,Math.min(+i.value,d.duration));f(p,d.duration),await d.seek(p)}),i.addEventListener("change",async()=>{u=!1;let p=Math.max(0,Math.min(+i.value,d.duration));await d.seek(p)});let m=(p,g)=>{let x=Math.max(0,Math.min(p,g));u||(i.value=String(Math.round(x)));let y=g?x/g*100:0;s.style.left=`${y}%`,f(x,g)};d.update(l.timeline)}function Qa(r){let e=Math.max(0,r),t=Math.floor(e/1e3),n=Math.floor(t/60),o=t%60,i=Math.floor(e%1e3);return`${n}:${String(o).padStart(2,"0")}.${String(i).padStart(3,"0")}`}async function Ja(r,e,t){let n=t.querySelector(".waveform-canvas"),o=t.querySelector(".width");n.replaceChildren(),n.style.position="relative",n.style.height="96px",n.style.overflow="hidden";let i=await Zn.init(r,e,{tileHeight:96,onChange:()=>s()}),s=()=>{let a=+o.value,c=Za(a,i.duration);i.zoom=c,n.style.width=`${a}px`,n.replaceChildren(...[...i.getTiles().values()].map(l=>(l.canvas.style.position="absolute",l.canvas.style.top="0",l.canvas.style.left=`${l.startTime*Za(a,i.duration)}px`,l.canvas.style.height="100%",l.canvas)))};o.oninput=s,i.range=[0,i.duration]}function Za(r,e){return e>0?r/e:0}async function vi(r,e){let t=new so(r),{videoA:n}=await t.load({videoA:co.make(e)});return{timeline:t.timeline(i=>{let s=i.text("content",{duration:1e3}),a=i.textStyle({fill:"green",fontSize:100});return i.set(s.id,{styleId:a.id}),i.sequence(i.stack(s,i.video(n,{duration:3e3,start:1e3}),i.audio(n,{duration:1e3})),i.gap(500),i.video(n,{duration:7e3,start:5e3}))}),omni:t}}async function ec(r,e){let t=e.querySelector(".range"),n=e.querySelector(".range-view"),o=e.querySelector(".range-size"),i=e.querySelector(".frequency"),s=e.querySelector(".frequency-view"),a=e.querySelector(".filmstrip"),c=1/10,l=.5;a.replaceChildren();let d=await Yn.init(r,{onChange(u){let f=u.sort((m,p)=>m.time-p.time);a.replaceChildren(...f.map(({time:m,canvas:p})=>Jc(m,p.canvas)))},frequency:c,canvasSinkOptions:{width:80,height:50,fit:"fill"}});o.oninput=()=>{l=+o.value;let u=+t.value,f=u+l;d.range=[u,f],n.textContent=`visible time range: [${u}, ${f}]`},t.oninput=()=>{let u=+t.value,f=u+l;d.range=[u,f],n.textContent=`visible time range: [${u}, ${f}]`},i.oninput=()=>{d.frequency=1/+i.value,s.textContent=`frame every ${d.frequency.toFixed(3)} second (${i.value} frames per second)`},d.range=[10,10.5]}function Jc(r,e){let t=document.createElement("div");t.style.position="relative",t.style.display="inline-block",t.style.marginRight="4px",t.appendChild(e);let n=document.createElement("div");return n.textContent=`${r.toFixed(2)}s`,n.style.position="absolute",n.style.top="2px",n.style.right="4px",n.style.fontSize="10px",n.style.color="white",n.style.background="rgba(0,0,0,0.6)",n.style.padding="2px 4px",n.style.borderRadius="4px",n.style.pointerEvents="none",t.appendChild(n),t}function tc(r,e){let t={width:1920,height:1080},n=document.createElement("canvas");n.width=t.width,n.height=t.height;let o=n.getContext("2d");async function i(){let s=r.decodeVideo({source:e,async onFrame(f){let m=await r.composite([{id:0,kind:"image",frame:f},{id:1,kind:"text",content:"omnitool",style:{fontSize:50,fill:"green"}}]);return f.close(),o?.drawImage(m,0,0),m}}),a=r.decodeAudio({source:e}),{readable:c,done:l}=r.encode({video:s.readable,audio:a.readable,config:{audio:{codec:"opus",bitrate:128e3},video:{codec:"vp9",bitrate:1e6}}}),u=await(await window.showSaveFilePicker()).createWritable();await Promise.all([c.pipeTo(u),l])}return{canvas:n,run:i}}var Wt=await $n.setup({workerUrl:new URL("../driver/driver.worker.bundle.min.js",import.meta.url)}),el=document.querySelector("[data-demo='transcode']"),tl=document.querySelector("[data-demo='filmstrip']"),rl=document.querySelector("[data-demo='waveform']"),rc=document.querySelector("[data-demo='playback']"),pt=document.querySelector("[data-demo='export']"),nc=pt.querySelector("[data-action='export']"),lo=null;await Wt.thread.work.hello(),Wt.machina.count===1?console.log("\u2705 driver works"):console.error("\u274C FAIL driver call didn't work");var jt=(r,e)=>{let t=r.querySelector(".progress"),n=r.querySelector(".status");!t||!n||(e==="running"?(t.removeAttribute("value"),n.textContent="running"):e==="done"?(t.value=1,n.textContent="done"):(t.value=0,n.textContent="idle"))},Pi=(r,e)=>{let t=r.querySelector("input[type='file']"),n=r.querySelector("[data-action='run']");n.disabled=!0,t.addEventListener("input",()=>{n.disabled=!t.files?.length}),n.addEventListener("click",async()=>{let o=t.files?.[0];if(o){n.disabled=!0,jt(r,"running");try{await e(o,r),jt(r,"done")}finally{n.disabled=!1}}})};Pi(el,async(r,e)=>{let t=e.querySelector(".demo-preview"),n=tc(Wt,r);t.replaceChildren(n.canvas),await n.run()});Pi(tl,async(r,e)=>{await ec(r,e)});Pi(rl,async(r,e)=>{await Ja(Wt,r,e)});{let r=rc.querySelector("input[type='file']");r.addEventListener("input",async()=>{let e=r.files?.[0];if(!e)return;let{timeline:t,omni:n}=await vi(Wt,e);await Ya(t,n,rc)})}{let r=pt.querySelector("input[type='file']");r.addEventListener("input",async()=>{let e=r.files?.[0];if(!e)return;jt(pt,"running");let{timeline:t,omni:n}=await vi(Wt,e);lo={timeline:t,omni:n},nc.disabled=!1;let o=pt.querySelector(".demo-preview"),i=await n.playback(t);await i.seek(0),o.replaceChildren(i.canvas),jt(pt,"done")})}nc.addEventListener("click",async()=>{lo&&(jt(pt,"running"),await lo.omni.render(lo.timeline),jt(pt,"done"))});
|
|
2415
|
+
`;function _a({name:r,renderer:e}){let t=Aa.default.find(c=>c.name===r),n=new gt,o=new $t,i=new Ir({}),s=new Ir({}),a=new go({glProgram:new po({vertex:Ca,fragment:Ia(t.glsl)}),resources:{from:i,to:s,uniforms:{...wi.basics,...wi.custom(t)}}});return n.filters=[a],{render({width:c,height:l,from:d,to:u,progress:f}){return(n.width!==c||n.height!==l)&&(n.setSize({width:c,height:l}),o.source.resize(c,l)),i.resource=d,s.resource=u,i.update(),s.update(),a.resources.uniforms.uniforms.progress=f,e.render({container:n,target:o,clear:!1,width:c,height:l}),o}}}var jn=class{pixi;onPointerDown=ve();onPointerUp=ve();static async setup(){let e=await Ti({width:1920,height:1080,preference:"webgl",background:"black",preferWebGLVersion:2}),t=new mo;return t.interactive=!0,new this({renderer:e,stage:t})}constructor(e){this.pixi=e}#e=new Map;#t=new Map;async composite(e){let{stage:t,renderer:n}=this.pixi;this.#l(this.#c(e));let{dispose:o}=await this.#r(e,t);n.render(t);let i=new VideoFrame(n.canvas,{timestamp:0,duration:0});return o(),i}getActiveObject(e){return this.#t.get(e)}async#r(e,t){if(Array.isArray(e)){e.reverse();let n=[];for(let o of e){let i=await this.#r(o,t);n.push(i.dispose)}return{dispose:()=>n.forEach(o=>o())}}switch(e.kind){case"text":return this.#n(e,t);case"image":return this.#i(e,t);case"transition":return this.#s(e,t);case"gap":return this.pixi?.renderer.clear(),{dispose:()=>{}};default:return console.warn("Unknown layer kind",e.kind),{dispose:()=>{}}}}#n(e,t){let{sprite:n,dispose:o}=this.#a(e);return this.#o(n,e.matrix),t.addChild(n),{dispose:()=>o()}}#i(e,t){let n=$t.from(e.frame),{sprite:o,dispose:i}=this.#a(e);return o.texture=n,this.#o(o,e.matrix),t.addChild(o),{dispose:()=>{n.destroy(!0),e.frame.close(),i()}}}#s({from:e,to:t,progress:n,name:o},i){let a=(this.#e.get(o)??(this.#e.set(o,_a({name:"circle",renderer:this.pixi.renderer})),this.#e.get(o))).render({from:e,to:t,progress:n,width:e.displayWidth,height:e.displayHeight}),c=new gt(a);return i.addChild(c),{dispose:()=>c.destroy(!1)}}#o(e,t){if(!t)return;let n=wa(t);e.setFromMatrix(n)}#a(e){let t=this.#t.get(e.id);if(t)return{sprite:t,dispose:()=>{}};switch(e.kind){case"text":{let n=new vr({text:e.content,style:e.style});n.eventMode="static";let o=()=>this.onPointerDown.publish({id:e.id,object:n}),i=()=>this.onPointerUp.publish({id:e.id,object:n});return n.on("pointerdown",o),n.on("pointerup",i),{sprite:this.#t.set(e.id,n).get(e.id),dispose:()=>{n.off("pointerdown",o),n.off("pointerup",i)}}}case"image":{let n=new gt;n.eventMode="static";let o=()=>this.onPointerDown.publish({id:e.id,object:n}),i=()=>this.onPointerUp.publish({id:e.id,object:n});return n.on("pointerdown",o),n.on("pointerup",i),{sprite:this.#t.set(e.id,n).get(e.id),dispose:()=>{n.off("pointerdown",o),n.off("pointerup",i)}}}}}#c(e){let t=new Set,n=o=>{if(Array.isArray(o))for(let i of o)n(i);else t.add(o.id)};return n(e),t}#l(e){for(let t of this.#t.keys())e.has(t)||(this.#t.get(t).destroy(!0),this.#t.delete(t))}};var Ea=r=>jr.host(e=>({async world(){r.count++}}));async function ce(r){return r instanceof Blob?new kr(r):new Sr(r)}var $n=class{machina;thread;compositor;static async setup(e){let t=new Hn,n=await jr.thread({label:"OmnitoolDriver",workerUrl:e?.workerUrl??"/node_modules/@omnimedia/omnitool/x/driver/driver.worker.bundle.min.js",setupHost:Ea(t)}),o=await jn.setup();return new this(t,n,o)}constructor(e,t,n){this.machina=e,this.thread=t,this.compositor=n}async hello(){return this.thread.work.hello()}async getAudioDuration(e){let n=await new ee({source:await ce(e),formats:ie}).getPrimaryAudioTrack();if(!n)throw new Error("primary audio track not found");return await n.computeDuration()}async getVideoDuration(e){return await(await new ee({source:await ce(e),formats:ie}).getPrimaryVideoTrack())?.computeDuration()}decodeVideo(e){let t=null,{port1:n,port2:o}=new MessageChannel,i=new TransformStream({async transform(s,a){let c=await e.onFrame?.(s)??s;t?.close(),a.enqueue(c),t=c}});return this.thread.work.decodeVideo[yt]({transfer:[i.writable,o]})({source:e.source,cancel:o,video:i.writable,start:e.start,end:e.end}),{readable:i.readable,cancel(){n.postMessage("close"),n.close()}}}decodeAudio(e){let t=new TransformStream,{port1:n,port2:o}=new MessageChannel;return this.thread.work.decodeAudio[yt]({transfer:[t.writable,o]})({source:e.source,cancel:o,audio:t.writable,start:e.start,end:e.end}),{readable:t.readable,cancel(){n.postMessage("close"),n.close()}}}encode({audio:e,video:t,config:n}){let{readable:o,writable:i}=new TransformStream,s=[e,t,i].filter(Er.happy),a=this.thread.work.encode[yt]({transfer:s})({audio:e,video:t,config:n,writable:i});return{readable:o,done:a}}async composite(e){return await this.compositor.composite(e)}};var M;(function(r){r[r.Sequence=0]="Sequence",r[r.Stack=1]="Stack",r[r.Video=2]="Video",r[r.Audio=3]="Audio",r[r.Text=4]="Text",r[r.Gap=5]="Gap",r[r.Spatial=6]="Spatial",r[r.Transition=7]="Transition",r[r.TextStyle=8]="TextStyle"})(M||(M={}));var Kn;(function(r){r[r.Crossfade=0]="Crossfade"})(Kn||(Kn={}));var Xn=class{datafile;duration=0;hasVideo=!1;hasAudio=!1;constructor(e){this.datafile=e}static async analyze(e){let t=new this(e),n=await this.duration(e.url)*1e3;t.duration=n;let{video:o,audio:i}=await this.#e(e.url);return t.hasAudio=i,t.hasVideo=o,t}static async duration(e){let n=await new ee({formats:ie,source:await ce(e)}).computeDuration();return Number(n.toFixed(5))}static async#e(e){let t=new ee({formats:ie,source:await ce(e)});return{audio:!!await t.getPrimaryAudioTrack(),video:!!await t.getPrimaryVideoTrack()}}};var Qn=class{#e=new Fr;async store(e){let t=await Xn.analyze(e),{hash:n}=t.datafile.checksum,{filename:o,bytes:i,url:s,blob:a}=t.datafile;if(this.#e.has(n)){let c=this.#e.require(n);c.filename=o}else this.#e.set(n,{kind:"media",filename:o,bytes:i,url:s,blob:a,duration:t.duration});return t}require(e){return this.#e.require(e)}};var Yn=class r{videoTrack;options;#e;#t=new Map;#r=[0,0];constructor(e,t){this.videoTrack=e,this.options=t,this.#e=new fr(e,t.canvasSinkOptions)}static async init(e,t){let o=await new ee({formats:ie,source:await ce(e)}).getPrimaryVideoTrack();if(o)return new r(o,{frequency:t.frequency??1,canvasSinkOptions:t.canvasSinkOptions??{width:80,height:50,fit:"fill"},onChange:t.onChange,onPlaceholders:t.onPlaceholders});throw new Error("Source has no video track")}set frequency(e){e!==this.options.frequency&&(this.options.frequency=e,this.#c())}get frequency(){return this.options.frequency}#n([e,t],n=1){let o=t-e;return[e-o*n,t+o*n]}async#i(){let[e,t]=this.#r,n=new Set,o=await this.videoTrack.computeDuration();for(let i=Math.max(0,e);i<=t;i+=this.options.frequency)i>=0&&i<=o&&n.add(i);this.options.onPlaceholders?.([...n])}async#s(){let[e,t]=this.#r,n=new Set,o=await this.videoTrack.computeDuration();for(let c=Math.max(0,e);c<=t;c+=this.options.frequency)c>=0&&c<=o&&n.add(c);let i=[...n].filter(c=>!this.#t.has(c)),s=0;for await(let c of this.#e.canvasesAtTimestamps(i))if(c){let l=i[s++];this.#t.set(l,c)}for(let c of this.#t.keys())n.has(c)||this.#t.delete(c);let a=[...this.#t.entries()].map(([c,l])=>({time:c,canvas:l}));this.options.onChange(a)}set range(e){let[t,n]=e,o=n-t,[i,s]=this.#r,a=i+o,c=s-o,l=t<a,d=n>c;!l&&!d||(this.#r=this.#n(e,2),this.#c())}#o=null;#a=!1;async#c(){if(this.#i(),this.#o){this.#a=!0;return}this.#o=this.#s(),await this.#o,this.#o=null,this.#a&&(this.#a=!1,await this.#c())}getThumbnail(e){return this.#t.get(e)}};function Fa(r,e){let t=typeof window<"u"&&window.devicePixelRatio||1,n=document.createElement("canvas");n.width=e.width*t,n.height=e.height*t,n.style.width=`${e.width}px`,n.style.height=`${e.height}px`;let o=n.getContext("2d");if(!o)return n;o.scale(t,t),o.fillStyle=e.color;let i=e.height/2,s=Math.max(1,e.width),a=r.length/s;for(let c=0;c<s;c++){let l=Math.floor(c*a),d=Math.max(l+1,Math.floor((c+1)*a)),u=0;for(let m=l;m<d&&m<r.length;m++)r[m]>u&&(u=r[m]);let f=u*e.height;o.fillRect(c,i-f/2,1,f)}return n}var ki=[2048,1024,512,256,128,64,32];async function Da(r,e){let t=await r.getAudioDuration(e)??0,n=r.decodeAudio({source:e}).readable,o=ki[ki.length-1],i=[],s=0,a=0,c=0;for await(let u of n){c||=u.sampleRate;let f=u.numberOfFrames,m=new Float32Array(f);u.copyTo(m,{planeIndex:0});for(let p=0;p<m.length;p++){let g=Math.abs(m[p]);g>s&&(s=g),a++,a>=o&&(i.push(s),s=0,a=0)}u.close()}a>0&&i.push(s);let l=new Float32Array(i),d=ki.map(u=>{let f=Math.max(1,Math.round(u/o)),m=f===1?l:Kc(l,f);return{samplesPerPeak:u,peaks:m,peaksPerSecond:c>0?c/u:0}});return{duration:t,levels:d}}function Kc(r,e){let t=new Float32Array(Math.ceil(r.length/e));for(let n=0;n<t.length;n++){let o=0,i=n*e,s=Math.min(i+e,r.length);for(let a=i;a<s;a++)r[a]>o&&(o=r[a]);t[n]=o}return t}var Xc=4096,Zn=class r{#e=new Map;#t=[0,0];#r=[0,0];#n;#i;#s;#o=!1;color;duration;tileSize;tileHeight;preloadMargin;constructor(e,t,n){this.#i=e,this.duration=t,this.tileSize=n.tileSize??1,this.#n=n.zoom??(n.tileWidth??256)/this.tileSize,this.tileHeight=n.tileHeight??96,this.preloadMargin=n.preloadMargin??2,this.color=n.color??"rgb(3, 148, 129)",this.#s=n.onChange}static async init(e,t,n={}){let{duration:o,levels:i}=await Da(e,t);return new r(i,o,n)}set zoom(e){let t=Math.max(1,e);t!==this.#n&&(this.#n=t,this.#e.clear(),this.#c())}get zoom(){return this.#n}get range(){return this.#r}#a([e,t],n=1){let o=t-e;return[Math.max(0,e-o*n),Math.min(this.duration,t+o*n)]}set range(e){this.#r=e;let[t,n]=e,o=n-t,[i,s]=this.#t,a=i>0,c=s<this.duration,l=!a||t>=i+o,d=!c||n<=s-o;l&&d||(this.#t=this.#a(e,this.preloadMargin),this.#c())}#c(){this.#o||(this.#o=!0,queueMicrotask(()=>{this.#o=!1,this.#l()}))}#l(){let[e,t]=this.#t,n=new Set,o=this.#d(),i=Math.max(0,Math.floor(e/this.tileSize)*this.tileSize),s=Math.min(this.duration,t);for(let a=i;a<=s;a+=this.tileSize)n.add(a);for(let a of n)if(!this.#e.has(a)){let c=Math.min(a+this.tileSize,this.duration);this.#e.set(a,this.#u(a,c,o))}for(let a of this.#e.keys())n.has(a)||this.#e.delete(a);this.#p()}#u(e,t,n){let o=this.#f(n,e,t);return{startTime:e,endTime:t,peaks:o,canvas:Fa(o,{width:this.#m(e,t),height:this.tileHeight,color:this.color})}}#d(){return this.#i.find(e=>e.peaksPerSecond>=this.#n)??this.#i[this.#i.length-1]}#f(e,t,n){if(!e.peaksPerSecond)return new Float32Array;let o=Math.max(0,Math.floor(t*e.peaksPerSecond)),i=Math.max(o+1,Math.min(e.peaks.length,Math.ceil(n*e.peaksPerSecond)));return e.peaks.slice(o,i)}#m(e,t){return Math.min(Xc,Math.max(1,Math.ceil((t-e)*this.#n)))}#p(){this.#s&&this.#s([...this.#e.values()].sort((e,t)=>e.startTime-t.startTime))}getTiles(){return this.#e}};var U=r=>r;var qt=r=>r;var Ra=()=>{let r=!1,e=qt(60),t=1e3/e,n=0,o=0,i=ve(),s=null,a=l=>{if(requestAnimationFrame(a),!!r)for(n=l;l-o>=t;)o+=t,s?.(),s=null,i()};async function*c(){for(n=performance.now(),o=n,requestAnimationFrame(a);;)await new Promise(l=>s=l),yield}return{play(){r||(r=!0,n=performance.now(),o=n)},pause(){r=!1},setFPS(l){e=l,t=1e3/e},isPlaying(){return r},ticks:c,onTick:i}},Ma=async(r,e)=>{let t=U(1e3/r.fps),n=r.duration/1e3,o=Math.ceil(n*r.fps);for(let i=0;i<o;i++){let s=U(i*t);await e(s,i)}};function Oa(r){return"duration"in r}function za(r){let e=[],t=new Map(r.timeline.items.map(n=>[n.id,n]));return Si(r.timeline.rootId,t,r.from,{sequence:()=>{},stack:()=>{},video:(n,o,i)=>e.push({item:n,localTime:o,ancestors:i}),text:(n,o,i)=>e.push({item:n,localTime:o,ancestors:i}),audio:(n,o,i)=>e.push({item:n,localTime:o,ancestors:i})}),e}function Ua(r,e,t){let n=Sa;for(let o of e)n=Ba(r,o,n);return Ba(r,t,n)}function Ba(r,e,t){if("spatialId"in e&&e.spatialId){let n=r.get(e.spatialId);if(n?.enabled){let o=Ta(n.transform);return ka(o,t)}}return t}function Si(r,e,t,n,o=[]){let i=e.get(r);if(i)switch(i.kind){case M.Stack:n.stack(i,t,o);for(let s of i.childrenIds)Si(s,e,t,n,[...o,i]);break;case M.Sequence:{n.sequence(i,t,o);let s=U(0);for(let a of i.childrenIds){let c=e.get(a);if(!c||!Oa(c))continue;let l=U(s+c.duration);if(t>=l){s=l;continue}let d=U(Math.max(0,t-s));Si(a,e,d,n,[...o,i]),s=l}break}case M.Video:n.video(i,t,o);break;case M.Text:n.text(i,t,o);break;case M.Audio:n.audio(i,t,o);break}}function pe(r,e){let t=e.items.find(n=>n.id===r);if(!t)return U(0);switch(t.kind){case M.Sequence:{let n=t.childrenIds.map(i=>e.items.find(s=>s.id===i)).filter(Boolean),o=U(0);for(let i=0;i<n.length;i++){let s=n[i];if(s.kind===M.Transition){let a=n[i-1],c=n[i+1];if(a&&c&&a.kind!==M.Transition&&c.kind!==M.Transition){let l=pe(a.id,e),d=pe(c.id,e),u=Math.max(0,Math.min(s.duration,l,d));o=U(o-u)}continue}o=U(o+pe(s.id,e))}return o}case M.Stack:{let n=U(0);for(let o of t.childrenIds){let i=pe(o,e);i>n&&(n=i)}return n}default:return Oa(t)?t.duration:U(0)}}var Pr=r=>r;var Jn=class{resolveMedia;#e=new Map;constructor(e){this.resolveMedia=e}async getSink(e){let t=this.#e.get(e);if(t)return t.sink;let n=new ee({formats:ie,source:await ce(this.resolveMedia(e))}),o=await n.getPrimaryVideoTrack(),s=!!o&&await o.canDecode()&&o?new Ct(o):null;return this.#e.set(e,{input:n,sink:s}),s}};async function Na(r,e,t,n){let[o,i]=await Promise.all([t,n]),s=o.find(l=>l.kind==="image")?.frame,a=i.find(l=>l.kind==="image")?.frame,c=[...o.filter(l=>l.kind!=="image"),...i.filter(l=>l.kind!=="image")];return s&&a?[{id:r.id,kind:"transition",name:"circle",progress:e,from:s,to:a},...c]:c}async function Va(r,e,t,n){let o=Qc(r,e,t);if(!o)return[];let i=[...n,e];return o.isTransitioning?Na(o.transition,o.progress,mt(r,o.outgoing,o.outgoingTime,i),mt(r,o.incoming,o.incomingTime,i)):mt(r,o.item,o.localTime,i)}function Qc(r,e,t){let n=e.childrenIds.map(i=>r.items.get(i)).filter(i=>!!i),o=U(0);for(let i=0;i<n.length;i++){let s=n[i];if(s.kind===M.Transition)continue;let a=o,c=pe(s.id,r.timeline),l=U(a+c),d=n[i+1];if(!(d?.kind===M.Transition)){if(t<l)return{isTransitioning:!1,item:s,localTime:U(t-a)};o=l;continue}let f=d,m=n[i+2];if(!m||m.kind===M.Transition){o=l;continue}let p=pe(m.id,r.timeline),g=Math.max(0,Math.min(f.duration,c,p)),x=U(l-g);if(t<x)return{isTransitioning:!1,item:s,localTime:U(t-a)};if(t<l){let y=U(t-x),b=U(t-a);return{isTransitioning:!0,incoming:m,outgoing:s,outgoingTime:b,incomingTime:y,progress:g>0?y/g:1,transition:f}}o=x,i++}return null}async function mt(r,e,t,n){let o=Ua(r.items,n,e);switch(e.kind){case M.Stack:{let i=[...n,e];return(await Promise.all(e.childrenIds.map(a=>r.items.get(a)).filter(a=>!!a).map(a=>mt(r,a,t,i)))).flat()}case M.Sequence:return Va(r,e,t,n);case M.Video:{if(t<0||t>=e.duration)return[];let i=await r.videoSampler(e,t);return i?[{kind:"image",frame:i,matrix:o,id:e.id}]:[]}case M.Text:{if(t<0||t>=e.duration)return[];let i=e.styleId?r.items.get(e.styleId)?.style:void 0;return[{id:e.id,kind:"text",content:e.content,style:i,matrix:o}]}case M.Gap:return[{id:e.id,kind:"gap"}];default:return[]}}function La(r){return async(e,t)=>{let o=await(await r.getSink(e.mediaHash))?.getSample(t/1e3),i=o?.toVideoFrame();return o?.close(),i??void 0}}function eo(r,e){let t=new Jn(r),n=e??La(t);return{async sample(o,i){let s=new Map(o.items.map(c=>[c.id,c])),a=s.get(o.rootId);return a?mt({videoSampler:n,timeline:o,items:s},a,i,[]):[]}}}var Gt=class{driver;resolveMedia;timeline;#e=-1/0;#t=new Map;#r;constructor(e,t,n){this.driver=e,this.resolveMedia=t,this.timeline=n,this.#r=eo(this.resolveMedia,(o,i)=>{let s=Ha(i),a=this.#t.get(o.id);if(!a){let c=this.resolveMedia(o.mediaHash),l=Ha(U(o.start+o.duration));a=this.#n(c,s,l),this.#t.set(o.id,a)}return a.next(s)})}next(e){if(e<this.#e)throw new Error(`Forward-only cursor regression: ${e}ms < ${this.#e}ms`);return this.#e=e,this.#r.sample(this.timeline,e)}async cancel(){await Promise.all([...this.#t.values()].map(e=>e.cancel())),this.#t.clear()}#n(e,t,n){let o=this.driver.decodeVideo({source:e,start:t/1e6,end:n/1e6}),i=o.readable.getReader(),s=null,a=null,c=!1,l=async()=>{if(c)return null;let{done:d,value:u}=await i.read();if(d)return c=!0,null;let f=new VideoFrame(u);return u.close(),f};return{async next(d){if(s??=await l(),!!s)for(;;){a??=l();let u=await a;if(!u)return new VideoFrame(s);let f=s.timestamp??-1/0,m=u.timestamp??f;if(m<d){s.close(),s=u,a=null;continue}if(Math.abs(m-d)<Math.abs(f-d)){s.close(),s=u,a=null;continue}return new VideoFrame(s)}},async cancel(){let d=a;a=null,c=!0,(await d?.catch(()=>null))?.close(),s?.close(),s=null,o.cancel()}}}},Ha=r=>Math.round(r*1e3);async function qa(r,e,t){return(await Promise.all(e.map(async({item:o,localTime:i})=>{if(o.kind!==M.Audio)return;let s=await r.getSink(o.mediaHash);if(!s)return;let a=o.start+i,c=Pr((t-a)/1e3),l=s.samples(a/1e3),d=await l.next();if(d.done)return;let u=d.value,f=l.next();return{offset:c,gain:o.gain??1,get currentSample(){return u},timelineTime:()=>Pr(c+u.timestamp),output:()=>({sample:u,timestamp:c+u.timestamp,gain:o.gain??1}),advance:async()=>{let m=await f;return m.done?!1:(u=m.value,f=l.next(),!0)}}}))).filter(o=>!!o)}var to=class{resolveMedia;#e=new Map;constructor(e){this.resolveMedia=e}async getSink(e){let t=this.#e.get(e);if(t)return t.sink;let n=new ee({formats:ie,source:await ce(this.resolveMedia(e))}),o=await n.getPrimaryAudioTrack(),s=!!o&&await o.canDecode()&&o?new mr(o):null;return this.#e.set(e,{input:n,sink:s}),s}};function Ga(r){let e={index:0,stream:r[0],time:r[0].timelineTime()};for(let[t,n]of r.entries()){let o=n.timelineTime();o<e.time&&(e={time:o,stream:n,index:t})}return e}function ro(r){let e=new to(r);return{async*sampleAudio(t,n){let o=za({timeline:t,from:n}),i=await qa(e,o,n);for(;i.length>0;){let{stream:s,index:a}=Ga(i);yield s.output(),await s.advance()||i.splice(a,1)}}}}var no=class{driver;timeline;resolveMedia;audioSampler;seekVisualSampler;playVisualSampler=null;#e=U(0);#t=null;#r=Ra();onTick=this.#r.onTick;audioContext=new AudioContext({sampleRate:48e3});audioGain=this.audioContext.createGain();audioNodes=new Set;#n=null;constructor(e,t,n){this.driver=e,this.timeline=t,this.resolveMedia=n,this.audioGain.connect(this.audioContext.destination),this.audioGain.gain.value=.7**2,this.seekVisualSampler=eo(this.resolveMedia),this.audioSampler=ro(this.resolveMedia),this.#i()}update(e){this.timeline=e}get isPlaying(){return this.#r.isPlaying()}async#i(){for await(let e of this.#r.ticks()){let t=await this.playVisualSampler?.next(this.currentTime)??[];(await this.driver.composite(t)).close(),this.currentTime>=this.duration&&this.pause()}}async seek(e){return this.pause(),this.#e=e,await this.seekVisualSampler.sample(this.timeline,e)}async start(){if(!this.#r.isPlaying()){await this.audioContext.resume(),this.#e=this.currentTime,this.#t=this.audioContext.currentTime,this.#n?.abort(),this.#n=new AbortController;for(let e of this.audioNodes)e.stop();this.audioNodes.clear(),this.playVisualSampler=new Gt(this.driver,this.resolveMedia,this.timeline),this.#r.play(),this.#s(this.#n.signal,Pr(this.#e/1e3))}}pause(){this.#e=this.currentTime,this.#r.pause(),this.#n?.abort();for(let e of this.audioNodes)e.stop();this.audioNodes.clear(),this.playVisualSampler&&(this.playVisualSampler.cancel(),this.playVisualSampler=null)}get duration(){return pe(this.timeline.rootId,this.timeline)}get currentTime(){if(!this.#r.isPlaying()||this.#t===null)return this.#e;let e=(this.audioContext.currentTime-this.#t)*1e3;return U(this.#e+e)}setFps(e){this.#r.setFPS(e)}async#s(e,t){let n=this.audioContext;if(this.#t!==null)for await(let{sample:o,timestamp:i}of this.audioSampler.sampleAudio(this.timeline,U(t*1e3))){if(e.aborted||!this.#r.isPlaying())return;for(;i-(n.currentTime-this.#t+t)>.75;)await new Promise(c=>setTimeout(c,25));let s=n.createBufferSource();s.buffer=o.toAudioBuffer(),s.connect(this.audioGain),s.onended=()=>this.audioNodes.delete(s),this.audioNodes.add(s);let a=this.#t+i-t;a>=n.currentTime?s.start(a):s.start(n.currentTime,n.currentTime-a)}}};var oo=class{driver;canvas;playback;#e=null;#t=null;constructor(e,t,n){this.driver=e,this.playback=new no(e,n,t),this.canvas=e.compositor.pixi.renderer.canvas}async play(){await this.playback.start()}pause(){this.playback.pause()}seek(e){return this.#e=e,this.#t??=this.#r().finally(()=>this.#t=null)}setFPS(e){this.playback.setFps(qt(e))}get isSeeking(){return this.#t!==null}get isPlaying(){return this.playback.isPlaying}get duration(){return this.playback.duration}get currentTime(){return this.playback.currentTime}update(e){this.playback.update(e)}async#r(){for(;this.#e!==null;){let e=this.#e;this.#e=null;let t=await this.playback.seek(U(e));(await this.driver.composite(t)).close()}}};var pt=class{state;constructor(e){this.state=e}require(e){return e===void 0?void 0:this.state.timeline.items.find(n=>n.id===e)}get timeline(){return this.state.timeline}getId(){return he.toInteger(he.random())}#e(e){this.state.timeline=e(this.state.timeline)}register(e){this.#e(t=>({...t,items:[...t.items,e]}))}textStyle=e=>{let t={id:this.getId(),kind:M.TextStyle,style:e};return this.register(t),t};spatial=e=>{let t={id:this.getId(),kind:M.Spatial,transform:e,enabled:!0};return this.register(t),t};sequence=(...e)=>{let t={id:this.getId(),kind:M.Sequence,childrenIds:e.map(n=>n.id)};return this.register(t),t};stack=(...e)=>{let t={kind:M.Stack,id:this.getId(),childrenIds:e.map(n=>n.id)};return this.register(t),t};video=(e,t)=>{if(!e.hasVideo)throw new Error(`Video clip error: media "${e.datafile.filename}" has no video track.`);let n={kind:M.Video,id:this.getId(),mediaHash:e.datafile.checksum.hash,start:t?.start??0,duration:t?.duration??e.duration};return this.register(n),n};audio=(e,t)=>{if(!e.hasAudio)throw new Error(`Audio clip error: media "${e.datafile.filename}" has no audio track.`);let n={kind:M.Audio,id:this.getId(),mediaHash:e.datafile.checksum.hash,start:t?.start??0,duration:t?.duration??e.duration,gain:t?.gain??1};return this.register(n),n};text=(e,t)=>{let n={id:this.getId(),content:e,kind:M.Text,duration:t?.duration??2e3};return t?.styles&&(n.styleId=this.textStyle(t.styles).id),this.register(n),n};gap=e=>{let t={id:this.getId(),kind:M.Gap,duration:e};return this.register(t),t};transition={crossfade:e=>{let t={id:this.getId(),kind:M.Transition,effect:Kn.Crossfade,duration:e};return this.register(t),t}};transform=e=>{let t=[e?.position?.[0]??0,e?.position?.[1]??0],n=[e?.scale?.[0]??1,e?.scale?.[1]??1],o=e?.rotation??0;return[t,n,o]};addChildren(e,...t){this.#e(n=>(n.items.find(({id:i})=>i===e.id).childrenIds.push(...t.map(i=>i.id)),n))}set=(e,t)=>{this.#e(n=>({...n,items:n.items.map(o=>o.id===e?{...o,...t}:o)}))}};var io=class{#e;#t;constructor(e={}){this.#e=e.chunkFrames??1024,this.#t=e.clamp??!0}async*mix(e){let t=this.#e,n=null,o=null,i=[],s=0,a=0;for await(let c of e){if(o===null)o=c.planes.length,n=c.sampleRate;else{if(c.planes.length!==o)throw new Error("Channel count changed");if(c.sampleRate!==n)throw new Error("Sample rate changed")}let l=Math.round(c.timestamp*n),d=c.planes[0]?.length??0;for(;s+t<=l;)yield this.#r(i,s,o,n),s+=t;i.push({startFrame:l,endFrame:l+d,data:c.planes}),a=Math.max(a,l+d)}if(o!==null&&n!==null)for(;s<a;)yield this.#r(i,s,o,n),s+=t}#r(e,t,n,o){let i=this.#e,s=new Float32Array(n*i),a=t+i;for(let c=0;c<n;c++){let l=c*i,d=s.subarray(l,l+i);for(let u of e){let f=u.data[c];if(!f)continue;let m=Math.max(t,u.startFrame),p=Math.min(a,u.endFrame);if(m>=p)continue;let g=m-t,x=m-u.startFrame,y=p-m;for(let b=0;b<y;b++)d[g+b]+=f[x+b]}if(this.#t)for(let u=0;u<i;u++){let f=d[u];d[u]=f<-1?-1:f>1?1:f}}for(let c=e.length-1;c>=0;c--)e[c].endFrame<=a&&e.splice(c,1);return{planar:s,sampleRate:o,channels:n,frames:i,startFrame:t}}};var Yc=(r,e,t)=>{if(e===t)return r;let n=t/e,o=Math.max(1,Math.round(r.length*n)),i=new Float32Array(o);for(let s=0;s<o;s++){let a=s/n,c=Math.floor(a),l=Math.min(c+1,r.length-1),d=a-c;i[s]=r[c]*(1-d)+r[l]*d}return i},Wa=(r,e)=>{let t=r.numberOfChannels,n=new Array(t),o=0;for(let i=0;i<t;i++){let s=new Float32Array(r.numberOfFrames);r.copyTo(s,{planeIndex:i,format:"f32-planar"});let a=Yc(s,r.sampleRate,e);n[i]=a,o=a.length}return{data:n,frames:o}};var ja=(r,e)=>{if(e!==1)for(let t of r)for(let n=0;n<t.length;n++)t[n]*=e};function $a({timeline:r,resolveMedia:e}){let t=new io,n=Zc(r,e),o=new TransformStream,i=o.writable.getWriter();async function s(){for await(let a of t.mix(n)){let c=new AudioData({format:"f32-planar",sampleRate:a.sampleRate,numberOfFrames:a.frames,numberOfChannels:a.channels,timestamp:Math.round(a.startFrame/a.sampleRate*1e6),data:new Float32Array(a.planar)});await i.write(c)}await i.close()}return s(),o.readable}async function*Zc(r,e){let t=ro(e);for await(let{sample:n,timestamp:o,gain:i}of t.sampleAudio(r,U(0))){let{data:s}=Wa(n,48e3);ja(s,i),yield{planes:s,sampleRate:48e3,timestamp:o},n.close()}}function Ka({timeline:r,fps:e,driver:t,resolveMedia:n}){let o=new TransformStream,i=o.writable.getWriter(),s=new Gt(t,n,r),a=1/e,c=pe(r.rootId,r);async function l(){await Ma({fps:e,duration:c},async(d,u)=>{let f=await s.next(d),m=await t.composite(f),p=new VideoFrame(m,{timestamp:Math.round(u*a*1e6),duration:Math.round(a*1e6)});await i.write(p),m.close()}),await i.close()}return l(),o.readable}function Xa(r){let e=$a({...r}),t=Ka({...r});return r.driver.encode({video:t,audio:e,config:{audio:{codec:"opus",bitrate:128e3},video:{codec:"vp9",bitrate:1e6}}})}var so=class{driver;resources=new Qn;constructor(e){this.driver=e}load=async e=>Object.fromEntries(await Promise.all(Object.entries(e).map(async([t,n])=>[t,await this.resources.store(await n)])));timeline=e=>{let t=new pt({timeline:{format:"timeline",info:"https://omniclip.app/",version:0,items:[],rootId:0}}),n=e(t);return t.timeline.rootId=n.id,t.timeline};playback=async e=>new oo(this.driver,t=>this.resources.require(t).url,e);render=async(e,t=30)=>Xa({timeline:e,fps:qt(t),driver:this.driver,resolveMedia:n=>this.resources.require(n).url})};var ao=class{data;bytes;hash;nickname;constructor(e,t,n,o){this.data=e,this.bytes=t,this.hash=n,this.nickname=o}static async make(e){let t=new Uint8Array(e),n=new Uint8Array(await crypto.subtle.digest("SHA-256",t)),o=_r.fromBytes(n),i=Ri.sigil.fromBytes(n);return new this(e,n,o,i)}};var co=class{url;bytes;blob;filename;checksum;constructor(e,t,n,o,i){this.url=e,this.bytes=t,this.blob=n,this.filename=o,this.checksum=i}static async make(e,t){let n=await e.arrayBuffer(),o=new Uint8Array(n),i=await ao.make(o),s=t??i.nickname,a=URL.createObjectURL(e);return new this(a,o,e,s,i)}static async load(e){}};async function Ya(r,e,t){let n=t.querySelector(".play"),o=t.querySelector(".stop"),i=t.querySelector(".scrub"),s=t.querySelector(".playhead"),a=t.querySelector(".timecode"),c=t.querySelector(".player-canvas"),l=new pt({timeline:r}),d=await e.playback(r);c.replaceChildren(d.canvas),n.disabled=!1,o.disabled=!1,n.addEventListener("click",()=>d.play()),o.addEventListener("click",()=>d.pause()),i.max=String(Math.ceil(d.duration));let u=!1;d.playback.onTick.on(()=>m(d.currentTime,d.duration));let f=(p,g)=>{a.textContent=`${Qa(p)} / ${Qa(g)}`};i.addEventListener("input",async()=>{u=!0;let p=Math.max(0,Math.min(+i.value,d.duration));f(p,d.duration),await d.seek(p)}),i.addEventListener("change",async()=>{u=!1;let p=Math.max(0,Math.min(+i.value,d.duration));await d.seek(p)});let m=(p,g)=>{let x=Math.max(0,Math.min(p,g));u||(i.value=String(Math.round(x)));let y=g?x/g*100:0;s.style.left=`${y}%`,f(x,g)};d.update(l.timeline)}function Qa(r){let e=Math.max(0,r),t=Math.floor(e/1e3),n=Math.floor(t/60),o=t%60,i=Math.floor(e%1e3);return`${n}:${String(o).padStart(2,"0")}.${String(i).padStart(3,"0")}`}async function Ja(r,e,t){let n=t.querySelector(".waveform-canvas"),o=t.querySelector(".width");n.replaceChildren(),n.style.position="relative",n.style.height="96px",n.style.overflow="hidden";let i=await Zn.init(r,e,{tileHeight:96,onChange:()=>s()}),s=()=>{let a=+o.value,c=Za(a,i.duration);i.zoom=c,n.style.width=`${a}px`,n.replaceChildren(...[...i.getTiles().values()].map(l=>(l.canvas.style.position="absolute",l.canvas.style.top="0",l.canvas.style.left=`${l.startTime*Za(a,i.duration)}px`,l.canvas.style.height="100%",l.canvas)))};o.oninput=s,i.range=[0,i.duration]}function Za(r,e){return e>0?r/e:0}async function vi(r,e){let t=new so(r),{videoA:n}=await t.load({videoA:co.make(e)});return{timeline:t.timeline(i=>{let s=i.text("content",{duration:1e3}),a=i.textStyle({fill:"green",fontSize:100});return i.set(s.id,{styleId:a.id}),i.sequence(i.stack(s,i.video(n,{duration:3e3,start:1e3}),i.audio(n,{duration:1e3})),i.gap(500),i.video(n,{duration:7e3,start:5e3}))}),omni:t}}async function ec(r,e){let t=e.querySelector(".range"),n=e.querySelector(".range-view"),o=e.querySelector(".range-size"),i=e.querySelector(".frequency"),s=e.querySelector(".frequency-view"),a=e.querySelector(".filmstrip"),c=1/10,l=.5;a.replaceChildren();let d=await Yn.init(r,{onChange(u){let f=u.sort((m,p)=>m.time-p.time);a.replaceChildren(...f.map(({time:m,canvas:p})=>Jc(m,p.canvas)))},frequency:c,canvasSinkOptions:{width:80,height:50,fit:"fill"}});o.oninput=()=>{l=+o.value;let u=+t.value,f=u+l;d.range=[u,f],n.textContent=`visible time range: [${u}, ${f}]`},t.oninput=()=>{let u=+t.value,f=u+l;d.range=[u,f],n.textContent=`visible time range: [${u}, ${f}]`},i.oninput=()=>{d.frequency=1/+i.value,s.textContent=`frame every ${d.frequency.toFixed(3)} second (${i.value} frames per second)`},d.range=[10,10.5]}function Jc(r,e){let t=document.createElement("div");t.style.position="relative",t.style.display="inline-block",t.style.marginRight="4px",t.appendChild(e);let n=document.createElement("div");return n.textContent=`${r.toFixed(2)}s`,n.style.position="absolute",n.style.top="2px",n.style.right="4px",n.style.fontSize="10px",n.style.color="white",n.style.background="rgba(0,0,0,0.6)",n.style.padding="2px 4px",n.style.borderRadius="4px",n.style.pointerEvents="none",t.appendChild(n),t}function tc(r,e){let t={width:1920,height:1080},n=document.createElement("canvas");n.width=t.width,n.height=t.height;let o=n.getContext("2d");async function i(){let s=r.decodeVideo({source:e,async onFrame(f){let m=await r.composite([{id:0,kind:"image",frame:f},{id:1,kind:"text",content:"omnitool",style:{fontSize:50,fill:"green"}}]);return f.close(),o?.drawImage(m,0,0),m}}),a=r.decodeAudio({source:e}),{readable:c,done:l}=r.encode({video:s.readable,audio:a.readable,config:{audio:{codec:"opus",bitrate:128e3},video:{codec:"vp9",bitrate:1e6}}}),u=await(await window.showSaveFilePicker()).createWritable();await Promise.all([c.pipeTo(u),l])}return{canvas:n,run:i}}var Wt=await $n.setup({workerUrl:new URL("../driver/driver.worker.bundle.min.js",import.meta.url)}),el=document.querySelector("[data-demo='transcode']"),tl=document.querySelector("[data-demo='filmstrip']"),rl=document.querySelector("[data-demo='waveform']"),rc=document.querySelector("[data-demo='playback']"),ht=document.querySelector("[data-demo='export']"),nc=ht.querySelector("[data-action='export']"),lo=null;await Wt.thread.work.hello(),Wt.machina.count===1?console.log("\u2705 driver works"):console.error("\u274C FAIL driver call didn't work");var jt=(r,e)=>{let t=r.querySelector(".progress"),n=r.querySelector(".status");!t||!n||(e==="running"?(t.removeAttribute("value"),n.textContent="running"):e==="done"?(t.value=1,n.textContent="done"):(t.value=0,n.textContent="idle"))},Pi=(r,e)=>{let t=r.querySelector("input[type='file']"),n=r.querySelector("[data-action='run']");n.disabled=!0,t.addEventListener("input",()=>{n.disabled=!t.files?.length}),n.addEventListener("click",async()=>{let o=t.files?.[0];if(o){n.disabled=!0,jt(r,"running");try{await e(o,r),jt(r,"done")}finally{n.disabled=!1}}})};Pi(el,async(r,e)=>{let t=e.querySelector(".demo-preview"),n=tc(Wt,r);t.replaceChildren(n.canvas),await n.run()});Pi(tl,async(r,e)=>{await ec(r,e)});Pi(rl,async(r,e)=>{await Ja(Wt,r,e)});{let r=rc.querySelector("input[type='file']");r.addEventListener("input",async()=>{let e=r.files?.[0];if(!e)return;let{timeline:t,omni:n}=await vi(Wt,e);await Ya(t,n,rc)})}{let r=ht.querySelector("input[type='file']");r.addEventListener("input",async()=>{let e=r.files?.[0];if(!e)return;jt(ht,"running");let{timeline:t,omni:n}=await vi(Wt,e);lo={timeline:t,omni:n},nc.disabled=!1;let o=ht.querySelector(".demo-preview"),i=await n.playback(t);await i.seek(0),o.replaceChildren(i.canvas),jt(ht,"done")})}nc.addEventListener("click",async()=>{lo&&(jt(ht,"running"),await lo.omni.render(lo.timeline),jt(ht,"done"))});
|
|
2416
2416
|
/*! Bundled license information:
|
|
2417
2417
|
|
|
2418
2418
|
mediabunny/dist/modules/src/misc.js:
|