@omnimedia/omnitool 1.1.0-51 → 1.1.0-52
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/timeline/renderers/player/parts/playback.ts +0 -2
- package/x/demo/demo.bundle.min.js +6 -6
- package/x/demo/demo.bundle.min.js.map +3 -3
- package/x/index.html +2 -2
- package/x/tests.bundle.min.js +6 -6
- package/x/tests.bundle.min.js.map +3 -3
- package/x/tests.html +1 -1
- package/x/timeline/renderers/player/parts/playback.d.ts +0 -1
- package/x/timeline/renderers/player/parts/playback.js +0 -3
- package/x/timeline/renderers/player/parts/playback.js.map +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./chunk-T3METYEY.js";import{c as Br,j as ji,k as $i,l as Co}from"./chunk-5ZZYIILO.js";import"./chunk-P3PTHHFE.js";import"./chunk-USLRKDKD.js";import"./chunk-Q4MWBZHL.js";import{b as Or}from"./chunk-YISSXWBT.js";import{Aa as Po,D as wo,H as er,N as ko,Q as Gi,R as tr,T as
|
|
1
|
+
import"./chunk-T3METYEY.js";import{c as Br,j as ji,k as $i,l as Co}from"./chunk-5ZZYIILO.js";import"./chunk-P3PTHHFE.js";import"./chunk-USLRKDKD.js";import"./chunk-Q4MWBZHL.js";import{b as Or}from"./chunk-YISSXWBT.js";import{Aa as Po,D as wo,H as er,N as ko,Q as Gi,R as tr,T as wt,a as Sc,b as Cc,c as Mr,d as Vi,da as So,h as To,i as Hi,k as Wi,m as qi}from"./chunk-PYG4RZZ2.js";var La=Sc((px,Ua)=>{Ua.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 St=Object.freeze({eq(n,e){if(n.length!==e.length)return!1;for(let t=0;t<=n.length;t++)if(n.at(t)!==e.at(t))return!1;return!0},random(n){return crypto.getRandomValues(new Uint8Array(n))}});var Z=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,r)=>[t,r])),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 u of e){if(u===this.lexicon.padding?.character)continue;let d=this.lookup[u];if(d===void 0)throw new Error(`Invalid character: ${u}`);for(a=a<<t|d,c+=t;c>=8;)c-=8,l.push(a>>c&255)}return new Uint8Array(l)}let r=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}`);r=r*o+BigInt(c)}let s=[];for(;r>0n;)s.unshift(Number(r%256n)),r=r/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 u=s>>a&(1<<t)-1;c+=this.lexicon.characters[u]}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 r=0n;for(let s of e)r=(r<<8n)+BigInt(s);if(r===0n)return this.lexicon.characters[0];let o=BigInt(this.lexicon.characters.length),i="";for(;r>0n;)i=this.lexicon.characters[Number(r%o)]+i,r=r/o;return i}toInteger(e){if(!e)return 0;let t=0n,r=!1,o=BigInt(this.lexicon.characters.length);e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),r=!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(r?-t:t)}fromInteger(e){e=Math.floor(e);let t=e<0,r=BigInt(t?-e:e);if(r===0n)return this.lexicon.characters[0];let o=BigInt(this.lexicon.characters.length),i="";for(;r>0n;)i=this.lexicon.characters[Number(r%o)]+i,r=r/o;return t?`${this.negativePrefix}${i}`:i}random(e=32){return this.fromBytes(St.random(e))}};var ye=new Z(Z.lexicons.hex),Dl=new Z(Z.lexicons.base2),Rl=new Z(Z.lexicons.base36),Io=new Z(Z.lexicons.base58),Ml=new Z(Z.lexicons.base62),Bl=new Z(Z.lexicons.base64),Ol=new Z(Z.lexicons.base64url);var Ao=["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 _o=["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 Ie={defaults:{groupSize:4,wordSeparator:".",groupSeparator:" "},random(n,e){let t=St.random(n);return this.fromBytes(t,e)},fromBytes(n,e={}){let{groupSize:t=Ie.defaults.groupSize,wordSeparator:r=Ie.defaults.wordSeparator,groupSeparator:o=Ie.defaults.groupSeparator}=e,i=[],s=[];n.forEach((c,l)=>{let u=l%2===0?Ao:_o;s.push(u[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(r));return a.join(o)},toBytes(n){let e=n.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 r=[];for(let o=0;o<e.length;o+=3)r.push(e.slice(o,o+3));return new Uint8Array(r.map((o,i)=>{let a=(i%2===0?Ao:_o).findIndex(c=>c===o);if(a===-1)throw new Error(`unknown triplet ${o}`);return a}))},toHex(n){return ye.fromBytes(Ie.toBytes(n))},fromHex(n,e){return Ie.fromBytes(ye.toBytes(n),e)}};var ve={defaults:{delimiter:".",sigilBytes:4,previewBytes:8},toBytes(n){n=n.trim();let e=n.split(/[^a-zA-Z0-9]+/m).filter(Boolean).map(o=>o.trim());if(e.length<2)return Ie.toBytes(e.join(""));let t=e.pop(),r=e.join("");return new Uint8Array([...Ie.toBytes(r),...Io.toBytes(t)])},parse(n,e){let t=ve.toBytes(n);return ve.build.fromBytes(t,e)},build:{fromBytes(n,e={}){let{delimiter:t,previewBytes:r,sigilBytes:o}={...ve.defaults,...e},i=u=>n.length>0?Ie.fromBytes(n.slice(0,u),{wordSeparator:t,groupSeparator:t}):"",s=i(o),a=i(r),c=n.length>r?Io.fromBytes(n.slice(r)):"",l=[a,c].filter(u=>u.length>0).join(t);return{raw:n,full:l,preview:a,bulk:c,sigil:s,bytes:n,thumbprint:l}},fromHex(n,e){let t=ye.toBytes(n);return ve.build.fromBytes(t,e)}},toHex(n){let e=ve.toBytes(n);return ye.fromBytes(e)},fromBytes(n,e){return ve.build.fromBytes(n,e).full},fromHex(n,e){return ve.fromBytes(ye.toBytes(n),e)},sigil:{fromHex(n,e){return ve.build.fromHex(n,e).sigil},fromBytes(n,e){return ve.build.fromBytes(n,e).sigil}}},Xi=ve;var zr=Object.freeze({fromBytes(n){return[...n].map(e=>e.toString(16).padStart(2,"0")).join("")},toBytes(n){if(n.length%2!==0)throw new Error("must have even number of hex characters");let e=new Uint8Array(n.length/2);for(let t=0;t<n.length;t+=2)e[t/2]=parseInt(n.slice(t,t+2),16);return e},random(n=32){return this.fromBytes(St.random(n))},string(n){return zr.fromBytes(n)},bytes(n){return zr.toBytes(n)}});function Te(){let n,e,t=new Promise((o,i)=>{n=o,e=i});function r(o){return o.then(n).catch(e),t}return{promise:t,resolve:n,reject:e,entangle:r}}var Nr=Object.freeze({happy:n=>n!=null,sad:n=>n==null,boolean:n=>typeof n=="boolean",number:n=>typeof n=="number",string:n=>typeof n=="string",bigint:n=>typeof n=="bigint",object:n=>typeof n=="object"&&n!==null,array:n=>Array.isArray(n),fn:n=>typeof n=="function",symbol:n=>typeof n=="symbol"});var Ur=class n 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,r){if(e.has(t))return e.get(t);{let o=r();return e.set(t,o),o}}array(){return[...this]}require(e){return n.require(this,e)}guarantee(e,t){return n.guarantee(this,e,t)}};var rr=class extends Error{milliseconds;name=this.constructor.name;constructor(e){super(`deadline exceeded (${(e/1e3).toFixed(1)} seconds)`),this.milliseconds=e}};function Ki(n,e){return n<=0||n===1/0?e():new Promise((t,r)=>{let o=setTimeout(()=>r(new rr(n)),n);e().then(t).catch(r).finally(()=>clearTimeout(o))})}function Lr(){let n=[];function e(){for(let t of n)t();n=[]}return e.schedule=(...t)=>(n.push(...t),e),e}function Qi(n,e){let t=n;for(let r of e)if(t=t[r],Nr.sad(t))break;return t}function Pc(){let n=new Set;async function e(...c){await Promise.all([...n].map(l=>l(...c)))}function t(c){return n.add(c),()=>{n.delete(c)}}async function r(...c){return e(...c)}function o(c){return t(c)}async function i(c){let{promise:l,resolve:u}=Te(),d=o(async(...m)=>{c&&await c(...m),u(m),d()});return l}function s(){n.clear()}let a={pub:r,sub:o,publish:e,subscribe:t,on:t,next:i,clear:s};return Object.assign(o,a),Object.assign(r,a),a}function Ue(n){let e=Pc();return n&&e.sub(n),e.pub}function Eo(n,e){return{error:t=>n.error({...e,...t}),rpcRequest:t=>n.rpcRequest({...e,...t}),rpcError:t=>n.rpcError({...e,...t})}}var Vr=()=>n=>({plain:n.none,errMessage:n.mix(n.brightRed,n.bold),errName:n.red,errStack:n.mix(n.red,n.dim),timestamp:n.blue,timestampErr:n.red});function Yi(){return Vr()}var Le=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 Hr=()=>({none:n=>n,uncolor:Ac,mix:_c,hex:Ec,rgb:Zi,bgRgb:Fc});function Ac(n){return n.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"")}function _c(...n){return e=>{for(let t of n)e=t(e);return e}}function Ec(n){n=n.replace(/^#/,"");let e,t,r,o;if(n.length===3)e=parseInt(n.split("").map(i=>i+i).join(""),16);else if(n.length===6)e=parseInt(n,16);else throw new Error("Invalid hex color");return t=e>>16&255,r=e>>8&255,o=e&255,Zi(t,r,o)}function Zi(n,e,t){let r=`\x1B[38;2;${n};${e};${t}m`;return o=>`${r}${o}${Le.reset}`}function Fc(n,e,t){let r=`\x1B[48;2;${n};${e};${t}m`;return o=>`${r}${o}${Le.reset}`}var nr={...Object.fromEntries(Object.entries(Le).map(([n])=>[n,e=>e])),...Hr()};var or={...Object.fromEntries(Object.entries(Le).map(([n,e])=>[n,t=>`${e}${t}${Le.reset}`])),...Hr()};function Fo(){return typeof Deno<"u"&&typeof Deno.version<"u"}function Do(){return typeof process<"u"&&process.versions&&process.versions.node}function Ji(){return Do()?process.env.FORCE_COLOR||process.stdout.isTTY&&process.env.TERM!=="dumb":Fo()?Deno.env.get("FORCE_COLOR")||Deno.isatty(Deno.stdout.rid)&&Deno.env.get("TERM")!=="dumb":!1}var Ro=()=>Ji()?or:nr;var Wr=()=>({colors:n,theme:e})=>{let t=e(n);function r(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 kt=Object.freeze({eq(n,e){if(n.length!==e.length)return!1;for(let t=0;t<=n.length;t++)if(n.at(t)!==e.at(t))return!1;return!0},random(n){return crypto.getRandomValues(new Uint8Array(n))}});var Z=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,r)=>[t,r])),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 u of e){if(u===this.lexicon.padding?.character)continue;let d=this.lookup[u];if(d===void 0)throw new Error(`Invalid character: ${u}`);for(a=a<<t|d,c+=t;c>=8;)c-=8,l.push(a>>c&255)}return new Uint8Array(l)}let r=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}`);r=r*o+BigInt(c)}let s=[];for(;r>0n;)s.unshift(Number(r%256n)),r=r/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 u=s>>a&(1<<t)-1;c+=this.lexicon.characters[u]}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 r=0n;for(let s of e)r=(r<<8n)+BigInt(s);if(r===0n)return this.lexicon.characters[0];let o=BigInt(this.lexicon.characters.length),i="";for(;r>0n;)i=this.lexicon.characters[Number(r%o)]+i,r=r/o;return i}toInteger(e){if(!e)return 0;let t=0n,r=!1,o=BigInt(this.lexicon.characters.length);e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),r=!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(r?-t:t)}fromInteger(e){e=Math.floor(e);let t=e<0,r=BigInt(t?-e:e);if(r===0n)return this.lexicon.characters[0];let o=BigInt(this.lexicon.characters.length),i="";for(;r>0n;)i=this.lexicon.characters[Number(r%o)]+i,r=r/o;return t?`${this.negativePrefix}${i}`:i}random(e=32){return this.fromBytes(kt.random(e))}};var ye=new Z(Z.lexicons.hex),Dl=new Z(Z.lexicons.base2),Rl=new Z(Z.lexicons.base36),Io=new Z(Z.lexicons.base58),Ml=new Z(Z.lexicons.base62),Bl=new Z(Z.lexicons.base64),Ol=new Z(Z.lexicons.base64url);var Ao=["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 _o=["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 Ie={defaults:{groupSize:4,wordSeparator:".",groupSeparator:" "},random(n,e){let t=kt.random(n);return this.fromBytes(t,e)},fromBytes(n,e={}){let{groupSize:t=Ie.defaults.groupSize,wordSeparator:r=Ie.defaults.wordSeparator,groupSeparator:o=Ie.defaults.groupSeparator}=e,i=[],s=[];n.forEach((c,l)=>{let u=l%2===0?Ao:_o;s.push(u[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(r));return a.join(o)},toBytes(n){let e=n.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 r=[];for(let o=0;o<e.length;o+=3)r.push(e.slice(o,o+3));return new Uint8Array(r.map((o,i)=>{let a=(i%2===0?Ao:_o).findIndex(c=>c===o);if(a===-1)throw new Error(`unknown triplet ${o}`);return a}))},toHex(n){return ye.fromBytes(Ie.toBytes(n))},fromHex(n,e){return Ie.fromBytes(ye.toBytes(n),e)}};var ve={defaults:{delimiter:".",sigilBytes:4,previewBytes:8},toBytes(n){n=n.trim();let e=n.split(/[^a-zA-Z0-9]+/m).filter(Boolean).map(o=>o.trim());if(e.length<2)return Ie.toBytes(e.join(""));let t=e.pop(),r=e.join("");return new Uint8Array([...Ie.toBytes(r),...Io.toBytes(t)])},parse(n,e){let t=ve.toBytes(n);return ve.build.fromBytes(t,e)},build:{fromBytes(n,e={}){let{delimiter:t,previewBytes:r,sigilBytes:o}={...ve.defaults,...e},i=u=>n.length>0?Ie.fromBytes(n.slice(0,u),{wordSeparator:t,groupSeparator:t}):"",s=i(o),a=i(r),c=n.length>r?Io.fromBytes(n.slice(r)):"",l=[a,c].filter(u=>u.length>0).join(t);return{raw:n,full:l,preview:a,bulk:c,sigil:s,bytes:n,thumbprint:l}},fromHex(n,e){let t=ye.toBytes(n);return ve.build.fromBytes(t,e)}},toHex(n){let e=ve.toBytes(n);return ye.fromBytes(e)},fromBytes(n,e){return ve.build.fromBytes(n,e).full},fromHex(n,e){return ve.fromBytes(ye.toBytes(n),e)},sigil:{fromHex(n,e){return ve.build.fromHex(n,e).sigil},fromBytes(n,e){return ve.build.fromBytes(n,e).sigil}}},Xi=ve;var zr=Object.freeze({fromBytes(n){return[...n].map(e=>e.toString(16).padStart(2,"0")).join("")},toBytes(n){if(n.length%2!==0)throw new Error("must have even number of hex characters");let e=new Uint8Array(n.length/2);for(let t=0;t<n.length;t+=2)e[t/2]=parseInt(n.slice(t,t+2),16);return e},random(n=32){return this.fromBytes(kt.random(n))},string(n){return zr.fromBytes(n)},bytes(n){return zr.toBytes(n)}});function Te(){let n,e,t=new Promise((o,i)=>{n=o,e=i});function r(o){return o.then(n).catch(e),t}return{promise:t,resolve:n,reject:e,entangle:r}}var Nr=Object.freeze({happy:n=>n!=null,sad:n=>n==null,boolean:n=>typeof n=="boolean",number:n=>typeof n=="number",string:n=>typeof n=="string",bigint:n=>typeof n=="bigint",object:n=>typeof n=="object"&&n!==null,array:n=>Array.isArray(n),fn:n=>typeof n=="function",symbol:n=>typeof n=="symbol"});var Ur=class n 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,r){if(e.has(t))return e.get(t);{let o=r();return e.set(t,o),o}}array(){return[...this]}require(e){return n.require(this,e)}guarantee(e,t){return n.guarantee(this,e,t)}};var rr=class extends Error{milliseconds;name=this.constructor.name;constructor(e){super(`deadline exceeded (${(e/1e3).toFixed(1)} seconds)`),this.milliseconds=e}};function Ki(n,e){return n<=0||n===1/0?e():new Promise((t,r)=>{let o=setTimeout(()=>r(new rr(n)),n);e().then(t).catch(r).finally(()=>clearTimeout(o))})}function Lr(){let n=[];function e(){for(let t of n)t();n=[]}return e.schedule=(...t)=>(n.push(...t),e),e}function Qi(n,e){let t=n;for(let r of e)if(t=t[r],Nr.sad(t))break;return t}function Pc(){let n=new Set;async function e(...c){await Promise.all([...n].map(l=>l(...c)))}function t(c){return n.add(c),()=>{n.delete(c)}}async function r(...c){return e(...c)}function o(c){return t(c)}async function i(c){let{promise:l,resolve:u}=Te(),d=o(async(...m)=>{c&&await c(...m),u(m),d()});return l}function s(){n.clear()}let a={pub:r,sub:o,publish:e,subscribe:t,on:t,next:i,clear:s};return Object.assign(o,a),Object.assign(r,a),a}function St(n){let e=Pc();return n&&e.sub(n),e.pub}function Eo(n,e){return{error:t=>n.error({...e,...t}),rpcRequest:t=>n.rpcRequest({...e,...t}),rpcError:t=>n.rpcError({...e,...t})}}var Vr=()=>n=>({plain:n.none,errMessage:n.mix(n.brightRed,n.bold),errName:n.red,errStack:n.mix(n.red,n.dim),timestamp:n.blue,timestampErr:n.red});function Yi(){return Vr()}var Ue=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 Hr=()=>({none:n=>n,uncolor:Ac,mix:_c,hex:Ec,rgb:Zi,bgRgb:Fc});function Ac(n){return n.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"")}function _c(...n){return e=>{for(let t of n)e=t(e);return e}}function Ec(n){n=n.replace(/^#/,"");let e,t,r,o;if(n.length===3)e=parseInt(n.split("").map(i=>i+i).join(""),16);else if(n.length===6)e=parseInt(n,16);else throw new Error("Invalid hex color");return t=e>>16&255,r=e>>8&255,o=e&255,Zi(t,r,o)}function Zi(n,e,t){let r=`\x1B[38;2;${n};${e};${t}m`;return o=>`${r}${o}${Ue.reset}`}function Fc(n,e,t){let r=`\x1B[48;2;${n};${e};${t}m`;return o=>`${r}${o}${Ue.reset}`}var nr={...Object.fromEntries(Object.entries(Ue).map(([n])=>[n,e=>e])),...Hr()};var or={...Object.fromEntries(Object.entries(Ue).map(([n,e])=>[n,t=>`${e}${t}${Ue.reset}`])),...Hr()};function Fo(){return typeof Deno<"u"&&typeof Deno.version<"u"}function Do(){return typeof process<"u"&&process.versions&&process.versions.node}function Ji(){return Do()?process.env.FORCE_COLOR||process.stdout.isTTY&&process.env.TERM!=="dumb":Fo()?Deno.env.get("FORCE_COLOR")||Deno.isatty(Deno.stdout.rid)&&Deno.env.get("TERM")!=="dumb":!1}var Ro=()=>Ji()?or:nr;var Wr=()=>({colors:n,theme:e})=>{let t=e(n);function r(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?r(s):s}function i(s){return s&&s instanceof Error?r(s):t.errMessage(s)}return{stdout:s=>s.map(o),stderr:s=>s.map(i)}};function ir(...n){return e=>({stdout:t=>{for(let r of n)t=r(e).stdout(t);return t},stderr:t=>{for(let r of n)t=r(e).stderr(t);return t}})}function Dc(){return{icon:"\u{1F6A8}",now:()=>Date.now()}}var qr=n=>({colors:e,theme:t})=>{let r={...Dc(),...n},o=t(e),i=new Date(r.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}`,u=i.getUTCHours().toString().padStart(2,"0"),d=i.getUTCMinutes().toString().padStart(2,"0"),m=i.getUTCSeconds().toString().padStart(2,"0"),f=i.getUTCMilliseconds().toString().padStart(3,"0"),p=`${u}:${d}:${m}.${f}`,h=`${l}::${p}`;return{stdout:g=>[o.timestamp(h),...g],stderr:g=>[o.timestampErr(h),...[r.icon].filter(Boolean),...g]}};function es(){return ir(Wr(),qr())}var Gr=()=>({stdout:async n=>{await Deno.stdout.write(new TextEncoder().encode(n+`
|
|
2337
2337
|
`))},stderr:async n=>{await Deno.stderr.write(new TextEncoder().encode(n+`
|
|
2338
2338
|
`))}});var jr=()=>({stdout:async n=>{process.stdout.write(n+`
|
|
2339
2339
|
`)},stderr:async n=>{process.stderr.write(n+`
|
|
2340
|
-
`)}});var $r=()=>({stdout:async n=>console.log(n),stderr:async n=>console.error(n)});var ts=()=>Fo()?Gr():Do()?jr():$r();var rs=()=>({stdout:async()=>{},stderr:async()=>{}});function ns(){return()=>({stdout:n=>n,stderr:n=>n})}var Ct=class n{static writers={auto:ts,void:rs,deno:Gr,node:jr,console:$r};static colors={auto:Ro,colorful:()=>or,colorless:()=>nr};static themes={auto:Yi,basic:Vr};static shapers={auto:es,none:ns,errors:Wr,timestamp:qr};writer=n.writers.auto();colors=n.colors.auto();theme=n.themes.auto();shaper=n.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=ir(...e),this}};var sr=class extends Ct{static dummy(){return new this().setWriter(Ct.writers.void())}rpcRequest=async({request:e,...t})=>{let r=this.colors.none;this.log(...this.#e(t),r(`${e.method}()`))};rpcError=async({request:e,error:t,...r})=>{this.error(...this.#e(r),`${e.method}()`,t)};#e({meta:e,label:t,remote:r}){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,r===void 0?void 0:r?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 we=class extends sr{rpcRequest=async()=>{}};var Ae;(function(n){n.version="2.0";function e(t){return"id"in t?t.id:null}n.getId=e,n.errorCodes={serverError:-32e3,unexposedError:-32001}})(Ae||(Ae={}));var Xr=class extends Error{name=this.constructor.name},Ye=class extends Error{name=this.constructor.name};async function os({tap:n,request:e,action:t}){let r=Ae.getId(e);try{let o=await t();return r===null?null:{id:r,result:o,jsonrpc:Ae.version}}catch(o){return n.rpcError({request:e,error:o}),r===null?null:{id:r,jsonrpc:Ae.version,error:o instanceof Xr?{code:Ae.errorCodes.serverError,message:o.message}:{code:Ae.errorCodes.unexposedError,message:"unexposed error"}}}}function Kr(n){let e=n.tap??new we;return async t=>{let r=t.method.split("."),o=Qi(n.fns,r),i=async()=>await o(...t.params);return e.rpcRequest({request:t}),await os({tap:e,request:t,action:i})}}var Pt=Symbol("tune"),Rc=Symbol("query"),Mc=Symbol("notify"),Bc=Symbol("settings");function is(n){function e(t){let r={notify:void 0};return new Proxy((()=>{}),{apply:(o,i,s)=>n(t,s,r),get:(o,i)=>{if(i!=="then")return i===Pt?s=>(...a)=>n(t,a,{...r,...s}):i===Mc?(...s)=>n(t,s,{...r,notify:!0}):i===Rc?(...s)=>n(t,s,{...r,notify:!1}):i===Bc?r:(o[i]||(o[i]=e([...t,i])),o[i])},set:(o,i,s)=>(o[i]=s,!0)})}return e([])}function Ze(n){let{endpoint:e,tap:t=new we}=n,r=1;return is(async(o,i,s)=>{let a=s.notify??n.notify??!1,c=s.transfer,l={jsonrpc:"2.0",method:o.join("."),params:i},u=a?l:{...l,id:r++};t.rpcRequest({request:u});let d=await e(u,{transfer:c});if(a&&!d)return null;if(!d)throw new Ye("response was null, but shouldn't be, because the request was not a notification");if("error"in d)throw new Ye(n.label?`${n.label}: ${d.error.message}`:d.error.message);return d.result})}function ar(n){return Ze({endpoint:Kr(n),tap:n.tap})}var Je=class{recv=Ue();sendRequest=Ue();sendResponse=Ue();static makeEntangledPair({origin:e="example.e280.org"}={}){let t=new this,r=new this,o=[t.sendRequest.sub(s=>r.recv(s,{origin:e})),t.sendResponse.sub(s=>r.recv(s,{origin:e})),r.sendRequest.sub(s=>t.recv(s,{origin:e})),r.sendResponse.sub(s=>t.recv(s,{origin:e}))];return[t,r,()=>o.forEach(s=>s())]}};function Qr(n,e){return n.addEventListener("message",e),()=>n.removeEventListener("message",e)}function ss(n,e){return async(t,{transfer:r}={})=>{if("id"in t){let o=Te();return e(t,r,o.promise),n.wait(t.id,t.method).then(i=>(o.resolve(i),i))}else{let o=Promise.resolve(null);return e(t,r,o),o}}}function as(n){let e=[],t=[];for(let r of Array.isArray(n)?n:[n])"method"in r?e.push(r):t.push(r);return{requests:e,responses:t}}async function cs(n,e){let t=(await Promise.all(e.map(async r=>n(r)))).filter(r=>r!==null);return t.length===0?null:t.length===1?t[0]:t}var It=class extends Je{dispose=Lr();constructor(e){super(),this.dispose.schedule(this.sendRequest.sub((t,r)=>e.postMessage(t,r)),this.sendResponse.sub((t,r)=>e.postMessage(t,r)),Qr(e,t=>this.recv(t.data,t)))}};var Yr=class{remote;transfer;constructor(e){this.remote=e}};var Mo=Object.freeze({timeout:6e4,maxRequestBytes:1e7});var Zr=class{timeout;pending=new Map;constructor(e){this.timeout=e}async wait(e,t){let r=Te();return this.pending.set(e,{method:t,deferred:r}),await Ki(this.timeout,()=>r.promise).catch(o=>{throw o instanceof rr&&(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 Ye(e.error.message)):t.deferred.resolve(e))}};var et=class{options;remote;remoteEndpoint;dispose=Lr();#e;constructor(e){this.options=e;let{conduit:t,tap:r}=e;this.#e=new Zr(e.timeout??Mo.timeout),this.remoteEndpoint=ss(this.#e,t.sendRequest.pub.bind(t.sendRequest)),this.remote=Ze({endpoint:this.remoteEndpoint,tap:r&&Eo(r,{remote:!0})}),this.dispose.schedule(t.recv.sub(o=>this.recv(o)))}async recv(e){let t=new Yr(this.remote),{conduit:r,rpc:o,tap:i}=this.options,{requests:s,responses:a}=as(e);for(let d of a)this.#e.deliverResponse(d);if(!o)return;let c=await o(t),l=Kr({fns:c,tap:i&&Eo(i,{remote:!1})}),u=await cs(l,s);u&&await r.sendResponse(u,t.transfer)}};var _e={derive:{host:n=>({host:n.remote.host,get transfer(){return n.transfer},set transfer(e){n.transfer=e}}),work:n=>({work:n.remote,get transfer(){return n.transfer},set transfer(e){n.transfer=e}})},mock:{host:()=>({host:void 0,transfer:void 0}),work:()=>({work:void 0,transfer:void 0})}};var Ee=new we;async function ls(n,e,t={}){let r=t.tap??Ee,o=new et({tap:r,timeout:t.timeout??1/0,conduit:new It(n.getSelf()),rpc:async i=>e(_e.derive.host(i))});return await o.remote.infra.ready(),o.remote.host}var At=class{worker;messenger;constructor(e,t){this.worker=e,this.messenger=t}static async make(e,t){let r=t.tap??Ee,o=t.label??"comrade",i=e.loadWorker(t.workerUrl,o),s=Te(),a={async ready(){s.resolve()}},c=new et({tap:r,timeout:t.timeout??1/0,conduit:new It(i),rpc:async l=>({infra:a,host:t.setupHost(_e.derive.work(l))})});return await s.promise,new this(i,c)}get work(){return this.messenger.remote}terminate(){this.worker.terminate()}};var Jr=class{threads;static async make(e,t){let r=t.workerCount??e.guessOptimalThreadCount(),o=await Promise.all([...Array(r)].map(async(i,s)=>At.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 r=t.tap??Ee,o=async(i,s)=>this.#r({request:i,prom:Te(),transfer:s?.transfer});this.work=Ze({tap:r,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 r=e.messenger.remoteEndpoint(t.request,{transfer:t.transfer});t.prom.entangle(r).finally(()=>{this.#e.add(e),this.#n()})}}};var us=n=>({thread:e=>At.make(n,e),cluster:e=>Jr.make(n,e),worker:(e,t={})=>ls(n,e,t),work:e=>e,host:e=>e,mocks(e){let{setupWork:t,setupHost:r,tap:o=Ee}=e,i=_e.mock.host(),s=_e.mock.work();return s.work=ar({tap:o,fns:t(i)}),i.host=ar({tap:o,fns:r(s)}),{workShell:s,hostShell:i,work:s.work,host:i.host}},mockWork(e,t=Ee){let r=_e.mock.host(),o=_e.mock.work();return o.work=ar({tap:t,fns:e(r)}),{workShell:o,hostShell:r,work:o.work,mockHost:i=>(r.host=ar({tap:t,fns:i(o)}),{workShell:o,hostShell:r,work:o.work,host:r.host})}}});var ds=()=>({getSelf(){return self},guessOptimalThreadCount(){let n=navigator.hardwareConcurrency??1;return Math.max(1,n-1)},loadWorker(n,e){return new window.Worker(n,{name:e,type:"module"})},async loadWasm(n){return WebAssembly.instantiateStreaming(fetch(n))}});var Nc=ds(),en=us(Nc);function b(n){if(!n)throw new Error("Assertion failed.")}var tn=n=>{let e=(n%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${n}.`)},ee=n=>n&&n[n.length-1];var V=class n{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,r=7-(this.pos&7),o=(t&1<<r)>>r;return this.pos++,o}readBits(e){if(e===1)return this.readBit();let t=0;for(let r=0;r<e;r++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let r=this.pos+e;for(let o=this.pos;o<r;o++){let i=Math.floor(o/8),s=this.bytes[i],a=7-(o&7);s&=~(1<<a),s|=(t&1<<r-o-1)>>r-o-1<<a,this.bytes[i]=s}this.pos=r}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 n(this.bytes);return e.pos=this.pos,e}},_=n=>{let e=0;for(;n.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+n.readBits(e)},Se=n=>{let e=_(n);return(e&1)===0?-(e>>1):e+1>>1};var fe=n=>n.constructor===Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n),z=n=>n.constructor===DataView?n:ArrayBuffer.isView(n)?new DataView(n.buffer,n.byteOffset,n.byteLength):new DataView(n),K=new TextDecoder;var Uo=n=>Object.fromEntries(Object.entries(n).map(([e,t])=>[t,e])),Lo={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},rn=Uo(Lo),Vo={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},nn=Uo(Vo),Ho={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},on=Uo(Ho);var sn=n=>n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer||ArrayBuffer.isView(n),ke=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e,t=new Promise(o=>{e=o}),r=this.currentPromise;return this.currentPromise=t,await r,e}},Wo=n=>[...n].map(e=>e.toString(16).padStart(2,"0")).join(""),qo=n=>(n=n>>1&1431655765|(n&1431655765)<<1,n=n>>2&858993459|(n&858993459)<<2,n=n>>4&252645135|(n&252645135)<<4,n=n>>8&16711935|(n&16711935)<<8,n=n>>16&65535|(n&65535)<<16,n>>>0),tt=(n,e,t)=>{let r=0,o=n.length-1,i=-1;for(;r<=o;){let s=r+o>>1,a=t(n[s]);a===e?(i=s,o=s-1):a<e?r=s+1:o=s-1}return i},O=(n,e,t)=>{let r=0,o=n.length-1,i=-1;for(;r<=o;){let s=r+(o-r+1)/2|0;t(n[s])<=e?(i=s,r=s+1):o=s-1}return i},Go=(n,e,t)=>{let r=O(n,t(e),t);n.splice(r+1,0,e)},te=()=>{let n,e;return{promise:new Promise((r,o)=>{n=r,e=o}),resolve:n,reject:e}};var jo=(n,e)=>{for(let t=n.length-1;t>=0;t--)if(e(n[t]))return n[t]},an=(n,e)=>{for(let t=n.length-1;t>=0;t--)if(e(n[t]))return t;return-1},fs=async function*(n){Symbol.iterator in n?yield*n[Symbol.iterator]():yield*n[Symbol.asyncIterator]()},ps=n=>{if(!(Symbol.iterator in n)&&!(Symbol.asyncIterator in n))throw new TypeError("Argument must be an iterable or async iterable.")},ue=n=>{throw new Error(`Unexpected value: ${n}`)},rt=(n,e,t)=>{let r=n.getUint8(e),o=n.getUint8(e+1),i=n.getUint8(e+2);return t?r|o<<8|i<<16:r<<16|o<<8|i},hs=(n,e,t)=>rt(n,e,t)<<8>>8,gs=(n,e,t,r)=>{t=t>>>0,t=t&16777215,r?(n.setUint8(e,t&255),n.setUint8(e+1,t>>>8&255),n.setUint8(e+2,t>>>16&255)):(n.setUint8(e,t>>>16&255),n.setUint8(e+1,t>>>8&255),n.setUint8(e+2,t&255))};var $o=(n,e)=>({async next(){let t=await n.next();return t.done?{value:void 0,done:!0}:{value:e(t.value),done:!1}},return(){return n.return()},throw(t){return n.throw(t)},[Symbol.asyncIterator](){return this}}),nt=(n,e,t)=>Math.max(e,Math.min(t,n)),Q="und",ot=n=>{let e=Math.round(n);return Math.abs(n/e-1)<10*Number.EPSILON?e:n},xs=(n,e)=>Math.round(n/e)*e,bs=n=>{let e=0;for(;n;)e++,n>>=1;return e},Uc=/^[a-z]{3}$/,cn=n=>Uc.test(n),Ce=1e6*(1+Number.EPSILON),Xo=(n,e)=>{let t={...n,...e};if(n.headers||e.headers){let r=n.headers?ms(n.headers):{},o=e.headers?ms(e.headers):{},i={...r};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},ms=n=>{if(n instanceof Headers){let e={};return n.forEach((t,r)=>{e[r]=t}),e}if(Array.isArray(n)){let e={};return n.forEach(([t,r])=>{e[t]=r}),e}return n},Ko=async(n,e,t,r,o)=>{let i=0;for(;;)try{return await n(e,t)}catch(s){if(o())throw s;i++;let a=r(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 cr=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},Bo=null,Ve=()=>Bo!==null?Bo:Bo=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),Oo=null,lr=()=>Oo!==null?Oo:Oo=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),zo=null,ur=()=>zo!==null?zo:zo=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),No=null,ys=()=>{if(No!==null)return No;if(typeof navigator>"u")return null;let n=/\bChrome\/(\d+)/.exec(navigator.userAgent);return n?No=Number(n[1]):null},it=(n,e)=>n!==-1?n:e,ln=(n,e,t,r)=>n<=r&&t<=e;var vs=n=>{let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t};var un=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},dr=n=>typeof n=="number"&&!Number.isNaN(n);var He=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.")}},dn=class{constructor(e,t,r,o){if(this.data=e,this.mimeType=t,this.name=r,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(r!==void 0&&typeof r!="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 ie={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};var We=["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"],Lc=["aac","opus","mp3","vorbis","flac"],gp=[...Lc,...We];var st=[{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 Ts=".01.01.01.01.00",ws=".0.110.01.01.01.0";var mn=n=>{let{codec:e,codecDescription:t,colorSpace:r,avcCodecInfo:o,hevcCodecInfo:i,vp9CodecInfo:s,av1CodecInfo:a}=n;if(e==="avc"){if(b(n.avcType!==null),o){let c=new Uint8Array([o.avcProfileIndication,o.profileCompatibility,o.avcLevelIndication]);return`avc${n.avcType}.${Wo(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${n.avcType}.${Wo(t.subarray(1,4))}`}else if(e==="hevc"){let c,l,u,d,m,f;if(i)c=i.generalProfileSpace,l=i.generalProfileIdc,u=qo(i.generalProfileCompatibilityFlags),d=i.generalTierFlag,m=i.generalLevelIdc,f=[...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 h=z(t),g=h.getUint8(1);c=g>>6&3,l=g&31,u=qo(h.getUint32(2)),d=g>>5&1,m=h.getUint8(12),f=[];for(let y=0;y<6;y++)f.push(h.getUint8(6+y))}let p="hev1.";for(p+=["","A","B","C"][c]+l,p+=".",p+=u.toString(16).toUpperCase(),p+=".",p+=d===0?"L":"H",p+=m;f.length>0&&f[f.length-1]===0;)f.pop();return f.length>0&&(p+=".",p+=f.map(h=>h.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!s){let y=n.width*n.height,x=ee(st).level;for(let v of st)if(y<=v.maxPictureSize){x=v.level;break}return`vp09.00.${x.toString().padStart(2,"0")}.08`}let c=s.profile.toString().padStart(2,"0"),l=s.level.toString().padStart(2,"0"),u=s.bitDepth.toString().padStart(2,"0"),d=s.chromaSubsampling.toString().padStart(2,"0"),m=s.colourPrimaries.toString().padStart(2,"0"),f=s.transferCharacteristics.toString().padStart(2,"0"),p=s.matrixCoefficients.toString().padStart(2,"0"),h=s.videoFullRangeFlag.toString().padStart(2,"0"),g=`vp09.${c}.${l}.${u}.${d}`;return g+=`.${m}.${f}.${p}.${h}`,g.endsWith(Ts)&&(g=g.slice(0,-Ts.length)),g}else if(e==="av1"){if(!a){let v=n.width*n.height,T=ee(st).level;for(let S of st)if(v<=S.maxPictureSize){T=S.level;break}return`av01.0.${T.toString().padStart(2,"0")}M.08`}let c=a.profile,l=a.level.toString().padStart(2,"0"),u=a.tier?"H":"M",d=a.bitDepth.toString().padStart(2,"0"),m=a.monochrome?"1":"0",f=100*a.chromaSubsamplingX+10*a.chromaSubsamplingY+1*(a.chromaSubsamplingX&&a.chromaSubsamplingY?a.chromaSamplePosition:0),p=r?.primaries?Lo[r.primaries]:1,h=r?.transfer?Vo[r.transfer]:1,g=r?.matrix?Ho[r.matrix]:1,y=r?.fullRange?1:0,x=`av01.${c}.${l}${u}.${d}`;return x+=`.${m}.${f.toString().padStart(3,"0")}`,x+=`.${p.toString().padStart(2,"0")}`,x+=`.${h.toString().padStart(2,"0")}`,x+=`.${g.toString().padStart(2,"0")}`,x+=`.${y}`,x.endsWith(ws)&&(x=x.slice(0,-ws.length)),x}}throw new TypeError(`Unhandled codec '${e}'.`)};var fn=n=>{let{codec:e,codecDescription:t,aacCodecInfo:r}=n;if(e==="aac"){if(!r)throw new TypeError("AAC codec info must be provided.");return r.isMpeg2?"mp4a.67":`mp4a.40.${Yo(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&&We.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},mr=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Qo=[-1,1,2,3,4,5,6,8],Yo=n=>{if(!n||n.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new V(n),t=e.readBits(5);t===31&&(t=32+e.readBits(6));let r=e.readBits(4),o=null;r===15?o=e.readBits(24):r<mr.length&&(o=mr[r]);let i=e.readBits(4),s=null;return i>=1&&i<=7&&(s=Qo[i]),{objectType:t,frequencyIndex:r,sampleRate:o,channelConfiguration:i,numberOfChannels:s}};var at=48e3,Vc=/^pcm-([usf])(\d+)+(be)?$/,pn=n=>{if(b(We.includes(n)),n==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(n==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=Vc.exec(n);b(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";let r=Number(e[2])/8,o=e[3]!=="be",i=n==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:r,littleEndian:o,silentValue:i}};var ct;(function(n){n[n.IDR=5]="IDR",n[n.SEI=6]="SEI",n[n.SPS=7]="SPS",n[n.PPS=8]="PPS",n[n.SPS_EXT=13]="SPS_EXT"})(ct||(ct={}));var re;(function(n){n[n.RASL_N=8]="RASL_N",n[n.RASL_R=9]="RASL_R",n[n.BLA_W_LP=16]="BLA_W_LP",n[n.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",n[n.VPS_NUT=32]="VPS_NUT",n[n.SPS_NUT=33]="SPS_NUT",n[n.PPS_NUT=34]="PPS_NUT",n[n.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",n[n.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(re||(re={}));var gn=n=>{let e=[],t=0;for(;t<n.length;){let r=-1,o=0;for(let i=t;i<n.length-3;i++){if(n[i]===0&&n[i+1]===0&&n[i+2]===1){r=i,o=3;break}if(i<n.length-4&&n[i]===0&&n[i+1]===0&&n[i+2]===0&&n[i+3]===1){r=i,o=4;break}}if(r===-1)break;if(t>0&&r>t){let i=n.subarray(t,r);i.length>0&&e.push(i)}t=r+o}if(t<n.length){let r=n.subarray(t);r.length>0&&e.push(r)}return e},Cs=(n,e)=>{let t=[],r=0,o=new DataView(n.buffer,n.byteOffset,n.byteLength);for(;r+e<=n.length;){let i;e===1?i=o.getUint8(r):e===2?i=o.getUint16(r,!1):e===3?i=rt(o,r,!1):e===4?i=o.getUint32(r,!1):(ue(e),b(!1)),r+=e;let s=n.subarray(r,r+i);t.push(s),r+=i}return t},hn=n=>{let e=[],t=n.length;for(let r=0;r<t;r++)r+2<t&&n[r]===0&&n[r+1]===0&&n[r+2]===3?(e.push(0,0),r+=2):e.push(n[r]);return new Uint8Array(e)},Zo=new Uint8Array([0,0,0,1]),Wc=n=>{let e=n.reduce((o,i)=>o+Zo.byteLength+i.byteLength,0),t=new Uint8Array(e),r=0;for(let o of n)t.set(Zo,r),r+=Zo.byteLength,t.set(o,r),r+=o.byteLength;return t},qc=(n,e)=>{let t=n.reduce((i,s)=>i+e+s.byteLength,0),r=new Uint8Array(t),o=0;for(let i of n){let s=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(e){case 1:s.setUint8(o,i.byteLength);break;case 2:s.setUint16(o,i.byteLength,!1);break;case 3:gs(s,o,i.byteLength,!1);break;case 4:s.setUint32(o,i.byteLength,!1);break}o+=e,r.set(i,o),o+=i.byteLength}return r},Jo=(n,e)=>{if(e.description){let o=(fe(e.description)[4]&3)+1;return Cs(n,o)}else return gn(n)},Ps=(n,e)=>{if(e.description){let o=(fe(e.description)[4]&3)+1;return qc(n,o)}else return Wc(n)},lt=n=>n[0]&31,Is=n=>{try{let e=gn(n),t=e.filter(c=>lt(c)===ct.SPS),r=e.filter(c=>lt(c)===ct.PPS),o=e.filter(c=>lt(c)===ct.SPS_EXT);if(t.length===0||r.length===0)return null;let i=t[0],s=ei(i);b(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:r,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 As=n=>{try{let e=z(n),t=0,r=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 f=0;f<c;f++){let p=e.getUint16(t,!1);t+=2,l.push(n.subarray(t,t+p)),t+=p}let u=e.getUint8(t++),d=[];for(let f=0;f<u;f++){let p=e.getUint16(t,!1);t+=2,d.push(n.subarray(t,t+p)),t+=p}let m={configurationVersion:r,avcProfileIndication:o,profileCompatibility:i,avcLevelIndication:s,lengthSizeMinusOne:a,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((o===100||o===110||o===122||o===144)&&t+4<=n.length){let f=e.getUint8(t++)&3,p=e.getUint8(t++)&7,h=e.getUint8(t++)&7,g=e.getUint8(t++);m.chromaFormat=f,m.bitDepthLumaMinus8=p,m.bitDepthChromaMinus8=h;let y=[];for(let x=0;x<g;x++){let v=e.getUint16(t,!1);t+=2,y.push(n.subarray(t,t+v)),t+=v}m.sequenceParameterSetExt=y}return m}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}},ei=n=>{try{let e=new V(hn(n));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let r=e.readAlignedByte(),o=e.readAlignedByte(),i=e.readAlignedByte();_(e);let s=null,a=null,c=null;if((r===100||r===110||r===122||r===244||r===44||r===83||r===86||r===118||r===128)&&(s=_(e),s===3&&e.skipBits(1),a=_(e),c=_(e),e.skipBits(1),e.readBits(1))){for(let m=0;m<(s!==3?8:12);m++)if(e.readBits(1)){let p=m<6?16:64,h=8,g=8;for(let y=0;y<p;y++){if(g!==0){let x=Se(e);g=(h+x+256)%256}h=g===0?h:g}}}_(e);let l=_(e);if(l===0)_(e);else if(l===1){e.skipBits(1),Se(e),Se(e);let d=_(e);for(let m=0;m<d;m++)Se(e)}_(e),e.skipBits(1),_(e),_(e);let u=e.readBits(1);return{profileIdc:r,constraintFlags:o,levelIdc:i,frameMbsOnlyFlag:u,chromaFormatIdc:s,bitDepthLumaMinus8:a,bitDepthChromaMinus8:c}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},ti=(n,e)=>{if(e.description){let o=(fe(e.description)[21]&3)+1;return Cs(n,o)}else return gn(n)},Fe=n=>n[0]>>1&63,_s=n=>{try{let e=gn(n),t=e.filter(R=>Fe(R)===re.VPS_NUT),r=e.filter(R=>Fe(R)===re.SPS_NUT),o=e.filter(R=>Fe(R)===re.PPS_NUT),i=e.filter(R=>Fe(R)===re.PREFIX_SEI_NUT||Fe(R)===re.SUFFIX_SEI_NUT);if(r.length===0||o.length===0)return null;let s=r[0],a=new V(hn(s));a.skipBits(16),a.readBits(4);let c=a.readBits(3),l=a.readBits(1),{general_profile_space:u,general_tier_flag:d,general_profile_idc:m,general_profile_compatibility_flags:f,general_constraint_indicator_flags:p,general_level_idc:h}=Gc(a,c);_(a);let g=_(a);g===3&&a.skipBits(1),_(a),_(a),a.readBits(1)&&(_(a),_(a),_(a),_(a));let y=_(a),x=_(a);_(a);let T=a.readBits(1)?0:c;for(let R=T;R<=c;R++)_(a),_(a),_(a);_(a),_(a),_(a),_(a),_(a),_(a),a.readBits(1)&&a.readBits(1)&&jc(a),a.skipBits(1),a.skipBits(1),a.readBits(1)&&(a.skipBits(4),a.skipBits(4),_(a),_(a),a.skipBits(1));let S=_(a);if($c(a,S),a.readBits(1)){let R=_(a);for(let D=0;D<R;D++)_(a),a.skipBits(1)}a.skipBits(1),a.skipBits(1);let k=0;a.readBits(1)&&(k=Kc(a,c));let I=0;if(o.length>0){let R=o[0],D=new V(hn(R));D.skipBits(16),_(D),_(D),D.skipBits(1),D.skipBits(1),D.skipBits(3),D.skipBits(1),D.skipBits(1),_(D),_(D),Se(D),D.skipBits(1),D.skipBits(1),D.readBits(1)&&_(D),Se(D),Se(D),D.skipBits(1),D.skipBits(1),D.skipBits(1),D.skipBits(1);let L=D.readBits(1),Y=D.readBits(1);!L&&!Y?I=0:L&&!Y?I=2:!L&&Y?I=3:I=0}let C=[...t.length?[{arrayCompleteness:1,nalUnitType:re.VPS_NUT,nalUnits:t}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:re.SPS_NUT,nalUnits:r}]:[],...o.length?[{arrayCompleteness:1,nalUnitType:re.PPS_NUT,nalUnits:o}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Fe(i[0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:u,generalTierFlag:d,generalProfileIdc:m,generalProfileCompatibilityFlags:f,generalConstraintIndicatorFlags:p,generalLevelIdc:h,minSpatialSegmentationIdc:k,parallelismType:I,chromaFormatIdc:g,bitDepthLumaMinus8:y,bitDepthChromaMinus8:x,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}},Gc=(n,e)=>{let t=n.readBits(2),r=n.readBits(1),o=n.readBits(5),i=0;for(let u=0;u<32;u++)i=i<<1|n.readBits(1);let s=new Uint8Array(6);for(let u=0;u<6;u++)s[u]=n.readBits(8);let a=n.readBits(8),c=[],l=[];for(let u=0;u<e;u++)c.push(n.readBits(1)),l.push(n.readBits(1));if(e>0)for(let u=e;u<8;u++)n.skipBits(2);for(let u=0;u<e;u++)c[u]&&n.skipBits(88),l[u]&&n.skipBits(8);return{general_profile_space:t,general_tier_flag:r,general_profile_idc:o,general_profile_compatibility_flags:i,general_constraint_indicator_flags:s,general_level_idc:a}},jc=n=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!n.readBits(1))_(n);else{let o=Math.min(64,1<<4+(e<<1));e>1&&Se(n);for(let i=0;i<o;i++)Se(n)}},$c=(n,e)=>{let t=[];for(let r=0;r<e;r++)t[r]=Xc(n,r,e,t)},Xc=(n,e,t,r)=>{let o=0,i=0,s=0;if(e!==0&&(i=n.readBits(1)),i){if(e===t){let c=_(n);s=e-(c+1)}else s=e-1;n.readBits(1),_(n);let a=r[s]??0;for(let c=0;c<=a;c++)n.readBits(1)||n.readBits(1);o=r[s]}else{let a=_(n),c=_(n);for(let l=0;l<a;l++)_(n),n.readBits(1);for(let l=0;l<c;l++)_(n),n.readBits(1);o=a+c}return o},Kc=(n,e)=>{if(n.readBits(1)&&n.readBits(8)===255&&(n.readBits(16),n.readBits(16)),n.readBits(1)&&n.readBits(1),n.readBits(1)&&(n.readBits(3),n.readBits(1),n.readBits(1)&&(n.readBits(8),n.readBits(8),n.readBits(8))),n.readBits(1)&&(_(n),_(n)),n.readBits(1),n.readBits(1),n.readBits(1),n.readBits(1)&&(_(n),_(n),_(n),_(n)),n.readBits(1)&&(n.readBits(32),n.readBits(32),n.readBits(1)&&_(n),n.readBits(1)&&Qc(n,!0,e)),n.readBits(1)){n.readBits(1),n.readBits(1),n.readBits(1);let t=_(n);return _(n),_(n),_(n),_(n),t}return 0},Qc=(n,e,t)=>{let r=!1,o=!1,i=!1;e&&(r=n.readBits(1)===1,o=n.readBits(1)===1,(r||o)&&(i=n.readBits(1)===1,i&&(n.readBits(8),n.readBits(5),n.readBits(1),n.readBits(5)),n.readBits(4),n.readBits(4),i&&n.readBits(4),n.readBits(5),n.readBits(5),n.readBits(5)));for(let s=0;s<=t;s++){let a=n.readBits(1)===1,c=!0;a||(c=n.readBits(1)===1);let l=!1;c?_(n):l=n.readBits(1)===1;let u=1;l||(u=_(n)+1),r&&ks(n,u,i),o&&ks(n,u,i)}},ks=(n,e,t)=>{for(let r=0;r<e;r++)_(n),_(n),t&&(_(n),_(n)),n.readBits(1)};var xn=n=>{let e=new V(n);if(e.readBits(2)!==2)return null;let r=e.readBits(1),i=(e.readBits(1)<<1)+r;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 u=e.readBits(3),d=0,m=0;if(u!==7)if(m=e.readBits(1),i===1||i===3){let I=e.readBits(1),C=e.readBits(1);d=!I&&!C?3:I&&!C?2:1,e.skipBits(1)}else d=1;else d=3,m=1;let f=e.readBits(16),p=e.readBits(16),h=f+1,g=p+1,y=h*g,x=ee(st).level;for(let k of st)if(y<=k.maxPictureSize){x=k.level;break}return{profile:i,level:x,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:m,colourPrimaries:u===2?1:u===1?6:2,transferCharacteristics:u===2?1:u===1?6:2,matrixCoefficients:u===7?0:u===2?1:u===1?6:2}},Es=function*(n){let e=new V(n),t=()=>{let r=0;for(let o=0;o<8;o++){let i=e.readAlignedByte();if(r|=(i&127)<<o*7,!(i&128))break;if(o===7&&i&128)return null}return r>=2**32-1?null:r};for(;e.getBitsLeft()>=8;){e.skipBits(1);let r=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);b(e.pos%8===0),yield{type:r,data:n.subarray(e.pos/8,e.pos/8+s)},e.skipBits(s*8)}},bn=n=>{for(let{type:e,data:t}of Es(n)){if(e!==1)continue;let r=new V(t),o=r.readBits(3),i=r.readBits(1),s=r.readBits(1),a=0,c=0,l=0;if(s)a=r.readBits(5);else{if(r.readBits(1)&&(r.skipBits(32),r.skipBits(32),r.readBits(1)))return null;let k=r.readBits(1);k&&(l=r.readBits(5),r.skipBits(32),r.skipBits(5),r.skipBits(5));let I=r.readBits(5);for(let C=0;C<=I;C++){r.skipBits(12);let A=r.readBits(5);if(C===0&&(a=A),A>7){let D=r.readBits(1);C===0&&(c=D)}if(k&&r.readBits(1)){let L=l+1;r.skipBits(L),r.skipBits(L),r.skipBits(1)}r.readBits(1)&&r.skipBits(4)}}let u=r.readBits(4),d=r.readBits(4),m=u+1;r.skipBits(m);let f=d+1;r.skipBits(f);let p=0;if(s?p=0:p=r.readBits(1),p&&(r.skipBits(4),r.skipBits(3)),r.skipBits(1),r.skipBits(1),r.skipBits(1),!s){r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);let S=r.readBits(1);S&&(r.skipBits(1),r.skipBits(1));let k=r.readBits(1),I=0;k?I=2:I=r.readBits(1),I>0&&(r.readBits(1)||r.skipBits(1)),S&&r.skipBits(3)}r.skipBits(1),r.skipBits(1),r.skipBits(1);let h=r.readBits(1),g=8;o===2&&h?g=r.readBits(1)?12:10:o<=2&&(g=h?10:8);let y=0;o!==1&&(y=r.readBits(1));let x=1,v=1,T=0;return y||(o===0?(x=1,v=1):o===1?(x=0,v=0):g===12&&(x=r.readBits(1),x&&(v=r.readBits(1))),x&&v&&(T=r.readBits(2))),{profile:o,level:a,tier:c,bitDepth:g,monochrome:y,chromaSubsamplingX:x,chromaSubsamplingY:v,chromaSamplePosition:T}}return null},Fs=n=>{let e=z(n),t=e.getUint8(9),r=e.getUint16(10,!0),o=e.getUint32(12,!0),i=e.getInt16(16,!0),s=e.getUint8(18),a=null;return s&&(a=n.subarray(19,21+t)),{outputChannelCount:t,preSkip:r,inputSampleRate:o,outputGain:i,channelMappingFamily:s,channelMappingTable:a}},Yc=[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],Ds=n=>{let e=n[0]>>3;return{durationInSamples:Yc[e]}},Rs=n=>{if(n.length<7)throw new Error("Setup header is too short.");if(n[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...n.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let t=n.length,r=new Uint8Array(t);for(let d=0;d<t;d++)r[d]=n[t-1-d];let o=new V(r),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 d=o.pos,m=o.readBits(8),f=o.readBits(16),p=o.readBits(16);if(m>63||f!==0||p!==0){o.pos=d;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 u=Array(l).fill(0);for(let d=l-1;d>=0;d--)o.skipBits(40),u[d]=o.readBits(1);return{modeBlockflags:u}},yn=(n,e,t)=>{switch(n){case"avc":{let r=Jo(t,e),o=r.some(i=>lt(i)===ct.IDR);if(!o&&(!ur()||ys()>=144))for(let i of r){if(lt(i)!==ct.SEI)continue;let a=hn(i),c=1;do{let l=0;for(;;){let m=a[c++];if(m===void 0||(l+=m,m<255))break}let u=0;for(;;){let m=a[c++];if(m===void 0||(u+=m,m<255))break}if(l===6){let m=new V(a);m.pos=8*c;let f=_(m),p=m.readBits(1);if(f===0&&p===1){o=!0;break}}c+=u}while(c<a.length-1)}return o?"key":"delta"}case"hevc":return ti(t,e).some(i=>{let s=Fe(i);return re.BLA_W_LP<=s&&s<=re.RSV_IRAP_VCL23})?"key":"delta";case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{let r=new V(t);if(r.readBits(2)!==2)return null;let o=r.readBits(1);return(r.readBits(1)<<1)+o===3&&r.skipBits(1),r.readBits(1)?null:r.readBits(1)===0?"key":"delta"}case"av1":{let r=!1;for(let{type:o,data:i}of Es(t))if(o===1){let s=new V(i);s.skipBits(4),r=!!s.readBits(1)}else if(o===3||o===6||o===7){if(r)return"key";let s=new V(i);return s.readBits(1)?null:s.readBits(2)===0?"key":"delta"}return null}default:ue(n),b(!1)}},qe;(function(n){n[n.STREAMINFO=0]="STREAMINFO",n[n.VORBIS_COMMENT=4]="VORBIS_COMMENT",n[n.PICTURE=6]="PICTURE"})(qe||(qe={}));var fr=(n,e)=>{let t=z(n),r=0,o=t.getUint32(r,!0);r+=4;let i=K.decode(n.subarray(r,r+o));r+=o,o>0&&(e.raw??={},e.raw.vendor??=i);let s=t.getUint32(r,!0);r+=4;for(let a=0;a<s;a++){let c=t.getUint32(r,!0);r+=4;let l=K.decode(n.subarray(r,r+c));r+=c;let u=l.indexOf("=");if(u===-1)continue;let d=l.slice(0,u).toUpperCase(),m=l.slice(u+1);switch(e.raw??={},e.raw[d]??=m,d){case"TITLE":e.title??=m;break;case"DESCRIPTION":e.description??=m;break;case"ARTIST":e.artist??=m;break;case"ALBUM":e.album??=m;break;case"ALBUMARTIST":e.albumArtist??=m;break;case"COMMENT":e.comment??=m;break;case"LYRICS":e.lyrics??=m;break;case"TRACKNUMBER":{let f=m.split("/"),p=Number.parseInt(f[0],10),h=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),h&&Number.isInteger(h)&&h>0&&(e.tracksTotal??=h)}break;case"TRACKTOTAL":{let f=Number.parseInt(m,10);Number.isInteger(f)&&f>0&&(e.tracksTotal??=f)}break;case"DISCNUMBER":{let f=m.split("/"),p=Number.parseInt(f[0],10),h=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),h&&Number.isInteger(h)&&h>0&&(e.discsTotal??=h)}break;case"DISCTOTAL":{let f=Number.parseInt(m,10);Number.isInteger(f)&&f>0&&(e.discsTotal??=f)}break;case"DATE":{let f=new Date(m);Number.isNaN(f.getTime())||(e.date??=f)}break;case"GENRE":e.genre??=m;break;case"METADATA_BLOCK_PICTURE":{let f=vs(m),p=z(f),h=p.getUint32(0,!1),g=p.getUint32(4,!1),y=String.fromCharCode(...f.subarray(8,8+g)),x=p.getUint32(8+g,!1),v=K.decode(f.subarray(12+g,12+g+x)),T=p.getUint32(g+x+28),S=f.subarray(g+x+32,g+x+32+T);e.images??=[],e.images.push({data:S,mimeType:y,kind:h===3?"coverFront":h===4?"coverBack":"unknown",name:void 0,description:v||void 0})}break}}};var J=class{constructor(e){this.input=e}};var vn=[],Tn=[];var G=new Uint8Array(0),H=class n{constructor(e,t,r,o,i=-1,s,a){if(this.data=e,this.type=t,this.timestamp=r,this.duration=o,this.sequenceNumber=i,e===G&&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(r))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===G}get microsecondTimestamp(){return Math.trunc(Ce*this.timestamp)}get microsecondDuration(){return Math.trunc(Ce*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 r=new Uint8Array(e.byteLength);return e.copyTo(r),new n(r,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 n(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}};var Ms=n=>{let t=0,r=0,o=~n;o&128&&(o&=-129,t=-1),r=((o&240)>>4)+5;let i=(1<<r|(o&15)<<r-4|1<<r-5)-33;return t===0?i:-i};var Bs=n=>{let e=0,t=0,r=n^85;r&128&&(r&=-129,e=-1),t=((r&240)>>4)+4;let o=0;return t!==4?o=1<<t|(r&15)<<t-4|1<<t-5:o=r<<1|1,e===0?o:-o};un();var Os=-1/0,zs=-1/0,gr=null;typeof FinalizationRegistry<"u"&&(gr=new FinalizationRegistry(n=>{let e=Date.now();n.type==="video"?(e-Os>=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."),Os=e),typeof VideoFrame<"u"&&n.data instanceof VideoFrame&&n.data.close()):(e-zs>=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."),zs=e),typeof AudioData<"u"&&n.data instanceof AudioData&&n.data.close())}));var Us=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Zc=new Set(Us),Et=class n{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(Ce*this.timestamp)}get microsecondDuration(){return Math.trunc(Ce*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||!Zc.has(t.format))throw new TypeError("init.format must be one of: "+Us.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=fe(e).slice(),this._layout=t.layout??Jc(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 hr(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 hr(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 n(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Ce),duration:Math.trunc((t.duration??0)*Ce)||void 0}),t);let r=0,o=0;if("naturalWidth"in e?(r=e.naturalWidth,o=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,o=e.videoHeight):"width"in e&&(r=Number(e.width),o=Number(e.height)),!r||!o)throw new TypeError("Could not determine dimensions.");let i=new OffscreenCanvas(r,o),s=i.getContext("2d",{alpha:lr(),willReadFrequently:!0});b(s),s.drawImage(e,0,0),this._data=i,this._layout=null,this.format="RGBX",this.codedWidth=r,this.codedHeight=o,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new hr({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");gr?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return b(this._data!==null),ut(this._data)?new n(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(b(this._layout),new n(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 n(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||(gr?.unregister(this),ut(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Ns(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(b(this._data!==null),!ut(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let t=this.toVideoFrame(),r=t.allocationSize(e);return t.close(),r}return ut(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,t={}){if(!sn(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ns(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(b(this._data!==null),!ut(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){let r=this.toVideoFrame(),o=await r.copyTo(e,t);return r.close(),o}if(ut(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array)return b(this._layout),fe(e).set(this._data),this._layout;{let o=this._data.getContext("2d");b(o);let i=o.getImageData(0,0,this.codedWidth,this.codedHeight);return fe(e).set(i.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return b(this._data!==null),ut(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,r,o,i,s,a,c,l){let u=0,d=0,m=this.displayWidth,f=this.displayHeight,p=0,h=0,g=this.displayWidth,y=this.displayHeight;if(s!==void 0?(u=t,d=r,m=o,f=i,p=s,h=a,c!==void 0?(g=c,y=l):(g=m,y=f)):(p=t,h=r,o!==void 0&&(g=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(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(m)||m<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(f)||f<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(h))throw new TypeError("dy must be a number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:u,sy:d,sWidth:m,sHeight:f}=this._rotateSourceRegion(u,d,m,f,this.rotation));let x=this.toCanvasImageSource();e.save();let v=p+g/2,T=h+y/2;e.translate(v,T),e.rotate(this.rotation*Math.PI/180);let S=this.rotation%180===0?1:g/y;e.scale(1/S,S),e.drawImage(x,u,d,m,f,-g/2,-y/2,g,y),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");t.crop!==void 0&&oi(t.crop,"options.");let r=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&&ni(t.crop,s,a);let c,l,u,d,{sx:m,sy:f,sWidth:p,sHeight:h}=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,u=r,d=o;else{let[y,x]=t.crop?[t.crop.width,t.crop.height]:[s,a],v=t.fit==="contain"?Math.min(r/y,o/x):Math.max(r/y,o/x);u=y*v,d=x*v,c=(r-u)/2,l=(o-d)/2}e.save();let g=i%180===0?1:u/d;e.translate(r/2,o/2),e.rotate(i*Math.PI/180),e.scale(1/g,g),e.translate(-r/2,-o/2),e.drawImage(this.toCanvasImageSource(),m,f,p,h,c,l,u,d),e.restore()}_rotateSourceRegion(e,t,r,o,i){return i===90?[e,t,r,o]=[t,this.codedHeight-e-r,o,r]:i===180?[e,t]=[this.codedWidth-e-r,this.codedHeight-t-o]:i===270&&([e,t,r,o]=[this.codedWidth-t-o,e,o,r]),{sx:e,sy:t,sWidth:r,sHeight:o}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(b(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()}},hr=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}}},ut=n=>typeof VideoFrame<"u"&&n instanceof VideoFrame,ni=(n,e,t)=>{n.left=Math.min(n.left,e),n.top=Math.min(n.top,t),n.width=Math.min(n.width,e-n.left),n.height=Math.min(n.height,t-n.top),b(n.width>=0),b(n.height>=0)},oi=(n,e)=>{if(!n||typeof n!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(n.left)||n.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(n.top)||n.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(n.width)||n.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(n.height)||n.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},Ns=n=>{if(!n||typeof n!="object")throw new TypeError("options must be an object.");if(n.colorSpace!==void 0&&!["display-p3","srgb"].includes(n.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(n.format!==void 0&&typeof n.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(n.layout!==void 0){if(!Array.isArray(n.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let e of n.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(n.rect!==void 0){if(!n.rect||typeof n.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(n.rect.x!==void 0&&(!Number.isInteger(n.rect.x)||n.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(n.rect.y!==void 0&&(!Number.isInteger(n.rect.y)||n.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(n.rect.width!==void 0&&(!Number.isInteger(n.rect.width)||n.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(n.rect.height!==void 0&&(!Number.isInteger(n.rect.height)||n.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},Jc=(n,e,t)=>{let r=el(n),o=[],i=0;for(let s of r){let a=Math.ceil(e/s.widthDivisor),c=Math.ceil(t/s.heightDivisor),l=a*s.sampleBytes,u=l*c;o.push({offset:i,stride:l}),i+=u}return o},el=n=>{let e=(t,r,o,i,s)=>{let a=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:r,widthDivisor:o,heightDivisor:i},{sampleBytes:r,widthDivisor:o,heightDivisor:i}];return s&&a.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),a};switch(n){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:ue(n),b(!1)}},ri=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),Ft=class n{get microsecondTimestamp(){return Math.trunc(Ce*this.timestamp)}get microsecondDuration(){return Math.trunc(Ce*this.duration)}constructor(e){if(this._closed=!1,pr(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(!ri.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/(dt(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let r;if(e.data instanceof ArrayBuffer)r=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))r=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let o=this.numberOfFrames*this.numberOfChannels*dt(this.format);if(r.byteLength<o)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=r}gr?.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&&!ri.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,r=e.frameOffset??0;if(r>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let o=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-r;if(o>this.numberOfFrames-r)throw new RangeError("frameCount out of range");let i=dt(t),s=_t(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(!sn(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&&!ri.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:r,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,u=this.numberOfChannels,d=s??0;if(d>=l)throw new RangeError("frameOffset out of range");let m=i!==void 0?i:l-d;if(m>l-d)throw new RangeError("frameCount out of range");let f=dt(c),p=_t(c);if(p&&r>=u)throw new RangeError("planeIndex out of range");if(!p&&r!==0)throw new RangeError("planeIndex out of range");let g=(p?m:m*u)*f;if(e.byteLength<g)throw new RangeError("Destination buffer is too small");let y=z(e),x=Vs(c);if(pr(this._data))Ve()&&u>2&&c!==a?tl(this._data,y,a,c,u,r,d,m):this._data.copyTo(e,{planeIndex:r,frameOffset:d,frameCount:m,format:c});else{let v=this._data,T=z(v),S=Ls(a),k=dt(a),I=_t(a);for(let C=0;C<m;C++)if(p){let A=C*f,R;I?R=(r*l+(C+d))*k:R=((C+d)*u+r)*k;let D=S(T,R);x(y,A,D)}else for(let A=0;A<u;A++){let D=(C*u+A)*f,L;I?L=(A*l+(C+d))*k:L=((C+d)*u+A)*k;let Y=S(T,L);x(y,D,Y)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(pr(this._data)){let e=new n(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new n({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(gr?.unregister(this),pr(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(pr(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(_t(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(new Uint8Array(t,r*e,e),{planeIndex:r,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{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 r=0;r<this.numberOfChannels;r++)this.copyTo(t,{planeIndex:r,format:"f32-planar"}),e.copyToChannel(t,r);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let r=48e3*5,o=e.numberOfChannels,i=e.sampleRate,s=e.length,a=Math.floor(r/o),c=0,l=s;for(;l>0;){let u=Math.min(a,l),d=new Float32Array(o*u);for(let m=0;m<o;m++)e.copyFromChannel(d.subarray(m*u,(m+1)*u),m,c);yield new n({format:"f32-planar",sampleRate:i,numberOfFrames:u,numberOfChannels:o,timestamp:t+c/i,data:d}),c+=u,l-=u}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let r=48e3*5,o=e.numberOfChannels,i=e.sampleRate,s=e.length,a=Math.floor(r/o),c=0,l=s,u=[];for(;l>0;){let d=Math.min(a,l),m=new Float32Array(o*d);for(let p=0;p<o;p++)e.copyFromChannel(m.subarray(p*d,(p+1)*d),p,c);let f=new n({format:"f32-planar",sampleRate:i,numberOfFrames:d,numberOfChannels:o,timestamp:t+c/i,data:m});u.push(f),c+=d,l-=d}return u}},dt=n=>{switch(n){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")}},_t=n=>{switch(n){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Ls=n=>{switch(n){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)}},Vs=n=>{switch(n){case"u8":case"u8-planar":return(e,t,r)=>e.setUint8(t,nt((r+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,r)=>e.setInt16(t,nt(Math.round(r*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,r)=>e.setInt32(t,nt(Math.round(r*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,r)=>e.setFloat32(t,r,!0)}},pr=n=>typeof AudioData<"u"&&n instanceof AudioData,tl=(n,e,t,r,o,i,s,a)=>{let c=Ls(t),l=Vs(r),u=dt(t),d=dt(r),m=_t(t);if(_t(r))if(m){let p=new ArrayBuffer(a*u),h=z(p);n.copyTo(p,{planeIndex:i,frameOffset:s,frameCount:a,format:t});for(let g=0;g<a;g++){let y=g*u,x=g*d,v=c(h,y);l(e,x,v)}}else{let p=new ArrayBuffer(a*o*u),h=z(p);n.copyTo(p,{planeIndex:0,frameOffset:s,frameCount:a,format:t});for(let g=0;g<a;g++){let y=(g*o+i)*u,x=g*d,v=c(h,y);l(e,x,v)}}else if(m){let p=a*u,h=new ArrayBuffer(p),g=z(h);for(let y=0;y<o;y++){n.copyTo(h,{planeIndex:y,frameOffset:s,frameCount:a,format:t});for(let x=0;x<a;x++){let v=x*u,T=(x*o+y)*d,S=c(g,v);l(e,T,S)}}}else{let p=new ArrayBuffer(a*o*u),h=z(p);n.copyTo(p,{planeIndex:0,frameOffset:s,frameCount:a,format:t});for(let g=0;g<a;g++)for(let y=0;y<o;y++){let x=g*o+y,v=x*u,T=x*d,S=c(h,v);l(e,T,S)}}};var Dt=n=>{if(!n||typeof n!="object")throw new TypeError("options must be an object.");if(n.metadataOnly!==void 0&&typeof n.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(n.verifyKeyPackets!==void 0&&typeof n.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(n.verifyKeyPackets&&n.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},Ge=n=>{if(!dr(n))throw new TypeError("timestamp must be a number.")},ii=(n,e,t)=>t.verifyKeyPackets?e.then(async r=>{if(!r||r.type==="delta")return r;let o=await n.determinePacketType(r);return o&&(r.type=o),r}):e,mt=class{constructor(e){if(!(e instanceof Mt))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(Dt(e),this._track.input._disposed)throw new j;return ii(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){if(Ge(e),Dt(t),this._track.input._disposed)throw new j;return ii(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof H))throw new TypeError("packet must be an EncodedPacket.");if(Dt(t),this._track.input._disposed)throw new j;return ii(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Ge(e),Dt(t),this._track.input._disposed)throw new j;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let r=await this._track._backing.getKeyPacket(e,t);return r&&(b(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getKeyPacket(r.timestamp-1/this._track.timeResolution,t):r)}async getNextKeyPacket(e,t={}){if(!(e instanceof H))throw new TypeError("packet must be an EncodedPacket.");if(Dt(t),this._track.input._disposed)throw new j;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let r=await this._track._backing.getNextKeyPacket(e,t);return r&&(b(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getNextKeyPacket(r,t):r)}packets(e,t,r={}){if(e!==void 0&&!(e instanceof H))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof H))throw new TypeError("endPacket must be an EncodedPacket.");if(Dt(r),this._track.input._disposed)throw new j;let o=[],{promise:i,resolve:s}=te(),{promise:a,resolve:c}=te(),l=!1,u=!1,d=null,m=[],f=()=>Math.max(2,m.length);(async()=>{let h=e??await this.getFirstPacket(r);for(;h&&!u&&!this._track.input._disposed&&!(t&&h.sequenceNumber>=t?.sequenceNumber);){if(o.length>f()){({promise:a,resolve:c}=te()),await a;continue}o.push(h),s(),{promise:i,resolve:s}=te(),h=await this.getNextPacket(h,r)}l=!0,s()})().catch(h=>{d||(d=h,s())});let p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new j;if(u)return{value:void 0,done:!0};if(d)throw d;if(o.length>0){let h=o.shift(),g=performance.now();for(m.push(g);m.length>0&&g-m[0]>=1e3;)m.shift();return c(),{value:h,done:!1}}else{if(l)return{value:void 0,done:!0};await i}}},async return(){return u=!0,c(),s(),{value:void 0,done:!0}},async throw(h){throw h},[Symbol.asyncIterator](){return this}}}},xr=class{constructor(e,t){this.onSample=e,this.onError=t}},br=class{mediaSamplesInRange(e=0,t=1/0){Ge(e),Ge(t);let r=[],o=!1,i=null,{promise:s,resolve:a}=te(),{promise:c,resolve:l}=te(),u=!1,d=!1,m=!1,f=null;(async()=>{let g=await this._createDecoder(k=>{if(l(),k.timestamp>=t&&(d=!0),d){k.close();return}i&&(k.timestamp>e?(r.push(i),o=!0):i.close()),k.timestamp>=e&&(r.push(k),o=!0),i=o?null:k,r.length>0&&(a(),{promise:s,resolve:a}=te())},k=>{f||(f=k,a())}),y=this._createPacketSink(),x=await y.getKeyPacket(e,{verifyKeyPackets:!0})??await y.getFirstPacket(),v=x,T;if(t<1/0){let k=await y.getPacket(t),I=k?k.type==="key"&&k.timestamp===t?k:await y.getNextKeyPacket(k,{verifyKeyPackets:!0}):null;I&&(T=I)}let S=y.packets(x??void 0,T);for(await S.next();v&&!d&&!this._track.input._disposed;){let k=Hs(r.length);if(r.length+g.getDecodeQueueSize()>k){({promise:c,resolve:l}=te()),await c;continue}g.decode(v);let I=await S.next();if(I.done)break;v=I.value}await S.return(),!m&&!this._track.input._disposed&&await g.flush(),g.close(),!o&&i&&r.push(i),u=!0,a()})().catch(g=>{f||(f=g,a())});let p=this._track,h=()=>{i?.close();for(let g of r)g.close()};return{async next(){for(;;){if(p.input._disposed)throw h(),new j;if(m)return{value:void 0,done:!0};if(f)throw h(),f;if(r.length>0){let g=r.shift();return l(),{value:g,done:!1}}else if(!u)await s;else return{value:void 0,done:!0}}},async return(){return m=!0,d=!0,l(),a(),h(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){ps(e);let t=fs(e),r=[],o=[],{promise:i,resolve:s}=te(),{promise:a,resolve:c}=te(),l=!1,u=!1,d=null,m=h=>{o.push(h),s(),{promise:i,resolve:s}=te()};(async()=>{let h=await this._createDecoder(k=>{if(c(),u){k.close();return}let I=0;for(;r.length>0&&k.timestamp-r[0]>-1e-10;)I++,r.shift();if(I>0)for(let C=0;C<I;C++)m(C<I-1?k.clone():k);else k.close()},k=>{d||(d=k,s())}),g=this._createPacketSink(),y=null,x=null,v=-1,T=async()=>{b(x);let k=x;for(h.decode(k);k.sequenceNumber<v;){let I=Hs(o.length);for(;o.length+h.getDecodeQueueSize()>I&&!u;)({promise:a,resolve:c}=te()),await a;if(u)break;let C=await g.getNextPacket(k);b(C),h.decode(C),k=C}v=-1},S=async()=>{await h.flush();for(let k=0;k<r.length;k++)m(null);r.length=0};for await(let k of t){if(Ge(k),u||this._track.input._disposed)break;let I=await g.getPacket(k),C=I&&await g.getKeyPacket(k,{verifyKeyPackets:!0});if(!C){v!==-1&&(await T(),await S()),m(null),y=null;continue}y&&(C.sequenceNumber!==x.sequenceNumber||I.timestamp<y.timestamp)&&(await T(),await S()),r.push(I.timestamp),v=Math.max(I.sequenceNumber,v),y=I,x=C}!u&&!this._track.input._disposed&&(v!==-1&&await T(),await S()),h.close(),l=!0,s()})().catch(h=>{d||(d=h,s())});let f=this._track,p=()=>{for(let h of o)h?.close()};return{async next(){for(;;){if(f.input._disposed)throw p(),new j;if(u)return{value:void 0,done:!0};if(d)throw p(),d;if(o.length>0){let h=o.shift();return b(h!==void 0),c(),{value:h,done:!1}}else if(!l)await i;else return{value:void 0,done:!0}}},async return(){return u=!0,c(),s(),p(),{value:void 0,done:!0}},async throw(h){throw h},[Symbol.asyncIterator](){return this}}}},Hs=n=>n===0?40:8,si=class extends xr{constructor(e,t,r,o,i,s){super(e,t),this.codec=r,this.decoderConfig=o,this.rotation=i,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new cr,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=vn.find(c=>c.supports(r,o));if(a)this.customDecoder=new a,this.customDecoder.codec=r,this.customDecoder.config=o,this.customDecoder.onSample=c=>{if(!(c instanceof Et))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=u=>{if(this.alphaQueue.length>0){let d=this.alphaQueue.shift();b(d!==void 0),this.mergeAlpha(u,d)}else this.colorQueue.push(u)};if(r==="avc"&&this.decoderConfig.description&&ur()){let u=As(fe(this.decoderConfig.description));if(u&&u.sequenceParameterSets.length>0){let d=ei(u.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let l=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:u=>{try{c(u)}catch(d){this.onError(d)}},error:u=>{u.stack=l,this.onError(u)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(b(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(b(this.decoder),Ve()||Go(this.inputTimestamps,e.timestamp,t=>t),ur()&&this.currentPacketIndex===0&&this.codec==="avc"){let r=Jo(e.data,this.decoderConfig).filter(i=>{let s=lt(i);return!(s>=20&&s<=31)}),o=Ps(r,this.decoderConfig);e=new H(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 ai}catch(r){console.error("Due to an error, only color data will be decoded.",r),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let r=i=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let s=this.colorQueue.shift();b(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();b(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{r(i)}catch(s){this.onError(s)}},error:i=>{i.stack=o,this.onError(i)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=yn(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 ti(e,this.decoderConfig).some(r=>{let o=Fe(r);return o===re.RASL_N||o===re.RASL_R})}sampleHandler(e){if(Ve()){if(this.sampleQueue.length>0&&e.timestamp>=ee(this.sampleQueue).timestamp){for(let t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}Go(this.sampleQueue,e,t=>t.timestamp)}else{let t=this.inputTimestamps.shift();b(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 Et(e);this.sampleHandler(i);return}b(this.merger),this.merger.update(e,t),e.close(),t.close();let r=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),o=new Et(r);this.sampleHandler(o)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(b(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),Ve()){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()):(b(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}},ai=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 $r=()=>({stdout:async n=>console.log(n),stderr:async n=>console.error(n)});var ts=()=>Fo()?Gr():Do()?jr():$r();var rs=()=>({stdout:async()=>{},stderr:async()=>{}});function ns(){return()=>({stdout:n=>n,stderr:n=>n})}var Ct=class n{static writers={auto:ts,void:rs,deno:Gr,node:jr,console:$r};static colors={auto:Ro,colorful:()=>or,colorless:()=>nr};static themes={auto:Yi,basic:Vr};static shapers={auto:es,none:ns,errors:Wr,timestamp:qr};writer=n.writers.auto();colors=n.colors.auto();theme=n.themes.auto();shaper=n.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=ir(...e),this}};var sr=class extends Ct{static dummy(){return new this().setWriter(Ct.writers.void())}rpcRequest=async({request:e,...t})=>{let r=this.colors.none;this.log(...this.#e(t),r(`${e.method}()`))};rpcError=async({request:e,error:t,...r})=>{this.error(...this.#e(r),`${e.method}()`,t)};#e({meta:e,label:t,remote:r}){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,r===void 0?void 0:r?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 we=class extends sr{rpcRequest=async()=>{}};var Ae;(function(n){n.version="2.0";function e(t){return"id"in t?t.id:null}n.getId=e,n.errorCodes={serverError:-32e3,unexposedError:-32001}})(Ae||(Ae={}));var Xr=class extends Error{name=this.constructor.name},Qe=class extends Error{name=this.constructor.name};async function os({tap:n,request:e,action:t}){let r=Ae.getId(e);try{let o=await t();return r===null?null:{id:r,result:o,jsonrpc:Ae.version}}catch(o){return n.rpcError({request:e,error:o}),r===null?null:{id:r,jsonrpc:Ae.version,error:o instanceof Xr?{code:Ae.errorCodes.serverError,message:o.message}:{code:Ae.errorCodes.unexposedError,message:"unexposed error"}}}}function Kr(n){let e=n.tap??new we;return async t=>{let r=t.method.split("."),o=Qi(n.fns,r),i=async()=>await o(...t.params);return e.rpcRequest({request:t}),await os({tap:e,request:t,action:i})}}var Pt=Symbol("tune"),Rc=Symbol("query"),Mc=Symbol("notify"),Bc=Symbol("settings");function is(n){function e(t){let r={notify:void 0};return new Proxy((()=>{}),{apply:(o,i,s)=>n(t,s,r),get:(o,i)=>{if(i!=="then")return i===Pt?s=>(...a)=>n(t,a,{...r,...s}):i===Mc?(...s)=>n(t,s,{...r,notify:!0}):i===Rc?(...s)=>n(t,s,{...r,notify:!1}):i===Bc?r:(o[i]||(o[i]=e([...t,i])),o[i])},set:(o,i,s)=>(o[i]=s,!0)})}return e([])}function Ye(n){let{endpoint:e,tap:t=new we}=n,r=1;return is(async(o,i,s)=>{let a=s.notify??n.notify??!1,c=s.transfer,l={jsonrpc:"2.0",method:o.join("."),params:i},u=a?l:{...l,id:r++};t.rpcRequest({request:u});let d=await e(u,{transfer:c});if(a&&!d)return null;if(!d)throw new Qe("response was null, but shouldn't be, because the request was not a notification");if("error"in d)throw new Qe(n.label?`${n.label}: ${d.error.message}`:d.error.message);return d.result})}function ar(n){return Ye({endpoint:Kr(n),tap:n.tap})}var Ze=class{recv=St();sendRequest=St();sendResponse=St();static makeEntangledPair({origin:e="example.e280.org"}={}){let t=new this,r=new this,o=[t.sendRequest.sub(s=>r.recv(s,{origin:e})),t.sendResponse.sub(s=>r.recv(s,{origin:e})),r.sendRequest.sub(s=>t.recv(s,{origin:e})),r.sendResponse.sub(s=>t.recv(s,{origin:e}))];return[t,r,()=>o.forEach(s=>s())]}};function Qr(n,e){return n.addEventListener("message",e),()=>n.removeEventListener("message",e)}function ss(n,e){return async(t,{transfer:r}={})=>{if("id"in t){let o=Te();return e(t,r,o.promise),n.wait(t.id,t.method).then(i=>(o.resolve(i),i))}else{let o=Promise.resolve(null);return e(t,r,o),o}}}function as(n){let e=[],t=[];for(let r of Array.isArray(n)?n:[n])"method"in r?e.push(r):t.push(r);return{requests:e,responses:t}}async function cs(n,e){let t=(await Promise.all(e.map(async r=>n(r)))).filter(r=>r!==null);return t.length===0?null:t.length===1?t[0]:t}var It=class extends Ze{dispose=Lr();constructor(e){super(),this.dispose.schedule(this.sendRequest.sub((t,r)=>e.postMessage(t,r)),this.sendResponse.sub((t,r)=>e.postMessage(t,r)),Qr(e,t=>this.recv(t.data,t)))}};var Yr=class{remote;transfer;constructor(e){this.remote=e}};var Mo=Object.freeze({timeout:6e4,maxRequestBytes:1e7});var Zr=class{timeout;pending=new Map;constructor(e){this.timeout=e}async wait(e,t){let r=Te();return this.pending.set(e,{method:t,deferred:r}),await Ki(this.timeout,()=>r.promise).catch(o=>{throw o instanceof rr&&(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 Qe(e.error.message)):t.deferred.resolve(e))}};var Je=class{options;remote;remoteEndpoint;dispose=Lr();#e;constructor(e){this.options=e;let{conduit:t,tap:r}=e;this.#e=new Zr(e.timeout??Mo.timeout),this.remoteEndpoint=ss(this.#e,t.sendRequest.pub.bind(t.sendRequest)),this.remote=Ye({endpoint:this.remoteEndpoint,tap:r&&Eo(r,{remote:!0})}),this.dispose.schedule(t.recv.sub(o=>this.recv(o)))}async recv(e){let t=new Yr(this.remote),{conduit:r,rpc:o,tap:i}=this.options,{requests:s,responses:a}=as(e);for(let d of a)this.#e.deliverResponse(d);if(!o)return;let c=await o(t),l=Kr({fns:c,tap:i&&Eo(i,{remote:!1})}),u=await cs(l,s);u&&await r.sendResponse(u,t.transfer)}};var _e={derive:{host:n=>({host:n.remote.host,get transfer(){return n.transfer},set transfer(e){n.transfer=e}}),work:n=>({work:n.remote,get transfer(){return n.transfer},set transfer(e){n.transfer=e}})},mock:{host:()=>({host:void 0,transfer:void 0}),work:()=>({work:void 0,transfer:void 0})}};var Ee=new we;async function ls(n,e,t={}){let r=t.tap??Ee,o=new Je({tap:r,timeout:t.timeout??1/0,conduit:new It(n.getSelf()),rpc:async i=>e(_e.derive.host(i))});return await o.remote.infra.ready(),o.remote.host}var At=class{worker;messenger;constructor(e,t){this.worker=e,this.messenger=t}static async make(e,t){let r=t.tap??Ee,o=t.label??"comrade",i=e.loadWorker(t.workerUrl,o),s=Te(),a={async ready(){s.resolve()}},c=new Je({tap:r,timeout:t.timeout??1/0,conduit:new It(i),rpc:async l=>({infra:a,host:t.setupHost(_e.derive.work(l))})});return await s.promise,new this(i,c)}get work(){return this.messenger.remote}terminate(){this.worker.terminate()}};var Jr=class{threads;static async make(e,t){let r=t.workerCount??e.guessOptimalThreadCount(),o=await Promise.all([...Array(r)].map(async(i,s)=>At.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 r=t.tap??Ee,o=async(i,s)=>this.#r({request:i,prom:Te(),transfer:s?.transfer});this.work=Ye({tap:r,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 r=e.messenger.remoteEndpoint(t.request,{transfer:t.transfer});t.prom.entangle(r).finally(()=>{this.#e.add(e),this.#n()})}}};var us=n=>({thread:e=>At.make(n,e),cluster:e=>Jr.make(n,e),worker:(e,t={})=>ls(n,e,t),work:e=>e,host:e=>e,mocks(e){let{setupWork:t,setupHost:r,tap:o=Ee}=e,i=_e.mock.host(),s=_e.mock.work();return s.work=ar({tap:o,fns:t(i)}),i.host=ar({tap:o,fns:r(s)}),{workShell:s,hostShell:i,work:s.work,host:i.host}},mockWork(e,t=Ee){let r=_e.mock.host(),o=_e.mock.work();return o.work=ar({tap:t,fns:e(r)}),{workShell:o,hostShell:r,work:o.work,mockHost:i=>(r.host=ar({tap:t,fns:i(o)}),{workShell:o,hostShell:r,work:o.work,host:r.host})}}});var ds=()=>({getSelf(){return self},guessOptimalThreadCount(){let n=navigator.hardwareConcurrency??1;return Math.max(1,n-1)},loadWorker(n,e){return new window.Worker(n,{name:e,type:"module"})},async loadWasm(n){return WebAssembly.instantiateStreaming(fetch(n))}});var Nc=ds(),en=us(Nc);function b(n){if(!n)throw new Error("Assertion failed.")}var tn=n=>{let e=(n%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${n}.`)},ee=n=>n&&n[n.length-1];var V=class n{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,r=7-(this.pos&7),o=(t&1<<r)>>r;return this.pos++,o}readBits(e){if(e===1)return this.readBit();let t=0;for(let r=0;r<e;r++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let r=this.pos+e;for(let o=this.pos;o<r;o++){let i=Math.floor(o/8),s=this.bytes[i],a=7-(o&7);s&=~(1<<a),s|=(t&1<<r-o-1)>>r-o-1<<a,this.bytes[i]=s}this.pos=r}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 n(this.bytes);return e.pos=this.pos,e}},_=n=>{let e=0;for(;n.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+n.readBits(e)},Se=n=>{let e=_(n);return(e&1)===0?-(e>>1):e+1>>1};var fe=n=>n.constructor===Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n),z=n=>n.constructor===DataView?n:ArrayBuffer.isView(n)?new DataView(n.buffer,n.byteOffset,n.byteLength):new DataView(n),K=new TextDecoder;var Uo=n=>Object.fromEntries(Object.entries(n).map(([e,t])=>[t,e])),Lo={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},rn=Uo(Lo),Vo={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},nn=Uo(Vo),Ho={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},on=Uo(Ho);var sn=n=>n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer||ArrayBuffer.isView(n),ke=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e,t=new Promise(o=>{e=o}),r=this.currentPromise;return this.currentPromise=t,await r,e}},Wo=n=>[...n].map(e=>e.toString(16).padStart(2,"0")).join(""),qo=n=>(n=n>>1&1431655765|(n&1431655765)<<1,n=n>>2&858993459|(n&858993459)<<2,n=n>>4&252645135|(n&252645135)<<4,n=n>>8&16711935|(n&16711935)<<8,n=n>>16&65535|(n&65535)<<16,n>>>0),et=(n,e,t)=>{let r=0,o=n.length-1,i=-1;for(;r<=o;){let s=r+o>>1,a=t(n[s]);a===e?(i=s,o=s-1):a<e?r=s+1:o=s-1}return i},O=(n,e,t)=>{let r=0,o=n.length-1,i=-1;for(;r<=o;){let s=r+(o-r+1)/2|0;t(n[s])<=e?(i=s,r=s+1):o=s-1}return i},Go=(n,e,t)=>{let r=O(n,t(e),t);n.splice(r+1,0,e)},te=()=>{let n,e;return{promise:new Promise((r,o)=>{n=r,e=o}),resolve:n,reject:e}};var jo=(n,e)=>{for(let t=n.length-1;t>=0;t--)if(e(n[t]))return n[t]},an=(n,e)=>{for(let t=n.length-1;t>=0;t--)if(e(n[t]))return t;return-1},fs=async function*(n){Symbol.iterator in n?yield*n[Symbol.iterator]():yield*n[Symbol.asyncIterator]()},ps=n=>{if(!(Symbol.iterator in n)&&!(Symbol.asyncIterator in n))throw new TypeError("Argument must be an iterable or async iterable.")},ue=n=>{throw new Error(`Unexpected value: ${n}`)},tt=(n,e,t)=>{let r=n.getUint8(e),o=n.getUint8(e+1),i=n.getUint8(e+2);return t?r|o<<8|i<<16:r<<16|o<<8|i},hs=(n,e,t)=>tt(n,e,t)<<8>>8,gs=(n,e,t,r)=>{t=t>>>0,t=t&16777215,r?(n.setUint8(e,t&255),n.setUint8(e+1,t>>>8&255),n.setUint8(e+2,t>>>16&255)):(n.setUint8(e,t>>>16&255),n.setUint8(e+1,t>>>8&255),n.setUint8(e+2,t&255))};var $o=(n,e)=>({async next(){let t=await n.next();return t.done?{value:void 0,done:!0}:{value:e(t.value),done:!1}},return(){return n.return()},throw(t){return n.throw(t)},[Symbol.asyncIterator](){return this}}),rt=(n,e,t)=>Math.max(e,Math.min(t,n)),Q="und",nt=n=>{let e=Math.round(n);return Math.abs(n/e-1)<10*Number.EPSILON?e:n},xs=(n,e)=>Math.round(n/e)*e,bs=n=>{let e=0;for(;n;)e++,n>>=1;return e},Uc=/^[a-z]{3}$/,cn=n=>Uc.test(n),Ce=1e6*(1+Number.EPSILON),Xo=(n,e)=>{let t={...n,...e};if(n.headers||e.headers){let r=n.headers?ms(n.headers):{},o=e.headers?ms(e.headers):{},i={...r};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},ms=n=>{if(n instanceof Headers){let e={};return n.forEach((t,r)=>{e[r]=t}),e}if(Array.isArray(n)){let e={};return n.forEach(([t,r])=>{e[t]=r}),e}return n},Ko=async(n,e,t,r,o)=>{let i=0;for(;;)try{return await n(e,t)}catch(s){if(o())throw s;i++;let a=r(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 cr=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},Bo=null,Le=()=>Bo!==null?Bo:Bo=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),Oo=null,lr=()=>Oo!==null?Oo:Oo=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),zo=null,ur=()=>zo!==null?zo:zo=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),No=null,ys=()=>{if(No!==null)return No;if(typeof navigator>"u")return null;let n=/\bChrome\/(\d+)/.exec(navigator.userAgent);return n?No=Number(n[1]):null},ot=(n,e)=>n!==-1?n:e,ln=(n,e,t,r)=>n<=r&&t<=e;var vs=n=>{let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t};var un=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},dr=n=>typeof n=="number"&&!Number.isNaN(n);var Ve=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.")}},dn=class{constructor(e,t,r,o){if(this.data=e,this.mimeType=t,this.name=r,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(r!==void 0&&typeof r!="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 ie={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};var He=["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"],Lc=["aac","opus","mp3","vorbis","flac"],gp=[...Lc,...He];var it=[{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 Ts=".01.01.01.01.00",ws=".0.110.01.01.01.0";var mn=n=>{let{codec:e,codecDescription:t,colorSpace:r,avcCodecInfo:o,hevcCodecInfo:i,vp9CodecInfo:s,av1CodecInfo:a}=n;if(e==="avc"){if(b(n.avcType!==null),o){let c=new Uint8Array([o.avcProfileIndication,o.profileCompatibility,o.avcLevelIndication]);return`avc${n.avcType}.${Wo(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${n.avcType}.${Wo(t.subarray(1,4))}`}else if(e==="hevc"){let c,l,u,d,m,f;if(i)c=i.generalProfileSpace,l=i.generalProfileIdc,u=qo(i.generalProfileCompatibilityFlags),d=i.generalTierFlag,m=i.generalLevelIdc,f=[...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 h=z(t),g=h.getUint8(1);c=g>>6&3,l=g&31,u=qo(h.getUint32(2)),d=g>>5&1,m=h.getUint8(12),f=[];for(let y=0;y<6;y++)f.push(h.getUint8(6+y))}let p="hev1.";for(p+=["","A","B","C"][c]+l,p+=".",p+=u.toString(16).toUpperCase(),p+=".",p+=d===0?"L":"H",p+=m;f.length>0&&f[f.length-1]===0;)f.pop();return f.length>0&&(p+=".",p+=f.map(h=>h.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!s){let y=n.width*n.height,x=ee(it).level;for(let v of it)if(y<=v.maxPictureSize){x=v.level;break}return`vp09.00.${x.toString().padStart(2,"0")}.08`}let c=s.profile.toString().padStart(2,"0"),l=s.level.toString().padStart(2,"0"),u=s.bitDepth.toString().padStart(2,"0"),d=s.chromaSubsampling.toString().padStart(2,"0"),m=s.colourPrimaries.toString().padStart(2,"0"),f=s.transferCharacteristics.toString().padStart(2,"0"),p=s.matrixCoefficients.toString().padStart(2,"0"),h=s.videoFullRangeFlag.toString().padStart(2,"0"),g=`vp09.${c}.${l}.${u}.${d}`;return g+=`.${m}.${f}.${p}.${h}`,g.endsWith(Ts)&&(g=g.slice(0,-Ts.length)),g}else if(e==="av1"){if(!a){let v=n.width*n.height,T=ee(it).level;for(let S of it)if(v<=S.maxPictureSize){T=S.level;break}return`av01.0.${T.toString().padStart(2,"0")}M.08`}let c=a.profile,l=a.level.toString().padStart(2,"0"),u=a.tier?"H":"M",d=a.bitDepth.toString().padStart(2,"0"),m=a.monochrome?"1":"0",f=100*a.chromaSubsamplingX+10*a.chromaSubsamplingY+1*(a.chromaSubsamplingX&&a.chromaSubsamplingY?a.chromaSamplePosition:0),p=r?.primaries?Lo[r.primaries]:1,h=r?.transfer?Vo[r.transfer]:1,g=r?.matrix?Ho[r.matrix]:1,y=r?.fullRange?1:0,x=`av01.${c}.${l}${u}.${d}`;return x+=`.${m}.${f.toString().padStart(3,"0")}`,x+=`.${p.toString().padStart(2,"0")}`,x+=`.${h.toString().padStart(2,"0")}`,x+=`.${g.toString().padStart(2,"0")}`,x+=`.${y}`,x.endsWith(ws)&&(x=x.slice(0,-ws.length)),x}}throw new TypeError(`Unhandled codec '${e}'.`)};var fn=n=>{let{codec:e,codecDescription:t,aacCodecInfo:r}=n;if(e==="aac"){if(!r)throw new TypeError("AAC codec info must be provided.");return r.isMpeg2?"mp4a.67":`mp4a.40.${Yo(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&&He.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},mr=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Qo=[-1,1,2,3,4,5,6,8],Yo=n=>{if(!n||n.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new V(n),t=e.readBits(5);t===31&&(t=32+e.readBits(6));let r=e.readBits(4),o=null;r===15?o=e.readBits(24):r<mr.length&&(o=mr[r]);let i=e.readBits(4),s=null;return i>=1&&i<=7&&(s=Qo[i]),{objectType:t,frequencyIndex:r,sampleRate:o,channelConfiguration:i,numberOfChannels:s}};var st=48e3,Vc=/^pcm-([usf])(\d+)+(be)?$/,pn=n=>{if(b(He.includes(n)),n==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(n==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=Vc.exec(n);b(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";let r=Number(e[2])/8,o=e[3]!=="be",i=n==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:r,littleEndian:o,silentValue:i}};var at;(function(n){n[n.IDR=5]="IDR",n[n.SEI=6]="SEI",n[n.SPS=7]="SPS",n[n.PPS=8]="PPS",n[n.SPS_EXT=13]="SPS_EXT"})(at||(at={}));var re;(function(n){n[n.RASL_N=8]="RASL_N",n[n.RASL_R=9]="RASL_R",n[n.BLA_W_LP=16]="BLA_W_LP",n[n.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",n[n.VPS_NUT=32]="VPS_NUT",n[n.SPS_NUT=33]="SPS_NUT",n[n.PPS_NUT=34]="PPS_NUT",n[n.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",n[n.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(re||(re={}));var gn=n=>{let e=[],t=0;for(;t<n.length;){let r=-1,o=0;for(let i=t;i<n.length-3;i++){if(n[i]===0&&n[i+1]===0&&n[i+2]===1){r=i,o=3;break}if(i<n.length-4&&n[i]===0&&n[i+1]===0&&n[i+2]===0&&n[i+3]===1){r=i,o=4;break}}if(r===-1)break;if(t>0&&r>t){let i=n.subarray(t,r);i.length>0&&e.push(i)}t=r+o}if(t<n.length){let r=n.subarray(t);r.length>0&&e.push(r)}return e},Cs=(n,e)=>{let t=[],r=0,o=new DataView(n.buffer,n.byteOffset,n.byteLength);for(;r+e<=n.length;){let i;e===1?i=o.getUint8(r):e===2?i=o.getUint16(r,!1):e===3?i=tt(o,r,!1):e===4?i=o.getUint32(r,!1):(ue(e),b(!1)),r+=e;let s=n.subarray(r,r+i);t.push(s),r+=i}return t},hn=n=>{let e=[],t=n.length;for(let r=0;r<t;r++)r+2<t&&n[r]===0&&n[r+1]===0&&n[r+2]===3?(e.push(0,0),r+=2):e.push(n[r]);return new Uint8Array(e)},Zo=new Uint8Array([0,0,0,1]),Wc=n=>{let e=n.reduce((o,i)=>o+Zo.byteLength+i.byteLength,0),t=new Uint8Array(e),r=0;for(let o of n)t.set(Zo,r),r+=Zo.byteLength,t.set(o,r),r+=o.byteLength;return t},qc=(n,e)=>{let t=n.reduce((i,s)=>i+e+s.byteLength,0),r=new Uint8Array(t),o=0;for(let i of n){let s=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(e){case 1:s.setUint8(o,i.byteLength);break;case 2:s.setUint16(o,i.byteLength,!1);break;case 3:gs(s,o,i.byteLength,!1);break;case 4:s.setUint32(o,i.byteLength,!1);break}o+=e,r.set(i,o),o+=i.byteLength}return r},Jo=(n,e)=>{if(e.description){let o=(fe(e.description)[4]&3)+1;return Cs(n,o)}else return gn(n)},Ps=(n,e)=>{if(e.description){let o=(fe(e.description)[4]&3)+1;return qc(n,o)}else return Wc(n)},ct=n=>n[0]&31,Is=n=>{try{let e=gn(n),t=e.filter(c=>ct(c)===at.SPS),r=e.filter(c=>ct(c)===at.PPS),o=e.filter(c=>ct(c)===at.SPS_EXT);if(t.length===0||r.length===0)return null;let i=t[0],s=ei(i);b(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:r,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 As=n=>{try{let e=z(n),t=0,r=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 f=0;f<c;f++){let p=e.getUint16(t,!1);t+=2,l.push(n.subarray(t,t+p)),t+=p}let u=e.getUint8(t++),d=[];for(let f=0;f<u;f++){let p=e.getUint16(t,!1);t+=2,d.push(n.subarray(t,t+p)),t+=p}let m={configurationVersion:r,avcProfileIndication:o,profileCompatibility:i,avcLevelIndication:s,lengthSizeMinusOne:a,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((o===100||o===110||o===122||o===144)&&t+4<=n.length){let f=e.getUint8(t++)&3,p=e.getUint8(t++)&7,h=e.getUint8(t++)&7,g=e.getUint8(t++);m.chromaFormat=f,m.bitDepthLumaMinus8=p,m.bitDepthChromaMinus8=h;let y=[];for(let x=0;x<g;x++){let v=e.getUint16(t,!1);t+=2,y.push(n.subarray(t,t+v)),t+=v}m.sequenceParameterSetExt=y}return m}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}},ei=n=>{try{let e=new V(hn(n));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let r=e.readAlignedByte(),o=e.readAlignedByte(),i=e.readAlignedByte();_(e);let s=null,a=null,c=null;if((r===100||r===110||r===122||r===244||r===44||r===83||r===86||r===118||r===128)&&(s=_(e),s===3&&e.skipBits(1),a=_(e),c=_(e),e.skipBits(1),e.readBits(1))){for(let m=0;m<(s!==3?8:12);m++)if(e.readBits(1)){let p=m<6?16:64,h=8,g=8;for(let y=0;y<p;y++){if(g!==0){let x=Se(e);g=(h+x+256)%256}h=g===0?h:g}}}_(e);let l=_(e);if(l===0)_(e);else if(l===1){e.skipBits(1),Se(e),Se(e);let d=_(e);for(let m=0;m<d;m++)Se(e)}_(e),e.skipBits(1),_(e),_(e);let u=e.readBits(1);return{profileIdc:r,constraintFlags:o,levelIdc:i,frameMbsOnlyFlag:u,chromaFormatIdc:s,bitDepthLumaMinus8:a,bitDepthChromaMinus8:c}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},ti=(n,e)=>{if(e.description){let o=(fe(e.description)[21]&3)+1;return Cs(n,o)}else return gn(n)},Fe=n=>n[0]>>1&63,_s=n=>{try{let e=gn(n),t=e.filter(R=>Fe(R)===re.VPS_NUT),r=e.filter(R=>Fe(R)===re.SPS_NUT),o=e.filter(R=>Fe(R)===re.PPS_NUT),i=e.filter(R=>Fe(R)===re.PREFIX_SEI_NUT||Fe(R)===re.SUFFIX_SEI_NUT);if(r.length===0||o.length===0)return null;let s=r[0],a=new V(hn(s));a.skipBits(16),a.readBits(4);let c=a.readBits(3),l=a.readBits(1),{general_profile_space:u,general_tier_flag:d,general_profile_idc:m,general_profile_compatibility_flags:f,general_constraint_indicator_flags:p,general_level_idc:h}=Gc(a,c);_(a);let g=_(a);g===3&&a.skipBits(1),_(a),_(a),a.readBits(1)&&(_(a),_(a),_(a),_(a));let y=_(a),x=_(a);_(a);let T=a.readBits(1)?0:c;for(let R=T;R<=c;R++)_(a),_(a),_(a);_(a),_(a),_(a),_(a),_(a),_(a),a.readBits(1)&&a.readBits(1)&&jc(a),a.skipBits(1),a.skipBits(1),a.readBits(1)&&(a.skipBits(4),a.skipBits(4),_(a),_(a),a.skipBits(1));let S=_(a);if($c(a,S),a.readBits(1)){let R=_(a);for(let D=0;D<R;D++)_(a),a.skipBits(1)}a.skipBits(1),a.skipBits(1);let k=0;a.readBits(1)&&(k=Kc(a,c));let I=0;if(o.length>0){let R=o[0],D=new V(hn(R));D.skipBits(16),_(D),_(D),D.skipBits(1),D.skipBits(1),D.skipBits(3),D.skipBits(1),D.skipBits(1),_(D),_(D),Se(D),D.skipBits(1),D.skipBits(1),D.readBits(1)&&_(D),Se(D),Se(D),D.skipBits(1),D.skipBits(1),D.skipBits(1),D.skipBits(1);let L=D.readBits(1),Y=D.readBits(1);!L&&!Y?I=0:L&&!Y?I=2:!L&&Y?I=3:I=0}let C=[...t.length?[{arrayCompleteness:1,nalUnitType:re.VPS_NUT,nalUnits:t}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:re.SPS_NUT,nalUnits:r}]:[],...o.length?[{arrayCompleteness:1,nalUnitType:re.PPS_NUT,nalUnits:o}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Fe(i[0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:u,generalTierFlag:d,generalProfileIdc:m,generalProfileCompatibilityFlags:f,generalConstraintIndicatorFlags:p,generalLevelIdc:h,minSpatialSegmentationIdc:k,parallelismType:I,chromaFormatIdc:g,bitDepthLumaMinus8:y,bitDepthChromaMinus8:x,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}},Gc=(n,e)=>{let t=n.readBits(2),r=n.readBits(1),o=n.readBits(5),i=0;for(let u=0;u<32;u++)i=i<<1|n.readBits(1);let s=new Uint8Array(6);for(let u=0;u<6;u++)s[u]=n.readBits(8);let a=n.readBits(8),c=[],l=[];for(let u=0;u<e;u++)c.push(n.readBits(1)),l.push(n.readBits(1));if(e>0)for(let u=e;u<8;u++)n.skipBits(2);for(let u=0;u<e;u++)c[u]&&n.skipBits(88),l[u]&&n.skipBits(8);return{general_profile_space:t,general_tier_flag:r,general_profile_idc:o,general_profile_compatibility_flags:i,general_constraint_indicator_flags:s,general_level_idc:a}},jc=n=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!n.readBits(1))_(n);else{let o=Math.min(64,1<<4+(e<<1));e>1&&Se(n);for(let i=0;i<o;i++)Se(n)}},$c=(n,e)=>{let t=[];for(let r=0;r<e;r++)t[r]=Xc(n,r,e,t)},Xc=(n,e,t,r)=>{let o=0,i=0,s=0;if(e!==0&&(i=n.readBits(1)),i){if(e===t){let c=_(n);s=e-(c+1)}else s=e-1;n.readBits(1),_(n);let a=r[s]??0;for(let c=0;c<=a;c++)n.readBits(1)||n.readBits(1);o=r[s]}else{let a=_(n),c=_(n);for(let l=0;l<a;l++)_(n),n.readBits(1);for(let l=0;l<c;l++)_(n),n.readBits(1);o=a+c}return o},Kc=(n,e)=>{if(n.readBits(1)&&n.readBits(8)===255&&(n.readBits(16),n.readBits(16)),n.readBits(1)&&n.readBits(1),n.readBits(1)&&(n.readBits(3),n.readBits(1),n.readBits(1)&&(n.readBits(8),n.readBits(8),n.readBits(8))),n.readBits(1)&&(_(n),_(n)),n.readBits(1),n.readBits(1),n.readBits(1),n.readBits(1)&&(_(n),_(n),_(n),_(n)),n.readBits(1)&&(n.readBits(32),n.readBits(32),n.readBits(1)&&_(n),n.readBits(1)&&Qc(n,!0,e)),n.readBits(1)){n.readBits(1),n.readBits(1),n.readBits(1);let t=_(n);return _(n),_(n),_(n),_(n),t}return 0},Qc=(n,e,t)=>{let r=!1,o=!1,i=!1;e&&(r=n.readBits(1)===1,o=n.readBits(1)===1,(r||o)&&(i=n.readBits(1)===1,i&&(n.readBits(8),n.readBits(5),n.readBits(1),n.readBits(5)),n.readBits(4),n.readBits(4),i&&n.readBits(4),n.readBits(5),n.readBits(5),n.readBits(5)));for(let s=0;s<=t;s++){let a=n.readBits(1)===1,c=!0;a||(c=n.readBits(1)===1);let l=!1;c?_(n):l=n.readBits(1)===1;let u=1;l||(u=_(n)+1),r&&ks(n,u,i),o&&ks(n,u,i)}},ks=(n,e,t)=>{for(let r=0;r<e;r++)_(n),_(n),t&&(_(n),_(n)),n.readBits(1)};var xn=n=>{let e=new V(n);if(e.readBits(2)!==2)return null;let r=e.readBits(1),i=(e.readBits(1)<<1)+r;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 u=e.readBits(3),d=0,m=0;if(u!==7)if(m=e.readBits(1),i===1||i===3){let I=e.readBits(1),C=e.readBits(1);d=!I&&!C?3:I&&!C?2:1,e.skipBits(1)}else d=1;else d=3,m=1;let f=e.readBits(16),p=e.readBits(16),h=f+1,g=p+1,y=h*g,x=ee(it).level;for(let k of it)if(y<=k.maxPictureSize){x=k.level;break}return{profile:i,level:x,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:m,colourPrimaries:u===2?1:u===1?6:2,transferCharacteristics:u===2?1:u===1?6:2,matrixCoefficients:u===7?0:u===2?1:u===1?6:2}},Es=function*(n){let e=new V(n),t=()=>{let r=0;for(let o=0;o<8;o++){let i=e.readAlignedByte();if(r|=(i&127)<<o*7,!(i&128))break;if(o===7&&i&128)return null}return r>=2**32-1?null:r};for(;e.getBitsLeft()>=8;){e.skipBits(1);let r=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);b(e.pos%8===0),yield{type:r,data:n.subarray(e.pos/8,e.pos/8+s)},e.skipBits(s*8)}},bn=n=>{for(let{type:e,data:t}of Es(n)){if(e!==1)continue;let r=new V(t),o=r.readBits(3),i=r.readBits(1),s=r.readBits(1),a=0,c=0,l=0;if(s)a=r.readBits(5);else{if(r.readBits(1)&&(r.skipBits(32),r.skipBits(32),r.readBits(1)))return null;let k=r.readBits(1);k&&(l=r.readBits(5),r.skipBits(32),r.skipBits(5),r.skipBits(5));let I=r.readBits(5);for(let C=0;C<=I;C++){r.skipBits(12);let A=r.readBits(5);if(C===0&&(a=A),A>7){let D=r.readBits(1);C===0&&(c=D)}if(k&&r.readBits(1)){let L=l+1;r.skipBits(L),r.skipBits(L),r.skipBits(1)}r.readBits(1)&&r.skipBits(4)}}let u=r.readBits(4),d=r.readBits(4),m=u+1;r.skipBits(m);let f=d+1;r.skipBits(f);let p=0;if(s?p=0:p=r.readBits(1),p&&(r.skipBits(4),r.skipBits(3)),r.skipBits(1),r.skipBits(1),r.skipBits(1),!s){r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);let S=r.readBits(1);S&&(r.skipBits(1),r.skipBits(1));let k=r.readBits(1),I=0;k?I=2:I=r.readBits(1),I>0&&(r.readBits(1)||r.skipBits(1)),S&&r.skipBits(3)}r.skipBits(1),r.skipBits(1),r.skipBits(1);let h=r.readBits(1),g=8;o===2&&h?g=r.readBits(1)?12:10:o<=2&&(g=h?10:8);let y=0;o!==1&&(y=r.readBits(1));let x=1,v=1,T=0;return y||(o===0?(x=1,v=1):o===1?(x=0,v=0):g===12&&(x=r.readBits(1),x&&(v=r.readBits(1))),x&&v&&(T=r.readBits(2))),{profile:o,level:a,tier:c,bitDepth:g,monochrome:y,chromaSubsamplingX:x,chromaSubsamplingY:v,chromaSamplePosition:T}}return null},Fs=n=>{let e=z(n),t=e.getUint8(9),r=e.getUint16(10,!0),o=e.getUint32(12,!0),i=e.getInt16(16,!0),s=e.getUint8(18),a=null;return s&&(a=n.subarray(19,21+t)),{outputChannelCount:t,preSkip:r,inputSampleRate:o,outputGain:i,channelMappingFamily:s,channelMappingTable:a}},Yc=[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],Ds=n=>{let e=n[0]>>3;return{durationInSamples:Yc[e]}},Rs=n=>{if(n.length<7)throw new Error("Setup header is too short.");if(n[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...n.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let t=n.length,r=new Uint8Array(t);for(let d=0;d<t;d++)r[d]=n[t-1-d];let o=new V(r),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 d=o.pos,m=o.readBits(8),f=o.readBits(16),p=o.readBits(16);if(m>63||f!==0||p!==0){o.pos=d;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 u=Array(l).fill(0);for(let d=l-1;d>=0;d--)o.skipBits(40),u[d]=o.readBits(1);return{modeBlockflags:u}},yn=(n,e,t)=>{switch(n){case"avc":{let r=Jo(t,e),o=r.some(i=>ct(i)===at.IDR);if(!o&&(!ur()||ys()>=144))for(let i of r){if(ct(i)!==at.SEI)continue;let a=hn(i),c=1;do{let l=0;for(;;){let m=a[c++];if(m===void 0||(l+=m,m<255))break}let u=0;for(;;){let m=a[c++];if(m===void 0||(u+=m,m<255))break}if(l===6){let m=new V(a);m.pos=8*c;let f=_(m),p=m.readBits(1);if(f===0&&p===1){o=!0;break}}c+=u}while(c<a.length-1)}return o?"key":"delta"}case"hevc":return ti(t,e).some(i=>{let s=Fe(i);return re.BLA_W_LP<=s&&s<=re.RSV_IRAP_VCL23})?"key":"delta";case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{let r=new V(t);if(r.readBits(2)!==2)return null;let o=r.readBits(1);return(r.readBits(1)<<1)+o===3&&r.skipBits(1),r.readBits(1)?null:r.readBits(1)===0?"key":"delta"}case"av1":{let r=!1;for(let{type:o,data:i}of Es(t))if(o===1){let s=new V(i);s.skipBits(4),r=!!s.readBits(1)}else if(o===3||o===6||o===7){if(r)return"key";let s=new V(i);return s.readBits(1)?null:s.readBits(2)===0?"key":"delta"}return null}default:ue(n),b(!1)}},We;(function(n){n[n.STREAMINFO=0]="STREAMINFO",n[n.VORBIS_COMMENT=4]="VORBIS_COMMENT",n[n.PICTURE=6]="PICTURE"})(We||(We={}));var fr=(n,e)=>{let t=z(n),r=0,o=t.getUint32(r,!0);r+=4;let i=K.decode(n.subarray(r,r+o));r+=o,o>0&&(e.raw??={},e.raw.vendor??=i);let s=t.getUint32(r,!0);r+=4;for(let a=0;a<s;a++){let c=t.getUint32(r,!0);r+=4;let l=K.decode(n.subarray(r,r+c));r+=c;let u=l.indexOf("=");if(u===-1)continue;let d=l.slice(0,u).toUpperCase(),m=l.slice(u+1);switch(e.raw??={},e.raw[d]??=m,d){case"TITLE":e.title??=m;break;case"DESCRIPTION":e.description??=m;break;case"ARTIST":e.artist??=m;break;case"ALBUM":e.album??=m;break;case"ALBUMARTIST":e.albumArtist??=m;break;case"COMMENT":e.comment??=m;break;case"LYRICS":e.lyrics??=m;break;case"TRACKNUMBER":{let f=m.split("/"),p=Number.parseInt(f[0],10),h=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),h&&Number.isInteger(h)&&h>0&&(e.tracksTotal??=h)}break;case"TRACKTOTAL":{let f=Number.parseInt(m,10);Number.isInteger(f)&&f>0&&(e.tracksTotal??=f)}break;case"DISCNUMBER":{let f=m.split("/"),p=Number.parseInt(f[0],10),h=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),h&&Number.isInteger(h)&&h>0&&(e.discsTotal??=h)}break;case"DISCTOTAL":{let f=Number.parseInt(m,10);Number.isInteger(f)&&f>0&&(e.discsTotal??=f)}break;case"DATE":{let f=new Date(m);Number.isNaN(f.getTime())||(e.date??=f)}break;case"GENRE":e.genre??=m;break;case"METADATA_BLOCK_PICTURE":{let f=vs(m),p=z(f),h=p.getUint32(0,!1),g=p.getUint32(4,!1),y=String.fromCharCode(...f.subarray(8,8+g)),x=p.getUint32(8+g,!1),v=K.decode(f.subarray(12+g,12+g+x)),T=p.getUint32(g+x+28),S=f.subarray(g+x+32,g+x+32+T);e.images??=[],e.images.push({data:S,mimeType:y,kind:h===3?"coverFront":h===4?"coverBack":"unknown",name:void 0,description:v||void 0})}break}}};var J=class{constructor(e){this.input=e}};var vn=[],Tn=[];var G=new Uint8Array(0),H=class n{constructor(e,t,r,o,i=-1,s,a){if(this.data=e,this.type=t,this.timestamp=r,this.duration=o,this.sequenceNumber=i,e===G&&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(r))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===G}get microsecondTimestamp(){return Math.trunc(Ce*this.timestamp)}get microsecondDuration(){return Math.trunc(Ce*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 r=new Uint8Array(e.byteLength);return e.copyTo(r),new n(r,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 n(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}};var Ms=n=>{let t=0,r=0,o=~n;o&128&&(o&=-129,t=-1),r=((o&240)>>4)+5;let i=(1<<r|(o&15)<<r-4|1<<r-5)-33;return t===0?i:-i};var Bs=n=>{let e=0,t=0,r=n^85;r&128&&(r&=-129,e=-1),t=((r&240)>>4)+4;let o=0;return t!==4?o=1<<t|(r&15)<<t-4|1<<t-5:o=r<<1|1,e===0?o:-o};un();var Os=-1/0,zs=-1/0,gr=null;typeof FinalizationRegistry<"u"&&(gr=new FinalizationRegistry(n=>{let e=Date.now();n.type==="video"?(e-Os>=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."),Os=e),typeof VideoFrame<"u"&&n.data instanceof VideoFrame&&n.data.close()):(e-zs>=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."),zs=e),typeof AudioData<"u"&&n.data instanceof AudioData&&n.data.close())}));var Us=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Zc=new Set(Us),Et=class n{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(Ce*this.timestamp)}get microsecondDuration(){return Math.trunc(Ce*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||!Zc.has(t.format))throw new TypeError("init.format must be one of: "+Us.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=fe(e).slice(),this._layout=t.layout??Jc(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 hr(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 hr(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 n(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Ce),duration:Math.trunc((t.duration??0)*Ce)||void 0}),t);let r=0,o=0;if("naturalWidth"in e?(r=e.naturalWidth,o=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,o=e.videoHeight):"width"in e&&(r=Number(e.width),o=Number(e.height)),!r||!o)throw new TypeError("Could not determine dimensions.");let i=new OffscreenCanvas(r,o),s=i.getContext("2d",{alpha:lr(),willReadFrequently:!0});b(s),s.drawImage(e,0,0),this._data=i,this._layout=null,this.format="RGBX",this.codedWidth=r,this.codedHeight=o,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new hr({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");gr?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return b(this._data!==null),lt(this._data)?new n(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(b(this._layout),new n(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 n(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||(gr?.unregister(this),lt(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Ns(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(b(this._data!==null),!lt(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let t=this.toVideoFrame(),r=t.allocationSize(e);return t.close(),r}return lt(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,t={}){if(!sn(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ns(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(b(this._data!==null),!lt(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){let r=this.toVideoFrame(),o=await r.copyTo(e,t);return r.close(),o}if(lt(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array)return b(this._layout),fe(e).set(this._data),this._layout;{let o=this._data.getContext("2d");b(o);let i=o.getImageData(0,0,this.codedWidth,this.codedHeight);return fe(e).set(i.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return b(this._data!==null),lt(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,r,o,i,s,a,c,l){let u=0,d=0,m=this.displayWidth,f=this.displayHeight,p=0,h=0,g=this.displayWidth,y=this.displayHeight;if(s!==void 0?(u=t,d=r,m=o,f=i,p=s,h=a,c!==void 0?(g=c,y=l):(g=m,y=f)):(p=t,h=r,o!==void 0&&(g=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(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(m)||m<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(f)||f<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(h))throw new TypeError("dy must be a number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:u,sy:d,sWidth:m,sHeight:f}=this._rotateSourceRegion(u,d,m,f,this.rotation));let x=this.toCanvasImageSource();e.save();let v=p+g/2,T=h+y/2;e.translate(v,T),e.rotate(this.rotation*Math.PI/180);let S=this.rotation%180===0?1:g/y;e.scale(1/S,S),e.drawImage(x,u,d,m,f,-g/2,-y/2,g,y),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");t.crop!==void 0&&oi(t.crop,"options.");let r=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&&ni(t.crop,s,a);let c,l,u,d,{sx:m,sy:f,sWidth:p,sHeight:h}=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,u=r,d=o;else{let[y,x]=t.crop?[t.crop.width,t.crop.height]:[s,a],v=t.fit==="contain"?Math.min(r/y,o/x):Math.max(r/y,o/x);u=y*v,d=x*v,c=(r-u)/2,l=(o-d)/2}e.save();let g=i%180===0?1:u/d;e.translate(r/2,o/2),e.rotate(i*Math.PI/180),e.scale(1/g,g),e.translate(-r/2,-o/2),e.drawImage(this.toCanvasImageSource(),m,f,p,h,c,l,u,d),e.restore()}_rotateSourceRegion(e,t,r,o,i){return i===90?[e,t,r,o]=[t,this.codedHeight-e-r,o,r]:i===180?[e,t]=[this.codedWidth-e-r,this.codedHeight-t-o]:i===270&&([e,t,r,o]=[this.codedWidth-t-o,e,o,r]),{sx:e,sy:t,sWidth:r,sHeight:o}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(b(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()}},hr=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}}},lt=n=>typeof VideoFrame<"u"&&n instanceof VideoFrame,ni=(n,e,t)=>{n.left=Math.min(n.left,e),n.top=Math.min(n.top,t),n.width=Math.min(n.width,e-n.left),n.height=Math.min(n.height,t-n.top),b(n.width>=0),b(n.height>=0)},oi=(n,e)=>{if(!n||typeof n!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(n.left)||n.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(n.top)||n.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(n.width)||n.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(n.height)||n.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},Ns=n=>{if(!n||typeof n!="object")throw new TypeError("options must be an object.");if(n.colorSpace!==void 0&&!["display-p3","srgb"].includes(n.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(n.format!==void 0&&typeof n.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(n.layout!==void 0){if(!Array.isArray(n.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let e of n.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(n.rect!==void 0){if(!n.rect||typeof n.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(n.rect.x!==void 0&&(!Number.isInteger(n.rect.x)||n.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(n.rect.y!==void 0&&(!Number.isInteger(n.rect.y)||n.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(n.rect.width!==void 0&&(!Number.isInteger(n.rect.width)||n.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(n.rect.height!==void 0&&(!Number.isInteger(n.rect.height)||n.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},Jc=(n,e,t)=>{let r=el(n),o=[],i=0;for(let s of r){let a=Math.ceil(e/s.widthDivisor),c=Math.ceil(t/s.heightDivisor),l=a*s.sampleBytes,u=l*c;o.push({offset:i,stride:l}),i+=u}return o},el=n=>{let e=(t,r,o,i,s)=>{let a=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:r,widthDivisor:o,heightDivisor:i},{sampleBytes:r,widthDivisor:o,heightDivisor:i}];return s&&a.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),a};switch(n){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:ue(n),b(!1)}},ri=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),Ft=class n{get microsecondTimestamp(){return Math.trunc(Ce*this.timestamp)}get microsecondDuration(){return Math.trunc(Ce*this.duration)}constructor(e){if(this._closed=!1,pr(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(!ri.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/(ut(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let r;if(e.data instanceof ArrayBuffer)r=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))r=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let o=this.numberOfFrames*this.numberOfChannels*ut(this.format);if(r.byteLength<o)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=r}gr?.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&&!ri.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,r=e.frameOffset??0;if(r>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let o=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-r;if(o>this.numberOfFrames-r)throw new RangeError("frameCount out of range");let i=ut(t),s=_t(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(!sn(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&&!ri.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:r,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,u=this.numberOfChannels,d=s??0;if(d>=l)throw new RangeError("frameOffset out of range");let m=i!==void 0?i:l-d;if(m>l-d)throw new RangeError("frameCount out of range");let f=ut(c),p=_t(c);if(p&&r>=u)throw new RangeError("planeIndex out of range");if(!p&&r!==0)throw new RangeError("planeIndex out of range");let g=(p?m:m*u)*f;if(e.byteLength<g)throw new RangeError("Destination buffer is too small");let y=z(e),x=Vs(c);if(pr(this._data))Le()&&u>2&&c!==a?tl(this._data,y,a,c,u,r,d,m):this._data.copyTo(e,{planeIndex:r,frameOffset:d,frameCount:m,format:c});else{let v=this._data,T=z(v),S=Ls(a),k=ut(a),I=_t(a);for(let C=0;C<m;C++)if(p){let A=C*f,R;I?R=(r*l+(C+d))*k:R=((C+d)*u+r)*k;let D=S(T,R);x(y,A,D)}else for(let A=0;A<u;A++){let D=(C*u+A)*f,L;I?L=(A*l+(C+d))*k:L=((C+d)*u+A)*k;let Y=S(T,L);x(y,D,Y)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(pr(this._data)){let e=new n(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new n({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(gr?.unregister(this),pr(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(pr(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(_t(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(new Uint8Array(t,r*e,e),{planeIndex:r,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{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 r=0;r<this.numberOfChannels;r++)this.copyTo(t,{planeIndex:r,format:"f32-planar"}),e.copyToChannel(t,r);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let r=48e3*5,o=e.numberOfChannels,i=e.sampleRate,s=e.length,a=Math.floor(r/o),c=0,l=s;for(;l>0;){let u=Math.min(a,l),d=new Float32Array(o*u);for(let m=0;m<o;m++)e.copyFromChannel(d.subarray(m*u,(m+1)*u),m,c);yield new n({format:"f32-planar",sampleRate:i,numberOfFrames:u,numberOfChannels:o,timestamp:t+c/i,data:d}),c+=u,l-=u}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let r=48e3*5,o=e.numberOfChannels,i=e.sampleRate,s=e.length,a=Math.floor(r/o),c=0,l=s,u=[];for(;l>0;){let d=Math.min(a,l),m=new Float32Array(o*d);for(let p=0;p<o;p++)e.copyFromChannel(m.subarray(p*d,(p+1)*d),p,c);let f=new n({format:"f32-planar",sampleRate:i,numberOfFrames:d,numberOfChannels:o,timestamp:t+c/i,data:m});u.push(f),c+=d,l-=d}return u}},ut=n=>{switch(n){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")}},_t=n=>{switch(n){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Ls=n=>{switch(n){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)}},Vs=n=>{switch(n){case"u8":case"u8-planar":return(e,t,r)=>e.setUint8(t,rt((r+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,r)=>e.setInt16(t,rt(Math.round(r*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,r)=>e.setInt32(t,rt(Math.round(r*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,r)=>e.setFloat32(t,r,!0)}},pr=n=>typeof AudioData<"u"&&n instanceof AudioData,tl=(n,e,t,r,o,i,s,a)=>{let c=Ls(t),l=Vs(r),u=ut(t),d=ut(r),m=_t(t);if(_t(r))if(m){let p=new ArrayBuffer(a*u),h=z(p);n.copyTo(p,{planeIndex:i,frameOffset:s,frameCount:a,format:t});for(let g=0;g<a;g++){let y=g*u,x=g*d,v=c(h,y);l(e,x,v)}}else{let p=new ArrayBuffer(a*o*u),h=z(p);n.copyTo(p,{planeIndex:0,frameOffset:s,frameCount:a,format:t});for(let g=0;g<a;g++){let y=(g*o+i)*u,x=g*d,v=c(h,y);l(e,x,v)}}else if(m){let p=a*u,h=new ArrayBuffer(p),g=z(h);for(let y=0;y<o;y++){n.copyTo(h,{planeIndex:y,frameOffset:s,frameCount:a,format:t});for(let x=0;x<a;x++){let v=x*u,T=(x*o+y)*d,S=c(g,v);l(e,T,S)}}}else{let p=new ArrayBuffer(a*o*u),h=z(p);n.copyTo(p,{planeIndex:0,frameOffset:s,frameCount:a,format:t});for(let g=0;g<a;g++)for(let y=0;y<o;y++){let x=g*o+y,v=x*u,T=x*d,S=c(h,v);l(e,T,S)}}};var Dt=n=>{if(!n||typeof n!="object")throw new TypeError("options must be an object.");if(n.metadataOnly!==void 0&&typeof n.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(n.verifyKeyPackets!==void 0&&typeof n.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(n.verifyKeyPackets&&n.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},qe=n=>{if(!dr(n))throw new TypeError("timestamp must be a number.")},ii=(n,e,t)=>t.verifyKeyPackets?e.then(async r=>{if(!r||r.type==="delta")return r;let o=await n.determinePacketType(r);return o&&(r.type=o),r}):e,dt=class{constructor(e){if(!(e instanceof Mt))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(Dt(e),this._track.input._disposed)throw new j;return ii(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){if(qe(e),Dt(t),this._track.input._disposed)throw new j;return ii(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof H))throw new TypeError("packet must be an EncodedPacket.");if(Dt(t),this._track.input._disposed)throw new j;return ii(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(qe(e),Dt(t),this._track.input._disposed)throw new j;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let r=await this._track._backing.getKeyPacket(e,t);return r&&(b(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getKeyPacket(r.timestamp-1/this._track.timeResolution,t):r)}async getNextKeyPacket(e,t={}){if(!(e instanceof H))throw new TypeError("packet must be an EncodedPacket.");if(Dt(t),this._track.input._disposed)throw new j;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let r=await this._track._backing.getNextKeyPacket(e,t);return r&&(b(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getNextKeyPacket(r,t):r)}packets(e,t,r={}){if(e!==void 0&&!(e instanceof H))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof H))throw new TypeError("endPacket must be an EncodedPacket.");if(Dt(r),this._track.input._disposed)throw new j;let o=[],{promise:i,resolve:s}=te(),{promise:a,resolve:c}=te(),l=!1,u=!1,d=null,m=[],f=()=>Math.max(2,m.length);(async()=>{let h=e??await this.getFirstPacket(r);for(;h&&!u&&!this._track.input._disposed&&!(t&&h.sequenceNumber>=t?.sequenceNumber);){if(o.length>f()){({promise:a,resolve:c}=te()),await a;continue}o.push(h),s(),{promise:i,resolve:s}=te(),h=await this.getNextPacket(h,r)}l=!0,s()})().catch(h=>{d||(d=h,s())});let p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new j;if(u)return{value:void 0,done:!0};if(d)throw d;if(o.length>0){let h=o.shift(),g=performance.now();for(m.push(g);m.length>0&&g-m[0]>=1e3;)m.shift();return c(),{value:h,done:!1}}else{if(l)return{value:void 0,done:!0};await i}}},async return(){return u=!0,c(),s(),{value:void 0,done:!0}},async throw(h){throw h},[Symbol.asyncIterator](){return this}}}},xr=class{constructor(e,t){this.onSample=e,this.onError=t}},br=class{mediaSamplesInRange(e=0,t=1/0){qe(e),qe(t);let r=[],o=!1,i=null,{promise:s,resolve:a}=te(),{promise:c,resolve:l}=te(),u=!1,d=!1,m=!1,f=null;(async()=>{let g=await this._createDecoder(k=>{if(l(),k.timestamp>=t&&(d=!0),d){k.close();return}i&&(k.timestamp>e?(r.push(i),o=!0):i.close()),k.timestamp>=e&&(r.push(k),o=!0),i=o?null:k,r.length>0&&(a(),{promise:s,resolve:a}=te())},k=>{f||(f=k,a())}),y=this._createPacketSink(),x=await y.getKeyPacket(e,{verifyKeyPackets:!0})??await y.getFirstPacket(),v=x,T;if(t<1/0){let k=await y.getPacket(t),I=k?k.type==="key"&&k.timestamp===t?k:await y.getNextKeyPacket(k,{verifyKeyPackets:!0}):null;I&&(T=I)}let S=y.packets(x??void 0,T);for(await S.next();v&&!d&&!this._track.input._disposed;){let k=Hs(r.length);if(r.length+g.getDecodeQueueSize()>k){({promise:c,resolve:l}=te()),await c;continue}g.decode(v);let I=await S.next();if(I.done)break;v=I.value}await S.return(),!m&&!this._track.input._disposed&&await g.flush(),g.close(),!o&&i&&r.push(i),u=!0,a()})().catch(g=>{f||(f=g,a())});let p=this._track,h=()=>{i?.close();for(let g of r)g.close()};return{async next(){for(;;){if(p.input._disposed)throw h(),new j;if(m)return{value:void 0,done:!0};if(f)throw h(),f;if(r.length>0){let g=r.shift();return l(),{value:g,done:!1}}else if(!u)await s;else return{value:void 0,done:!0}}},async return(){return m=!0,d=!0,l(),a(),h(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){ps(e);let t=fs(e),r=[],o=[],{promise:i,resolve:s}=te(),{promise:a,resolve:c}=te(),l=!1,u=!1,d=null,m=h=>{o.push(h),s(),{promise:i,resolve:s}=te()};(async()=>{let h=await this._createDecoder(k=>{if(c(),u){k.close();return}let I=0;for(;r.length>0&&k.timestamp-r[0]>-1e-10;)I++,r.shift();if(I>0)for(let C=0;C<I;C++)m(C<I-1?k.clone():k);else k.close()},k=>{d||(d=k,s())}),g=this._createPacketSink(),y=null,x=null,v=-1,T=async()=>{b(x);let k=x;for(h.decode(k);k.sequenceNumber<v;){let I=Hs(o.length);for(;o.length+h.getDecodeQueueSize()>I&&!u;)({promise:a,resolve:c}=te()),await a;if(u)break;let C=await g.getNextPacket(k);b(C),h.decode(C),k=C}v=-1},S=async()=>{await h.flush();for(let k=0;k<r.length;k++)m(null);r.length=0};for await(let k of t){if(qe(k),u||this._track.input._disposed)break;let I=await g.getPacket(k),C=I&&await g.getKeyPacket(k,{verifyKeyPackets:!0});if(!C){v!==-1&&(await T(),await S()),m(null),y=null;continue}y&&(C.sequenceNumber!==x.sequenceNumber||I.timestamp<y.timestamp)&&(await T(),await S()),r.push(I.timestamp),v=Math.max(I.sequenceNumber,v),y=I,x=C}!u&&!this._track.input._disposed&&(v!==-1&&await T(),await S()),h.close(),l=!0,s()})().catch(h=>{d||(d=h,s())});let f=this._track,p=()=>{for(let h of o)h?.close()};return{async next(){for(;;){if(f.input._disposed)throw p(),new j;if(u)return{value:void 0,done:!0};if(d)throw p(),d;if(o.length>0){let h=o.shift();return b(h!==void 0),c(),{value:h,done:!1}}else if(!l)await i;else return{value:void 0,done:!0}}},async return(){return u=!0,c(),s(),p(),{value:void 0,done:!0}},async throw(h){throw h},[Symbol.asyncIterator](){return this}}}},Hs=n=>n===0?40:8,si=class extends xr{constructor(e,t,r,o,i,s){super(e,t),this.codec=r,this.decoderConfig=o,this.rotation=i,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new cr,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=vn.find(c=>c.supports(r,o));if(a)this.customDecoder=new a,this.customDecoder.codec=r,this.customDecoder.config=o,this.customDecoder.onSample=c=>{if(!(c instanceof Et))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=u=>{if(this.alphaQueue.length>0){let d=this.alphaQueue.shift();b(d!==void 0),this.mergeAlpha(u,d)}else this.colorQueue.push(u)};if(r==="avc"&&this.decoderConfig.description&&ur()){let u=As(fe(this.decoderConfig.description));if(u&&u.sequenceParameterSets.length>0){let d=ei(u.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let l=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:u=>{try{c(u)}catch(d){this.onError(d)}},error:u=>{u.stack=l,this.onError(u)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(b(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(b(this.decoder),Le()||Go(this.inputTimestamps,e.timestamp,t=>t),ur()&&this.currentPacketIndex===0&&this.codec==="avc"){let r=Jo(e.data,this.decoderConfig).filter(i=>{let s=ct(i);return!(s>=20&&s<=31)}),o=Ps(r,this.decoderConfig);e=new H(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 ai}catch(r){console.error("Due to an error, only color data will be decoded.",r),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let r=i=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let s=this.colorQueue.shift();b(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();b(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{r(i)}catch(s){this.onError(s)}},error:i=>{i.stack=o,this.onError(i)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=yn(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 ti(e,this.decoderConfig).some(r=>{let o=Fe(r);return o===re.RASL_N||o===re.RASL_R})}sampleHandler(e){if(Le()){if(this.sampleQueue.length>0&&e.timestamp>=ee(this.sampleQueue).timestamp){for(let t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}Go(this.sampleQueue,e,t=>t.timestamp)}else{let t=this.inputTimestamps.shift();b(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 Et(e);this.sampleHandler(i);return}b(this.merger),this.merger.update(e,t),e.close(),t.close();let r=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),o=new Et(r);this.sampleHandler(o)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(b(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),Le()){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()):(b(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}},ai=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
|
-
`),r=this.gl.createProgram();return this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),r}createShader(e,t){let r=this.gl.createShader(e);return this.gl.shaderSource(r,t),this.gl.compileShader(r),r}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]),r=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,r),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}},Rt=class extends br{constructor(e){if(!(e instanceof Pe))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 r=this._track.codec,o=this._track.rotation,i=await this._track.getDecoderConfig(),s=this._track.timeResolution;return b(r&&i),new si(e,t,r,i,o,s)}_createPacketSink(){return new mt(this._track)}async getSample(e){Ge(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)}},yr=class{constructor(e,t={}){if(this._nextCanvasIndex=0,!(e instanceof Pe))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&&oi(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 r=t.rotation??e.rotation,[o,i]=r%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],s=t.crop;s&&ni(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=r,this._crop=s,this._fit=t.fit??"fill",this._videoSampleSink=new Rt(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let t=this._canvasPool[this._nextCanvasIndex],r=!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),r=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let o=t.getContext("2d",{alpha:this._alpha||lr()});b(o),o.resetTransform(),r||(!this._alpha&&lr()?(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){Ge(e);let t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return $o(this._videoSampleSink.samples(e,t),r=>this._videoSampleToWrappedCanvas(r))}canvasesAtTimestamps(e){return $o(this._videoSampleSink.samplesAtTimestamps(e),t=>t&&this._videoSampleToWrappedCanvas(t))}},ci=class extends xr{constructor(e,t,r,o){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new cr,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=Tn.find(a=>a.supports(r,o));if(s)this.customDecoder=new s,this.customDecoder.codec=r,this.customDecoder.config=o,this.customDecoder.onSample=a=>{if(!(a instanceof Ft))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 Ft(c))}catch(l){this.onError(l)}},error:c=>{c.stack=a,this.onError(c)}}),this.decoder.configure(o)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(b(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(b(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(b(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(b(this.decoder),this.decoder.close())}},li=class extends xr{constructor(e,t,r){super(e,t),this.decoderConfig=r,this.currentTimestamp=null,b(We.includes(r.codec)),this.codec=r.codec;let{dataType:o,sampleSize:i,littleEndian:s}=pn(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)=>Ms(a.getUint8(c)):o==="alaw"?this.readInputValue=(a,c)=>Bs(a.getUint8(c)):b(!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):b(!1);break;case 3:o==="unsigned"?this.readInputValue=(a,c)=>rt(a,c,s)-2**23:o==="signed"?this.readInputValue=(a,c)=>hs(a,c,s):b(!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):b(!1);break;case 8:o==="float"?this.readInputValue=(a,c)=>a.getFloat64(c,s):b(!1);break;default:ue(i),b(!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:ue(i),b(!1)}}getDecodeQueueSize(){return 0}decode(e){let t=z(e.data),r=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,o=r*this.decoderConfig.numberOfChannels*this.outputSampleSize,i=new ArrayBuffer(o),s=new DataView(i);for(let u=0;u<r*this.decoderConfig.numberOfChannels;u++){let d=u*this.inputSampleSize,m=u*this.outputSampleSize,f=this.readInputValue(t,d);this.writeOutputValue(s,m,f)}let a=r/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 Ft({format:this.outputFormat,data:i,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:r,timestamp:c});this.onSample(l)}async flush(){}close(){}},vr=class extends br{constructor(e){if(!(e instanceof $))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 r=this._track.codec,o=await this._track.getDecoderConfig();return b(r&&o),We.includes(o.codec)?new li(e,t,o):new ci(e,t,r,o)}_createPacketSink(){return new mt(this._track)}async getSample(e){Ge(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 Mt=class{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Pe}isAudioTrack(){return this instanceof $}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 mt(this),r=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;r=Math.min(r,a.timestamp),o=Math.max(o,a.timestamp+a.duration),i++,s+=a.byteLength}return{packetCount:i,averagePacketRate:i?Number((i/(o-r)).toPrecision(16)):0,averageBitrate:i?Number((8*s/(o-r)).toPrecision(16)):0}}},Pe=class extends Mt{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 b(t!==null),vn.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 H))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 b(t),yn(this.codec,t,e.data)}},$=class extends Mt{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 b(t!==null),Tn.some(r=>r.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 H))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}};var Ws=n=>{let t=(n.hasVideo?"video/":n.hasAudio?"audio/":"application/")+(n.isQuickTime?"quicktime":"mp4");if(n.codecStrings.length>0){let r=[...new Set(n.codecStrings)];t+=`; codecs="${r.join(", ")}"`}return t};var ft=8,Bt=16,De=n=>{let e=P(n),t=W(n,4),r=8;e===1&&(e=ae(n),r=16);let i=e-r;return i<0?null:{name:t,totalSize:e,headerSize:r,contentSize:i}},je=n=>Re(n)/65536,wn=n=>Re(n)/1073741824,kn=n=>{let e=0;for(let t=0;t<4;t++){e<<=7;let r=E(n);if(e|=r&127,(r&128)===0)break}return e},pe=n=>{let e=X(n);return n.skip(2),e=Math.min(e,n.remainingLength),K.decode(F(n,e))},qs=n=>{let e=De(n);if(!e||e.name!=="data"||n.remainingLength<8)return null;let t=P(n);n.skip(4);let r=F(n,e.contentSize-8);switch(t){case 1:return K.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new He(r,"image/jpeg");case 14:return new He(r,"image/png");case 27:return new He(r,"image/bmp");default:return r}};var Sn=class extends J{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(r=>r.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 Ws({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,ft,Bt);if(t instanceof Promise&&(t=await t),!t)break;let r=e,o=De(t);if(!o)break;if(o.name==="ftyp"){let i=W(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=r+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),b(t);let r=P(t),o=this.reader.fileSize-r;if(o>=0&&o<=this.reader.fileSize-Bt){let i=this.reader.requestSliceRange(o,ft,Bt);if(i instanceof Promise&&(i=await i),i){let s=De(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,b(this.moovSlice);let r=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(r),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&We.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){b(e.info?.type==="audio");let i=pn(e.info.codec),s=[],a=[];for(let c=0;c<t.sampleToChunk.length;c++){let l=t.sampleToChunk[c],u=t.sampleToChunk[c+1],d=(u?u.startChunkIndex:t.chunkOffsets.length)-l.startChunkIndex;for(let m=0;m<d;m++){let f=l.startSampleIndex+m*l.samplesPerChunk,p=f+l.samplesPerChunk,h=O(t.sampleTimingEntries,f,C=>C.startIndex),g=t.sampleTimingEntries[h],y=O(t.sampleTimingEntries,p,C=>C.startIndex),x=t.sampleTimingEntries[y],v=g.startDecodeTimestamp+(f-g.startIndex)*g.delta,S=x.startDecodeTimestamp+(p-x.startIndex)*x.delta-v,k=ee(s);k&&k.delta===S?k.count++:s.push({startIndex:l.startChunkIndex+m,startDecodeTimestamp:v,count:1,delta:S});let I=l.samplesPerChunk*i.sampleSize*e.info.numberOfChannels;a.push(I)}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,ft,Bt);t instanceof Promise&&(t=await t),b(t);let r=De(t);b(r?.name==="moof");let o=this.reader.requestSlice(e,r.totalSize);o instanceof Promise&&(o=await o),b(o),this.traverseBox(o);let i=this.lastReadFragment;b(i&&i.moofOffset===e);for(let[,s]of i.trackData){let a=s.track,{fragmentPositionCache:c}=a;if(!s.startTimestampIsFinal){let u=a.fragmentLookupTable.find(d=>d.moofOffset===i.moofOffset);if(u)ui(s,u.timestamp);else{let d=O(c,i.moofOffset-1,m=>m.moofOffset);if(d!==-1){let m=c[d];ui(s,m.endTimestamp)}}s.startTimestampIsFinal=!0}let l=O(c,s.startTimestamp,u=>u.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-ft&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-ft;){let r=e.filePos,o=De(e);if(!o)break;yield{boxInfo:o,slice:e},e.filePos=r+o.totalSize}}traverseBox(e){let t=e.filePos,r=De(e);if(!r)return!1;let o=e.filePos,i=t+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(e.slice(o,r.contentSize));break;case"mvhd":{let s=E(e);e.skip(3),s===1?(e.skip(16),this.movieTimescale=P(e),this.movieDurationInTimescale=ae(e)):(e.skip(8),this.movieTimescale=P(e),this.movieDurationInTimescale=P(e))}break;case"trak":{let s={id:-1,demuxer:this,inputTrack:null,disposition:{...ie},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Q,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=s,this.readContiguousBoxes(e.slice(o,r.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 Pe(this.input,new di(a)),this.tracks.push(s)}else if(s.info.type==="audio"&&s.info.numberOfChannels!==-1){let a=s;s.inputTrack=new $(this.input,new mi(a)),this.tracks.push(s)}}this.currentTrack=null}break;case"tkhd":{let s=this.currentTrack;if(!s)break;let a=E(e),l=!!($e(e)&1);if(s.disposition.default=l,a===0)e.skip(8),s.id=P(e),e.skip(4),s.durationInMovieTimescale=P(e);else if(a===1)e.skip(16),s.id=P(e),e.skip(4),s.durationInMovieTimescale=ae(e);else throw new Error(`Incorrect track header version ${a}.`);e.skip(16);let u=[je(e),je(e),wn(e),je(e),je(e),wn(e),je(e),je(e),wn(e)],d=tn(xs(il(u),90));b(d===0||d===90||d===180||d===270),s.rotation=d}break;case"elst":{let s=this.currentTrack;if(!s)break;let a=E(e);e.skip(3);let c=!1,l=0,u=P(e);for(let d=0;d<u;d++){let m=a===1?ae(e):P(e),f=a===1?js(e):Re(e),p=je(e);if(m!==0){if(c){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(f===-1){l+=m;continue}if(p!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}s.editListPreviousSegmentDurations=l,s.editListOffset=f,c=!0}}}break;case"mdhd":{let s=this.currentTrack;if(!s)break;let a=E(e);e.skip(3),a===0?(e.skip(8),s.timescale=P(e),s.durationInMediaTimescale=P(e)):a===1&&(e.skip(16),s.timescale=P(e),s.durationInMediaTimescale=ae(e));let c=X(e);if(c>0){s.languageCode="";for(let l=0;l<3;l++)s.languageCode=String.fromCharCode(96+(c&31))+s.languageCode,c>>=5;cn(s.languageCode)||(s.languageCode=Q)}}break;case"hdlr":{let s=this.currentTrack;if(!s)break;e.skip(8);let a=W(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,r.contentSize))}break;case"stsd":{let s=this.currentTrack;if(!s||s.info===null||s.sampleTable)break;let a=E(e);e.skip(3);let c=P(e);for(let l=0;l<c;l++){let u=e.filePos,d=De(e);if(!d)break;s.internalCodecId=d.name;let m=d.name.toLowerCase();if(s.info.type==="video")m==="avc1"||m==="avc3"?(s.info.codec="avc",s.info.avcType=m==="avc1"?1:3):m==="hvc1"||m==="hev1"?s.info.codec="hevc":m==="vp08"?s.info.codec="vp8":m==="vp09"?s.info.codec="vp9":m==="av01"?s.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${d.name}').`),e.skip(24),s.info.width=X(e),s.info.height=X(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,u+d.totalSize-e.filePos));else{m==="mp4a"||(m==="opus"?s.info.codec="opus":m==="flac"?s.info.codec="flac":m==="twos"||m==="sowt"||m==="raw "||m==="in24"||m==="in32"||m==="fl32"||m==="fl64"||m==="lpcm"||m==="ipcm"||m==="fpcm"||(m==="ulaw"?s.info.codec="ulaw":m==="alaw"?s.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${d.name}').`))),e.skip(8);let f=X(e);e.skip(6);let p=X(e),h=X(e);e.skip(4);let g=P(e)/65536;if(a===0&&f>0){if(f===1)e.skip(4),h=8*P(e),e.skip(8);else if(f===2){e.skip(4),g=Pn(e),p=P(e),e.skip(4),h=P(e);let y=P(e);if(e.skip(8),m==="lpcm"){let x=h+7>>3,v=!!(y&1),T=!!(y&2),S=y&4?-1:0;h>0&&h<=64&&(v?h===32&&(s.info.codec=T?"pcm-f32be":"pcm-f32"):S&1<<x-1?x===1?s.info.codec="pcm-s8":x===2?s.info.codec=T?"pcm-s16be":"pcm-s16":x===3?s.info.codec=T?"pcm-s24be":"pcm-s24":x===4&&(s.info.codec=T?"pcm-s32be":"pcm-s32"):x===1&&(s.info.codec="pcm-u8")),s.info.codec===null&&console.warn("Unsupported PCM format.")}}}s.info.codec==="opus"&&(g=at),s.info.numberOfChannels=p,s.info.sampleRate=g,m==="twos"?h===8?s.info.codec="pcm-s8":h===16?s.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${h} for codec 'twos'.`),s.info.codec=null):m==="sowt"?h===8?s.info.codec="pcm-s8":h===16?s.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${h} for codec 'sowt'.`),s.info.codec=null):m==="raw "?s.info.codec="pcm-u8":m==="in24"?s.info.codec="pcm-s24be":m==="in32"?s.info.codec="pcm-s32be":m==="fl32"?s.info.codec="pcm-f32be":m==="fl64"?s.info.codec="pcm-f64be":m==="ipcm"?s.info.codec="pcm-s16be":m==="fpcm"&&(s.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,u+d.totalSize-e.filePos))}}}break;case"avcC":{let s=this.currentTrack;if(!s)break;b(s.info),s.info.codecDescription=F(e,r.contentSize)}break;case"hvcC":{let s=this.currentTrack;if(!s)break;b(s.info),s.info.codecDescription=F(e,r.contentSize)}break;case"vpcC":{let s=this.currentTrack;if(!s)break;b(s.info?.type==="video"),e.skip(4);let a=E(e),c=E(e),l=E(e),u=l>>4,d=l>>1&7,m=l&1,f=E(e),p=E(e),h=E(e);s.info.vp9CodecInfo={profile:a,level:c,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:m,colourPrimaries:f,transferCharacteristics:p,matrixCoefficients:h}}break;case"av1C":{let s=this.currentTrack;if(!s)break;b(s.info?.type==="video"),e.skip(1);let a=E(e),c=a>>5,l=a&31,u=E(e),d=u>>7,m=u>>6&1,f=u>>5&1,p=u>>4&1,h=u>>3&1,g=u>>2&1,y=u&3,x=c===2&&m?f?12:10:m?10:8;s.info.av1CodecInfo={profile:c,level:l,tier:d,bitDepth:x,monochrome:p,chromaSubsamplingX:h,chromaSubsamplingY:g,chromaSamplePosition:y}}break;case"colr":{let s=this.currentTrack;if(!s||(b(s.info?.type==="video"),W(e,4)!=="nclx"))break;let c=X(e),l=X(e),u=X(e),d=!!(E(e)&128);s.info.colorSpace={primaries:rn[c],transfer:nn[l],matrix:on[u],fullRange:d}}break;case"wave":this.readContiguousBoxes(e.slice(o,r.contentSize));break;case"esds":{let s=this.currentTrack;if(!s)break;b(s.info?.type==="audio"),e.skip(4);let a=E(e);b(a===3),kn(e),e.skip(2);let c=E(e),l=(c&128)!==0,u=(c&64)!==0,d=(c&32)!==0;if(l&&e.skip(2),u){let g=E(e);e.skip(g)}d&&e.skip(2);let m=E(e);b(m===4);let f=kn(e),p=e.filePos,h=E(e);if(h===64||h===103?(s.info.codec="aac",s.info.aacCodecInfo={isMpeg2:h===103}):h===105||h===107?s.info.codec="mp3":h===221?s.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${h}) - discarding track.`),e.skip(12),f>e.filePos-p){let g=E(e);b(g===5);let y=kn(e);if(s.info.codecDescription=F(e,y),s.info.codec==="aac"){let x=Yo(s.info.codecDescription);x.numberOfChannels!==null&&(s.info.numberOfChannels=x.numberOfChannels),x.sampleRate!==null&&(s.info.sampleRate=x.sampleRate)}}}break;case"enda":{let s=this.currentTrack;if(!s)break;b(s.info?.type==="audio"),X(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;b(s.info?.type==="audio"),e.skip(4);let c=!!(E(e)&1),l=E(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;b(s.info?.type==="audio"),e.skip(1);let a=E(e),c=X(e),l=P(e),u=Tr(e),d=E(e),m;d!==0?m=F(e,2+a):m=new Uint8Array(0);let f=new Uint8Array(19+m.byteLength),p=new DataView(f.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,u,!0),p.setUint8(18,d),f.set(m,19),s.info.codecDescription=f,s.info.numberOfChannels=a}break;case"dfLa":{let s=this.currentTrack;if(!s)break;b(s.info?.type==="audio"),e.skip(4);let a=127,c=128,l=e.filePos;for(;e.filePos<i;){let p=E(e),h=$e(e);if((p&a)===qe.STREAMINFO){e.skip(10);let y=P(e),x=y>>>12,v=(y>>9&7)+1;s.info.sampleRate=x,s.info.numberOfChannels=v,e.skip(20)}else e.skip(h);if(p&c)break}let u=e.filePos;e.filePos=l;let d=F(e,u-l),m=new Uint8Array(4+d.byteLength);new DataView(m.buffer).setUint32(0,1716281667,!1),m.set(d,4),s.info.codecDescription=m}break;case"stts":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=P(e),c=0,l=0;for(let u=0;u<a;u++){let d=P(e),m=P(e);s.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:l,count:d,delta:m}),c+=d,l+=d*m}}break;case"ctts":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=P(e),c=0;for(let l=0;l<a;l++){let u=P(e),d=Re(e);s.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:u,offset:d}),c+=u}}break;case"stsz":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=P(e),c=P(e);if(a===0)for(let l=0;l<c;l++){let u=P(e);s.sampleTable.sampleSizes.push(u)}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=E(e),c=P(e),l=F(e,Math.ceil(c*a/8)),u=new V(l);for(let d=0;d<c;d++){let m=u.readBits(a);s.sampleTable.sampleSizes.push(m)}}break;case"stss":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4),s.sampleTable.keySampleIndices=[];let a=P(e);for(let c=0;c<a;c++){let l=P(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=P(e);for(let l=0;l<a;l++){let u=P(e)-1,d=P(e),m=P(e);s.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:u,samplesPerChunk:d,sampleDescriptionIndex:m})}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 d=s.sampleTable.sampleToChunk[l+1].startChunkIndex-s.sampleTable.sampleToChunk[l].startChunkIndex;c+=d*s.sampleTable.sampleToChunk[l].samplesPerChunk}}break;case"stco":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=P(e);for(let c=0;c<a;c++){let l=P(e);s.sampleTable.chunkOffsets.push(l)}}break;case"co64":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=P(e);for(let c=0;c<a;c++){let l=ae(e);s.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(o,r.contentSize));break;case"mehd":{let s=E(e);e.skip(3);let a=s===1?ae(e):P(e);this.movieDurationInTimescale=a}break;case"trex":{e.skip(4);let s=P(e),a=P(e),c=P(e),l=P(e),u=P(e);this.fragmentTrackDefaults.push({trackId:s,defaultSampleDescriptionIndex:a,defaultSampleDuration:c,defaultSampleSize:l,defaultSampleFlags:u})}break;case"tfra":{let s=E(e);e.skip(3);let a=P(e),c=this.tracks.find(x=>x.id===a);if(!c)break;let l=P(e),u=(l&48)>>4,d=(l&12)>>2,m=l&3,f=[E,X,$e,P],p=f[u],h=f[d],g=f[m],y=P(e);for(let x=0;x<y;x++){let v=s===1?ae(e):P(e),T=s===1?ae(e):P(e);p(e),h(e),g(e),c.fragmentLookupTable.push({timestamp:v,moofOffset:T})}c.fragmentLookupTable.sort((x,v)=>x.timestamp-v.timestamp);for(let x=0;x<c.fragmentLookupTable.length-1;x++){let v=c.fragmentLookupTable[x],T=c.fragmentLookupTable[x+1];v.timestamp===T.timestamp&&(c.fragmentLookupTable.splice(x+1,1),x--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:r.totalSize,implicitBaseDataOffset:t,trackData:new Map},this.readContiguousBoxes(e.slice(o,r.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(b(this.currentFragment),this.readContiguousBoxes(e.slice(o,r.contentSize)),this.currentTrack){let s=this.currentFragment.trackData.get(this.currentTrack.id);if(s){let{currentFragmentState:a}=this.currentTrack;b(a),a.startTimestamp!==null&&(ui(s,a.startTimestamp),s.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{b(this.currentFragment),e.skip(1);let s=$e(e),a=!!(s&1),c=!!(s&2),l=!!(s&8),u=!!(s&16),d=!!(s&32),m=!!(s&65536),f=!!(s&131072),p=P(e),h=this.tracks.find(y=>y.id===p);if(!h)break;let g=this.fragmentTrackDefaults.find(y=>y.trackId===p);this.currentTrack=h,h.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:g?.defaultSampleDescriptionIndex??null,defaultSampleDuration:g?.defaultSampleDuration??null,defaultSampleSize:g?.defaultSampleSize??null,defaultSampleFlags:g?.defaultSampleFlags??null,startTimestamp:null},a?h.currentFragmentState.baseDataOffset=ae(e):f&&(h.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(h.currentFragmentState.sampleDescriptionIndex=P(e)),l&&(h.currentFragmentState.defaultSampleDuration=P(e)),u&&(h.currentFragmentState.defaultSampleSize=P(e)),d&&(h.currentFragmentState.defaultSampleFlags=P(e)),m&&(h.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let s=this.currentTrack;if(!s)break;b(s.currentFragmentState);let a=E(e);e.skip(3);let c=a===0?P(e):ae(e);s.currentFragmentState.startTimestamp=c}break;case"trun":{let s=this.currentTrack;if(!s)break;if(b(this.currentFragment),b(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=E(e),c=$e(e),l=!!(c&1),u=!!(c&4),d=!!(c&256),m=!!(c&512),f=!!(c&1024),p=!!(c&2048),h=P(e),g=s.currentFragmentState.baseDataOffset;l&&(g+=Re(e));let y=null;u&&(y=P(e));let x=g;if(h===0){this.currentFragment.implicitBaseDataOffset=x;break}let v=0,T={track:s,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(s.id,T);for(let I=0;I<h;I++){let C;d?C=P(e):(b(s.currentFragmentState.defaultSampleDuration!==null),C=s.currentFragmentState.defaultSampleDuration);let A;m?A=P(e):(b(s.currentFragmentState.defaultSampleSize!==null),A=s.currentFragmentState.defaultSampleSize);let R;f?R=P(e):(b(s.currentFragmentState.defaultSampleFlags!==null),R=s.currentFragmentState.defaultSampleFlags),I===0&&y!==null&&(R=y);let D=0;p&&(a===0?D=P(e):D=Re(e));let L=!(R&65536);T.samples.push({presentationTimestamp:v+D,duration:C,byteOffset:x,byteSize:A,isKeyFrame:L}),x+=A,v+=C}T.presentationTimestamps=T.samples.map((I,C)=>({presentationTimestamp:I.presentationTimestamp,sampleIndex:C})).sort((I,C)=>I.presentationTimestamp-C.presentationTimestamp);for(let I=0;I<T.presentationTimestamps.length;I++){let C=T.presentationTimestamps[I],A=T.samples[C.sampleIndex];if(T.firstKeyFrameTimestamp===null&&A.isKeyFrame&&(T.firstKeyFrameTimestamp=A.presentationTimestamp),I<T.presentationTimestamps.length-1){let R=T.presentationTimestamps[I+1];A.duration=R.presentationTimestamp-C.presentationTimestamp}}let S=T.samples[T.presentationTimestamps[0].sampleIndex],k=T.samples[ee(T.presentationTimestamps).sampleIndex];T.startTimestamp=S.presentationTimestamp,T.endTimestamp=k.presentationTimestamp+k.duration,this.currentFragment.implicitBaseDataOffset=x}break;case"udta":{let s=this.iterateContiguousBoxes(e.slice(o,r.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]??=pe(c):this.metadataTags.raw[a.name]??=F(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=K.decode(F(c,a.contentSize)):this.metadataTags.title??=pe(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=pe(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=pe(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=pe(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=pe(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=pe(c));break;case"\xA9day":if(!this.currentTrack){let l=new Date(pe(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=pe(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=pe(c));break}}}break;case"meta":{if(this.currentTrack)break;let a=P(e)!==0;this.currentMetadataKeys=new Map,a?this.readContiguousBoxes(e.slice(o,r.contentSize)):this.readContiguousBoxes(e.slice(o+4,r.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let s=P(e);for(let a=0;a<s;a++){let c=P(e);e.skip(4);let l=K.decode(F(e,c-8));this.currentMetadataKeys.set(a+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let s=this.iterateContiguousBoxes(e.slice(o,r.contentSize));for(let{boxInfo:a,slice:c}of s){let l=a.name,u=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(u)&&(l=this.currentMetadataKeys.get(u));let d=qs(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=d,l){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof d=="string"&&(this.metadataTags.title??=d);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof d=="string"&&(this.metadataTags.description??=d);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof d=="string"&&(this.metadataTags.artist??=d);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof d=="string"&&(this.metadataTags.album??=d);break;case"aART":case"album_artist":typeof d=="string"&&(this.metadataTags.albumArtist??=d);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof d=="string"&&(this.metadataTags.comment??=d);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof d=="string"&&(this.metadataTags.genre??=d);break;case"\xA9lyr":case"lyrics":typeof d=="string"&&(this.metadataTags.lyrics??=d);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof d=="string"){let m=new Date(d);Number.isNaN(m.getTime())||(this.metadataTags.date??=m)}break;case"covr":case"com.apple.quicktime.artwork":d instanceof He?(this.metadataTags.images??=[],this.metadataTags.images.push({data:d.data,kind:"coverFront",mimeType:d.mimeType})):d instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:d,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof d=="string"){let m=d.split("/"),f=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(d instanceof Uint8Array&&d.length>=6){let m=z(d),f=m.getUint16(2,!1),p=m.getUint16(4,!1);f>0&&(this.metadataTags.trackNumber??=f),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(d instanceof Uint8Array&&d.length>=6){let m=z(d),f=m.getUint16(2,!1),p=m.getUint16(4,!1);f>0&&(this.metadataTags.discNumber??=f),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=i,!0}},Cn=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,r=>r.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return ot(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let r=this.mapTimestampIntoTimescale(e),o=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=fi(o,r),s=await this.fetchPacketForSampleIndex(i,t);return!Gs(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=O(c.presentationTimestamps,r,m=>m.presentationTimestamp),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&r<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},r,r,t)}async getNextPacket(e,t){let r=this.packetToSampleIndex.get(e);if(r!==void 0)return this.fetchPacketForSampleIndex(r+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 r=this.mapTimestampIntoTimescale(e),o=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=rl(o,r),s=await this.fetchPacketForSampleIndex(i,t);return!Gs(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=an(c.presentationTimestamps,m=>c.samples[m.sampleIndex].isKeyFrame&&m.presentationTimestamp<=r),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&r<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},r,r,t)}async getNextKeyPacket(e,t){let r=this.packetToSampleIndex.get(e);if(r!==void 0){let i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=ol(i,r);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 b(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 r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),o=nl(r,e);if(!o)return null;let i;if(t.metadataOnly)i=G;else{let l=this.internalTrack.demuxer.reader.requestSlice(o.sampleOffset,o.sampleSize);l instanceof Promise&&(l=await l),b(l),i=F(l,o.sampleSize)}let s=(o.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=o.duration/this.internalTrack.timescale,c=new H(i,o.isKeyFrame?"key":"delta",s,a,e,o.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,r){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).samples[t];b(i);let s;if(r.metadataOnly)s=G;else{let u=this.internalTrack.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);u instanceof Promise&&(u=await u),b(u),s=F(u,i.byteSize)}let a=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=i.duration/this.internalTrack.timescale,l=new H(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,r,o,i){let s=this.internalTrack.demuxer,a=null,c=null,l=-1;if(e){let{sampleIndex:g,correctSampleFound:y}=t(e);if(y)return this.fetchPacketInFragment(e,g,i);g!==-1&&(c=e,l=g)}let u=O(this.internalTrack.fragmentLookupTable,r,g=>g.timestamp),d=u!==-1?this.internalTrack.fragmentLookupTable[u]:null,m=O(this.internalTrack.fragmentPositionCache,r,g=>g.startTimestamp),f=m!==-1?this.internalTrack.fragmentPositionCache[m]:null,p=Math.max(d?.moofOffset??0,f?.moofOffset??0)||null,h;for(e?p===null||e.moofOffset>=p?(h=e.moofOffset+e.moofSize,a=e):h=p:h=p??0;;){if(a){let v=a.trackData.get(this.internalTrack.id);if(v&&v.startTimestamp>o)break}let g=s.reader.requestSliceRange(h,ft,Bt);if(g instanceof Promise&&(g=await g),!g)break;let y=h,x=De(g);if(!x)break;if(x.name==="moof"){a=await s.readFragment(y);let{sampleIndex:v,correctSampleFound:T}=t(a);if(T)return this.fetchPacketInFragment(a,v,i);v!==-1&&(c=a,l=v)}h=y+x.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){let g=this.internalTrack.fragmentLookupTable[u-1];b(!g||g.timestamp<d.timestamp);let y=g?.timestamp??-1/0;return this.performFragmentedLookup(null,t,y,o,i)}return c?this.fetchPacketInFragment(c,l,i):null}},di=class extends Cn{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&&xn(e.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&bn(e.data)}return{codec:mn(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}},mi=class extends Cn{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:fn(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},fi=(n,e)=>{if(n.presentationTimestamps){let t=O(n.presentationTimestamps,e,r=>r.presentationTimestamp);return t===-1?-1:n.presentationTimestamps[t].sampleIndex}else{let t=O(n.sampleTimingEntries,e,o=>o.startDecodeTimestamp);if(t===-1)return-1;let r=n.sampleTimingEntries[t];return r.startIndex+Math.min(Math.floor((e-r.startDecodeTimestamp)/r.delta),r.count-1)}},rl=(n,e)=>{if(!n.keySampleIndices)return fi(n,e);if(n.presentationTimestamps){let t=O(n.presentationTimestamps,e,r=>r.presentationTimestamp);if(t===-1)return-1;for(let r=t;r>=0;r--){let o=n.presentationTimestamps[r].sampleIndex;if(tt(n.keySampleIndices,o,s=>s)!==-1)return o}return-1}else{let t=fi(n,e),r=O(n.keySampleIndices,t,o=>o);return n.keySampleIndices[r]??-1}},nl=(n,e)=>{let t=O(n.sampleTimingEntries,e,y=>y.startIndex),r=n.sampleTimingEntries[t];if(!r||r.startIndex+r.count<=e)return null;let i=r.startDecodeTimestamp+(e-r.startIndex)*r.delta,s=O(n.sampleCompositionTimeOffsets,e,y=>y.startIndex),a=n.sampleCompositionTimeOffsets[s];a&&e-a.startIndex<a.count&&(i+=a.offset);let c=n.sampleSizes[Math.min(e,n.sampleSizes.length-1)],l=O(n.sampleToChunk,e,y=>y.startSampleIndex),u=n.sampleToChunk[l];b(u);let d=u.startChunkIndex+Math.floor((e-u.startSampleIndex)/u.samplesPerChunk),m=n.chunkOffsets[d],f=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk,p=0,h=m;if(n.sampleSizes.length===1)h+=c*(e-f),p+=c*u.samplesPerChunk;else for(let y=f;y<f+u.samplesPerChunk;y++){let x=n.sampleSizes[y];y<e&&(h+=x),p+=x}let g=r.delta;if(n.presentationTimestamps){let y=n.presentationTimestampIndexMap[e];b(y!==void 0),y<n.presentationTimestamps.length-1&&(g=n.presentationTimestamps[y+1].presentationTimestamp-i)}return{presentationTimestamp:i,duration:g,sampleOffset:h,sampleSize:c,chunkOffset:m,chunkSize:p,isKeyFrame:n.keySampleIndices?tt(n.keySampleIndices,e,y=>y)!==-1:!0}},ol=(n,e)=>{if(!n.keySampleIndices)return e+1;let t=O(n.keySampleIndices,e,r=>r);return n.keySampleIndices[t+1]??-1},ui=(n,e)=>{n.startTimestamp+=e,n.endTimestamp+=e;for(let t of n.samples)t.presentationTimestamp+=e;for(let t of n.presentationTimestamps)t.presentationTimestamp+=e},il=n=>{let[e,,,t]=n,r=Math.hypot(e,t),o=e/r,i=t/r,s=-Math.atan2(i,o)*(180/Math.PI);return Number.isFinite(s)?s:0},Gs=n=>n.sampleSizes.length===0;var w;(function(n){n[n.EBML=440786851]="EBML",n[n.EBMLVersion=17030]="EBMLVersion",n[n.EBMLReadVersion=17143]="EBMLReadVersion",n[n.EBMLMaxIDLength=17138]="EBMLMaxIDLength",n[n.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",n[n.DocType=17026]="DocType",n[n.DocTypeVersion=17031]="DocTypeVersion",n[n.DocTypeReadVersion=17029]="DocTypeReadVersion",n[n.Void=236]="Void",n[n.Segment=408125543]="Segment",n[n.SeekHead=290298740]="SeekHead",n[n.Seek=19899]="Seek",n[n.SeekID=21419]="SeekID",n[n.SeekPosition=21420]="SeekPosition",n[n.Duration=17545]="Duration",n[n.Info=357149030]="Info",n[n.TimestampScale=2807729]="TimestampScale",n[n.MuxingApp=19840]="MuxingApp",n[n.WritingApp=22337]="WritingApp",n[n.Tracks=374648427]="Tracks",n[n.TrackEntry=174]="TrackEntry",n[n.TrackNumber=215]="TrackNumber",n[n.TrackUID=29637]="TrackUID",n[n.TrackType=131]="TrackType",n[n.FlagEnabled=185]="FlagEnabled",n[n.FlagDefault=136]="FlagDefault",n[n.FlagForced=21930]="FlagForced",n[n.FlagOriginal=21934]="FlagOriginal",n[n.FlagHearingImpaired=21931]="FlagHearingImpaired",n[n.FlagVisualImpaired=21932]="FlagVisualImpaired",n[n.FlagCommentary=21935]="FlagCommentary",n[n.FlagLacing=156]="FlagLacing",n[n.Name=21358]="Name",n[n.Language=2274716]="Language",n[n.LanguageBCP47=2274717]="LanguageBCP47",n[n.CodecID=134]="CodecID",n[n.CodecPrivate=25506]="CodecPrivate",n[n.CodecDelay=22186]="CodecDelay",n[n.SeekPreRoll=22203]="SeekPreRoll",n[n.DefaultDuration=2352003]="DefaultDuration",n[n.Video=224]="Video",n[n.PixelWidth=176]="PixelWidth",n[n.PixelHeight=186]="PixelHeight",n[n.AlphaMode=21440]="AlphaMode",n[n.Audio=225]="Audio",n[n.SamplingFrequency=181]="SamplingFrequency",n[n.Channels=159]="Channels",n[n.BitDepth=25188]="BitDepth",n[n.SimpleBlock=163]="SimpleBlock",n[n.BlockGroup=160]="BlockGroup",n[n.Block=161]="Block",n[n.BlockAdditions=30113]="BlockAdditions",n[n.BlockMore=166]="BlockMore",n[n.BlockAdditional=165]="BlockAdditional",n[n.BlockAddID=238]="BlockAddID",n[n.BlockDuration=155]="BlockDuration",n[n.ReferenceBlock=251]="ReferenceBlock",n[n.Cluster=524531317]="Cluster",n[n.Timestamp=231]="Timestamp",n[n.Cues=475249515]="Cues",n[n.CuePoint=187]="CuePoint",n[n.CueTime=179]="CueTime",n[n.CueTrackPositions=183]="CueTrackPositions",n[n.CueTrack=247]="CueTrack",n[n.CueClusterPosition=241]="CueClusterPosition",n[n.Colour=21936]="Colour",n[n.MatrixCoefficients=21937]="MatrixCoefficients",n[n.TransferCharacteristics=21946]="TransferCharacteristics",n[n.Primaries=21947]="Primaries",n[n.Range=21945]="Range",n[n.Projection=30320]="Projection",n[n.ProjectionType=30321]="ProjectionType",n[n.ProjectionPoseRoll=30325]="ProjectionPoseRoll",n[n.Attachments=423732329]="Attachments",n[n.AttachedFile=24999]="AttachedFile",n[n.FileDescription=18046]="FileDescription",n[n.FileName=18030]="FileName",n[n.FileMediaType=18016]="FileMediaType",n[n.FileData=18012]="FileData",n[n.FileUID=18094]="FileUID",n[n.Chapters=272869232]="Chapters",n[n.Tags=307544935]="Tags",n[n.Tag=29555]="Tag",n[n.Targets=25536]="Targets",n[n.TargetTypeValue=26826]="TargetTypeValue",n[n.TargetType=25546]="TargetType",n[n.TagTrackUID=25541]="TagTrackUID",n[n.TagEditionUID=25545]="TagEditionUID",n[n.TagChapterUID=25540]="TagChapterUID",n[n.TagAttachmentUID=25542]="TagAttachmentUID",n[n.SimpleTag=26568]="SimpleTag",n[n.TagName=17827]="TagName",n[n.TagLanguage=17530]="TagLanguage",n[n.TagString=17543]="TagString",n[n.TagBinary=17541]="TagBinary",n[n.ContentEncodings=28032]="ContentEncodings",n[n.ContentEncoding=25152]="ContentEncoding",n[n.ContentEncodingOrder=20529]="ContentEncodingOrder",n[n.ContentEncodingScope=20530]="ContentEncodingScope",n[n.ContentCompression=20532]="ContentCompression",n[n.ContentCompAlgo=16980]="ContentCompAlgo",n[n.ContentCompSettings=16981]="ContentCompSettings",n[n.ContentEncryption=20533]="ContentEncryption"})(w||(w={}));var sl=[w.EBML,w.Segment],Ot=[w.SeekHead,w.Info,w.Cluster,w.Tracks,w.Cues,w.Attachments,w.Chapters,w.Tags],wr=[...sl,...Ot];var pi=8,ce=2,he=2*pi,hi=n=>{let e=E(n);if(n.skip(-1),e===0)return null;let t=1,r=128;for(;(e&r)===0;)t++,r>>=1;return t},zt=n=>{let e=E(n);if(e===0)return null;let t=1,r=128;for(;(e&r)===0;)t++,r>>=1;let o=e&r-1;for(let i=1;i<t;i++)o*=256,o+=E(n);return o},M=(n,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let r=0;r<e;r++)t*=256,t+=E(n);return t},$s=(n,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let t=0n;for(let r=0;r<e;r++)t<<=8n,t+=BigInt(E(n));return t};var In=n=>{let e=hi(n);return e===null?null:M(n,e)},gi=n=>{let e=E(n);return e===255?e=null:(n.skip(-1),e=zt(n),e===72057594037927940&&(e=null)),e},ge=n=>{let e=In(n);if(e===null)return null;let t=gi(n);return{id:e,size:t}},Xe=(n,e)=>{let t=F(n,e),r=0;for(;r<e&&t[r]!==0;)r+=1;return String.fromCharCode(...t.subarray(0,r))},Nt=(n,e)=>{let t=F(n,e),r=0;for(;r<e&&t[r]!==0;)r+=1;return K.decode(t.subarray(0,r))},An=(n,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?Xs(n):Pn(n)},_n=async(n,e,t,r)=>{let o=new Set(t),i=e;for(;r===null||i<r;){let s=n.requestSliceRange(i,ce,he);if(s instanceof Promise&&(s=await s),!s)break;let a=ge(s);if(!a)break;if(o.has(a.id))return{pos:i,found:!0};Me(a.size),i=s.filePos+a.size}return{pos:r!==null&&r>i?r:i,found:!1}},xi=async(n,e,t,r)=>{let i=new Set(t),s=e;for(;s<r;){let a=n.requestSliceRange(s,0,Math.min(65536,r-s));if(a instanceof Promise&&(a=await a),!a||a.length<pi)break;for(let c=0;c<a.length-pi;c++){a.filePos=s;let l=In(a);if(l!==null&&i.has(l))return s;s++}}return null},xe={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 Me(n){if(n===null)throw new Error("Undefined element size is used in a place where it is not supported.")}var Ks=n=>{let t=(n.hasVideo?"video/":n.hasAudio?"audio/":"application/")+(n.isWebM?"webm":"x-matroska");if(n.codecStrings.length>0){let r=[...new Set(n.codecStrings.filter(Boolean))];t+=`; codecs="${r.join(", ")}"`}return t};var Be;(function(n){n[n.None=0]="None",n[n.Xiph=1]="Xiph",n[n.FixedSize=2]="FixedSize",n[n.Ebml=3]="Ebml"})(Be||(Be={}));var En;(function(n){n[n.Block=1]="Block",n[n.Private=2]="Private",n[n.Next=4]="Next"})(En||(En={}));var kr;(function(n){n[n.Zlib=0]="Zlib",n[n.Bzlib=1]="Bzlib",n[n.lzo1x=2]="lzo1x",n[n.HeaderStripping=3]="HeaderStripping"})(kr||(kr={}));var bi=[{id:w.SeekHead,flag:"seekHeadSeen"},{id:w.Info,flag:"infoSeen"},{id:w.Tracks,flag:"tracksSeen"},{id:w.Cues,flag:"cuesSeen"}],Qs=10*2**20,Fn=class extends J{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(r=>r.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(r=>r.getCodecParameterString()));return Ks({isWebM:this.isWebM,hasVideo:this.segments.some(r=>r.tracks.some(o=>o.info?.type==="video")),hasAudio:this.segments.some(r=>r.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,ce,he);if(t instanceof Promise&&(t=await t),!t)break;let r=ge(t);if(!r)break;let o=r.id,i=r.size,s=t.filePos;if(o===w.EBML){Me(i);let a=this.reader.requestSlice(s,i);if(a instanceof Promise&&(a=await a),!a)break;this.readContiguousElements(a)}else if(o===w.Segment){if(await this.readSegment(s,i),i===null||this.reader.fileSize===null)break}else if(o===w.Cluster){if(this.reader.fileSize===null)break;i===null&&(i=(await _n(this.reader,s,wr,this.reader.fileSize)).pos-s);let a=ee(this.segments);a&&(a.elementEndPos=s+i)}Me(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 r=e;for(;this.currentSegment.elementEndPos===null||r<this.currentSegment.elementEndPos;){let a=this.reader.requestSliceRange(r,ce,he);if(a instanceof Promise&&(a=await a),!a)break;let c=r,l=ge(a);if(!l||!Ot.includes(l.id)&&l.id!==w.Void){let p=await xi(this.reader,c,Ot,Math.min(this.currentSegment.elementEndPos??1/0,c+Qs));if(p){r=p;continue}else break}let{id:u,size:d}=l,m=a.filePos,f=bi.findIndex(p=>p.id===u);if(f!==-1){let p=bi[f].flag;this.currentSegment[p]=!0,Me(d);let h=this.reader.requestSlice(m,d);h instanceof Promise&&(h=await h),h&&this.readContiguousElements(h)}else if(u===w.Tags||u===w.Attachments){u===w.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Me(d);let p=this.reader.requestSlice(m,d);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(u===w.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(d===null)break;r=m+d}if(this.currentSegment.seekEntries.sort((a,c)=>a.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(let a of this.currentSegment.seekEntries){let c=bi.find(p=>p.id===a.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+a.segmentPosition,ce,he);if(l instanceof Promise&&(l=await l),!l)continue;let u=ge(l);if(!u)continue;let{id:d,size:m}=u;if(d!==c.id)continue;Me(m),this.currentSegment[c.flag]=!0;let f=this.reader.requestSlice(l.filePos,m);f instanceof Promise&&(f=await f),f&&this.readContiguousElements(f)}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],u=a.cuePoints[c+1];l.time===u.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 r=this.reader.requestSliceRange(e,ce,he);r instanceof Promise&&(r=await r),b(r);let o=e,i=ge(r);b(i);let s=i.id;b(s===w.Cluster);let a=i.size,c=r.filePos;a===null&&(a=(await _n(this.reader,c,wr,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,a);l instanceof Promise&&(l=await l);let u={segment:t,elementStartPos:o,elementEndPos:c+a,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){let d=this.readContiguousElements(l,wr);u.elementEndPos=d}for(let[,d]of u.trackData){let m=d.track;b(d.blocks.length>0);let f=!1;for(let y=0;y<d.blocks.length;y++){let x=d.blocks[y];x.timestamp+=u.timestamp,f||=x.lacing!==Be.None}d.presentationTimestamps=d.blocks.map((y,x)=>({timestamp:y.timestamp,blockIndex:x})).sort((y,x)=>y.timestamp-x.timestamp);for(let y=0;y<d.presentationTimestamps.length;y++){let x=d.presentationTimestamps[y],v=d.blocks[x.blockIndex];if(d.firstKeyFrameTimestamp===null&&v.isKeyFrame&&(d.firstKeyFrameTimestamp=v.timestamp),y<d.presentationTimestamps.length-1){let T=d.presentationTimestamps[y+1];v.duration=T.timestamp-v.timestamp}else v.duration===0&&m.defaultDuration!=null&&v.lacing===Be.None&&(v.duration=m.defaultDuration)}f&&(this.expandLacedBlocks(d.blocks,m),d.presentationTimestamps=d.blocks.map((y,x)=>({timestamp:y.timestamp,blockIndex:x})).sort((y,x)=>y.timestamp-x.timestamp));let p=d.blocks[d.presentationTimestamps[0].blockIndex],h=d.blocks[ee(d.presentationTimestamps).blockIndex];d.startTimestamp=p.timestamp,d.endTimestamp=h.timestamp+h.duration;let g=O(m.clusterPositionCache,d.startTimestamp,y=>y.startTimestamp);(g===-1||m.clusterPositionCache[g].elementStartPos!==o)&&m.clusterPositionCache.splice(g+1,0,{elementStartPos:u.elementStartPos,startTimestamp:d.startTimestamp})}return t.lastReadCluster=u,u}getTrackDataInCluster(e,t){let r=e.trackData.get(t);if(!r){let o=e.segment.tracks.find(i=>i.id===t);if(!o)return null;r={track:o,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,r)}return r}expandLacedBlocks(e,t){for(let r=0;r<e.length;r++){let o=e[r];if(o.lacing===Be.None)continue;o.decoded||(o.data=this.decodeBlockData(t,o.data),o.decoded=!0);let i=Ut.tempFromBytes(o.data),s=[],a=E(i)+1;switch(o.lacing){case Be.Xiph:{let l=0;for(let u=0;u<a-1;u++){let d=0;for(;i.bufferPos<i.length;){let m=E(i);if(d+=m,m<255){s.push(d),l+=d;break}}}s.push(i.length-(i.bufferPos+l))}break;case Be.FixedSize:{let l=i.length-1,u=Math.floor(l/a);for(let d=0;d<a;d++)s.push(u)}break;case Be.Ebml:{let l=zt(i);b(l!==null);let u=l;s.push(u);let d=u;for(let m=1;m<a-1;m++){let f=i.bufferPos,p=zt(i);b(p!==null);let h=p,y=(1<<(i.bufferPos-f)*7-1)-1,x=h-y;u+=x,s.push(u),d+=u}s.push(i.length-(i.bufferPos+d))}break;default:b(!1)}b(s.length===a),e.splice(r,1);let c=o.duration||a*(t.defaultDuration??0);for(let l=0;l<a;l++){let u=s[l],d=F(i,u),m=o.timestamp+c*l/a,f=c/a;e.splice(r+l,0,{timestamp:m,duration:f,isKeyFrame:o.isKeyFrame,data:d,lacing:Be.None,decoded:!0,mainAdditional:o.mainAdditional})}r+=a,r--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if(!(t.id===w.Tags&&!e.tagsSeen)){if(!(t.id===w.Attachments&&!e.attachmentsSeen))continue}let r=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,ce,he);if(r instanceof Promise&&(r=await r),!r)continue;let o=ge(r);if(!o||o.id!==t.id)continue;let{size:i}=o;Me(i),b(!this.currentSegment),this.currentSegment=e;let s=this.reader.requestSlice(r.filePos,i);s instanceof Promise&&(s=await s),s&&this.readContiguousElements(s),this.currentSegment=null,t.id===w.Tags?e.tagsSeen=!0:t.id===w.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){let r=e.filePos;for(;e.filePos-r<=e.length-ce;){let o=e.filePos;if(!this.traverseElement(e,t))return o}return e.filePos}traverseElement(e,t){let r=ge(e);if(!r||t&&t.includes(r.id))return!1;let{id:o,size:i}=r,s=e.filePos;switch(Me(i),o){case w.DocType:this.isWebM=Xe(e,i)==="webm";break;case w.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 w.SeekID:{let a=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!a)break;a.id=M(e,i)}break;case w.SeekPosition:{let a=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!a)break;a.segmentPosition=M(e,i)}break;case w.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=M(e,i),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case w.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=An(e,i)}break;case w.TrackEntry:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...ie},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:Q,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(s,i)),this.currentTrack.decodingInstructions.some(a=>a.data?.type!=="decompress"||a.scope!==En.Block||a.data.algorithm!==kr.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===xe.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===xe.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===xe.vp8?this.currentTrack.info.codec="vp8":c===xe.vp9?this.currentTrack.info.codec="vp9":c===xe.av1&&(this.currentTrack.info.codec="av1");let l=this.currentTrack,u=new Pe(this.input,new yi(l));this.currentTrack.inputTrack=u,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){c===xe.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===xe.mp3?this.currentTrack.info.codec="mp3":c===xe.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=at):c===xe.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===xe.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,u=new $(this.input,new vi(l));this.currentTrack.inputTrack=u,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case w.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=M(e,i)}break;case w.TrackType:{if(!this.currentTrack)break;let a=M(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 w.FlagEnabled:{if(!this.currentTrack)break;M(e,i)||(this.currentSegment.tracks.pop(),this.currentTrack=null)}break;case w.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!M(e,i)}break;case w.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!M(e,i)}break;case w.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!M(e,i)}break;case w.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!M(e,i)}break;case w.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!M(e,i)}break;case w.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!M(e,i)}break;case w.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=Xe(e,i)}break;case w.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=F(e,i)}break;case w.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*M(e,i)/1e9}break;case w.Name:{if(!this.currentTrack)break;this.currentTrack.name=Nt(e,i)}break;case w.Language:{if(!this.currentTrack||this.currentTrack.languageCode!==Q)break;this.currentTrack.languageCode=Xe(e,i),cn(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Q)}break;case w.LanguageBCP47:{if(!this.currentTrack)break;let c=Xe(e,i).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=Q}break;case w.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(s,i))}break;case w.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=M(e,i)}break;case w.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=M(e,i)}break;case w.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=M(e,i)===1}break;case w.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(s,i))}break;case w.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=M(e,i),c=on[a]??null;this.currentTrack.info.colorSpace.matrix=c}break;case w.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=M(e,i)===2}break;case w.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=M(e,i),c=nn[a]??null;this.currentTrack.info.colorSpace.transfer=c}break;case w.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=M(e,i),c=rn[a]??null;this.currentTrack.info.colorSpace.primaries=c}break;case w.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(s,i))}break;case w.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let c=-An(e,i);try{this.currentTrack.info.rotation=tn(c)}catch{}}break;case w.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(s,i))}break;case w.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=An(e,i)}break;case w.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=M(e,i)}break;case w.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=M(e,i)}break;case w.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(s,i)),this.currentCueTime=null}break;case w.CueTime:this.currentCueTime=M(e,i);break;case w.CueTrackPositions:{if(this.currentCueTime===null)break;b(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 w.CueTrack:{let a=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!a)break;a.trackId=M(e,i)}break;case w.CueClusterPosition:{let a=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!a)break;b(this.currentSegment),a.clusterPosition=this.currentSegment.dataStartPos+M(e,i)}break;case w.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=M(e,i)}break;case w.SimpleBlock:{if(!this.currentCluster)break;let a=zt(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let l=Tr(e),u=E(e),d=u>>1&3,m=!!(u&128);c.track.info?.type==="audio"&&c.track.info.codec&&(m=!0);let f=F(e,i-(e.filePos-s)),p=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:m,data:f,lacing:d,decoded:!p,mainAdditional:null})}break;case w.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(s,i)),this.currentBlock=null}break;case w.Block:{if(!this.currentCluster)break;let a=zt(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let l=Tr(e),d=E(e)>>1&3,m=F(e,i-(e.filePos-s)),f=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:m,lacing:d,decoded:!f,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case w.BlockAdditions:this.readContiguousElements(e.slice(s,i));break;case w.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 w.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=F(e,i)}break;case w.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=M(e,i)}break;case w.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=M(e,i)}break;case w.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case w.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(s,i));break;case w.Targets:this.readContiguousElements(e.slice(s,i));break;case w.TargetTypeValue:M(e,i)!==50&&(this.currentTagTargetIsMovie=!1);break;case w.TagTrackUID:case w.TagEditionUID:case w.TagChapterUID:case w.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case w.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(s,i))}break;case w.TagName:this.currentSimpleTagName=Nt(e,i);break;case w.TagString:{if(!this.currentSimpleTagName)break;let a=Nt(e,i);this.processTagValue(this.currentSimpleTagName,a)}break;case w.TagBinary:{if(!this.currentSimpleTagName)break;let a=F(e,i);this.processTagValue(this.currentSimpleTagName,a)}break;case w.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 dn(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 u=c.toLowerCase();u.startsWith("cover.")?l="coverFront":u.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 w.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=$s(e,i)}break;case w.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Nt(e,i)}break;case w.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Xe(e,i)}break;case w.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=F(e,i)}break;case w.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Nt(e,i)}break;case w.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(s,i)),this.currentTrack.decodingInstructions.sort((a,c)=>c.order-a.order)}break;case w.ContentEncoding:this.currentDecodingInstruction={order:0,scope:En.Block,data:null},this.readContiguousElements(e.slice(s,i)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case w.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=M(e,i)}break;case w.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=M(e,i)}break;case w.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:kr.Zlib,settings:null},this.readContiguousElements(e.slice(s,i))}break;case w.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=M(e,i)}break;case w.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=F(e,i)}break;case w.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=s+i,!0}decodeBlockData(e,t){b(e.decodingInstructions.length>0);let r=t;for(let o of e.decodingInstructions)switch(b(o.data),o.data.type){case"decompress":switch(o.data.algorithm){case kr.HeaderStripping:if(o.data.settings&&o.data.settings.length>0){let i=o.data.settings,s=new Uint8Array(i.length+r.length);s.set(i,0),s.set(r,i.length),r=s}break;default:}break;default:}return r}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let r=this.currentSegment.metadataTags;if(r.raw??={},r.raw[e]??=t,typeof t=="string")switch(e.toLowerCase()){case"title":r.title??=t;break;case"description":r.description??=t;break;case"artist":r.artist??=t;break;case"album":r.album??=t;break;case"album_artist":r.albumArtist??=t;break;case"genre":r.genre??=t;break;case"comment":r.comment??=t;break;case"lyrics":r.lyrics??=t;break;case"date":{let o=new Date(t);Number.isNaN(o.getTime())||(r.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&&(r.trackNumber??=i),s&&Number.isInteger(s)&&s>0&&(r.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&&(r.discNumber??=i),s&&Number.isInteger(s)&&s>0&&(r.discsTotal??=s)}break}}},Dn=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 ot(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let r=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=O(i.presentationTimestamps,r,l=>l.timestamp),a=s!==-1?i.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&r<i.endTimestamp;return{blockIndex:a,correctBlockFound:c}},r,r,t)}async getNextPacket(e,t){let r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,o=>{if(o===r.cluster){let i=o.trackData.get(this.internalTrack.id);if(r.blockIndex+1<i.blocks.length)return{blockIndex:r.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 r=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=an(i.presentationTimestamps,l=>i.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=r),a=s!==-1?i.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&r<i.endTimestamp;return{blockIndex:a,correctBlockFound:c}},r,r,t)}async getNextKeyPacket(e,t){let r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,o=>{if(o===r.cluster){let s=o.trackData.get(this.internalTrack.id).blocks.findIndex((a,c)=>a.isKeyFrame&&c>r.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 b(s!==-1),{blockIndex:s,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,r){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).blocks[t];b(i),i.decoded||(i.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,i.data),i.decoded=!0);let s=r.metadataOnly?G: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=r.metadataOnly?G:i.mainAdditional,l.alphaByteLength=i.mainAdditional.byteLength);let u=new H(s,i.isKeyFrame?"key":"delta",a,c,e.dataStartPos+t,i.data.byteLength,l);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u}async performClusterLookup(e,t,r,o,i){let{demuxer:s,segment:a}=this.internalTrack,c=null,l=null,u=-1;if(e){let{blockIndex:y,correctBlockFound:x}=t(e);if(x)return this.fetchPacketInCluster(e,y,i);y!==-1&&(l=e,u=y)}let d=O(this.internalTrack.cuePoints,r,y=>y.time),m=d!==-1?this.internalTrack.cuePoints[d]:null,f=O(this.internalTrack.clusterPositionCache,r,y=>y.startTimestamp),p=f!==-1?this.internalTrack.clusterPositionCache[f]:null,h=Math.max(m?.clusterPosition??0,p?.elementStartPos??0)||null,g;for(e?h===null||e.elementStartPos>=h?(g=e.elementEndPos,c=e):g=h:g=h??a.clusterSeekStartPos;a.elementEndPos===null||g<=a.elementEndPos-ce;){if(c){let C=c.trackData.get(this.internalTrack.id);if(C&&C.startTimestamp>o)break}let y=s.reader.requestSliceRange(g,ce,he);if(y instanceof Promise&&(y=await y),!y)break;let x=g,v=ge(y);if(!v||!Ot.includes(v.id)&&v.id!==w.Void){let C=await xi(s.reader,x,Ot,Math.min(a.elementEndPos??1/0,x+Qs));if(C){g=C;continue}else break}let T=v.id,S=v.size,k=y.filePos;if(T===w.Cluster){c=await s.readCluster(x,a),S=c.elementEndPos-k;let{blockIndex:C,correctBlockFound:A}=t(c);if(A)return this.fetchPacketInCluster(c,C,i);C!==-1&&(l=c,u=C)}S===null&&(b(T!==w.Cluster),S=(await _n(s.reader,k,wr,a.elementEndPos)).pos-k);let I=k+S;if(a.elementEndPos===null){let C=s.reader.requestSliceRange(I,ce,he);if(C instanceof Promise&&(C=await C),!C)break;if(In(C)===w.Segment){a.elementEndPos=I;break}}g=I}if(m&&(!l||l.elementStartPos<m.clusterPosition)){let y=this.internalTrack.cuePoints[d-1];b(!y||y.time<m.time);let x=y?.time??-1/0;return this.performClusterLookup(null,t,x,o,i)}return l?this.fetchPacketInCluster(l,u,i):null}},yi=class extends Dn{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:mn({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?Is(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?_s(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?xn(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?bn(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}},vi=class extends Dn{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:fn({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 al=[44100,48e3,32e3],cl=[-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],Ys=1483304551,Zs=1231971951,ll=(n,e,t,r,o)=>e===0?0:e===1?Math.floor(144*t/(r<<n))+o:e===2?Math.floor(144*t/r)+o:(Math.floor(12*t/r)+o)*4,Js=(n,e)=>n===3?e===3?21:36:e===3?13:21,ea=(n,e)=>{let t=n>>>24,r=n>>>16&255,o=n>>>8&255,i=n&255;if(t!==255&&r!==255&&o!==255&&i!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((r&224)!==224)return{header:null,bytesAdvanced:1};let s=0,a=0;r&16?s=r&8?0:1:(s=1,a=1);let c=r>>3&3,l=r>>1&3,u=o>>4&15,d=(o>>2&3)%3,m=o>>1&1,f=i>>6&3,p=i>>4&3,h=i>>3&1,g=i>>2&1,y=i&3,x=cl[s*16*4+l*16+u];if(x===-1)return{header:null,bytesAdvanced:1};let v=x*1e3,T=al[d]>>s+a,S=ll(s,l,v,T,m);if(e!==null&&e<S)return{header:null,bytesAdvanced:1};let k;return c===3?k=l===3?384:1152:l===3?k=384:l===2?k=1152:k=576,{header:{totalSize:S,mpegVersionId:c,layer:l,bitrate:v,frequencyIndex:d,sampleRate:T,channel:f,modeExtension:p,copyright:h,original:g,emphasis:y,audioSamplesInFrame:k},bytesAdvanced:1}};var Rn=n=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=n&e,e>>=8;return t};var Vt;(function(n){n[n.Unsynchronisation=128]="Unsynchronisation",n[n.ExtendedHeader=64]="ExtendedHeader",n[n.ExperimentalIndicator=32]="ExperimentalIndicator",n[n.Footer=16]="Footer"})(Vt||(Vt={}));var Ht;(function(n){n[n.ISO_8859_1=0]="ISO_8859_1",n[n.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",n[n.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",n[n.UTF_8=3]="UTF_8"})(Ht||(Ht={}));var Sr=128,qt=10,Wt=["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"],ta=(n,e)=>{let t=n.filePos;e.raw??={},e.raw.TAG??=F(n,Sr-3),n.filePos=t;let r=Lt(n,30);r&&(e.title??=r);let o=Lt(n,30);o&&(e.artist??=o);let i=Lt(n,30);i&&(e.album??=i);let s=Lt(n,4),a=Number.parseInt(s,10);Number.isInteger(a)&&a>0&&(e.date??=new Date(a,0,1));let c=F(n,30),l;if(c[28]===0&&c[29]!==0){let d=c[29];d>0&&(e.trackNumber??=d),n.skip(-30),l=Lt(n,28),n.skip(2)}else n.skip(-30),l=Lt(n,30);l&&(e.comment??=l);let u=E(n);u<Wt.length&&(e.genre??=Wt[u])},Lt=(n,e)=>{let t=F(n,e),r=it(t.indexOf(0),t.length),o=t.subarray(0,r),i="";for(let s=0;s<o.length;s++)i+=String.fromCharCode(o[s]);return i.trimEnd()},pt=n=>{let e=n.filePos,t=W(n,3),r=E(n),o=E(n),i=E(n),s=P(n);if(t!=="ID3"||r===255||o===255||(s&2155905152)!==0)return n.filePos=e,null;let a=Rn(s);return{majorVersion:r,revision:o,flags:i,size:a}},Mn=(n,e,t)=>{if(![2,3,4].includes(e.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let r=F(n,e.size),o=new Ti(e,r);if(e.flags&Vt.Footer&&o.removeFooter(),e.flags&Vt.Unsynchronisation&&e.majorVersion===3&&o.ununsynchronizeAll(),e.flags&Vt.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,u=!1;if(e.majorVersion===3?(c=!!(i.flags&64),l=!!(i.flags&128)):e.majorVersion===4&&(c=!!(i.flags&4),l=!!(i.flags&8),u=!!(i.flags&2)||!!(e.flags&Vt.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(u&&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 m=o.readId3V2EncodingAndText(a).split("/"),f=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(f)&&f>0&&(t.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(t.tracksTotal??=p)}break;case"TPOS":case"TPA":{let m=o.readId3V2EncodingAndText(a).split("/"),f=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(f)&&f>0&&(t.discNumber??=f),p&&Number.isInteger(p)&&p>0&&(t.discsTotal??=p)}break;case"TCON":case"TCO":{let d=o.readId3V2EncodingAndText(a),m=/^\((\d+)\)/.exec(d);if(m){let f=Number.parseInt(m[1]);if(Wt[f]!==void 0){t.genre??=Wt[f];break}}if(m=/^\d+$/.exec(d),m){let f=Number.parseInt(m[0]);if(Wt[f]!==void 0){t.genre??=Wt[f];break}}t.genre??=d}break;case"TDRC":case"TDAT":{let d=o.readId3V2EncodingAndText(a),m=new Date(d);Number.isNaN(m.getTime())||(t.date??=m)}break;case"TYER":case"TYE":{let d=o.readId3V2EncodingAndText(a),m=Number.parseInt(d,10);Number.isInteger(m)&&(t.date??=new Date(m,0,1))}break;case"USLT":case"ULT":{let d=o.readU8();o.pos+=3,o.readId3V2Text(d,a),t.lyrics??=o.readId3V2Text(d,a)}break;case"COMM":case"COM":{let d=o.readU8();o.pos+=3,o.readId3V2Text(d,a),t.comment??=o.readId3V2Text(d,a)}break;case"APIC":case"PIC":{let d=o.readId3V2TextEncoding(),m;if(e.majorVersion===2){let g=o.readAscii(3);m=g==="PNG"?"image/png":g==="JPG"?"image/jpeg":"image/*"}else m=o.readId3V2Text(d,a);let f=o.readU8(),p=o.readId3V2Text(d,a).trimEnd(),h=a-o.pos;if(h>=0){let g=o.readBytes(h);t.images||(t.images=[]),t.images.push({data:g,mimeType:m,kind:f===3?"coverFront":f===4?"coverBack":"unknown",description:p})}}break;default:o.pos+=i.size;break}o.pos=a}},Ti=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 r=this.bytes[t];e.push(r),r===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 r=[];for(let s=e;s<t;s++){let a=this.bytes[s];r.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+r.length+i.length),this.bytes.set(o,0),this.bytes.set(r,o.length),this.bytes.set(i,o.length+r.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-qt),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 r=0;r<e;r++)t+=String.fromCharCode(this.view.getUint8(this.pos+r));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){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(),r=this.header.majorVersion===4?Rn(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(r)){let a=this.header.majorVersion===4?t:Rn(t);s(a)&&(r=a)}return this.pos=i,{id:e,size:r,flags:o}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let r=this.pos,o=this.readBytes(t-this.pos);switch(e){case Ht.ISO_8859_1:{let i="";for(let s=0;s<o.length;s++){let a=o[s];if(a===0){this.pos=r+s+1;break}i+=String.fromCharCode(a)}return i}case Ht.UTF_16_WITH_BOM:if(o[0]===255&&o[1]===254){let i=new TextDecoder("utf-16le"),s=it(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=r+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=it(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=r+Math.min(s+2,o.length),i.decode(o.subarray(2,s))}else{let i=it(o.findIndex(s=>s===0),o.length);return this.pos=r+Math.min(i+1,o.length),K.decode(o.subarray(0,i))}case Ht.UTF_16_BE_NO_BOM:{let i=new TextDecoder("utf-16be"),s=it(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=r+Math.min(s+2,o.length),i.decode(o.subarray(0,s))}case Ht.UTF_8:{let i=it(o.findIndex(s=>s===0),o.length);return this.pos=r+Math.min(i+1,o.length),K.decode(o.subarray(0,i))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}};var Cr=async(n,e,t)=>{let r=e;for(;t===null||r<t;){let o=n.requestSlice(r,4);if(o instanceof Promise&&(o=await o),!o)break;let i=P(o),s=ea(i,n.fileSize!==null?n.fileSize-r:null);if(s.header)return{header:s.header,startPos:r};r+=s.bytesAdvanced}return null};var Bn=class extends J{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new ke,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 $(this.input,new wi(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,qt);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}let c=pt(a);if(!c)break;this.lastLoadedPos=a.filePos+c.size}let e=await Cr(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 r=Js(t.mpegVersionId,t.channel),o=this.reader.requestSlice(e.startPos+r,4);if(o instanceof Promise&&(o=await o),o){let a=P(o);if(a===Ys||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 b(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,r=!1;for(;;){let o=this.reader.requestSlice(t,qt);if(o instanceof Promise&&(o=await o),!o)break;let i=pt(o);if(!i)break;r=!0;let s=this.reader.requestSlice(o.filePos,i.size);if(s instanceof Promise&&(s=await s),!s)break;Mn(s,i,this.metadataTags),t=o.filePos+i.size}if(!r&&this.reader.fileSize!==null&&this.reader.fileSize>=Sr){let o=this.reader.requestSlice(this.reader.fileSize-Sr,Sr);o instanceof Promise&&(o=await o),b(o),W(o,3)==="TAG"&&ta(o,this.metadataTags)}return this.metadataTags}finally{e()}}},wi=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return b(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 Q}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return b(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return b(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...ie}}async getDecoderConfig(){return b(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 r=this.demuxer.loadedSamples[e];if(!r)return null;let o;if(t.metadataOnly)o=G;else{let i=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(i instanceof Promise&&(i=await i),!i)return null;o=F(i,r.dataSize)}return new H(o,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{let o=tt(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{r()}}async getPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{for(;;){let o=O(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{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var ki=1399285583,ul=79764919,na=new Uint32Array(256);for(let n=0;n<256;n++){let e=n<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^ul:e<<1;na[n]=e>>>0&4294967295}var oa=n=>{let e=z(n),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let r=0;for(let o=0;o<n.length;o++){let i=n[o];r=(r<<8^na[r>>>24^i])>>>0}return e.setUint32(22,t,!0),r},ia=(n,e,t)=>{let r=0,o=null;if(n.length>0)if(e.codec==="vorbis"){b(e.vorbisInfo);let i=e.vorbisInfo.modeBlockflags.length,a=(1<<bs(i-1))-1<<1,c=(n[0]&a)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=t,u=e.vorbisInfo.modeBlockflags[c];if(o=e.vorbisInfo.blocksizes[u],u===1){let d=(a|1)+1,m=n[0]&d?1:0;l=e.vorbisInfo.blocksizes[m]}r=l!==null?l+o>>2:0}else e.codec==="opus"&&(r=Ds(n).durationInSamples);return{durationInSamples:r,vorbisBlockSize:o}},sa=n=>{let e="audio/ogg";if(n.codecStrings){let t=[...new Set(n.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};var Ke=27,gt=282,aa=gt+65025,Gt=n=>{let e=n.filePos;if(ht(n)!==ki)return null;n.skip(1);let r=E(n),o=la(n),i=ht(n),s=ht(n),a=ht(n),c=E(n),l=new Uint8Array(c);for(let f=0;f<c;f++)l[f]=E(n);let u=27+c,d=l.reduce((f,p)=>f+p,0),m=u+d;return{headerStartPos:e,totalSize:m,dataStartPos:e+u,dataSize:d,headerType:r,granulePosition:o,serialNumber:i,sequenceNumber:s,checksum:a,lacingValues:l}},ca=(n,e)=>{for(;n.filePos<e-3;){let t=ht(n),r=t&255,o=t>>>8&255,i=t>>>16&255,s=t>>>24&255,a=79;if(!(r!==a&&o!==a&&i!==a&&s!==a)){if(n.skip(-4),t===ki)return!0;n.skip(1)}}return!1};var On=class extends J{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,Ke,gt);if(t instanceof Promise&&(t=await t),!t)break;let r=Gt(t);if(!r||!!!(r.headerType&2))break;this.bitstreams.push({serialNumber:r.serialNumber,bosPage:r,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=r.headerStartPos+r.totalSize}for(let t of this.bitstreams){let r=await this.readPacket(t.bosPage,0);r&&(r.data.byteLength>=7&&r.data[0]===1&&r.data[1]===118&&r.data[2]===111&&r.data[3]===114&&r.data[4]===98&&r.data[5]===105&&r.data[6]===115?await this.readVorbisMetadata(r,t):r.data.byteLength>=8&&r.data[0]===79&&r.data[1]===112&&r.data[2]===117&&r.data[3]===115&&r.data[4]===72&&r.data[5]===101&&r.data[6]===97&&r.data[7]===100&&await this.readOpusMetadata(r,t),t.codecInfo.codec!==null&&this.tracks.push(new $(this.input,new Si(t,this))))}})()}async readVorbisMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;let o=await this.readPacket(r.startPage,r.startSegmentIndex);if(!o||(r=await this.findNextPacketStart(o),!r))return;let i=await this.readPacket(r.startPage,r.startSegmentIndex);if(!i||o.data[0]!==3||i.data[0]!==5)return;let s=[],a=d=>{for(;s.push(Math.min(255,d)),!(d<255);)d-=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 u=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(u&15),1<<(u>>4)],modeBlockflags:Rs(i.data).modeBlockflags},fr(o.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;let o=await this.readPacket(r.startPage,r.startSegmentIndex);if(!o)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=o;let i=Fs(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=at,t.codecInfo.opusInfo={preSkip:i.preSkip},fr(o.data.subarray(8),this.metadataTags)}async readPacket(e,t){b(t<e.lacingValues.length);let r=0;for(let d=0;d<t;d++)r+=e.lacingValues[d];let o=e,i=r,s=t,a=[];e:for(;;){let d=this.reader.requestSlice(o.dataStartPos,o.dataSize);d instanceof Promise&&(d=await d),b(d);let m=F(d,o.dataSize);for(;;){if(s===o.lacingValues.length){a.push(m.subarray(r,i));break}let p=o.lacingValues[s];if(i+=p,p<255){a.push(m.subarray(r,i));break e}s++}let f=o.headerStartPos+o.totalSize;for(;;){let p=this.reader.requestSliceRange(f,Ke,gt);if(p instanceof Promise&&(p=await p),!p)return null;let h=Gt(p);if(!h)return null;if(o=h,o.serialNumber===e.serialNumber)break;f=o.headerStartPos+o.totalSize}r=0,i=0,s=0}let c=a.reduce((d,m)=>d+m.length,0),l=new Uint8Array(c),u=0;for(let d=0;d<a.length;d++){let m=a[d];l.set(m,u),u+=m.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 r=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let o=this.reader.requestSliceRange(r,Ke,gt);if(o instanceof Promise&&(o=await o),!o)return null;let i=Gt(o);if(!i)return null;if(i.serialNumber===e.endPage.serialNumber)return{startPage:i,startSegmentIndex:0};r=i.headerStartPos+i.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(t=>t.getCodecParameterString()));return sa({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(r=>r.computeDuration()));return Math.max(0,...t)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Si=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new ke,this.internalSampleRate=e.codecInfo.codec==="opus"?at: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 b(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 Q}getDisposition(){return{...ie}}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"?(b(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,r){if(!e)return null;let{durationInSamples:o,vorbisBlockSize:i}=ia(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new H(r.metadataOnly?G: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){b(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=0;this.bitstream.codecInfo.codec==="opus"&&(b(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);let o=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(o,{timestampInSamples:r,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let r=this.encodedPacketToMetadata.get(e);if(!r)throw new Error("Packet was not created from this track.");let o=await this.demuxer.findNextPacketStart(r.packet);if(!o)return null;let i=r.timestampInSamples+r.durationInSamples,s=await this.demuxer.readPacket(o.startPage,o.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:i,vorbisLastBlocksize:r.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let r=ot(e*this.internalSampleRate);if(r===0)return this.getFirstPacket(t);if(r<0)return null;b(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 x=i.headerStartPos,v=Math.floor((x+s)/2),T=v;for(;;){let S=Math.min(T+aa,s-Ke),k=this.demuxer.reader.requestSlice(T,S-T);if(k instanceof Promise&&(k=await k),b(k),!ca(k,S)){s=v+Ke;continue e}let C=this.demuxer.reader.requestSliceRange(k.filePos,Ke,gt);C instanceof Promise&&(C=await C),b(C);let A=Gt(C);b(A);let R=!1;if(A.serialNumber===this.bitstream.serialNumber)R=!0;else{let L=this.demuxer.reader.requestSlice(A.headerStartPos,A.totalSize);L instanceof Promise&&(L=await L),b(L);let Y=F(L,A.totalSize);R=oa(Y)===A.checksum}if(!R){T=A.headerStartPos+4;continue}if(R&&A.serialNumber!==this.bitstream.serialNumber){T=A.headerStartPos+A.totalSize;continue}if(A.granulePosition===-1){T=A.headerStartPos+A.totalSize;continue}this.granulePositionToTimestampInSamples(A.granulePosition)>r?s=A.headerStartPos:(i=A,a.push(A));continue e}}let c=o.startPage;for(let x of a){if(x.granulePosition===i.granulePosition)break;(!c||x.headerStartPos>c.headerStartPos)&&(c=x)}let l=c,u=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===i.granulePosition);){let x=l.headerStartPos+l.totalSize,v=this.demuxer.reader.requestSliceRange(x,Ke,gt);v instanceof Promise&&(v=await v),b(v);let T=Gt(v);b(T),l=T,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}b(l.granulePosition!==-1);let d=null,m,f,p=l,h=0;if(l.headerStartPos===o.startPage.headerStartPos)m=this.granulePositionToTimestampInSamples(0),f=!0,d=0;else{m=0,f=!1;for(let T=l.lacingValues.length-1;T>=0;T--)if(l.lacingValues[T]<255){d=T+1;break}if(d===null)throw new Error("Invalid page with granule position: no packets end on this page.");h=d-1;let x={data:G,endPage:p,endSegmentIndex:h};if(await this.demuxer.findNextPacketStart(x)){let T=da(u,l,d);b(T);let S=ua(u,T.page,T.segmentIndex);S&&(l=S.page,d=S.segmentIndex)}else for(;;){let T=da(u,l,d);if(!T)break;let S=ua(u,T.page,T.segmentIndex);if(!S)break;if(l=S.page,d=S.segmentIndex,T.page.headerStartPos!==p.headerStartPos){p=T.page,h=T.segmentIndex;break}}}let g=null,y=null;for(;l!==null;){b(d!==null);let x=await this.demuxer.readPacket(l,d);if(!x)break;if(!(l.headerStartPos===o.startPage.headerStartPos&&d<o.startSegmentIndex)){let S=this.createEncodedPacketFromOggPacket(x,{timestampInSamples:m,vorbisLastBlocksize:y?.vorbisBlockSize??null},t);b(S);let k=this.encodedPacketToMetadata.get(S);if(b(k),!f&&x.endPage.headerStartPos===p.headerStartPos&&x.endSegmentIndex===h?(m=this.granulePositionToTimestampInSamples(l.granulePosition),f=!0,S=this.createEncodedPacketFromOggPacket(x,{timestampInSamples:m-k.durationInSamples,vorbisLastBlocksize:y?.vorbisBlockSize??null},t),b(S),k=this.encodedPacketToMetadata.get(S),b(k)):m+=k.durationInSamples,g=S,y=k,f&&(Math.max(m,0)>r||Math.max(k.timestampInSamples,0)===r))break}let T=await this.demuxer.findNextPacketStart(x);if(!T)break;l=T.startPage,d=T.startSegmentIndex}return g}async getPacketSequential(e,t){let r=await this.sequentialScanMutex.acquire();try{let o=ot(e*this.internalSampleRate);e=o/this.internalSampleRate;let i=O(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);b(l),this.sequentialScanCache.length>0&&b(ee(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return s}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},ua=(n,e,t)=>{let r=e,o=t;e:for(;;){for(o--,o;o>=0;o--)if(r.lacingValues[o]<255){o++;break e}if(b(o===-1),!(r.headerType&1)){o=0;break}let s=jo(n,a=>a.headerStartPos<r.headerStartPos);if(!s)return null;r=s,o=r.lacingValues.length}if(b(o!==-1),o===r.lacingValues.length){let i=n[n.indexOf(r)+1];b(i),r=i,o=0}return{page:r,segmentIndex:o}},da=(n,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};let r=jo(n,o=>o.headerStartPos<e.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};var Oe;(function(n){n[n.PCM=1]="PCM",n[n.IEEE_FLOAT=3]="IEEE_FLOAT",n[n.ALAW=6]="ALAW",n[n.MULAW=7]="MULAW",n[n.EXTENSIBLE=65534]="EXTENSIBLE"})(Oe||(Oe={}));var zn=class extends J{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),b(e);let t=W(e,4),r=t!=="RIFX",o=t==="RF64",i=ze(e,r),s=o?this.reader.fileSize:Math.min(i+8,this.reader.fileSize??1/0);if(W(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,u=e.filePos;for(;s===null||u<s;){let m=this.reader.requestSlice(u,8);if(m instanceof Promise&&(m=await m),!m)break;let f=W(m,4),p=ze(m,r),h=m.filePos;if(o&&c===0&&f!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(f==="fmt ")await this.parseFmtChunk(h,p,r);else if(f==="data"){if(l??=p,this.dataStart=m.filePos,this.dataSize=Math.min(l,(s??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(f==="ds64"){let g=this.reader.requestSlice(h,p);if(g instanceof Promise&&(g=await g),!g)break;let y=Pi(g,r);l=Pi(g,r),s=Math.min(y+8,this.reader.fileSize??1/0)}else f==="LIST"?await this.parseListChunk(h,p,r):(f==="ID3 "||f==="id3 ")&&await this.parseId3Chunk(h,p);u=h+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 d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.tracks.push(new $(this.input,new Ci(this)))})()}async parseFmtChunk(e,t,r){let o=this.reader.requestSlice(e,t);if(o instanceof Promise&&(o=await o),!o)return;let i=$t(o,r),s=$t(o,r),a=ze(o,r);o.skip(4);let c=$t(o,r),l;if(t===14?l=8:l=$t(o,r),t>=18&&i!==357){let u=$t(o,r),d=t-18;if(Math.min(d,u)>=22&&i===Oe.EXTENSIBLE){o.skip(6);let f=F(o,16);i=f[0]|f[1]<<8}}(i===Oe.MULAW||i===Oe.ALAW)&&(l=8),this.audioInfo={format:i,numberOfChannels:s,sampleRate:a,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}}async parseListChunk(e,t,r){let o=this.reader.requestSlice(e,t);if(o instanceof Promise&&(o=await o),!o)return;let i=W(o,4);if(i!=="INFO"&&i!=="INF0")return;let s=o.filePos;for(;s<=e+t-8;){o.filePos=s;let a=W(o,4),c=ze(o,r),l=F(o,c),u=0;for(let m=0;m<l.length&&l[m]!==0;m++)u++;let d=String.fromCharCode(...l.subarray(0,u));switch(this.metadataTags.raw??={},this.metadataTags.raw[a]=d,a){case"INAM":case"TITL":this.metadataTags.title??=d;break;case"TIT3":this.metadataTags.description??=d;break;case"IART":this.metadataTags.artist??=d;break;case"IPRD":this.metadataTags.album??=d;break;case"IPRT":case"ITRK":case"TRCK":{let m=d.split("/"),f=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{let m=new Date(d);Number.isNaN(m.getTime())||(this.metadataTags.date??=m)}break;case"YEAR":{let m=Number.parseInt(d,10);Number.isInteger(m)&&m>0&&(this.metadataTags.date??=new Date(m,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=d;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=d;break}s+=8+c+(c&1)}}async parseId3Chunk(e,t){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let o=pt(r);if(o){let i=r.slice(e+10,o.size);Mn(i,o,this.metadataTags)}}getCodec(){if(b(this.audioInfo),this.audioInfo.format===Oe.MULAW)return"ulaw";if(this.audioInfo.format===Oe.ALAW)return"alaw";if(this.audioInfo.format===Oe.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===Oe.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 b(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},jt=2048,Ci=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(b(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 b(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Q}getDisposition(){return{...ie}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){b(this.demuxer.audioInfo);let r=e*jt*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;let o=Math.min(jt*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,o);if(c instanceof Promise&&(c=await c),!c)return null}let i;if(t.metadataOnly)i=G;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,o);c instanceof Promise&&(c=await c),b(c),i=F(c,o)}let s=e*jt/this.demuxer.audioInfo.sampleRate,a=o/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,s),new H(i,"key",s,a,e,o)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){b(this.demuxer.audioInfo);let r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/jt,(this.demuxer.dataSize-1)/(jt*this.demuxer.audioInfo.blockSizeInBytes))),o=await this.getPacketAtIndex(r,t);if(o)return o;if(r===0)return null;b(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){b(this.demuxer.audioInfo);let r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/jt);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Xt=7,Kt=9,Pr=n=>{let e=n.filePos,t=F(n,9),r=new V(t);if(r.readBits(12)!==4095||(r.skipBits(1),r.readBits(2)!==0))return null;let s=r.readBits(1),a=r.readBits(2)+1,c=r.readBits(4);if(c===15)return null;r.skipBits(1);let l=r.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);let u=r.readBits(13);r.skipBits(11);let d=r.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let m=null;return s===1?n.filePos-=2:m=r.readBits(16),{objectType:a,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:u,numberOfAacFrames:d,crcCheck:m,startPos:e}};var Ii=1024,Nn=class extends J{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new ke,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();b(this.firstFrameHeader),this.tracks=[new $(this.input,new Ai(this))]})()}async advanceReader(){let e=this.reader.requestSliceRange(this.lastLoadedPos,Xt,Kt);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=Pr(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 r=mr[t.samplingFrequencyIndex];b(r!==void 0);let o=Ii/r,i=t.crcCheck?Kt:Xt,s={timestamp:this.nextTimestampInSamples/r,duration:o,dataStart:t.startPos+i,dataSize:t.frameLength-i};this.loadedSamples.push(s),this.nextTimestampInSamples+=Ii,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 b(e),e.computeDuration()}async getMetadataTags(){return{}}},Ai=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/Ii}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return Q}getCodec(){return"aac"}getInternalCodecId(){return b(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){b(this.demuxer.firstFrameHeader);let e=Qo[this.demuxer.firstFrameHeader.channelConfiguration];return b(e!==void 0),e}getSampleRate(){b(this.demuxer.firstFrameHeader);let e=mr[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return b(e!==void 0),e}getDisposition(){return{...ie}}async getDecoderConfig(){b(this.demuxer.firstFrameHeader);let e=new Uint8Array(3),t=new V(e),{objectType:r,samplingFrequencyIndex:o,channelConfiguration:i}=this.demuxer.firstFrameHeader;return r>31?(t.writeBits(5,31),t.writeBits(6,r-32)):t.writeBits(5,r),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 r=this.demuxer.loadedSamples[e];if(!r)return null;let o;if(t.metadataOnly)o=G;else{let i=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(i instanceof Promise&&(i=await i),!i)return null;o=F(i,r.dataSize)}return new H(o,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{let o=tt(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{r()}}async getPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{for(;;){let o=O(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{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var ma=n=>n===0?null:n===1?192:n>=2&&n<=5?144*2**n:n===6?"uncommon-u8":n===7?"uncommon-u16":n>=8&&n<=15?2**n:null,fa=(n,e)=>{switch(n){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}},pa=n=>{let e=0,t=new V(F(n,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);let r=[],o=e-1,i=new V(F(n,o)),s=8-e-1;for(let c=0;c<s;c++)r.unshift(t.readBits(1));for(let c=0;c<o;c++)for(let l=0;l<8;l++){let u=i.readBits(1);l<2||r.unshift(u)}return r.reduce((c,l,u)=>c|l<<u,0)},ha=(n,e)=>{if(e==="uncommon-u16")return X(n)+1;if(e==="uncommon-u8")return E(n)+1;if(typeof e=="number")return e;ue(e),b(!1)},ga=(n,e)=>e==="uncommon-u16"?X(n):e==="uncommon-u16-10"?X(n)*10:e==="uncommon-u8"?E(n):typeof e=="number"?e:null,xa=n=>{let t=0;for(let r of n){t^=r;for(let o=0;o<8;o++)(t&128)!==0?t=t<<1^7:t<<=1,t&=255}return t};var Un=class extends J{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 ke,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),b(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),b(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.`);b(t);let r=E(t),o=$e(t),i=(r&128)!==0;switch(r&127){case qe.STREAMINFO:{let a=this.reader.requestSlice(e,o);if(a instanceof Promise&&(a=await a),b(a),a===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let c=F(a,34),l=new V(c),u=l.readBits(16),d=l.readBits(16),m=l.readBits(24),f=l.readBits(24),p=l.readBits(20),h=l.readBits(3)+1;l.readBits(5);let g=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:h,sampleRate:p,totalSamples:g,minimumBlockSize:u,maximumBlockSize:d,minimumFrameSize:m,maximumFrameSize:f,description:y},this.track=new $(this.input,new _i(this));break}case qe.VORBIS_COMMENT:{let a=this.reader.requestSlice(e,o);a instanceof Promise&&(a=await a),b(a),fr(F(a,o),this.metadataTags);break}case qe.PICTURE:{let a=this.reader.requestSlice(e,o);a instanceof Promise&&(a=await a),b(a);let c=P(a),l=P(a),u=K.decode(F(a,l)),d=P(a),m=K.decode(F(a,d));a.skip(16);let f=P(a),p=F(a,f);this.metadataTags.images??=[],this.metadataTags.images.push({data:p,mimeType:u,kind:c===3?"coverFront":c===4?"coverBack":"unknown",description:m});break}default:break}if(e+=o,i){this.lastLoadedPos=e;break}}})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){b(this.audioInfo);let r=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-r)return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:s.end-e,isLastFrame:!0};if(E(s)===255){let l=s.filePos,u=E(s),d=this.blockingBit===1?249:248;if(u!==d){s.filePos=l;continue}s.skip(-2);let m=s.filePos-e,f=this.readFlacFrameHeader({slice:s,isFirstPacket:!1});if(!f){s.filePos=l;continue}if(this.blockingBit===0){if(f.num-a.num!==1){s.filePos=l;continue}}else if(f.num-a.num!==a.blockSize){s.filePos=l;continue}return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:m,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){let r=e.filePos,o=F(e,4),i=new V(o);if(i.readBits(15)!==32764)return null;if(this.blockingBit===null){b(t);let g=i.readBits(1);this.blockingBit=g}else if(this.blockingBit===1){if(b(!t),i.readBits(1)!==1)return null}else if(this.blockingBit===0){if(b(!t),i.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");let a=ma(i.readBits(4));if(!a)return null;b(this.audioInfo);let c=fa(i.readBits(4),this.audioInfo.sampleRate);if(!c||(i.readBits(4),i.readBits(3),i.readBits(1)!==0))return null;let u=pa(e),d=ha(e,a),m=ga(e,c);if(m===null||m!==this.audioInfo.sampleRate)return null;let f=e.filePos-r,p=E(e);e.skip(-f),e.skip(-1);let h=xa(F(e,f));return p!==h?null:{num:u,blockSize:d,sampleRate:m}}async advanceReader(){await this.readMetadata(),b(this.lastLoadedPos!==null),b(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}let r=this.loadedSamples[this.loadedSamples.length-1],i={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(i),t.isLastFrame){this.lastSampleLoaded=!0;return}}},_i=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return b(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 b(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Q}getTimeResolution(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...ie}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return b(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(b(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");let r=await this.demuxer.readingMutex.acquire();try{for(;;){let o=O(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{r()}}async getNextPacket(e,t){let r=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{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let r=this.demuxer.loadedSamples[e];if(!r)return null;let o;if(t.metadataOnly)o=G;else{let a=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(a instanceof Promise&&(a=await a),!a)return null;o=F(a,r.byteSize)}b(this.demuxer.audioInfo);let i=r.blockOffset/this.demuxer.audioInfo.sampleRate,s=r.blockSize/this.demuxer.audioInfo.sampleRate;return new H(o,"key",i,s,e,r.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}};var de=class{},Ir=class extends de{async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);return t instanceof Promise&&(t=await t),!t||(t.skip(4),W(t,4)!=="ftyp")?null:W(t,4)}_createDemuxer(e){return new Sn(e)}},Ln=class extends Ir{async _canReadInput(e){let t=await this._getMajorBrand(e);return!!t&&t!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},Vn=class extends Ir{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},Ar=class extends de{async isSupportedEBMLOfDocType(e,t){let r=e._reader.requestSlice(0,he);if(r instanceof Promise&&(r=await r),!r)return!1;let o=hi(r);if(o===null||o<1||o>8||M(r,o)!==w.EBML)return!1;let s=gi(r);if(s===null)return!1;let a=e._reader.requestSlice(r.filePos,s);if(a instanceof Promise&&(a=await a),!a)return!1;let c=r.filePos;for(;a.filePos<=c+s-ce;){let l=ge(a);if(!l)break;let{id:u,size:d}=l,m=a.filePos;if(d===null)return!1;switch(u){case w.EBMLVersion:if(M(a,d)!==1)return!1;break;case w.EBMLReadVersion:if(M(a,d)!==1)return!1;break;case w.DocType:if(Xe(a,d)!==t)return!1;break;case w.DocTypeVersion:if(M(a,d)>4)return!1;break}a.filePos=m+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Fn(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},Hn=class extends Ar{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},Wn=class extends de{async _canReadInput(e){let t=e._reader.requestSlice(0,10);if(t instanceof Promise&&(t=await t),!t)return!1;let r=0,o=!1;for(;;){let l=e._reader.requestSlice(r,qt);if(l instanceof Promise&&(l=await l),!l)break;let u=pt(l);if(!u)break;o=!0,r=l.filePos+u.size}let i=await Cr(e._reader,r,r+4096);if(!i)return!1;if(o)return!0;r=i.startPos+i.header.totalSize;let s=await Cr(e._reader,r,r+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 Bn(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},qn=class extends de{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let r=W(t,4);return r!=="RIFF"&&r!=="RIFX"&&r!=="RF64"?!1:(t.skip(4),W(t,4)==="WAVE")}_createDemuxer(e){return new zn(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},Gn=class extends de{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?W(t,4)==="OggS":!1}_createDemuxer(e){return new On(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},jn=class extends de{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?W(t,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Un(e)}},$n=class extends de{async _canReadInput(e){let t=e._reader.requestSliceRange(0,Xt,Kt);if(t instanceof Promise&&(t=await t),!t)return!1;let r=Pr(t);if(!r||(t=e._reader.requestSliceRange(r.frameLength,Xt,Kt),t instanceof Promise&&(t=await t),!t))return!1;let o=Pr(t);return o?r.objectType===o.objectType&&r.samplingFrequencyIndex===o.samplingFrequencyIndex&&r.channelConfiguration===o.channelConfiguration:!1}_createDemuxer(e){return new Nn(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},ba=new Ln,ya=new Vn,va=new Ar,Ta=new Hn,wa=new Wn,ka=new qn,Sa=new Gn,Ca=new $n,Pa=new jn,le=[ba,ya,va,Ta,ka,Sa,Pa,wa,Ca];var xt=class{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new j;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new j;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}};var _r=class extends xt{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&&(!dr(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 Xn({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:Aa.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&&!Ve()?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:r,value:o}=await t.read();if(r)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 r=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+r.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(r))}e.running=!1,e.aborted&&await t?.cancel()}_dispose(){this._orchestrator.dispose()}},Ia=.5*2**20,dl=((n,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**(n-2),16)}),Er=class extends xt{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&&(!dr(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??dl,this._orchestrator=new Xn({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:Aa.network})}async _retrieveSize(){let e=new AbortController,t=await Ko(this._options.fetchFn??fetch,this._url,Xo(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 r,o;if(t.status===206)o=this._getTotalLengthFromRangeResponse(t),r=this._orchestrator.createWorker(0,Math.min(o,Ia));else{let i=t.headers.get("Content-Length");if(i)o=Number(i),r=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(r,{response:t,abortController:e}),this._orchestrator.runWorker(r),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 r=t?.abortController,o=t?.response;if(r||(r=new AbortController,o=await Ko(this._options.fetchFn??fetch,this._url,Xo(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:r.signal}),this._getRetryDelay,()=>this._disposed)),b(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){r.abort(),e.running=!1;return}let s;try{s=await i.read()}catch(l){if(this._disposed)throw l;let u=this._getRetryDelay(1,l,this._url);if(u!==null){console.error("Error while reading response stream. Attempting to resume.",l),await new Promise(d=>setTimeout(d,1e3*u));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 r=e.headers.get("Content-Length");if(r)return Number(r);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}};var Aa={none:(n,e)=>({start:n,end:e}),fileSystem:(n,e)=>(n=Math.floor((n-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:n,end:e}),network:(n,e,t)=>{n=Math.max(0,Math.floor((n-65536)/65536)*65536);for(let o of t){let s=Math.max((o.startPos+o.targetPos)/2,o.targetPos-8388608);if(ln(n,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)),u=Math.min(l,c);e=Math.max(e,o.startPos+u)}}return e=Math.max(e,n+Ia),{start:n,end:e}}},Xn=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){b(this.fileSize!==null);let r=this.options.prefetchProfile(e,t,this.workers),o=Math.max(r.start,0),i=Math.min(r.end,this.fileSize);b(o<=e&&t<=i);let s=null,a=O(this.cache,e,x=>x.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=O(this.cache,o,x=>x.start),u=s?null:new Uint8Array(t-e),d=0,m=o,f=[];if(l!==-1){for(let x=l;x<this.cache.length;x++){let v=this.cache[x];if(v.start>=i)break;if(v.end<=o)continue;let T=Math.max(o,v.start),S=Math.min(i,v.end);if(b(T<=S),m<T&&f.push({start:m,end:T}),m=S,u){let k=Math.max(e,v.start),I=Math.min(t,v.end);if(k<I){let C=k-e;u.set(v.bytes.subarray(k-v.start,I-v.start),C),C===d&&(d=I-e)}}v.age=this.nextAge++}m<i&&f.push({start:m,end:i})}else f.push({start:o,end:i});if(u&&d>=u.length&&(s={bytes:u,view:z(u),offset:e}),f.length===0)return b(s),s;let{promise:p,resolve:h,reject:g}=te(),y=[];for(let x of f){let v=Math.max(e,x.start),T=Math.min(t,x.end);v===x.start&&T===x.end?y.push(x):v<T&&y.push({start:v,end:T})}for(let x of f){let v=u&&{start:e,bytes:u,holes:y,resolve:h,reject:g},T=!1;for(let S of this.workers)if(ln(x.start-131072,x.start,S.currentPos,S.targetPos)){S.targetPos=Math.max(S.targetPos,x.end),T=!0,v&&!S.pendingSlices.includes(v)&&S.pendingSlices.push(v),S.running||this.runWorker(S);break}if(!T){let S=this.createWorker(x.start,x.end);v&&(S.pendingSlices=[v]),this.runWorker(S)}}return s||(b(u),s=p.then(x=>({bytes:x,view:z(x),offset:e}))),s}createWorker(e,t){let r={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(r);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 r}runWorker(e){b(!e.running),b(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(r=>r.reject(t)),e.pendingSlices.length=0;else throw t})}supplyWorkerData(e,t){b(!e.aborted);let r=e.currentPos,o=r+t.length;this.insertIntoCache({start:r,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(r,s.start),c=Math.min(o,s.start+s.bytes.length);a<c&&s.bytes.set(t.subarray(a-r,c-r),a-s.start);for(let l=0;l<s.holes.length;l++){let u=s.holes[l];r<=u.start&&o>u.start&&(u.start=o),u.end<=u.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||ln(r,o,s.currentPos,s.targetPos)&&(this.workers.splice(i,1),i--)}}forgetWorker(e){let t=this.workers.indexOf(e);b(t!==-1),this.workers.splice(t,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=O(this.cache,e.start,r=>r.start)+1;if(t>0){let r=this.cache[t-1];if(r.end>=e.end)return;if(r.end>e.start){let o=new Uint8Array(e.end-r.start);o.set(r.bytes,0),o.set(e.bytes,e.start-r.start),this.currentCacheSize+=e.end-r.end,r.bytes=o,r.view=z(o),r.end=e.end,t--,e=r}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let r=t+1;r<this.cache.length;r++){let o=this.cache[r];if(e.end<=o.start)break;if(e.end>=o.end){this.cache.splice(r,1),this.currentCacheSize-=o.bytes.length,r--;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(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let r=0,o=this.cache[0];for(let i=1;i<this.cache.length;i++){let s=this.cache[i];s.age<o.age&&(r=i,o=s)}if(this.currentCacheSize-o.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(r,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}};un();var ne=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 de)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof xt))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 Kn(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(),b(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()}},j=class extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}};var Kn=class{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new j;if(this.fileSize!==null&&e+t>this.fileSize)return null;let r=e+t,o=this.source._read(e,r);return o instanceof Promise?o.then(i=>i?new Ut(i.bytes,i.view,i.offset,e,r):null):o?new Ut(o.bytes,o.view,o.offset,e,r):null}requestSliceRange(e,t,r){if(this.source._disposed)throw new j;if(this.fileSize!==null)return this.requestSlice(e,nt(this.fileSize-e,t,r));{let o=this.requestSlice(e,r),i=s=>{if(s)return s;let a=l=>(b(l!==null),this.requestSlice(e,nt(l-e,t,r))),c=this.source._retrieveSize();return c instanceof Promise?c.then(a):a(c)};return o instanceof Promise?o.then(i):i(o)}}},Ut=class n{constructor(e,t,r,o,i){this.bytes=e,this.view=t,this.offset=r,this.start=o,this.end=i,this.bufferPos=o-r}static tempFromBytes(e){return new n(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 n(this.bytes,this.view,this.offset,e,e+t)}},se=(n,e)=>{if(n.filePos<n.start||n.filePos+e>n.end)throw new RangeError(`Tried reading [${n.filePos}, ${n.filePos+e}), but slice is [${n.start}, ${n.end}). This is likely an internal error, please report it alongside the file that caused it.`)},F=(n,e)=>{se(n,e);let t=n.bytes.subarray(n.bufferPos,n.bufferPos+e);return n.bufferPos+=e,t},E=n=>(se(n,1),n.view.getUint8(n.bufferPos++)),$t=(n,e)=>{se(n,2);let t=n.view.getUint16(n.bufferPos,e);return n.bufferPos+=2,t},X=n=>{se(n,2);let e=n.view.getUint16(n.bufferPos,!1);return n.bufferPos+=2,e},$e=n=>{se(n,3);let e=rt(n.view,n.bufferPos,!1);return n.bufferPos+=3,e},Tr=n=>{se(n,2);let e=n.view.getInt16(n.bufferPos,!1);return n.bufferPos+=2,e},ze=(n,e)=>{se(n,4);let t=n.view.getUint32(n.bufferPos,e);return n.bufferPos+=4,t},P=n=>{se(n,4);let e=n.view.getUint32(n.bufferPos,!1);return n.bufferPos+=4,e},ht=n=>{se(n,4);let e=n.view.getUint32(n.bufferPos,!0);return n.bufferPos+=4,e},Re=n=>{se(n,4);let e=n.view.getInt32(n.bufferPos,!1);return n.bufferPos+=4,e},ml=n=>{se(n,4);let e=n.view.getInt32(n.bufferPos,!0);return n.bufferPos+=4,e},Pi=(n,e)=>{let t,r;return e?(t=ze(n,!0),r=ze(n,!0)):(r=ze(n,!1),t=ze(n,!1)),r*4294967296+t},ae=n=>{let e=P(n),t=P(n);return e*4294967296+t},js=n=>{let e=Re(n),t=P(n);return e*4294967296+t},la=n=>{let e=ht(n);return ml(n)*4294967296+e},Xs=n=>{se(n,4);let e=n.view.getFloat32(n.bufferPos,!1);return n.bufferPos+=4,e},Pn=n=>{se(n,8);let e=n.view.getFloat64(n.bufferPos,!1);return n.bufferPos+=8,e},W=(n,e)=>{se(n,e);let t="";for(let r=0;r<e;r++)t+=String.fromCharCode(n.bytes[n.bufferPos++]);return t};var Qn=class{count=0};var _a={extension:{type:Mr.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await import("./browserAll-5AZHDDG6.js")}};var Ea={extension:{type:Mr.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await import("./webworkerAll-QKIC5O27.js")}};var Yn;function Fa(n){return Yn!==void 0||(Yn=(()=>{let e={stencil:!0,failIfMajorPerformanceCaveat:n??Or.defaultOptions.failIfMajorPerformanceCaveat};try{if(!tr.get().getWebGLRenderingContext())return!1;let r=tr.get().createCanvas().getContext("webgl",e),o=!!r?.getContextAttributes()?.stencil;if(r){let i=r.getExtension("WEBGL_lose_context");i&&i.loseContext()}return r=null,o}catch{return!1}})()),Yn}var Zn;async function Da(n={}){return Zn!==void 0||(Zn=await(async()=>{let e=tr.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(n)).requestDevice(),!0}catch{return!1}})()),Zn}var Ra=["webgl","webgpu","canvas"];async function Ei(n){let e=[];n.preference?(e.push(n.preference),Ra.forEach(i=>{i!==n.preference&&e.push(i)})):e=Ra.slice();let t,r={};for(let i=0;i<e.length;i++){let s=e[i];if(s==="webgpu"&&await Da()){let{WebGPURenderer:a}=await import("./WebGPURenderer-RBOFXPL5.js");t=a,r={...n,...n.webgpu};break}else if(s==="webgl"&&Fa(n.failIfMajorPerformanceCaveat??Or.defaultOptions.failIfMajorPerformanceCaveat)){let{WebGLRenderer:a}=await import("./WebGLRenderer-NLGJGAXK.js");t=a,r={...n,...n.webgl};break}else if(s==="canvas")throw r={...n},new Error("CanvasRenderer is not yet implemented")}if(delete r.webgpu,delete r.webgl,!t)throw new Error("No available renderer for the current environment");let o=new t;return await o.init(r),o}var Jn=class extends Gi{constructor(e,t){let{text:r,resolution:o,style:i,anchor:s,width:a,height:c,roundPixels:l,...u}=e;super({...u}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=t,this.text=r??"",this.style=i,this.resolution=o??null,this.allowChildren=!1,this._anchor=new Hi({_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,r=this.bounds.height,o=-t*this.anchor.x,i=0;return e.x>=o&&e.x<=o+t&&(i=-r*this.anchor.y,e.y>=i&&e.y<=i+r)}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 Ma(n,e){let t=n[0]??{};return(typeof t=="string"||n[1])&&(qi(Wi,`use new ${e}({ text: "hi!", style }) instead`),t={text:t,style:n[1]}),t}var Fr=class extends Jn{constructor(...e){let t=Ma(e,"Text");super(t,ji),this.renderPipeId="text",t.textureStyle&&(this.textureStyle=t.textureStyle instanceof wo?t.textureStyle:new wo(t.textureStyle))}updateBounds(){let e=this._bounds,t=this._anchor,r=0,o=0;if(this._style.trim){let{frame:i,canvasAndContext:s}=Co.getCanvasAndContext({text:this.text,style:this._style,resolution:1});Co.returnCanvasAndContext(s),r=i.width,o=i.height}else{let i=$i.measureText(this._text,this._style);r=i.width,o=i.height}e.minX=-t._x*r,e.maxX=e.minX+r,e.minY=-t._y*o,e.maxY=e.minY+o}};Vi.add(_a,Ea);var Ba=n=>{let[e,t,r]=n,[o,i]=e,[s,a]=t,c=r*Math.PI/180,l=Math.cos(c),u=Math.sin(c);return[l*s,u*s,-u*a,l*a,o,i]},Oa=([n,e,t,r,o,i])=>new To(n,e,t,r,o,i);var za=(n,e)=>{let[t,r,o,i,s,a]=n,[c,l,u,d,m,f]=e;return[t*c+o*l,r*c+i*l,t*u+o*d,r*u+i*d,t*m+o*f+s,r*m+i*f+a]},Na=[1,0,0,1,0,0];var Wa=Cc(La(),1);var Va=`
|
|
2362
|
+
`),r=this.gl.createProgram();return this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),r}createShader(e,t){let r=this.gl.createShader(e);return this.gl.shaderSource(r,t),this.gl.compileShader(r),r}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]),r=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,r),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}},Rt=class extends br{constructor(e){if(!(e instanceof Pe))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 r=this._track.codec,o=this._track.rotation,i=await this._track.getDecoderConfig(),s=this._track.timeResolution;return b(r&&i),new si(e,t,r,i,o,s)}_createPacketSink(){return new dt(this._track)}async getSample(e){qe(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)}},yr=class{constructor(e,t={}){if(this._nextCanvasIndex=0,!(e instanceof Pe))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&&oi(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 r=t.rotation??e.rotation,[o,i]=r%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],s=t.crop;s&&ni(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=r,this._crop=s,this._fit=t.fit??"fill",this._videoSampleSink=new Rt(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let t=this._canvasPool[this._nextCanvasIndex],r=!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),r=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let o=t.getContext("2d",{alpha:this._alpha||lr()});b(o),o.resetTransform(),r||(!this._alpha&&lr()?(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){qe(e);let t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return $o(this._videoSampleSink.samples(e,t),r=>this._videoSampleToWrappedCanvas(r))}canvasesAtTimestamps(e){return $o(this._videoSampleSink.samplesAtTimestamps(e),t=>t&&this._videoSampleToWrappedCanvas(t))}},ci=class extends xr{constructor(e,t,r,o){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new cr,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=Tn.find(a=>a.supports(r,o));if(s)this.customDecoder=new s,this.customDecoder.codec=r,this.customDecoder.config=o,this.customDecoder.onSample=a=>{if(!(a instanceof Ft))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 Ft(c))}catch(l){this.onError(l)}},error:c=>{c.stack=a,this.onError(c)}}),this.decoder.configure(o)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(b(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(b(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(b(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(b(this.decoder),this.decoder.close())}},li=class extends xr{constructor(e,t,r){super(e,t),this.decoderConfig=r,this.currentTimestamp=null,b(He.includes(r.codec)),this.codec=r.codec;let{dataType:o,sampleSize:i,littleEndian:s}=pn(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)=>Ms(a.getUint8(c)):o==="alaw"?this.readInputValue=(a,c)=>Bs(a.getUint8(c)):b(!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):b(!1);break;case 3:o==="unsigned"?this.readInputValue=(a,c)=>tt(a,c,s)-2**23:o==="signed"?this.readInputValue=(a,c)=>hs(a,c,s):b(!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):b(!1);break;case 8:o==="float"?this.readInputValue=(a,c)=>a.getFloat64(c,s):b(!1);break;default:ue(i),b(!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:ue(i),b(!1)}}getDecodeQueueSize(){return 0}decode(e){let t=z(e.data),r=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,o=r*this.decoderConfig.numberOfChannels*this.outputSampleSize,i=new ArrayBuffer(o),s=new DataView(i);for(let u=0;u<r*this.decoderConfig.numberOfChannels;u++){let d=u*this.inputSampleSize,m=u*this.outputSampleSize,f=this.readInputValue(t,d);this.writeOutputValue(s,m,f)}let a=r/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 Ft({format:this.outputFormat,data:i,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:r,timestamp:c});this.onSample(l)}async flush(){}close(){}},vr=class extends br{constructor(e){if(!(e instanceof $))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 r=this._track.codec,o=await this._track.getDecoderConfig();return b(r&&o),He.includes(o.codec)?new li(e,t,o):new ci(e,t,r,o)}_createPacketSink(){return new dt(this._track)}async getSample(e){qe(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 Mt=class{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Pe}isAudioTrack(){return this instanceof $}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 dt(this),r=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;r=Math.min(r,a.timestamp),o=Math.max(o,a.timestamp+a.duration),i++,s+=a.byteLength}return{packetCount:i,averagePacketRate:i?Number((i/(o-r)).toPrecision(16)):0,averageBitrate:i?Number((8*s/(o-r)).toPrecision(16)):0}}},Pe=class extends Mt{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 b(t!==null),vn.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 H))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 b(t),yn(this.codec,t,e.data)}},$=class extends Mt{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 b(t!==null),Tn.some(r=>r.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 H))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}};var Ws=n=>{let t=(n.hasVideo?"video/":n.hasAudio?"audio/":"application/")+(n.isQuickTime?"quicktime":"mp4");if(n.codecStrings.length>0){let r=[...new Set(n.codecStrings)];t+=`; codecs="${r.join(", ")}"`}return t};var mt=8,Bt=16,De=n=>{let e=P(n),t=W(n,4),r=8;e===1&&(e=ae(n),r=16);let i=e-r;return i<0?null:{name:t,totalSize:e,headerSize:r,contentSize:i}},Ge=n=>Re(n)/65536,wn=n=>Re(n)/1073741824,kn=n=>{let e=0;for(let t=0;t<4;t++){e<<=7;let r=E(n);if(e|=r&127,(r&128)===0)break}return e},pe=n=>{let e=X(n);return n.skip(2),e=Math.min(e,n.remainingLength),K.decode(F(n,e))},qs=n=>{let e=De(n);if(!e||e.name!=="data"||n.remainingLength<8)return null;let t=P(n);n.skip(4);let r=F(n,e.contentSize-8);switch(t){case 1:return K.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new Ve(r,"image/jpeg");case 14:return new Ve(r,"image/png");case 27:return new Ve(r,"image/bmp");default:return r}};var Sn=class extends J{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(r=>r.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 Ws({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,mt,Bt);if(t instanceof Promise&&(t=await t),!t)break;let r=e,o=De(t);if(!o)break;if(o.name==="ftyp"){let i=W(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=r+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),b(t);let r=P(t),o=this.reader.fileSize-r;if(o>=0&&o<=this.reader.fileSize-Bt){let i=this.reader.requestSliceRange(o,mt,Bt);if(i instanceof Promise&&(i=await i),i){let s=De(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,b(this.moovSlice);let r=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(r),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&He.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){b(e.info?.type==="audio");let i=pn(e.info.codec),s=[],a=[];for(let c=0;c<t.sampleToChunk.length;c++){let l=t.sampleToChunk[c],u=t.sampleToChunk[c+1],d=(u?u.startChunkIndex:t.chunkOffsets.length)-l.startChunkIndex;for(let m=0;m<d;m++){let f=l.startSampleIndex+m*l.samplesPerChunk,p=f+l.samplesPerChunk,h=O(t.sampleTimingEntries,f,C=>C.startIndex),g=t.sampleTimingEntries[h],y=O(t.sampleTimingEntries,p,C=>C.startIndex),x=t.sampleTimingEntries[y],v=g.startDecodeTimestamp+(f-g.startIndex)*g.delta,S=x.startDecodeTimestamp+(p-x.startIndex)*x.delta-v,k=ee(s);k&&k.delta===S?k.count++:s.push({startIndex:l.startChunkIndex+m,startDecodeTimestamp:v,count:1,delta:S});let I=l.samplesPerChunk*i.sampleSize*e.info.numberOfChannels;a.push(I)}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,mt,Bt);t instanceof Promise&&(t=await t),b(t);let r=De(t);b(r?.name==="moof");let o=this.reader.requestSlice(e,r.totalSize);o instanceof Promise&&(o=await o),b(o),this.traverseBox(o);let i=this.lastReadFragment;b(i&&i.moofOffset===e);for(let[,s]of i.trackData){let a=s.track,{fragmentPositionCache:c}=a;if(!s.startTimestampIsFinal){let u=a.fragmentLookupTable.find(d=>d.moofOffset===i.moofOffset);if(u)ui(s,u.timestamp);else{let d=O(c,i.moofOffset-1,m=>m.moofOffset);if(d!==-1){let m=c[d];ui(s,m.endTimestamp)}}s.startTimestampIsFinal=!0}let l=O(c,s.startTimestamp,u=>u.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-mt&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-mt;){let r=e.filePos,o=De(e);if(!o)break;yield{boxInfo:o,slice:e},e.filePos=r+o.totalSize}}traverseBox(e){let t=e.filePos,r=De(e);if(!r)return!1;let o=e.filePos,i=t+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(e.slice(o,r.contentSize));break;case"mvhd":{let s=E(e);e.skip(3),s===1?(e.skip(16),this.movieTimescale=P(e),this.movieDurationInTimescale=ae(e)):(e.skip(8),this.movieTimescale=P(e),this.movieDurationInTimescale=P(e))}break;case"trak":{let s={id:-1,demuxer:this,inputTrack:null,disposition:{...ie},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Q,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=s,this.readContiguousBoxes(e.slice(o,r.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 Pe(this.input,new di(a)),this.tracks.push(s)}else if(s.info.type==="audio"&&s.info.numberOfChannels!==-1){let a=s;s.inputTrack=new $(this.input,new mi(a)),this.tracks.push(s)}}this.currentTrack=null}break;case"tkhd":{let s=this.currentTrack;if(!s)break;let a=E(e),l=!!(je(e)&1);if(s.disposition.default=l,a===0)e.skip(8),s.id=P(e),e.skip(4),s.durationInMovieTimescale=P(e);else if(a===1)e.skip(16),s.id=P(e),e.skip(4),s.durationInMovieTimescale=ae(e);else throw new Error(`Incorrect track header version ${a}.`);e.skip(16);let u=[Ge(e),Ge(e),wn(e),Ge(e),Ge(e),wn(e),Ge(e),Ge(e),wn(e)],d=tn(xs(il(u),90));b(d===0||d===90||d===180||d===270),s.rotation=d}break;case"elst":{let s=this.currentTrack;if(!s)break;let a=E(e);e.skip(3);let c=!1,l=0,u=P(e);for(let d=0;d<u;d++){let m=a===1?ae(e):P(e),f=a===1?js(e):Re(e),p=Ge(e);if(m!==0){if(c){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(f===-1){l+=m;continue}if(p!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}s.editListPreviousSegmentDurations=l,s.editListOffset=f,c=!0}}}break;case"mdhd":{let s=this.currentTrack;if(!s)break;let a=E(e);e.skip(3),a===0?(e.skip(8),s.timescale=P(e),s.durationInMediaTimescale=P(e)):a===1&&(e.skip(16),s.timescale=P(e),s.durationInMediaTimescale=ae(e));let c=X(e);if(c>0){s.languageCode="";for(let l=0;l<3;l++)s.languageCode=String.fromCharCode(96+(c&31))+s.languageCode,c>>=5;cn(s.languageCode)||(s.languageCode=Q)}}break;case"hdlr":{let s=this.currentTrack;if(!s)break;e.skip(8);let a=W(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,r.contentSize))}break;case"stsd":{let s=this.currentTrack;if(!s||s.info===null||s.sampleTable)break;let a=E(e);e.skip(3);let c=P(e);for(let l=0;l<c;l++){let u=e.filePos,d=De(e);if(!d)break;s.internalCodecId=d.name;let m=d.name.toLowerCase();if(s.info.type==="video")m==="avc1"||m==="avc3"?(s.info.codec="avc",s.info.avcType=m==="avc1"?1:3):m==="hvc1"||m==="hev1"?s.info.codec="hevc":m==="vp08"?s.info.codec="vp8":m==="vp09"?s.info.codec="vp9":m==="av01"?s.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${d.name}').`),e.skip(24),s.info.width=X(e),s.info.height=X(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,u+d.totalSize-e.filePos));else{m==="mp4a"||(m==="opus"?s.info.codec="opus":m==="flac"?s.info.codec="flac":m==="twos"||m==="sowt"||m==="raw "||m==="in24"||m==="in32"||m==="fl32"||m==="fl64"||m==="lpcm"||m==="ipcm"||m==="fpcm"||(m==="ulaw"?s.info.codec="ulaw":m==="alaw"?s.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${d.name}').`))),e.skip(8);let f=X(e);e.skip(6);let p=X(e),h=X(e);e.skip(4);let g=P(e)/65536;if(a===0&&f>0){if(f===1)e.skip(4),h=8*P(e),e.skip(8);else if(f===2){e.skip(4),g=Pn(e),p=P(e),e.skip(4),h=P(e);let y=P(e);if(e.skip(8),m==="lpcm"){let x=h+7>>3,v=!!(y&1),T=!!(y&2),S=y&4?-1:0;h>0&&h<=64&&(v?h===32&&(s.info.codec=T?"pcm-f32be":"pcm-f32"):S&1<<x-1?x===1?s.info.codec="pcm-s8":x===2?s.info.codec=T?"pcm-s16be":"pcm-s16":x===3?s.info.codec=T?"pcm-s24be":"pcm-s24":x===4&&(s.info.codec=T?"pcm-s32be":"pcm-s32"):x===1&&(s.info.codec="pcm-u8")),s.info.codec===null&&console.warn("Unsupported PCM format.")}}}s.info.codec==="opus"&&(g=st),s.info.numberOfChannels=p,s.info.sampleRate=g,m==="twos"?h===8?s.info.codec="pcm-s8":h===16?s.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${h} for codec 'twos'.`),s.info.codec=null):m==="sowt"?h===8?s.info.codec="pcm-s8":h===16?s.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${h} for codec 'sowt'.`),s.info.codec=null):m==="raw "?s.info.codec="pcm-u8":m==="in24"?s.info.codec="pcm-s24be":m==="in32"?s.info.codec="pcm-s32be":m==="fl32"?s.info.codec="pcm-f32be":m==="fl64"?s.info.codec="pcm-f64be":m==="ipcm"?s.info.codec="pcm-s16be":m==="fpcm"&&(s.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,u+d.totalSize-e.filePos))}}}break;case"avcC":{let s=this.currentTrack;if(!s)break;b(s.info),s.info.codecDescription=F(e,r.contentSize)}break;case"hvcC":{let s=this.currentTrack;if(!s)break;b(s.info),s.info.codecDescription=F(e,r.contentSize)}break;case"vpcC":{let s=this.currentTrack;if(!s)break;b(s.info?.type==="video"),e.skip(4);let a=E(e),c=E(e),l=E(e),u=l>>4,d=l>>1&7,m=l&1,f=E(e),p=E(e),h=E(e);s.info.vp9CodecInfo={profile:a,level:c,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:m,colourPrimaries:f,transferCharacteristics:p,matrixCoefficients:h}}break;case"av1C":{let s=this.currentTrack;if(!s)break;b(s.info?.type==="video"),e.skip(1);let a=E(e),c=a>>5,l=a&31,u=E(e),d=u>>7,m=u>>6&1,f=u>>5&1,p=u>>4&1,h=u>>3&1,g=u>>2&1,y=u&3,x=c===2&&m?f?12:10:m?10:8;s.info.av1CodecInfo={profile:c,level:l,tier:d,bitDepth:x,monochrome:p,chromaSubsamplingX:h,chromaSubsamplingY:g,chromaSamplePosition:y}}break;case"colr":{let s=this.currentTrack;if(!s||(b(s.info?.type==="video"),W(e,4)!=="nclx"))break;let c=X(e),l=X(e),u=X(e),d=!!(E(e)&128);s.info.colorSpace={primaries:rn[c],transfer:nn[l],matrix:on[u],fullRange:d}}break;case"wave":this.readContiguousBoxes(e.slice(o,r.contentSize));break;case"esds":{let s=this.currentTrack;if(!s)break;b(s.info?.type==="audio"),e.skip(4);let a=E(e);b(a===3),kn(e),e.skip(2);let c=E(e),l=(c&128)!==0,u=(c&64)!==0,d=(c&32)!==0;if(l&&e.skip(2),u){let g=E(e);e.skip(g)}d&&e.skip(2);let m=E(e);b(m===4);let f=kn(e),p=e.filePos,h=E(e);if(h===64||h===103?(s.info.codec="aac",s.info.aacCodecInfo={isMpeg2:h===103}):h===105||h===107?s.info.codec="mp3":h===221?s.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${h}) - discarding track.`),e.skip(12),f>e.filePos-p){let g=E(e);b(g===5);let y=kn(e);if(s.info.codecDescription=F(e,y),s.info.codec==="aac"){let x=Yo(s.info.codecDescription);x.numberOfChannels!==null&&(s.info.numberOfChannels=x.numberOfChannels),x.sampleRate!==null&&(s.info.sampleRate=x.sampleRate)}}}break;case"enda":{let s=this.currentTrack;if(!s)break;b(s.info?.type==="audio"),X(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;b(s.info?.type==="audio"),e.skip(4);let c=!!(E(e)&1),l=E(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;b(s.info?.type==="audio"),e.skip(1);let a=E(e),c=X(e),l=P(e),u=Tr(e),d=E(e),m;d!==0?m=F(e,2+a):m=new Uint8Array(0);let f=new Uint8Array(19+m.byteLength),p=new DataView(f.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,u,!0),p.setUint8(18,d),f.set(m,19),s.info.codecDescription=f,s.info.numberOfChannels=a}break;case"dfLa":{let s=this.currentTrack;if(!s)break;b(s.info?.type==="audio"),e.skip(4);let a=127,c=128,l=e.filePos;for(;e.filePos<i;){let p=E(e),h=je(e);if((p&a)===We.STREAMINFO){e.skip(10);let y=P(e),x=y>>>12,v=(y>>9&7)+1;s.info.sampleRate=x,s.info.numberOfChannels=v,e.skip(20)}else e.skip(h);if(p&c)break}let u=e.filePos;e.filePos=l;let d=F(e,u-l),m=new Uint8Array(4+d.byteLength);new DataView(m.buffer).setUint32(0,1716281667,!1),m.set(d,4),s.info.codecDescription=m}break;case"stts":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=P(e),c=0,l=0;for(let u=0;u<a;u++){let d=P(e),m=P(e);s.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:l,count:d,delta:m}),c+=d,l+=d*m}}break;case"ctts":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=P(e),c=0;for(let l=0;l<a;l++){let u=P(e),d=Re(e);s.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:u,offset:d}),c+=u}}break;case"stsz":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=P(e),c=P(e);if(a===0)for(let l=0;l<c;l++){let u=P(e);s.sampleTable.sampleSizes.push(u)}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=E(e),c=P(e),l=F(e,Math.ceil(c*a/8)),u=new V(l);for(let d=0;d<c;d++){let m=u.readBits(a);s.sampleTable.sampleSizes.push(m)}}break;case"stss":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4),s.sampleTable.keySampleIndices=[];let a=P(e);for(let c=0;c<a;c++){let l=P(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=P(e);for(let l=0;l<a;l++){let u=P(e)-1,d=P(e),m=P(e);s.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:u,samplesPerChunk:d,sampleDescriptionIndex:m})}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 d=s.sampleTable.sampleToChunk[l+1].startChunkIndex-s.sampleTable.sampleToChunk[l].startChunkIndex;c+=d*s.sampleTable.sampleToChunk[l].samplesPerChunk}}break;case"stco":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=P(e);for(let c=0;c<a;c++){let l=P(e);s.sampleTable.chunkOffsets.push(l)}}break;case"co64":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=P(e);for(let c=0;c<a;c++){let l=ae(e);s.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(o,r.contentSize));break;case"mehd":{let s=E(e);e.skip(3);let a=s===1?ae(e):P(e);this.movieDurationInTimescale=a}break;case"trex":{e.skip(4);let s=P(e),a=P(e),c=P(e),l=P(e),u=P(e);this.fragmentTrackDefaults.push({trackId:s,defaultSampleDescriptionIndex:a,defaultSampleDuration:c,defaultSampleSize:l,defaultSampleFlags:u})}break;case"tfra":{let s=E(e);e.skip(3);let a=P(e),c=this.tracks.find(x=>x.id===a);if(!c)break;let l=P(e),u=(l&48)>>4,d=(l&12)>>2,m=l&3,f=[E,X,je,P],p=f[u],h=f[d],g=f[m],y=P(e);for(let x=0;x<y;x++){let v=s===1?ae(e):P(e),T=s===1?ae(e):P(e);p(e),h(e),g(e),c.fragmentLookupTable.push({timestamp:v,moofOffset:T})}c.fragmentLookupTable.sort((x,v)=>x.timestamp-v.timestamp);for(let x=0;x<c.fragmentLookupTable.length-1;x++){let v=c.fragmentLookupTable[x],T=c.fragmentLookupTable[x+1];v.timestamp===T.timestamp&&(c.fragmentLookupTable.splice(x+1,1),x--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:r.totalSize,implicitBaseDataOffset:t,trackData:new Map},this.readContiguousBoxes(e.slice(o,r.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(b(this.currentFragment),this.readContiguousBoxes(e.slice(o,r.contentSize)),this.currentTrack){let s=this.currentFragment.trackData.get(this.currentTrack.id);if(s){let{currentFragmentState:a}=this.currentTrack;b(a),a.startTimestamp!==null&&(ui(s,a.startTimestamp),s.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{b(this.currentFragment),e.skip(1);let s=je(e),a=!!(s&1),c=!!(s&2),l=!!(s&8),u=!!(s&16),d=!!(s&32),m=!!(s&65536),f=!!(s&131072),p=P(e),h=this.tracks.find(y=>y.id===p);if(!h)break;let g=this.fragmentTrackDefaults.find(y=>y.trackId===p);this.currentTrack=h,h.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:g?.defaultSampleDescriptionIndex??null,defaultSampleDuration:g?.defaultSampleDuration??null,defaultSampleSize:g?.defaultSampleSize??null,defaultSampleFlags:g?.defaultSampleFlags??null,startTimestamp:null},a?h.currentFragmentState.baseDataOffset=ae(e):f&&(h.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(h.currentFragmentState.sampleDescriptionIndex=P(e)),l&&(h.currentFragmentState.defaultSampleDuration=P(e)),u&&(h.currentFragmentState.defaultSampleSize=P(e)),d&&(h.currentFragmentState.defaultSampleFlags=P(e)),m&&(h.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let s=this.currentTrack;if(!s)break;b(s.currentFragmentState);let a=E(e);e.skip(3);let c=a===0?P(e):ae(e);s.currentFragmentState.startTimestamp=c}break;case"trun":{let s=this.currentTrack;if(!s)break;if(b(this.currentFragment),b(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=E(e),c=je(e),l=!!(c&1),u=!!(c&4),d=!!(c&256),m=!!(c&512),f=!!(c&1024),p=!!(c&2048),h=P(e),g=s.currentFragmentState.baseDataOffset;l&&(g+=Re(e));let y=null;u&&(y=P(e));let x=g;if(h===0){this.currentFragment.implicitBaseDataOffset=x;break}let v=0,T={track:s,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(s.id,T);for(let I=0;I<h;I++){let C;d?C=P(e):(b(s.currentFragmentState.defaultSampleDuration!==null),C=s.currentFragmentState.defaultSampleDuration);let A;m?A=P(e):(b(s.currentFragmentState.defaultSampleSize!==null),A=s.currentFragmentState.defaultSampleSize);let R;f?R=P(e):(b(s.currentFragmentState.defaultSampleFlags!==null),R=s.currentFragmentState.defaultSampleFlags),I===0&&y!==null&&(R=y);let D=0;p&&(a===0?D=P(e):D=Re(e));let L=!(R&65536);T.samples.push({presentationTimestamp:v+D,duration:C,byteOffset:x,byteSize:A,isKeyFrame:L}),x+=A,v+=C}T.presentationTimestamps=T.samples.map((I,C)=>({presentationTimestamp:I.presentationTimestamp,sampleIndex:C})).sort((I,C)=>I.presentationTimestamp-C.presentationTimestamp);for(let I=0;I<T.presentationTimestamps.length;I++){let C=T.presentationTimestamps[I],A=T.samples[C.sampleIndex];if(T.firstKeyFrameTimestamp===null&&A.isKeyFrame&&(T.firstKeyFrameTimestamp=A.presentationTimestamp),I<T.presentationTimestamps.length-1){let R=T.presentationTimestamps[I+1];A.duration=R.presentationTimestamp-C.presentationTimestamp}}let S=T.samples[T.presentationTimestamps[0].sampleIndex],k=T.samples[ee(T.presentationTimestamps).sampleIndex];T.startTimestamp=S.presentationTimestamp,T.endTimestamp=k.presentationTimestamp+k.duration,this.currentFragment.implicitBaseDataOffset=x}break;case"udta":{let s=this.iterateContiguousBoxes(e.slice(o,r.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]??=pe(c):this.metadataTags.raw[a.name]??=F(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=K.decode(F(c,a.contentSize)):this.metadataTags.title??=pe(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=pe(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=pe(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=pe(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=pe(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=pe(c));break;case"\xA9day":if(!this.currentTrack){let l=new Date(pe(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=pe(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=pe(c));break}}}break;case"meta":{if(this.currentTrack)break;let a=P(e)!==0;this.currentMetadataKeys=new Map,a?this.readContiguousBoxes(e.slice(o,r.contentSize)):this.readContiguousBoxes(e.slice(o+4,r.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let s=P(e);for(let a=0;a<s;a++){let c=P(e);e.skip(4);let l=K.decode(F(e,c-8));this.currentMetadataKeys.set(a+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let s=this.iterateContiguousBoxes(e.slice(o,r.contentSize));for(let{boxInfo:a,slice:c}of s){let l=a.name,u=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(u)&&(l=this.currentMetadataKeys.get(u));let d=qs(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=d,l){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof d=="string"&&(this.metadataTags.title??=d);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof d=="string"&&(this.metadataTags.description??=d);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof d=="string"&&(this.metadataTags.artist??=d);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof d=="string"&&(this.metadataTags.album??=d);break;case"aART":case"album_artist":typeof d=="string"&&(this.metadataTags.albumArtist??=d);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof d=="string"&&(this.metadataTags.comment??=d);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof d=="string"&&(this.metadataTags.genre??=d);break;case"\xA9lyr":case"lyrics":typeof d=="string"&&(this.metadataTags.lyrics??=d);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof d=="string"){let m=new Date(d);Number.isNaN(m.getTime())||(this.metadataTags.date??=m)}break;case"covr":case"com.apple.quicktime.artwork":d instanceof Ve?(this.metadataTags.images??=[],this.metadataTags.images.push({data:d.data,kind:"coverFront",mimeType:d.mimeType})):d instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:d,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof d=="string"){let m=d.split("/"),f=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(d instanceof Uint8Array&&d.length>=6){let m=z(d),f=m.getUint16(2,!1),p=m.getUint16(4,!1);f>0&&(this.metadataTags.trackNumber??=f),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(d instanceof Uint8Array&&d.length>=6){let m=z(d),f=m.getUint16(2,!1),p=m.getUint16(4,!1);f>0&&(this.metadataTags.discNumber??=f),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=i,!0}},Cn=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,r=>r.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return nt(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let r=this.mapTimestampIntoTimescale(e),o=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=fi(o,r),s=await this.fetchPacketForSampleIndex(i,t);return!Gs(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=O(c.presentationTimestamps,r,m=>m.presentationTimestamp),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&r<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},r,r,t)}async getNextPacket(e,t){let r=this.packetToSampleIndex.get(e);if(r!==void 0)return this.fetchPacketForSampleIndex(r+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 r=this.mapTimestampIntoTimescale(e),o=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=rl(o,r),s=await this.fetchPacketForSampleIndex(i,t);return!Gs(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=an(c.presentationTimestamps,m=>c.samples[m.sampleIndex].isKeyFrame&&m.presentationTimestamp<=r),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&r<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},r,r,t)}async getNextKeyPacket(e,t){let r=this.packetToSampleIndex.get(e);if(r!==void 0){let i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=ol(i,r);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 b(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 r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),o=nl(r,e);if(!o)return null;let i;if(t.metadataOnly)i=G;else{let l=this.internalTrack.demuxer.reader.requestSlice(o.sampleOffset,o.sampleSize);l instanceof Promise&&(l=await l),b(l),i=F(l,o.sampleSize)}let s=(o.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=o.duration/this.internalTrack.timescale,c=new H(i,o.isKeyFrame?"key":"delta",s,a,e,o.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,r){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).samples[t];b(i);let s;if(r.metadataOnly)s=G;else{let u=this.internalTrack.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);u instanceof Promise&&(u=await u),b(u),s=F(u,i.byteSize)}let a=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=i.duration/this.internalTrack.timescale,l=new H(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,r,o,i){let s=this.internalTrack.demuxer,a=null,c=null,l=-1;if(e){let{sampleIndex:g,correctSampleFound:y}=t(e);if(y)return this.fetchPacketInFragment(e,g,i);g!==-1&&(c=e,l=g)}let u=O(this.internalTrack.fragmentLookupTable,r,g=>g.timestamp),d=u!==-1?this.internalTrack.fragmentLookupTable[u]:null,m=O(this.internalTrack.fragmentPositionCache,r,g=>g.startTimestamp),f=m!==-1?this.internalTrack.fragmentPositionCache[m]:null,p=Math.max(d?.moofOffset??0,f?.moofOffset??0)||null,h;for(e?p===null||e.moofOffset>=p?(h=e.moofOffset+e.moofSize,a=e):h=p:h=p??0;;){if(a){let v=a.trackData.get(this.internalTrack.id);if(v&&v.startTimestamp>o)break}let g=s.reader.requestSliceRange(h,mt,Bt);if(g instanceof Promise&&(g=await g),!g)break;let y=h,x=De(g);if(!x)break;if(x.name==="moof"){a=await s.readFragment(y);let{sampleIndex:v,correctSampleFound:T}=t(a);if(T)return this.fetchPacketInFragment(a,v,i);v!==-1&&(c=a,l=v)}h=y+x.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){let g=this.internalTrack.fragmentLookupTable[u-1];b(!g||g.timestamp<d.timestamp);let y=g?.timestamp??-1/0;return this.performFragmentedLookup(null,t,y,o,i)}return c?this.fetchPacketInFragment(c,l,i):null}},di=class extends Cn{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&&xn(e.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&bn(e.data)}return{codec:mn(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}},mi=class extends Cn{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:fn(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},fi=(n,e)=>{if(n.presentationTimestamps){let t=O(n.presentationTimestamps,e,r=>r.presentationTimestamp);return t===-1?-1:n.presentationTimestamps[t].sampleIndex}else{let t=O(n.sampleTimingEntries,e,o=>o.startDecodeTimestamp);if(t===-1)return-1;let r=n.sampleTimingEntries[t];return r.startIndex+Math.min(Math.floor((e-r.startDecodeTimestamp)/r.delta),r.count-1)}},rl=(n,e)=>{if(!n.keySampleIndices)return fi(n,e);if(n.presentationTimestamps){let t=O(n.presentationTimestamps,e,r=>r.presentationTimestamp);if(t===-1)return-1;for(let r=t;r>=0;r--){let o=n.presentationTimestamps[r].sampleIndex;if(et(n.keySampleIndices,o,s=>s)!==-1)return o}return-1}else{let t=fi(n,e),r=O(n.keySampleIndices,t,o=>o);return n.keySampleIndices[r]??-1}},nl=(n,e)=>{let t=O(n.sampleTimingEntries,e,y=>y.startIndex),r=n.sampleTimingEntries[t];if(!r||r.startIndex+r.count<=e)return null;let i=r.startDecodeTimestamp+(e-r.startIndex)*r.delta,s=O(n.sampleCompositionTimeOffsets,e,y=>y.startIndex),a=n.sampleCompositionTimeOffsets[s];a&&e-a.startIndex<a.count&&(i+=a.offset);let c=n.sampleSizes[Math.min(e,n.sampleSizes.length-1)],l=O(n.sampleToChunk,e,y=>y.startSampleIndex),u=n.sampleToChunk[l];b(u);let d=u.startChunkIndex+Math.floor((e-u.startSampleIndex)/u.samplesPerChunk),m=n.chunkOffsets[d],f=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk,p=0,h=m;if(n.sampleSizes.length===1)h+=c*(e-f),p+=c*u.samplesPerChunk;else for(let y=f;y<f+u.samplesPerChunk;y++){let x=n.sampleSizes[y];y<e&&(h+=x),p+=x}let g=r.delta;if(n.presentationTimestamps){let y=n.presentationTimestampIndexMap[e];b(y!==void 0),y<n.presentationTimestamps.length-1&&(g=n.presentationTimestamps[y+1].presentationTimestamp-i)}return{presentationTimestamp:i,duration:g,sampleOffset:h,sampleSize:c,chunkOffset:m,chunkSize:p,isKeyFrame:n.keySampleIndices?et(n.keySampleIndices,e,y=>y)!==-1:!0}},ol=(n,e)=>{if(!n.keySampleIndices)return e+1;let t=O(n.keySampleIndices,e,r=>r);return n.keySampleIndices[t+1]??-1},ui=(n,e)=>{n.startTimestamp+=e,n.endTimestamp+=e;for(let t of n.samples)t.presentationTimestamp+=e;for(let t of n.presentationTimestamps)t.presentationTimestamp+=e},il=n=>{let[e,,,t]=n,r=Math.hypot(e,t),o=e/r,i=t/r,s=-Math.atan2(i,o)*(180/Math.PI);return Number.isFinite(s)?s:0},Gs=n=>n.sampleSizes.length===0;var w;(function(n){n[n.EBML=440786851]="EBML",n[n.EBMLVersion=17030]="EBMLVersion",n[n.EBMLReadVersion=17143]="EBMLReadVersion",n[n.EBMLMaxIDLength=17138]="EBMLMaxIDLength",n[n.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",n[n.DocType=17026]="DocType",n[n.DocTypeVersion=17031]="DocTypeVersion",n[n.DocTypeReadVersion=17029]="DocTypeReadVersion",n[n.Void=236]="Void",n[n.Segment=408125543]="Segment",n[n.SeekHead=290298740]="SeekHead",n[n.Seek=19899]="Seek",n[n.SeekID=21419]="SeekID",n[n.SeekPosition=21420]="SeekPosition",n[n.Duration=17545]="Duration",n[n.Info=357149030]="Info",n[n.TimestampScale=2807729]="TimestampScale",n[n.MuxingApp=19840]="MuxingApp",n[n.WritingApp=22337]="WritingApp",n[n.Tracks=374648427]="Tracks",n[n.TrackEntry=174]="TrackEntry",n[n.TrackNumber=215]="TrackNumber",n[n.TrackUID=29637]="TrackUID",n[n.TrackType=131]="TrackType",n[n.FlagEnabled=185]="FlagEnabled",n[n.FlagDefault=136]="FlagDefault",n[n.FlagForced=21930]="FlagForced",n[n.FlagOriginal=21934]="FlagOriginal",n[n.FlagHearingImpaired=21931]="FlagHearingImpaired",n[n.FlagVisualImpaired=21932]="FlagVisualImpaired",n[n.FlagCommentary=21935]="FlagCommentary",n[n.FlagLacing=156]="FlagLacing",n[n.Name=21358]="Name",n[n.Language=2274716]="Language",n[n.LanguageBCP47=2274717]="LanguageBCP47",n[n.CodecID=134]="CodecID",n[n.CodecPrivate=25506]="CodecPrivate",n[n.CodecDelay=22186]="CodecDelay",n[n.SeekPreRoll=22203]="SeekPreRoll",n[n.DefaultDuration=2352003]="DefaultDuration",n[n.Video=224]="Video",n[n.PixelWidth=176]="PixelWidth",n[n.PixelHeight=186]="PixelHeight",n[n.AlphaMode=21440]="AlphaMode",n[n.Audio=225]="Audio",n[n.SamplingFrequency=181]="SamplingFrequency",n[n.Channels=159]="Channels",n[n.BitDepth=25188]="BitDepth",n[n.SimpleBlock=163]="SimpleBlock",n[n.BlockGroup=160]="BlockGroup",n[n.Block=161]="Block",n[n.BlockAdditions=30113]="BlockAdditions",n[n.BlockMore=166]="BlockMore",n[n.BlockAdditional=165]="BlockAdditional",n[n.BlockAddID=238]="BlockAddID",n[n.BlockDuration=155]="BlockDuration",n[n.ReferenceBlock=251]="ReferenceBlock",n[n.Cluster=524531317]="Cluster",n[n.Timestamp=231]="Timestamp",n[n.Cues=475249515]="Cues",n[n.CuePoint=187]="CuePoint",n[n.CueTime=179]="CueTime",n[n.CueTrackPositions=183]="CueTrackPositions",n[n.CueTrack=247]="CueTrack",n[n.CueClusterPosition=241]="CueClusterPosition",n[n.Colour=21936]="Colour",n[n.MatrixCoefficients=21937]="MatrixCoefficients",n[n.TransferCharacteristics=21946]="TransferCharacteristics",n[n.Primaries=21947]="Primaries",n[n.Range=21945]="Range",n[n.Projection=30320]="Projection",n[n.ProjectionType=30321]="ProjectionType",n[n.ProjectionPoseRoll=30325]="ProjectionPoseRoll",n[n.Attachments=423732329]="Attachments",n[n.AttachedFile=24999]="AttachedFile",n[n.FileDescription=18046]="FileDescription",n[n.FileName=18030]="FileName",n[n.FileMediaType=18016]="FileMediaType",n[n.FileData=18012]="FileData",n[n.FileUID=18094]="FileUID",n[n.Chapters=272869232]="Chapters",n[n.Tags=307544935]="Tags",n[n.Tag=29555]="Tag",n[n.Targets=25536]="Targets",n[n.TargetTypeValue=26826]="TargetTypeValue",n[n.TargetType=25546]="TargetType",n[n.TagTrackUID=25541]="TagTrackUID",n[n.TagEditionUID=25545]="TagEditionUID",n[n.TagChapterUID=25540]="TagChapterUID",n[n.TagAttachmentUID=25542]="TagAttachmentUID",n[n.SimpleTag=26568]="SimpleTag",n[n.TagName=17827]="TagName",n[n.TagLanguage=17530]="TagLanguage",n[n.TagString=17543]="TagString",n[n.TagBinary=17541]="TagBinary",n[n.ContentEncodings=28032]="ContentEncodings",n[n.ContentEncoding=25152]="ContentEncoding",n[n.ContentEncodingOrder=20529]="ContentEncodingOrder",n[n.ContentEncodingScope=20530]="ContentEncodingScope",n[n.ContentCompression=20532]="ContentCompression",n[n.ContentCompAlgo=16980]="ContentCompAlgo",n[n.ContentCompSettings=16981]="ContentCompSettings",n[n.ContentEncryption=20533]="ContentEncryption"})(w||(w={}));var sl=[w.EBML,w.Segment],Ot=[w.SeekHead,w.Info,w.Cluster,w.Tracks,w.Cues,w.Attachments,w.Chapters,w.Tags],wr=[...sl,...Ot];var pi=8,ce=2,he=2*pi,hi=n=>{let e=E(n);if(n.skip(-1),e===0)return null;let t=1,r=128;for(;(e&r)===0;)t++,r>>=1;return t},zt=n=>{let e=E(n);if(e===0)return null;let t=1,r=128;for(;(e&r)===0;)t++,r>>=1;let o=e&r-1;for(let i=1;i<t;i++)o*=256,o+=E(n);return o},M=(n,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let r=0;r<e;r++)t*=256,t+=E(n);return t},$s=(n,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let t=0n;for(let r=0;r<e;r++)t<<=8n,t+=BigInt(E(n));return t};var In=n=>{let e=hi(n);return e===null?null:M(n,e)},gi=n=>{let e=E(n);return e===255?e=null:(n.skip(-1),e=zt(n),e===72057594037927940&&(e=null)),e},ge=n=>{let e=In(n);if(e===null)return null;let t=gi(n);return{id:e,size:t}},$e=(n,e)=>{let t=F(n,e),r=0;for(;r<e&&t[r]!==0;)r+=1;return String.fromCharCode(...t.subarray(0,r))},Nt=(n,e)=>{let t=F(n,e),r=0;for(;r<e&&t[r]!==0;)r+=1;return K.decode(t.subarray(0,r))},An=(n,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?Xs(n):Pn(n)},_n=async(n,e,t,r)=>{let o=new Set(t),i=e;for(;r===null||i<r;){let s=n.requestSliceRange(i,ce,he);if(s instanceof Promise&&(s=await s),!s)break;let a=ge(s);if(!a)break;if(o.has(a.id))return{pos:i,found:!0};Me(a.size),i=s.filePos+a.size}return{pos:r!==null&&r>i?r:i,found:!1}},xi=async(n,e,t,r)=>{let i=new Set(t),s=e;for(;s<r;){let a=n.requestSliceRange(s,0,Math.min(65536,r-s));if(a instanceof Promise&&(a=await a),!a||a.length<pi)break;for(let c=0;c<a.length-pi;c++){a.filePos=s;let l=In(a);if(l!==null&&i.has(l))return s;s++}}return null},xe={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 Me(n){if(n===null)throw new Error("Undefined element size is used in a place where it is not supported.")}var Ks=n=>{let t=(n.hasVideo?"video/":n.hasAudio?"audio/":"application/")+(n.isWebM?"webm":"x-matroska");if(n.codecStrings.length>0){let r=[...new Set(n.codecStrings.filter(Boolean))];t+=`; codecs="${r.join(", ")}"`}return t};var Be;(function(n){n[n.None=0]="None",n[n.Xiph=1]="Xiph",n[n.FixedSize=2]="FixedSize",n[n.Ebml=3]="Ebml"})(Be||(Be={}));var En;(function(n){n[n.Block=1]="Block",n[n.Private=2]="Private",n[n.Next=4]="Next"})(En||(En={}));var kr;(function(n){n[n.Zlib=0]="Zlib",n[n.Bzlib=1]="Bzlib",n[n.lzo1x=2]="lzo1x",n[n.HeaderStripping=3]="HeaderStripping"})(kr||(kr={}));var bi=[{id:w.SeekHead,flag:"seekHeadSeen"},{id:w.Info,flag:"infoSeen"},{id:w.Tracks,flag:"tracksSeen"},{id:w.Cues,flag:"cuesSeen"}],Qs=10*2**20,Fn=class extends J{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(r=>r.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(r=>r.getCodecParameterString()));return Ks({isWebM:this.isWebM,hasVideo:this.segments.some(r=>r.tracks.some(o=>o.info?.type==="video")),hasAudio:this.segments.some(r=>r.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,ce,he);if(t instanceof Promise&&(t=await t),!t)break;let r=ge(t);if(!r)break;let o=r.id,i=r.size,s=t.filePos;if(o===w.EBML){Me(i);let a=this.reader.requestSlice(s,i);if(a instanceof Promise&&(a=await a),!a)break;this.readContiguousElements(a)}else if(o===w.Segment){if(await this.readSegment(s,i),i===null||this.reader.fileSize===null)break}else if(o===w.Cluster){if(this.reader.fileSize===null)break;i===null&&(i=(await _n(this.reader,s,wr,this.reader.fileSize)).pos-s);let a=ee(this.segments);a&&(a.elementEndPos=s+i)}Me(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 r=e;for(;this.currentSegment.elementEndPos===null||r<this.currentSegment.elementEndPos;){let a=this.reader.requestSliceRange(r,ce,he);if(a instanceof Promise&&(a=await a),!a)break;let c=r,l=ge(a);if(!l||!Ot.includes(l.id)&&l.id!==w.Void){let p=await xi(this.reader,c,Ot,Math.min(this.currentSegment.elementEndPos??1/0,c+Qs));if(p){r=p;continue}else break}let{id:u,size:d}=l,m=a.filePos,f=bi.findIndex(p=>p.id===u);if(f!==-1){let p=bi[f].flag;this.currentSegment[p]=!0,Me(d);let h=this.reader.requestSlice(m,d);h instanceof Promise&&(h=await h),h&&this.readContiguousElements(h)}else if(u===w.Tags||u===w.Attachments){u===w.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Me(d);let p=this.reader.requestSlice(m,d);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(u===w.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(d===null)break;r=m+d}if(this.currentSegment.seekEntries.sort((a,c)=>a.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(let a of this.currentSegment.seekEntries){let c=bi.find(p=>p.id===a.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+a.segmentPosition,ce,he);if(l instanceof Promise&&(l=await l),!l)continue;let u=ge(l);if(!u)continue;let{id:d,size:m}=u;if(d!==c.id)continue;Me(m),this.currentSegment[c.flag]=!0;let f=this.reader.requestSlice(l.filePos,m);f instanceof Promise&&(f=await f),f&&this.readContiguousElements(f)}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],u=a.cuePoints[c+1];l.time===u.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 r=this.reader.requestSliceRange(e,ce,he);r instanceof Promise&&(r=await r),b(r);let o=e,i=ge(r);b(i);let s=i.id;b(s===w.Cluster);let a=i.size,c=r.filePos;a===null&&(a=(await _n(this.reader,c,wr,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,a);l instanceof Promise&&(l=await l);let u={segment:t,elementStartPos:o,elementEndPos:c+a,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){let d=this.readContiguousElements(l,wr);u.elementEndPos=d}for(let[,d]of u.trackData){let m=d.track;b(d.blocks.length>0);let f=!1;for(let y=0;y<d.blocks.length;y++){let x=d.blocks[y];x.timestamp+=u.timestamp,f||=x.lacing!==Be.None}d.presentationTimestamps=d.blocks.map((y,x)=>({timestamp:y.timestamp,blockIndex:x})).sort((y,x)=>y.timestamp-x.timestamp);for(let y=0;y<d.presentationTimestamps.length;y++){let x=d.presentationTimestamps[y],v=d.blocks[x.blockIndex];if(d.firstKeyFrameTimestamp===null&&v.isKeyFrame&&(d.firstKeyFrameTimestamp=v.timestamp),y<d.presentationTimestamps.length-1){let T=d.presentationTimestamps[y+1];v.duration=T.timestamp-v.timestamp}else v.duration===0&&m.defaultDuration!=null&&v.lacing===Be.None&&(v.duration=m.defaultDuration)}f&&(this.expandLacedBlocks(d.blocks,m),d.presentationTimestamps=d.blocks.map((y,x)=>({timestamp:y.timestamp,blockIndex:x})).sort((y,x)=>y.timestamp-x.timestamp));let p=d.blocks[d.presentationTimestamps[0].blockIndex],h=d.blocks[ee(d.presentationTimestamps).blockIndex];d.startTimestamp=p.timestamp,d.endTimestamp=h.timestamp+h.duration;let g=O(m.clusterPositionCache,d.startTimestamp,y=>y.startTimestamp);(g===-1||m.clusterPositionCache[g].elementStartPos!==o)&&m.clusterPositionCache.splice(g+1,0,{elementStartPos:u.elementStartPos,startTimestamp:d.startTimestamp})}return t.lastReadCluster=u,u}getTrackDataInCluster(e,t){let r=e.trackData.get(t);if(!r){let o=e.segment.tracks.find(i=>i.id===t);if(!o)return null;r={track:o,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,r)}return r}expandLacedBlocks(e,t){for(let r=0;r<e.length;r++){let o=e[r];if(o.lacing===Be.None)continue;o.decoded||(o.data=this.decodeBlockData(t,o.data),o.decoded=!0);let i=Ut.tempFromBytes(o.data),s=[],a=E(i)+1;switch(o.lacing){case Be.Xiph:{let l=0;for(let u=0;u<a-1;u++){let d=0;for(;i.bufferPos<i.length;){let m=E(i);if(d+=m,m<255){s.push(d),l+=d;break}}}s.push(i.length-(i.bufferPos+l))}break;case Be.FixedSize:{let l=i.length-1,u=Math.floor(l/a);for(let d=0;d<a;d++)s.push(u)}break;case Be.Ebml:{let l=zt(i);b(l!==null);let u=l;s.push(u);let d=u;for(let m=1;m<a-1;m++){let f=i.bufferPos,p=zt(i);b(p!==null);let h=p,y=(1<<(i.bufferPos-f)*7-1)-1,x=h-y;u+=x,s.push(u),d+=u}s.push(i.length-(i.bufferPos+d))}break;default:b(!1)}b(s.length===a),e.splice(r,1);let c=o.duration||a*(t.defaultDuration??0);for(let l=0;l<a;l++){let u=s[l],d=F(i,u),m=o.timestamp+c*l/a,f=c/a;e.splice(r+l,0,{timestamp:m,duration:f,isKeyFrame:o.isKeyFrame,data:d,lacing:Be.None,decoded:!0,mainAdditional:o.mainAdditional})}r+=a,r--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if(!(t.id===w.Tags&&!e.tagsSeen)){if(!(t.id===w.Attachments&&!e.attachmentsSeen))continue}let r=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,ce,he);if(r instanceof Promise&&(r=await r),!r)continue;let o=ge(r);if(!o||o.id!==t.id)continue;let{size:i}=o;Me(i),b(!this.currentSegment),this.currentSegment=e;let s=this.reader.requestSlice(r.filePos,i);s instanceof Promise&&(s=await s),s&&this.readContiguousElements(s),this.currentSegment=null,t.id===w.Tags?e.tagsSeen=!0:t.id===w.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){let r=e.filePos;for(;e.filePos-r<=e.length-ce;){let o=e.filePos;if(!this.traverseElement(e,t))return o}return e.filePos}traverseElement(e,t){let r=ge(e);if(!r||t&&t.includes(r.id))return!1;let{id:o,size:i}=r,s=e.filePos;switch(Me(i),o){case w.DocType:this.isWebM=$e(e,i)==="webm";break;case w.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 w.SeekID:{let a=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!a)break;a.id=M(e,i)}break;case w.SeekPosition:{let a=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!a)break;a.segmentPosition=M(e,i)}break;case w.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=M(e,i),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case w.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=An(e,i)}break;case w.TrackEntry:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...ie},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:Q,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(s,i)),this.currentTrack.decodingInstructions.some(a=>a.data?.type!=="decompress"||a.scope!==En.Block||a.data.algorithm!==kr.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===xe.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===xe.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===xe.vp8?this.currentTrack.info.codec="vp8":c===xe.vp9?this.currentTrack.info.codec="vp9":c===xe.av1&&(this.currentTrack.info.codec="av1");let l=this.currentTrack,u=new Pe(this.input,new yi(l));this.currentTrack.inputTrack=u,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){c===xe.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===xe.mp3?this.currentTrack.info.codec="mp3":c===xe.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=st):c===xe.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===xe.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,u=new $(this.input,new vi(l));this.currentTrack.inputTrack=u,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case w.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=M(e,i)}break;case w.TrackType:{if(!this.currentTrack)break;let a=M(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 w.FlagEnabled:{if(!this.currentTrack)break;M(e,i)||(this.currentSegment.tracks.pop(),this.currentTrack=null)}break;case w.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!M(e,i)}break;case w.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!M(e,i)}break;case w.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!M(e,i)}break;case w.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!M(e,i)}break;case w.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!M(e,i)}break;case w.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!M(e,i)}break;case w.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=$e(e,i)}break;case w.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=F(e,i)}break;case w.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*M(e,i)/1e9}break;case w.Name:{if(!this.currentTrack)break;this.currentTrack.name=Nt(e,i)}break;case w.Language:{if(!this.currentTrack||this.currentTrack.languageCode!==Q)break;this.currentTrack.languageCode=$e(e,i),cn(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Q)}break;case w.LanguageBCP47:{if(!this.currentTrack)break;let c=$e(e,i).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=Q}break;case w.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(s,i))}break;case w.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=M(e,i)}break;case w.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=M(e,i)}break;case w.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=M(e,i)===1}break;case w.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(s,i))}break;case w.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=M(e,i),c=on[a]??null;this.currentTrack.info.colorSpace.matrix=c}break;case w.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=M(e,i)===2}break;case w.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=M(e,i),c=nn[a]??null;this.currentTrack.info.colorSpace.transfer=c}break;case w.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=M(e,i),c=rn[a]??null;this.currentTrack.info.colorSpace.primaries=c}break;case w.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(s,i))}break;case w.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let c=-An(e,i);try{this.currentTrack.info.rotation=tn(c)}catch{}}break;case w.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(s,i))}break;case w.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=An(e,i)}break;case w.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=M(e,i)}break;case w.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=M(e,i)}break;case w.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(s,i)),this.currentCueTime=null}break;case w.CueTime:this.currentCueTime=M(e,i);break;case w.CueTrackPositions:{if(this.currentCueTime===null)break;b(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 w.CueTrack:{let a=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!a)break;a.trackId=M(e,i)}break;case w.CueClusterPosition:{let a=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!a)break;b(this.currentSegment),a.clusterPosition=this.currentSegment.dataStartPos+M(e,i)}break;case w.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=M(e,i)}break;case w.SimpleBlock:{if(!this.currentCluster)break;let a=zt(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let l=Tr(e),u=E(e),d=u>>1&3,m=!!(u&128);c.track.info?.type==="audio"&&c.track.info.codec&&(m=!0);let f=F(e,i-(e.filePos-s)),p=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:m,data:f,lacing:d,decoded:!p,mainAdditional:null})}break;case w.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(s,i)),this.currentBlock=null}break;case w.Block:{if(!this.currentCluster)break;let a=zt(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let l=Tr(e),d=E(e)>>1&3,m=F(e,i-(e.filePos-s)),f=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:m,lacing:d,decoded:!f,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case w.BlockAdditions:this.readContiguousElements(e.slice(s,i));break;case w.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 w.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=F(e,i)}break;case w.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=M(e,i)}break;case w.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=M(e,i)}break;case w.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case w.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(s,i));break;case w.Targets:this.readContiguousElements(e.slice(s,i));break;case w.TargetTypeValue:M(e,i)!==50&&(this.currentTagTargetIsMovie=!1);break;case w.TagTrackUID:case w.TagEditionUID:case w.TagChapterUID:case w.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case w.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(s,i))}break;case w.TagName:this.currentSimpleTagName=Nt(e,i);break;case w.TagString:{if(!this.currentSimpleTagName)break;let a=Nt(e,i);this.processTagValue(this.currentSimpleTagName,a)}break;case w.TagBinary:{if(!this.currentSimpleTagName)break;let a=F(e,i);this.processTagValue(this.currentSimpleTagName,a)}break;case w.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 dn(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 u=c.toLowerCase();u.startsWith("cover.")?l="coverFront":u.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 w.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=$s(e,i)}break;case w.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Nt(e,i)}break;case w.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=$e(e,i)}break;case w.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=F(e,i)}break;case w.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Nt(e,i)}break;case w.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(s,i)),this.currentTrack.decodingInstructions.sort((a,c)=>c.order-a.order)}break;case w.ContentEncoding:this.currentDecodingInstruction={order:0,scope:En.Block,data:null},this.readContiguousElements(e.slice(s,i)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case w.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=M(e,i)}break;case w.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=M(e,i)}break;case w.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:kr.Zlib,settings:null},this.readContiguousElements(e.slice(s,i))}break;case w.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=M(e,i)}break;case w.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=F(e,i)}break;case w.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=s+i,!0}decodeBlockData(e,t){b(e.decodingInstructions.length>0);let r=t;for(let o of e.decodingInstructions)switch(b(o.data),o.data.type){case"decompress":switch(o.data.algorithm){case kr.HeaderStripping:if(o.data.settings&&o.data.settings.length>0){let i=o.data.settings,s=new Uint8Array(i.length+r.length);s.set(i,0),s.set(r,i.length),r=s}break;default:}break;default:}return r}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let r=this.currentSegment.metadataTags;if(r.raw??={},r.raw[e]??=t,typeof t=="string")switch(e.toLowerCase()){case"title":r.title??=t;break;case"description":r.description??=t;break;case"artist":r.artist??=t;break;case"album":r.album??=t;break;case"album_artist":r.albumArtist??=t;break;case"genre":r.genre??=t;break;case"comment":r.comment??=t;break;case"lyrics":r.lyrics??=t;break;case"date":{let o=new Date(t);Number.isNaN(o.getTime())||(r.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&&(r.trackNumber??=i),s&&Number.isInteger(s)&&s>0&&(r.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&&(r.discNumber??=i),s&&Number.isInteger(s)&&s>0&&(r.discsTotal??=s)}break}}},Dn=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 nt(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let r=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=O(i.presentationTimestamps,r,l=>l.timestamp),a=s!==-1?i.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&r<i.endTimestamp;return{blockIndex:a,correctBlockFound:c}},r,r,t)}async getNextPacket(e,t){let r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,o=>{if(o===r.cluster){let i=o.trackData.get(this.internalTrack.id);if(r.blockIndex+1<i.blocks.length)return{blockIndex:r.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 r=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=an(i.presentationTimestamps,l=>i.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=r),a=s!==-1?i.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&r<i.endTimestamp;return{blockIndex:a,correctBlockFound:c}},r,r,t)}async getNextKeyPacket(e,t){let r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,o=>{if(o===r.cluster){let s=o.trackData.get(this.internalTrack.id).blocks.findIndex((a,c)=>a.isKeyFrame&&c>r.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 b(s!==-1),{blockIndex:s,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,r){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).blocks[t];b(i),i.decoded||(i.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,i.data),i.decoded=!0);let s=r.metadataOnly?G: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=r.metadataOnly?G:i.mainAdditional,l.alphaByteLength=i.mainAdditional.byteLength);let u=new H(s,i.isKeyFrame?"key":"delta",a,c,e.dataStartPos+t,i.data.byteLength,l);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u}async performClusterLookup(e,t,r,o,i){let{demuxer:s,segment:a}=this.internalTrack,c=null,l=null,u=-1;if(e){let{blockIndex:y,correctBlockFound:x}=t(e);if(x)return this.fetchPacketInCluster(e,y,i);y!==-1&&(l=e,u=y)}let d=O(this.internalTrack.cuePoints,r,y=>y.time),m=d!==-1?this.internalTrack.cuePoints[d]:null,f=O(this.internalTrack.clusterPositionCache,r,y=>y.startTimestamp),p=f!==-1?this.internalTrack.clusterPositionCache[f]:null,h=Math.max(m?.clusterPosition??0,p?.elementStartPos??0)||null,g;for(e?h===null||e.elementStartPos>=h?(g=e.elementEndPos,c=e):g=h:g=h??a.clusterSeekStartPos;a.elementEndPos===null||g<=a.elementEndPos-ce;){if(c){let C=c.trackData.get(this.internalTrack.id);if(C&&C.startTimestamp>o)break}let y=s.reader.requestSliceRange(g,ce,he);if(y instanceof Promise&&(y=await y),!y)break;let x=g,v=ge(y);if(!v||!Ot.includes(v.id)&&v.id!==w.Void){let C=await xi(s.reader,x,Ot,Math.min(a.elementEndPos??1/0,x+Qs));if(C){g=C;continue}else break}let T=v.id,S=v.size,k=y.filePos;if(T===w.Cluster){c=await s.readCluster(x,a),S=c.elementEndPos-k;let{blockIndex:C,correctBlockFound:A}=t(c);if(A)return this.fetchPacketInCluster(c,C,i);C!==-1&&(l=c,u=C)}S===null&&(b(T!==w.Cluster),S=(await _n(s.reader,k,wr,a.elementEndPos)).pos-k);let I=k+S;if(a.elementEndPos===null){let C=s.reader.requestSliceRange(I,ce,he);if(C instanceof Promise&&(C=await C),!C)break;if(In(C)===w.Segment){a.elementEndPos=I;break}}g=I}if(m&&(!l||l.elementStartPos<m.clusterPosition)){let y=this.internalTrack.cuePoints[d-1];b(!y||y.time<m.time);let x=y?.time??-1/0;return this.performClusterLookup(null,t,x,o,i)}return l?this.fetchPacketInCluster(l,u,i):null}},yi=class extends Dn{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:mn({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?Is(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?_s(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?xn(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?bn(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}},vi=class extends Dn{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:fn({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 al=[44100,48e3,32e3],cl=[-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],Ys=1483304551,Zs=1231971951,ll=(n,e,t,r,o)=>e===0?0:e===1?Math.floor(144*t/(r<<n))+o:e===2?Math.floor(144*t/r)+o:(Math.floor(12*t/r)+o)*4,Js=(n,e)=>n===3?e===3?21:36:e===3?13:21,ea=(n,e)=>{let t=n>>>24,r=n>>>16&255,o=n>>>8&255,i=n&255;if(t!==255&&r!==255&&o!==255&&i!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((r&224)!==224)return{header:null,bytesAdvanced:1};let s=0,a=0;r&16?s=r&8?0:1:(s=1,a=1);let c=r>>3&3,l=r>>1&3,u=o>>4&15,d=(o>>2&3)%3,m=o>>1&1,f=i>>6&3,p=i>>4&3,h=i>>3&1,g=i>>2&1,y=i&3,x=cl[s*16*4+l*16+u];if(x===-1)return{header:null,bytesAdvanced:1};let v=x*1e3,T=al[d]>>s+a,S=ll(s,l,v,T,m);if(e!==null&&e<S)return{header:null,bytesAdvanced:1};let k;return c===3?k=l===3?384:1152:l===3?k=384:l===2?k=1152:k=576,{header:{totalSize:S,mpegVersionId:c,layer:l,bitrate:v,frequencyIndex:d,sampleRate:T,channel:f,modeExtension:p,copyright:h,original:g,emphasis:y,audioSamplesInFrame:k},bytesAdvanced:1}};var Rn=n=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=n&e,e>>=8;return t};var Vt;(function(n){n[n.Unsynchronisation=128]="Unsynchronisation",n[n.ExtendedHeader=64]="ExtendedHeader",n[n.ExperimentalIndicator=32]="ExperimentalIndicator",n[n.Footer=16]="Footer"})(Vt||(Vt={}));var Ht;(function(n){n[n.ISO_8859_1=0]="ISO_8859_1",n[n.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",n[n.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",n[n.UTF_8=3]="UTF_8"})(Ht||(Ht={}));var Sr=128,qt=10,Wt=["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"],ta=(n,e)=>{let t=n.filePos;e.raw??={},e.raw.TAG??=F(n,Sr-3),n.filePos=t;let r=Lt(n,30);r&&(e.title??=r);let o=Lt(n,30);o&&(e.artist??=o);let i=Lt(n,30);i&&(e.album??=i);let s=Lt(n,4),a=Number.parseInt(s,10);Number.isInteger(a)&&a>0&&(e.date??=new Date(a,0,1));let c=F(n,30),l;if(c[28]===0&&c[29]!==0){let d=c[29];d>0&&(e.trackNumber??=d),n.skip(-30),l=Lt(n,28),n.skip(2)}else n.skip(-30),l=Lt(n,30);l&&(e.comment??=l);let u=E(n);u<Wt.length&&(e.genre??=Wt[u])},Lt=(n,e)=>{let t=F(n,e),r=ot(t.indexOf(0),t.length),o=t.subarray(0,r),i="";for(let s=0;s<o.length;s++)i+=String.fromCharCode(o[s]);return i.trimEnd()},ft=n=>{let e=n.filePos,t=W(n,3),r=E(n),o=E(n),i=E(n),s=P(n);if(t!=="ID3"||r===255||o===255||(s&2155905152)!==0)return n.filePos=e,null;let a=Rn(s);return{majorVersion:r,revision:o,flags:i,size:a}},Mn=(n,e,t)=>{if(![2,3,4].includes(e.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let r=F(n,e.size),o=new Ti(e,r);if(e.flags&Vt.Footer&&o.removeFooter(),e.flags&Vt.Unsynchronisation&&e.majorVersion===3&&o.ununsynchronizeAll(),e.flags&Vt.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,u=!1;if(e.majorVersion===3?(c=!!(i.flags&64),l=!!(i.flags&128)):e.majorVersion===4&&(c=!!(i.flags&4),l=!!(i.flags&8),u=!!(i.flags&2)||!!(e.flags&Vt.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(u&&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 m=o.readId3V2EncodingAndText(a).split("/"),f=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(f)&&f>0&&(t.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(t.tracksTotal??=p)}break;case"TPOS":case"TPA":{let m=o.readId3V2EncodingAndText(a).split("/"),f=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(f)&&f>0&&(t.discNumber??=f),p&&Number.isInteger(p)&&p>0&&(t.discsTotal??=p)}break;case"TCON":case"TCO":{let d=o.readId3V2EncodingAndText(a),m=/^\((\d+)\)/.exec(d);if(m){let f=Number.parseInt(m[1]);if(Wt[f]!==void 0){t.genre??=Wt[f];break}}if(m=/^\d+$/.exec(d),m){let f=Number.parseInt(m[0]);if(Wt[f]!==void 0){t.genre??=Wt[f];break}}t.genre??=d}break;case"TDRC":case"TDAT":{let d=o.readId3V2EncodingAndText(a),m=new Date(d);Number.isNaN(m.getTime())||(t.date??=m)}break;case"TYER":case"TYE":{let d=o.readId3V2EncodingAndText(a),m=Number.parseInt(d,10);Number.isInteger(m)&&(t.date??=new Date(m,0,1))}break;case"USLT":case"ULT":{let d=o.readU8();o.pos+=3,o.readId3V2Text(d,a),t.lyrics??=o.readId3V2Text(d,a)}break;case"COMM":case"COM":{let d=o.readU8();o.pos+=3,o.readId3V2Text(d,a),t.comment??=o.readId3V2Text(d,a)}break;case"APIC":case"PIC":{let d=o.readId3V2TextEncoding(),m;if(e.majorVersion===2){let g=o.readAscii(3);m=g==="PNG"?"image/png":g==="JPG"?"image/jpeg":"image/*"}else m=o.readId3V2Text(d,a);let f=o.readU8(),p=o.readId3V2Text(d,a).trimEnd(),h=a-o.pos;if(h>=0){let g=o.readBytes(h);t.images||(t.images=[]),t.images.push({data:g,mimeType:m,kind:f===3?"coverFront":f===4?"coverBack":"unknown",description:p})}}break;default:o.pos+=i.size;break}o.pos=a}},Ti=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 r=this.bytes[t];e.push(r),r===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 r=[];for(let s=e;s<t;s++){let a=this.bytes[s];r.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+r.length+i.length),this.bytes.set(o,0),this.bytes.set(r,o.length),this.bytes.set(i,o.length+r.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-qt),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 r=0;r<e;r++)t+=String.fromCharCode(this.view.getUint8(this.pos+r));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){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(),r=this.header.majorVersion===4?Rn(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(r)){let a=this.header.majorVersion===4?t:Rn(t);s(a)&&(r=a)}return this.pos=i,{id:e,size:r,flags:o}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let r=this.pos,o=this.readBytes(t-this.pos);switch(e){case Ht.ISO_8859_1:{let i="";for(let s=0;s<o.length;s++){let a=o[s];if(a===0){this.pos=r+s+1;break}i+=String.fromCharCode(a)}return i}case Ht.UTF_16_WITH_BOM:if(o[0]===255&&o[1]===254){let i=new TextDecoder("utf-16le"),s=ot(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=r+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=ot(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=r+Math.min(s+2,o.length),i.decode(o.subarray(2,s))}else{let i=ot(o.findIndex(s=>s===0),o.length);return this.pos=r+Math.min(i+1,o.length),K.decode(o.subarray(0,i))}case Ht.UTF_16_BE_NO_BOM:{let i=new TextDecoder("utf-16be"),s=ot(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=r+Math.min(s+2,o.length),i.decode(o.subarray(0,s))}case Ht.UTF_8:{let i=ot(o.findIndex(s=>s===0),o.length);return this.pos=r+Math.min(i+1,o.length),K.decode(o.subarray(0,i))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}};var Cr=async(n,e,t)=>{let r=e;for(;t===null||r<t;){let o=n.requestSlice(r,4);if(o instanceof Promise&&(o=await o),!o)break;let i=P(o),s=ea(i,n.fileSize!==null?n.fileSize-r:null);if(s.header)return{header:s.header,startPos:r};r+=s.bytesAdvanced}return null};var Bn=class extends J{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new ke,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 $(this.input,new wi(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,qt);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}let c=ft(a);if(!c)break;this.lastLoadedPos=a.filePos+c.size}let e=await Cr(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 r=Js(t.mpegVersionId,t.channel),o=this.reader.requestSlice(e.startPos+r,4);if(o instanceof Promise&&(o=await o),o){let a=P(o);if(a===Ys||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 b(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,r=!1;for(;;){let o=this.reader.requestSlice(t,qt);if(o instanceof Promise&&(o=await o),!o)break;let i=ft(o);if(!i)break;r=!0;let s=this.reader.requestSlice(o.filePos,i.size);if(s instanceof Promise&&(s=await s),!s)break;Mn(s,i,this.metadataTags),t=o.filePos+i.size}if(!r&&this.reader.fileSize!==null&&this.reader.fileSize>=Sr){let o=this.reader.requestSlice(this.reader.fileSize-Sr,Sr);o instanceof Promise&&(o=await o),b(o),W(o,3)==="TAG"&&ta(o,this.metadataTags)}return this.metadataTags}finally{e()}}},wi=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return b(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 Q}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return b(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return b(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...ie}}async getDecoderConfig(){return b(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 r=this.demuxer.loadedSamples[e];if(!r)return null;let o;if(t.metadataOnly)o=G;else{let i=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(i instanceof Promise&&(i=await i),!i)return null;o=F(i,r.dataSize)}return new H(o,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{let o=et(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{r()}}async getPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{for(;;){let o=O(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{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var ki=1399285583,ul=79764919,na=new Uint32Array(256);for(let n=0;n<256;n++){let e=n<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^ul:e<<1;na[n]=e>>>0&4294967295}var oa=n=>{let e=z(n),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let r=0;for(let o=0;o<n.length;o++){let i=n[o];r=(r<<8^na[r>>>24^i])>>>0}return e.setUint32(22,t,!0),r},ia=(n,e,t)=>{let r=0,o=null;if(n.length>0)if(e.codec==="vorbis"){b(e.vorbisInfo);let i=e.vorbisInfo.modeBlockflags.length,a=(1<<bs(i-1))-1<<1,c=(n[0]&a)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=t,u=e.vorbisInfo.modeBlockflags[c];if(o=e.vorbisInfo.blocksizes[u],u===1){let d=(a|1)+1,m=n[0]&d?1:0;l=e.vorbisInfo.blocksizes[m]}r=l!==null?l+o>>2:0}else e.codec==="opus"&&(r=Ds(n).durationInSamples);return{durationInSamples:r,vorbisBlockSize:o}},sa=n=>{let e="audio/ogg";if(n.codecStrings){let t=[...new Set(n.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};var Xe=27,ht=282,aa=ht+65025,Gt=n=>{let e=n.filePos;if(pt(n)!==ki)return null;n.skip(1);let r=E(n),o=la(n),i=pt(n),s=pt(n),a=pt(n),c=E(n),l=new Uint8Array(c);for(let f=0;f<c;f++)l[f]=E(n);let u=27+c,d=l.reduce((f,p)=>f+p,0),m=u+d;return{headerStartPos:e,totalSize:m,dataStartPos:e+u,dataSize:d,headerType:r,granulePosition:o,serialNumber:i,sequenceNumber:s,checksum:a,lacingValues:l}},ca=(n,e)=>{for(;n.filePos<e-3;){let t=pt(n),r=t&255,o=t>>>8&255,i=t>>>16&255,s=t>>>24&255,a=79;if(!(r!==a&&o!==a&&i!==a&&s!==a)){if(n.skip(-4),t===ki)return!0;n.skip(1)}}return!1};var On=class extends J{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,Xe,ht);if(t instanceof Promise&&(t=await t),!t)break;let r=Gt(t);if(!r||!!!(r.headerType&2))break;this.bitstreams.push({serialNumber:r.serialNumber,bosPage:r,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=r.headerStartPos+r.totalSize}for(let t of this.bitstreams){let r=await this.readPacket(t.bosPage,0);r&&(r.data.byteLength>=7&&r.data[0]===1&&r.data[1]===118&&r.data[2]===111&&r.data[3]===114&&r.data[4]===98&&r.data[5]===105&&r.data[6]===115?await this.readVorbisMetadata(r,t):r.data.byteLength>=8&&r.data[0]===79&&r.data[1]===112&&r.data[2]===117&&r.data[3]===115&&r.data[4]===72&&r.data[5]===101&&r.data[6]===97&&r.data[7]===100&&await this.readOpusMetadata(r,t),t.codecInfo.codec!==null&&this.tracks.push(new $(this.input,new Si(t,this))))}})()}async readVorbisMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;let o=await this.readPacket(r.startPage,r.startSegmentIndex);if(!o||(r=await this.findNextPacketStart(o),!r))return;let i=await this.readPacket(r.startPage,r.startSegmentIndex);if(!i||o.data[0]!==3||i.data[0]!==5)return;let s=[],a=d=>{for(;s.push(Math.min(255,d)),!(d<255);)d-=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 u=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(u&15),1<<(u>>4)],modeBlockflags:Rs(i.data).modeBlockflags},fr(o.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;let o=await this.readPacket(r.startPage,r.startSegmentIndex);if(!o)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=o;let i=Fs(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=st,t.codecInfo.opusInfo={preSkip:i.preSkip},fr(o.data.subarray(8),this.metadataTags)}async readPacket(e,t){b(t<e.lacingValues.length);let r=0;for(let d=0;d<t;d++)r+=e.lacingValues[d];let o=e,i=r,s=t,a=[];e:for(;;){let d=this.reader.requestSlice(o.dataStartPos,o.dataSize);d instanceof Promise&&(d=await d),b(d);let m=F(d,o.dataSize);for(;;){if(s===o.lacingValues.length){a.push(m.subarray(r,i));break}let p=o.lacingValues[s];if(i+=p,p<255){a.push(m.subarray(r,i));break e}s++}let f=o.headerStartPos+o.totalSize;for(;;){let p=this.reader.requestSliceRange(f,Xe,ht);if(p instanceof Promise&&(p=await p),!p)return null;let h=Gt(p);if(!h)return null;if(o=h,o.serialNumber===e.serialNumber)break;f=o.headerStartPos+o.totalSize}r=0,i=0,s=0}let c=a.reduce((d,m)=>d+m.length,0),l=new Uint8Array(c),u=0;for(let d=0;d<a.length;d++){let m=a[d];l.set(m,u),u+=m.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 r=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let o=this.reader.requestSliceRange(r,Xe,ht);if(o instanceof Promise&&(o=await o),!o)return null;let i=Gt(o);if(!i)return null;if(i.serialNumber===e.endPage.serialNumber)return{startPage:i,startSegmentIndex:0};r=i.headerStartPos+i.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(t=>t.getCodecParameterString()));return sa({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(r=>r.computeDuration()));return Math.max(0,...t)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Si=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new ke,this.internalSampleRate=e.codecInfo.codec==="opus"?st: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 b(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 Q}getDisposition(){return{...ie}}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"?(b(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,r){if(!e)return null;let{durationInSamples:o,vorbisBlockSize:i}=ia(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new H(r.metadataOnly?G: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){b(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=0;this.bitstream.codecInfo.codec==="opus"&&(b(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);let o=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(o,{timestampInSamples:r,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let r=this.encodedPacketToMetadata.get(e);if(!r)throw new Error("Packet was not created from this track.");let o=await this.demuxer.findNextPacketStart(r.packet);if(!o)return null;let i=r.timestampInSamples+r.durationInSamples,s=await this.demuxer.readPacket(o.startPage,o.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:i,vorbisLastBlocksize:r.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let r=nt(e*this.internalSampleRate);if(r===0)return this.getFirstPacket(t);if(r<0)return null;b(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 x=i.headerStartPos,v=Math.floor((x+s)/2),T=v;for(;;){let S=Math.min(T+aa,s-Xe),k=this.demuxer.reader.requestSlice(T,S-T);if(k instanceof Promise&&(k=await k),b(k),!ca(k,S)){s=v+Xe;continue e}let C=this.demuxer.reader.requestSliceRange(k.filePos,Xe,ht);C instanceof Promise&&(C=await C),b(C);let A=Gt(C);b(A);let R=!1;if(A.serialNumber===this.bitstream.serialNumber)R=!0;else{let L=this.demuxer.reader.requestSlice(A.headerStartPos,A.totalSize);L instanceof Promise&&(L=await L),b(L);let Y=F(L,A.totalSize);R=oa(Y)===A.checksum}if(!R){T=A.headerStartPos+4;continue}if(R&&A.serialNumber!==this.bitstream.serialNumber){T=A.headerStartPos+A.totalSize;continue}if(A.granulePosition===-1){T=A.headerStartPos+A.totalSize;continue}this.granulePositionToTimestampInSamples(A.granulePosition)>r?s=A.headerStartPos:(i=A,a.push(A));continue e}}let c=o.startPage;for(let x of a){if(x.granulePosition===i.granulePosition)break;(!c||x.headerStartPos>c.headerStartPos)&&(c=x)}let l=c,u=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===i.granulePosition);){let x=l.headerStartPos+l.totalSize,v=this.demuxer.reader.requestSliceRange(x,Xe,ht);v instanceof Promise&&(v=await v),b(v);let T=Gt(v);b(T),l=T,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}b(l.granulePosition!==-1);let d=null,m,f,p=l,h=0;if(l.headerStartPos===o.startPage.headerStartPos)m=this.granulePositionToTimestampInSamples(0),f=!0,d=0;else{m=0,f=!1;for(let T=l.lacingValues.length-1;T>=0;T--)if(l.lacingValues[T]<255){d=T+1;break}if(d===null)throw new Error("Invalid page with granule position: no packets end on this page.");h=d-1;let x={data:G,endPage:p,endSegmentIndex:h};if(await this.demuxer.findNextPacketStart(x)){let T=da(u,l,d);b(T);let S=ua(u,T.page,T.segmentIndex);S&&(l=S.page,d=S.segmentIndex)}else for(;;){let T=da(u,l,d);if(!T)break;let S=ua(u,T.page,T.segmentIndex);if(!S)break;if(l=S.page,d=S.segmentIndex,T.page.headerStartPos!==p.headerStartPos){p=T.page,h=T.segmentIndex;break}}}let g=null,y=null;for(;l!==null;){b(d!==null);let x=await this.demuxer.readPacket(l,d);if(!x)break;if(!(l.headerStartPos===o.startPage.headerStartPos&&d<o.startSegmentIndex)){let S=this.createEncodedPacketFromOggPacket(x,{timestampInSamples:m,vorbisLastBlocksize:y?.vorbisBlockSize??null},t);b(S);let k=this.encodedPacketToMetadata.get(S);if(b(k),!f&&x.endPage.headerStartPos===p.headerStartPos&&x.endSegmentIndex===h?(m=this.granulePositionToTimestampInSamples(l.granulePosition),f=!0,S=this.createEncodedPacketFromOggPacket(x,{timestampInSamples:m-k.durationInSamples,vorbisLastBlocksize:y?.vorbisBlockSize??null},t),b(S),k=this.encodedPacketToMetadata.get(S),b(k)):m+=k.durationInSamples,g=S,y=k,f&&(Math.max(m,0)>r||Math.max(k.timestampInSamples,0)===r))break}let T=await this.demuxer.findNextPacketStart(x);if(!T)break;l=T.startPage,d=T.startSegmentIndex}return g}async getPacketSequential(e,t){let r=await this.sequentialScanMutex.acquire();try{let o=nt(e*this.internalSampleRate);e=o/this.internalSampleRate;let i=O(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);b(l),this.sequentialScanCache.length>0&&b(ee(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return s}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},ua=(n,e,t)=>{let r=e,o=t;e:for(;;){for(o--,o;o>=0;o--)if(r.lacingValues[o]<255){o++;break e}if(b(o===-1),!(r.headerType&1)){o=0;break}let s=jo(n,a=>a.headerStartPos<r.headerStartPos);if(!s)return null;r=s,o=r.lacingValues.length}if(b(o!==-1),o===r.lacingValues.length){let i=n[n.indexOf(r)+1];b(i),r=i,o=0}return{page:r,segmentIndex:o}},da=(n,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};let r=jo(n,o=>o.headerStartPos<e.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};var Oe;(function(n){n[n.PCM=1]="PCM",n[n.IEEE_FLOAT=3]="IEEE_FLOAT",n[n.ALAW=6]="ALAW",n[n.MULAW=7]="MULAW",n[n.EXTENSIBLE=65534]="EXTENSIBLE"})(Oe||(Oe={}));var zn=class extends J{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),b(e);let t=W(e,4),r=t!=="RIFX",o=t==="RF64",i=ze(e,r),s=o?this.reader.fileSize:Math.min(i+8,this.reader.fileSize??1/0);if(W(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,u=e.filePos;for(;s===null||u<s;){let m=this.reader.requestSlice(u,8);if(m instanceof Promise&&(m=await m),!m)break;let f=W(m,4),p=ze(m,r),h=m.filePos;if(o&&c===0&&f!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(f==="fmt ")await this.parseFmtChunk(h,p,r);else if(f==="data"){if(l??=p,this.dataStart=m.filePos,this.dataSize=Math.min(l,(s??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(f==="ds64"){let g=this.reader.requestSlice(h,p);if(g instanceof Promise&&(g=await g),!g)break;let y=Pi(g,r);l=Pi(g,r),s=Math.min(y+8,this.reader.fileSize??1/0)}else f==="LIST"?await this.parseListChunk(h,p,r):(f==="ID3 "||f==="id3 ")&&await this.parseId3Chunk(h,p);u=h+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 d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.tracks.push(new $(this.input,new Ci(this)))})()}async parseFmtChunk(e,t,r){let o=this.reader.requestSlice(e,t);if(o instanceof Promise&&(o=await o),!o)return;let i=$t(o,r),s=$t(o,r),a=ze(o,r);o.skip(4);let c=$t(o,r),l;if(t===14?l=8:l=$t(o,r),t>=18&&i!==357){let u=$t(o,r),d=t-18;if(Math.min(d,u)>=22&&i===Oe.EXTENSIBLE){o.skip(6);let f=F(o,16);i=f[0]|f[1]<<8}}(i===Oe.MULAW||i===Oe.ALAW)&&(l=8),this.audioInfo={format:i,numberOfChannels:s,sampleRate:a,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}}async parseListChunk(e,t,r){let o=this.reader.requestSlice(e,t);if(o instanceof Promise&&(o=await o),!o)return;let i=W(o,4);if(i!=="INFO"&&i!=="INF0")return;let s=o.filePos;for(;s<=e+t-8;){o.filePos=s;let a=W(o,4),c=ze(o,r),l=F(o,c),u=0;for(let m=0;m<l.length&&l[m]!==0;m++)u++;let d=String.fromCharCode(...l.subarray(0,u));switch(this.metadataTags.raw??={},this.metadataTags.raw[a]=d,a){case"INAM":case"TITL":this.metadataTags.title??=d;break;case"TIT3":this.metadataTags.description??=d;break;case"IART":this.metadataTags.artist??=d;break;case"IPRD":this.metadataTags.album??=d;break;case"IPRT":case"ITRK":case"TRCK":{let m=d.split("/"),f=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{let m=new Date(d);Number.isNaN(m.getTime())||(this.metadataTags.date??=m)}break;case"YEAR":{let m=Number.parseInt(d,10);Number.isInteger(m)&&m>0&&(this.metadataTags.date??=new Date(m,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=d;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=d;break}s+=8+c+(c&1)}}async parseId3Chunk(e,t){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let o=ft(r);if(o){let i=r.slice(e+10,o.size);Mn(i,o,this.metadataTags)}}getCodec(){if(b(this.audioInfo),this.audioInfo.format===Oe.MULAW)return"ulaw";if(this.audioInfo.format===Oe.ALAW)return"alaw";if(this.audioInfo.format===Oe.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===Oe.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 b(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},jt=2048,Ci=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(b(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 b(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Q}getDisposition(){return{...ie}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){b(this.demuxer.audioInfo);let r=e*jt*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;let o=Math.min(jt*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,o);if(c instanceof Promise&&(c=await c),!c)return null}let i;if(t.metadataOnly)i=G;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,o);c instanceof Promise&&(c=await c),b(c),i=F(c,o)}let s=e*jt/this.demuxer.audioInfo.sampleRate,a=o/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,s),new H(i,"key",s,a,e,o)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){b(this.demuxer.audioInfo);let r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/jt,(this.demuxer.dataSize-1)/(jt*this.demuxer.audioInfo.blockSizeInBytes))),o=await this.getPacketAtIndex(r,t);if(o)return o;if(r===0)return null;b(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){b(this.demuxer.audioInfo);let r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/jt);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Xt=7,Kt=9,Pr=n=>{let e=n.filePos,t=F(n,9),r=new V(t);if(r.readBits(12)!==4095||(r.skipBits(1),r.readBits(2)!==0))return null;let s=r.readBits(1),a=r.readBits(2)+1,c=r.readBits(4);if(c===15)return null;r.skipBits(1);let l=r.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);let u=r.readBits(13);r.skipBits(11);let d=r.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let m=null;return s===1?n.filePos-=2:m=r.readBits(16),{objectType:a,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:u,numberOfAacFrames:d,crcCheck:m,startPos:e}};var Ii=1024,Nn=class extends J{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new ke,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();b(this.firstFrameHeader),this.tracks=[new $(this.input,new Ai(this))]})()}async advanceReader(){let e=this.reader.requestSliceRange(this.lastLoadedPos,Xt,Kt);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=Pr(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 r=mr[t.samplingFrequencyIndex];b(r!==void 0);let o=Ii/r,i=t.crcCheck?Kt:Xt,s={timestamp:this.nextTimestampInSamples/r,duration:o,dataStart:t.startPos+i,dataSize:t.frameLength-i};this.loadedSamples.push(s),this.nextTimestampInSamples+=Ii,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 b(e),e.computeDuration()}async getMetadataTags(){return{}}},Ai=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/Ii}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return Q}getCodec(){return"aac"}getInternalCodecId(){return b(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){b(this.demuxer.firstFrameHeader);let e=Qo[this.demuxer.firstFrameHeader.channelConfiguration];return b(e!==void 0),e}getSampleRate(){b(this.demuxer.firstFrameHeader);let e=mr[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return b(e!==void 0),e}getDisposition(){return{...ie}}async getDecoderConfig(){b(this.demuxer.firstFrameHeader);let e=new Uint8Array(3),t=new V(e),{objectType:r,samplingFrequencyIndex:o,channelConfiguration:i}=this.demuxer.firstFrameHeader;return r>31?(t.writeBits(5,31),t.writeBits(6,r-32)):t.writeBits(5,r),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 r=this.demuxer.loadedSamples[e];if(!r)return null;let o;if(t.metadataOnly)o=G;else{let i=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(i instanceof Promise&&(i=await i),!i)return null;o=F(i,r.dataSize)}return new H(o,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{let o=et(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{r()}}async getPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{for(;;){let o=O(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{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var ma=n=>n===0?null:n===1?192:n>=2&&n<=5?144*2**n:n===6?"uncommon-u8":n===7?"uncommon-u16":n>=8&&n<=15?2**n:null,fa=(n,e)=>{switch(n){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}},pa=n=>{let e=0,t=new V(F(n,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);let r=[],o=e-1,i=new V(F(n,o)),s=8-e-1;for(let c=0;c<s;c++)r.unshift(t.readBits(1));for(let c=0;c<o;c++)for(let l=0;l<8;l++){let u=i.readBits(1);l<2||r.unshift(u)}return r.reduce((c,l,u)=>c|l<<u,0)},ha=(n,e)=>{if(e==="uncommon-u16")return X(n)+1;if(e==="uncommon-u8")return E(n)+1;if(typeof e=="number")return e;ue(e),b(!1)},ga=(n,e)=>e==="uncommon-u16"?X(n):e==="uncommon-u16-10"?X(n)*10:e==="uncommon-u8"?E(n):typeof e=="number"?e:null,xa=n=>{let t=0;for(let r of n){t^=r;for(let o=0;o<8;o++)(t&128)!==0?t=t<<1^7:t<<=1,t&=255}return t};var Un=class extends J{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 ke,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),b(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),b(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.`);b(t);let r=E(t),o=je(t),i=(r&128)!==0;switch(r&127){case We.STREAMINFO:{let a=this.reader.requestSlice(e,o);if(a instanceof Promise&&(a=await a),b(a),a===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let c=F(a,34),l=new V(c),u=l.readBits(16),d=l.readBits(16),m=l.readBits(24),f=l.readBits(24),p=l.readBits(20),h=l.readBits(3)+1;l.readBits(5);let g=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:h,sampleRate:p,totalSamples:g,minimumBlockSize:u,maximumBlockSize:d,minimumFrameSize:m,maximumFrameSize:f,description:y},this.track=new $(this.input,new _i(this));break}case We.VORBIS_COMMENT:{let a=this.reader.requestSlice(e,o);a instanceof Promise&&(a=await a),b(a),fr(F(a,o),this.metadataTags);break}case We.PICTURE:{let a=this.reader.requestSlice(e,o);a instanceof Promise&&(a=await a),b(a);let c=P(a),l=P(a),u=K.decode(F(a,l)),d=P(a),m=K.decode(F(a,d));a.skip(16);let f=P(a),p=F(a,f);this.metadataTags.images??=[],this.metadataTags.images.push({data:p,mimeType:u,kind:c===3?"coverFront":c===4?"coverBack":"unknown",description:m});break}default:break}if(e+=o,i){this.lastLoadedPos=e;break}}})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){b(this.audioInfo);let r=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-r)return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:s.end-e,isLastFrame:!0};if(E(s)===255){let l=s.filePos,u=E(s),d=this.blockingBit===1?249:248;if(u!==d){s.filePos=l;continue}s.skip(-2);let m=s.filePos-e,f=this.readFlacFrameHeader({slice:s,isFirstPacket:!1});if(!f){s.filePos=l;continue}if(this.blockingBit===0){if(f.num-a.num!==1){s.filePos=l;continue}}else if(f.num-a.num!==a.blockSize){s.filePos=l;continue}return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:m,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){let r=e.filePos,o=F(e,4),i=new V(o);if(i.readBits(15)!==32764)return null;if(this.blockingBit===null){b(t);let g=i.readBits(1);this.blockingBit=g}else if(this.blockingBit===1){if(b(!t),i.readBits(1)!==1)return null}else if(this.blockingBit===0){if(b(!t),i.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");let a=ma(i.readBits(4));if(!a)return null;b(this.audioInfo);let c=fa(i.readBits(4),this.audioInfo.sampleRate);if(!c||(i.readBits(4),i.readBits(3),i.readBits(1)!==0))return null;let u=pa(e),d=ha(e,a),m=ga(e,c);if(m===null||m!==this.audioInfo.sampleRate)return null;let f=e.filePos-r,p=E(e);e.skip(-f),e.skip(-1);let h=xa(F(e,f));return p!==h?null:{num:u,blockSize:d,sampleRate:m}}async advanceReader(){await this.readMetadata(),b(this.lastLoadedPos!==null),b(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}let r=this.loadedSamples[this.loadedSamples.length-1],i={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(i),t.isLastFrame){this.lastSampleLoaded=!0;return}}},_i=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return b(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 b(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Q}getTimeResolution(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...ie}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return b(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(b(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");let r=await this.demuxer.readingMutex.acquire();try{for(;;){let o=O(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{r()}}async getNextPacket(e,t){let r=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{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let r=this.demuxer.loadedSamples[e];if(!r)return null;let o;if(t.metadataOnly)o=G;else{let a=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(a instanceof Promise&&(a=await a),!a)return null;o=F(a,r.byteSize)}b(this.demuxer.audioInfo);let i=r.blockOffset/this.demuxer.audioInfo.sampleRate,s=r.blockSize/this.demuxer.audioInfo.sampleRate;return new H(o,"key",i,s,e,r.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}};var de=class{},Ir=class extends de{async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);return t instanceof Promise&&(t=await t),!t||(t.skip(4),W(t,4)!=="ftyp")?null:W(t,4)}_createDemuxer(e){return new Sn(e)}},Ln=class extends Ir{async _canReadInput(e){let t=await this._getMajorBrand(e);return!!t&&t!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},Vn=class extends Ir{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},Ar=class extends de{async isSupportedEBMLOfDocType(e,t){let r=e._reader.requestSlice(0,he);if(r instanceof Promise&&(r=await r),!r)return!1;let o=hi(r);if(o===null||o<1||o>8||M(r,o)!==w.EBML)return!1;let s=gi(r);if(s===null)return!1;let a=e._reader.requestSlice(r.filePos,s);if(a instanceof Promise&&(a=await a),!a)return!1;let c=r.filePos;for(;a.filePos<=c+s-ce;){let l=ge(a);if(!l)break;let{id:u,size:d}=l,m=a.filePos;if(d===null)return!1;switch(u){case w.EBMLVersion:if(M(a,d)!==1)return!1;break;case w.EBMLReadVersion:if(M(a,d)!==1)return!1;break;case w.DocType:if($e(a,d)!==t)return!1;break;case w.DocTypeVersion:if(M(a,d)>4)return!1;break}a.filePos=m+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Fn(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},Hn=class extends Ar{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},Wn=class extends de{async _canReadInput(e){let t=e._reader.requestSlice(0,10);if(t instanceof Promise&&(t=await t),!t)return!1;let r=0,o=!1;for(;;){let l=e._reader.requestSlice(r,qt);if(l instanceof Promise&&(l=await l),!l)break;let u=ft(l);if(!u)break;o=!0,r=l.filePos+u.size}let i=await Cr(e._reader,r,r+4096);if(!i)return!1;if(o)return!0;r=i.startPos+i.header.totalSize;let s=await Cr(e._reader,r,r+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 Bn(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},qn=class extends de{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let r=W(t,4);return r!=="RIFF"&&r!=="RIFX"&&r!=="RF64"?!1:(t.skip(4),W(t,4)==="WAVE")}_createDemuxer(e){return new zn(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},Gn=class extends de{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?W(t,4)==="OggS":!1}_createDemuxer(e){return new On(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},jn=class extends de{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?W(t,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Un(e)}},$n=class extends de{async _canReadInput(e){let t=e._reader.requestSliceRange(0,Xt,Kt);if(t instanceof Promise&&(t=await t),!t)return!1;let r=Pr(t);if(!r||(t=e._reader.requestSliceRange(r.frameLength,Xt,Kt),t instanceof Promise&&(t=await t),!t))return!1;let o=Pr(t);return o?r.objectType===o.objectType&&r.samplingFrequencyIndex===o.samplingFrequencyIndex&&r.channelConfiguration===o.channelConfiguration:!1}_createDemuxer(e){return new Nn(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},ba=new Ln,ya=new Vn,va=new Ar,Ta=new Hn,wa=new Wn,ka=new qn,Sa=new Gn,Ca=new $n,Pa=new jn,le=[ba,ya,va,Ta,ka,Sa,Pa,wa,Ca];var gt=class{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new j;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new j;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}};var _r=class extends gt{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&&(!dr(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 Xn({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:Aa.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&&!Le()?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:r,value:o}=await t.read();if(r)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 r=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+r.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(r))}e.running=!1,e.aborted&&await t?.cancel()}_dispose(){this._orchestrator.dispose()}},Ia=.5*2**20,dl=((n,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**(n-2),16)}),Er=class extends gt{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&&(!dr(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??dl,this._orchestrator=new Xn({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:Aa.network})}async _retrieveSize(){let e=new AbortController,t=await Ko(this._options.fetchFn??fetch,this._url,Xo(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 r,o;if(t.status===206)o=this._getTotalLengthFromRangeResponse(t),r=this._orchestrator.createWorker(0,Math.min(o,Ia));else{let i=t.headers.get("Content-Length");if(i)o=Number(i),r=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(r,{response:t,abortController:e}),this._orchestrator.runWorker(r),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 r=t?.abortController,o=t?.response;if(r||(r=new AbortController,o=await Ko(this._options.fetchFn??fetch,this._url,Xo(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:r.signal}),this._getRetryDelay,()=>this._disposed)),b(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){r.abort(),e.running=!1;return}let s;try{s=await i.read()}catch(l){if(this._disposed)throw l;let u=this._getRetryDelay(1,l,this._url);if(u!==null){console.error("Error while reading response stream. Attempting to resume.",l),await new Promise(d=>setTimeout(d,1e3*u));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 r=e.headers.get("Content-Length");if(r)return Number(r);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}};var Aa={none:(n,e)=>({start:n,end:e}),fileSystem:(n,e)=>(n=Math.floor((n-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:n,end:e}),network:(n,e,t)=>{n=Math.max(0,Math.floor((n-65536)/65536)*65536);for(let o of t){let s=Math.max((o.startPos+o.targetPos)/2,o.targetPos-8388608);if(ln(n,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)),u=Math.min(l,c);e=Math.max(e,o.startPos+u)}}return e=Math.max(e,n+Ia),{start:n,end:e}}},Xn=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){b(this.fileSize!==null);let r=this.options.prefetchProfile(e,t,this.workers),o=Math.max(r.start,0),i=Math.min(r.end,this.fileSize);b(o<=e&&t<=i);let s=null,a=O(this.cache,e,x=>x.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=O(this.cache,o,x=>x.start),u=s?null:new Uint8Array(t-e),d=0,m=o,f=[];if(l!==-1){for(let x=l;x<this.cache.length;x++){let v=this.cache[x];if(v.start>=i)break;if(v.end<=o)continue;let T=Math.max(o,v.start),S=Math.min(i,v.end);if(b(T<=S),m<T&&f.push({start:m,end:T}),m=S,u){let k=Math.max(e,v.start),I=Math.min(t,v.end);if(k<I){let C=k-e;u.set(v.bytes.subarray(k-v.start,I-v.start),C),C===d&&(d=I-e)}}v.age=this.nextAge++}m<i&&f.push({start:m,end:i})}else f.push({start:o,end:i});if(u&&d>=u.length&&(s={bytes:u,view:z(u),offset:e}),f.length===0)return b(s),s;let{promise:p,resolve:h,reject:g}=te(),y=[];for(let x of f){let v=Math.max(e,x.start),T=Math.min(t,x.end);v===x.start&&T===x.end?y.push(x):v<T&&y.push({start:v,end:T})}for(let x of f){let v=u&&{start:e,bytes:u,holes:y,resolve:h,reject:g},T=!1;for(let S of this.workers)if(ln(x.start-131072,x.start,S.currentPos,S.targetPos)){S.targetPos=Math.max(S.targetPos,x.end),T=!0,v&&!S.pendingSlices.includes(v)&&S.pendingSlices.push(v),S.running||this.runWorker(S);break}if(!T){let S=this.createWorker(x.start,x.end);v&&(S.pendingSlices=[v]),this.runWorker(S)}}return s||(b(u),s=p.then(x=>({bytes:x,view:z(x),offset:e}))),s}createWorker(e,t){let r={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(r);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 r}runWorker(e){b(!e.running),b(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(r=>r.reject(t)),e.pendingSlices.length=0;else throw t})}supplyWorkerData(e,t){b(!e.aborted);let r=e.currentPos,o=r+t.length;this.insertIntoCache({start:r,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(r,s.start),c=Math.min(o,s.start+s.bytes.length);a<c&&s.bytes.set(t.subarray(a-r,c-r),a-s.start);for(let l=0;l<s.holes.length;l++){let u=s.holes[l];r<=u.start&&o>u.start&&(u.start=o),u.end<=u.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||ln(r,o,s.currentPos,s.targetPos)&&(this.workers.splice(i,1),i--)}}forgetWorker(e){let t=this.workers.indexOf(e);b(t!==-1),this.workers.splice(t,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=O(this.cache,e.start,r=>r.start)+1;if(t>0){let r=this.cache[t-1];if(r.end>=e.end)return;if(r.end>e.start){let o=new Uint8Array(e.end-r.start);o.set(r.bytes,0),o.set(e.bytes,e.start-r.start),this.currentCacheSize+=e.end-r.end,r.bytes=o,r.view=z(o),r.end=e.end,t--,e=r}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let r=t+1;r<this.cache.length;r++){let o=this.cache[r];if(e.end<=o.start)break;if(e.end>=o.end){this.cache.splice(r,1),this.currentCacheSize-=o.bytes.length,r--;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(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let r=0,o=this.cache[0];for(let i=1;i<this.cache.length;i++){let s=this.cache[i];s.age<o.age&&(r=i,o=s)}if(this.currentCacheSize-o.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(r,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}};un();var ne=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 de)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof gt))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 Kn(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(),b(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()}},j=class extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}};var Kn=class{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new j;if(this.fileSize!==null&&e+t>this.fileSize)return null;let r=e+t,o=this.source._read(e,r);return o instanceof Promise?o.then(i=>i?new Ut(i.bytes,i.view,i.offset,e,r):null):o?new Ut(o.bytes,o.view,o.offset,e,r):null}requestSliceRange(e,t,r){if(this.source._disposed)throw new j;if(this.fileSize!==null)return this.requestSlice(e,rt(this.fileSize-e,t,r));{let o=this.requestSlice(e,r),i=s=>{if(s)return s;let a=l=>(b(l!==null),this.requestSlice(e,rt(l-e,t,r))),c=this.source._retrieveSize();return c instanceof Promise?c.then(a):a(c)};return o instanceof Promise?o.then(i):i(o)}}},Ut=class n{constructor(e,t,r,o,i){this.bytes=e,this.view=t,this.offset=r,this.start=o,this.end=i,this.bufferPos=o-r}static tempFromBytes(e){return new n(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 n(this.bytes,this.view,this.offset,e,e+t)}},se=(n,e)=>{if(n.filePos<n.start||n.filePos+e>n.end)throw new RangeError(`Tried reading [${n.filePos}, ${n.filePos+e}), but slice is [${n.start}, ${n.end}). This is likely an internal error, please report it alongside the file that caused it.`)},F=(n,e)=>{se(n,e);let t=n.bytes.subarray(n.bufferPos,n.bufferPos+e);return n.bufferPos+=e,t},E=n=>(se(n,1),n.view.getUint8(n.bufferPos++)),$t=(n,e)=>{se(n,2);let t=n.view.getUint16(n.bufferPos,e);return n.bufferPos+=2,t},X=n=>{se(n,2);let e=n.view.getUint16(n.bufferPos,!1);return n.bufferPos+=2,e},je=n=>{se(n,3);let e=tt(n.view,n.bufferPos,!1);return n.bufferPos+=3,e},Tr=n=>{se(n,2);let e=n.view.getInt16(n.bufferPos,!1);return n.bufferPos+=2,e},ze=(n,e)=>{se(n,4);let t=n.view.getUint32(n.bufferPos,e);return n.bufferPos+=4,t},P=n=>{se(n,4);let e=n.view.getUint32(n.bufferPos,!1);return n.bufferPos+=4,e},pt=n=>{se(n,4);let e=n.view.getUint32(n.bufferPos,!0);return n.bufferPos+=4,e},Re=n=>{se(n,4);let e=n.view.getInt32(n.bufferPos,!1);return n.bufferPos+=4,e},ml=n=>{se(n,4);let e=n.view.getInt32(n.bufferPos,!0);return n.bufferPos+=4,e},Pi=(n,e)=>{let t,r;return e?(t=ze(n,!0),r=ze(n,!0)):(r=ze(n,!1),t=ze(n,!1)),r*4294967296+t},ae=n=>{let e=P(n),t=P(n);return e*4294967296+t},js=n=>{let e=Re(n),t=P(n);return e*4294967296+t},la=n=>{let e=pt(n);return ml(n)*4294967296+e},Xs=n=>{se(n,4);let e=n.view.getFloat32(n.bufferPos,!1);return n.bufferPos+=4,e},Pn=n=>{se(n,8);let e=n.view.getFloat64(n.bufferPos,!1);return n.bufferPos+=8,e},W=(n,e)=>{se(n,e);let t="";for(let r=0;r<e;r++)t+=String.fromCharCode(n.bytes[n.bufferPos++]);return t};var Qn=class{count=0};var _a={extension:{type:Mr.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await import("./browserAll-5AZHDDG6.js")}};var Ea={extension:{type:Mr.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await import("./webworkerAll-QKIC5O27.js")}};var Yn;function Fa(n){return Yn!==void 0||(Yn=(()=>{let e={stencil:!0,failIfMajorPerformanceCaveat:n??Or.defaultOptions.failIfMajorPerformanceCaveat};try{if(!tr.get().getWebGLRenderingContext())return!1;let r=tr.get().createCanvas().getContext("webgl",e),o=!!r?.getContextAttributes()?.stencil;if(r){let i=r.getExtension("WEBGL_lose_context");i&&i.loseContext()}return r=null,o}catch{return!1}})()),Yn}var Zn;async function Da(n={}){return Zn!==void 0||(Zn=await(async()=>{let e=tr.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(n)).requestDevice(),!0}catch{return!1}})()),Zn}var Ra=["webgl","webgpu","canvas"];async function Ei(n){let e=[];n.preference?(e.push(n.preference),Ra.forEach(i=>{i!==n.preference&&e.push(i)})):e=Ra.slice();let t,r={};for(let i=0;i<e.length;i++){let s=e[i];if(s==="webgpu"&&await Da()){let{WebGPURenderer:a}=await import("./WebGPURenderer-RBOFXPL5.js");t=a,r={...n,...n.webgpu};break}else if(s==="webgl"&&Fa(n.failIfMajorPerformanceCaveat??Or.defaultOptions.failIfMajorPerformanceCaveat)){let{WebGLRenderer:a}=await import("./WebGLRenderer-NLGJGAXK.js");t=a,r={...n,...n.webgl};break}else if(s==="canvas")throw r={...n},new Error("CanvasRenderer is not yet implemented")}if(delete r.webgpu,delete r.webgl,!t)throw new Error("No available renderer for the current environment");let o=new t;return await o.init(r),o}var Jn=class extends Gi{constructor(e,t){let{text:r,resolution:o,style:i,anchor:s,width:a,height:c,roundPixels:l,...u}=e;super({...u}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=t,this.text=r??"",this.style=i,this.resolution=o??null,this.allowChildren=!1,this._anchor=new Hi({_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,r=this.bounds.height,o=-t*this.anchor.x,i=0;return e.x>=o&&e.x<=o+t&&(i=-r*this.anchor.y,e.y>=i&&e.y<=i+r)}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 Ma(n,e){let t=n[0]??{};return(typeof t=="string"||n[1])&&(qi(Wi,`use new ${e}({ text: "hi!", style }) instead`),t={text:t,style:n[1]}),t}var Fr=class extends Jn{constructor(...e){let t=Ma(e,"Text");super(t,ji),this.renderPipeId="text",t.textureStyle&&(this.textureStyle=t.textureStyle instanceof wo?t.textureStyle:new wo(t.textureStyle))}updateBounds(){let e=this._bounds,t=this._anchor,r=0,o=0;if(this._style.trim){let{frame:i,canvasAndContext:s}=Co.getCanvasAndContext({text:this.text,style:this._style,resolution:1});Co.returnCanvasAndContext(s),r=i.width,o=i.height}else{let i=$i.measureText(this._text,this._style);r=i.width,o=i.height}e.minX=-t._x*r,e.maxX=e.minX+r,e.minY=-t._y*o,e.maxY=e.minY+o}};Vi.add(_a,Ea);var Ba=n=>{let[e,t,r]=n,[o,i]=e,[s,a]=t,c=r*Math.PI/180,l=Math.cos(c),u=Math.sin(c);return[l*s,u*s,-u*a,l*a,o,i]},Oa=([n,e,t,r,o,i])=>new To(n,e,t,r,o,i);var za=(n,e)=>{let[t,r,o,i,s,a]=n,[c,l,u,d,m,f]=e;return[t*c+o*l,r*c+i*l,t*u+o*d,r*u+i*d,t*m+o*f+s,r*m+i*f+a]},Na=[1,0,0,1,0,0];var Wa=Cc(La(),1);var Va=`
|
|
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 qa({name:n,renderer:e}){let t=Wa.default.find(c=>c.name===n),r=new kt,o=new er,i=new Br({}),s=new Br({}),a=new Po({glProgram:new So({vertex:Va,fragment:Ha(t.glsl)}),resources:{from:i,to:s,uniforms:{...Fi.basics,...Fi.custom(t)}}});return r.filters=[a],{render({width:c,height:l,from:u,to:d,progress:m}){return(r.width!==c||r.height!==l)&&(r.setSize({width:c,height:l}),o.source.resize(c,l)),i.resource=u,s.resource=d,i.update(),s.update(),a.resources.uniforms.uniforms.progress=m,e.render({container:r,target:o,clear:!1,width:c,height:l}),o}}}var eo=class{pixi;static async setup(){let e=await Ei({width:1920,height:1080,preference:"webgl",background:"black",preferWebGLVersion:2}),t=new ko;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:r}=this.pixi;this.#l(this.#a(e));let{dispose:o}=await this.#r(e,t);r.render(t);let i=new VideoFrame(r.canvas,{timestamp:0,duration:0});return o(),i}async#r(e,t){if(Array.isArray(e)){e.reverse();let r=[];for(let o of e){let i=await this.#r(o,t);r.push(i.dispose)}return{dispose:()=>r.forEach(o=>o())}}switch(e.kind){case"text":return this.#n(e,t);case"image":return this.#o(e,t);case"transition":return this.#c(e,t);case"gap":return this.pixi?.renderer.clear(),{dispose:()=>{}};default:return console.warn("Unknown layer kind",e.kind),{dispose:()=>{}}}}#n(e,t){let r=this.#s(e);return this.#i(r,e.matrix),t.addChild(r),{dispose:()=>{}}}#o(e,t){let r=er.from(e.frame),o=this.#s(e);return o.texture=r,this.#i(o,e.matrix),t.addChild(o),{dispose:()=>{r.destroy(!0),e.frame.close()}}}#c({from:e,to:t,progress:r,name:o},i){let a=(this.#e.get(o)??(this.#e.set(o,qa({name:"circle",renderer:this.pixi.renderer})),this.#e.get(o))).render({from:e,to:t,progress:r,width:e.displayWidth,height:e.displayHeight}),c=new kt(a);return i.addChild(c),{dispose:()=>c.destroy(!1)}}#i(e,t){if(!t)return;let r=Oa(t);e.setFromMatrix(r)}#s(e){let t=this.#t.get(e.id);if(t)return t;switch(e.kind){case"text":{let r=new Fr({text:e.content,style:e.style});return r.onmouseenter=()=>console.log("enter text"),this.#t.set(e.id,r).get(e.id)}case"image":{let r=new kt;return r.onmouseenter=()=>console.log("enter"),this.#t.set(e.id,r).get(e.id)}}}#a(e){let t=new Set,r=o=>{if(Array.isArray(o))for(let i of o)r(i);else t.add(o.id)};return r(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 Ga=n=>en.host(e=>({async world(){n.count++}}));async function me(n){return n instanceof Blob?new _r(n):new Er(n)}var to=class{machina;thread;compositor;static async setup(e){let t=new Qn,r=await en.thread({label:"OmnitoolDriver",workerUrl:e?.workerUrl??"/node_modules/@omnimedia/omnitool/x/driver/driver.worker.bundle.min.js",setupHost:Ga(t)}),o=await eo.setup();return new this(t,r,o)}constructor(e,t,r){this.machina=e,this.thread=t,this.compositor=r}async hello(){return this.thread.work.hello()}async getAudioDuration(e){let r=await new ne({source:await me(e),formats:le}).getPrimaryAudioTrack();if(!r)throw new Error("primary audio track not found");return await r.computeDuration()}async getVideoDuration(e){return await(await new ne({source:await me(e),formats:le}).getPrimaryVideoTrack())?.computeDuration()}decodeVideo(e){let t=null,r=new TransformStream({async transform(o,i){let s=await e.onFrame?.(o)??o;t?.close(),i.enqueue(s),t=s}});return this.thread.work.decodeVideo[Pt]({transfer:[r.writable]})({source:e.source,video:r.writable,start:e.start,end:e.end}),r.readable}decodeAudio(e){let t=new TransformStream;return this.thread.work.decodeAudio[Pt]({transfer:[t.writable]})({source:e.source,audio:t.writable,start:e.start,end:e.end}),t.readable}encode({audio:e,video:t,config:r}){let{readable:o,writable:i}=new TransformStream,s=[e,t,i].filter(Nr.happy),a=this.thread.work.encode[Pt]({transfer:s})({audio:e,video:t,config:r,writable:i});return{readable:o,done:a}}async composite(e){return await this.compositor.composite(e)}};var B;(function(n){n[n.Sequence=0]="Sequence",n[n.Stack=1]="Stack",n[n.Video=2]="Video",n[n.Audio=3]="Audio",n[n.Text=4]="Text",n[n.Gap=5]="Gap",n[n.Spatial=6]="Spatial",n[n.Transition=7]="Transition",n[n.TextStyle=8]="TextStyle"})(B||(B={}));var ro;(function(n){n[n.Crossfade=0]="Crossfade"})(ro||(ro={}));var no=class{datafile;duration=0;hasVideo=!1;hasAudio=!1;constructor(e){this.datafile=e}static async analyze(e){let t=new this(e),r=await this.duration(e.url)*1e3;t.duration=r;let{video:o,audio:i}=await this.#e(e.url);return t.hasAudio=i,t.hasVideo=o,t}static async duration(e){let r=await new ne({formats:le,source:await me(e)}).computeDuration();return Number(r.toFixed(5))}static async#e(e){let t=new ne({formats:le,source:await me(e)});return{audio:!!await t.getPrimaryAudioTrack(),video:!!await t.getPrimaryVideoTrack()}}};var oo=class{#e=new Ur;async store(e){let t=await no.analyze(e),{hash:r}=t.datafile.checksum,{filename:o,bytes:i,url:s,blob:a}=t.datafile;if(this.#e.has(r)){let c=this.#e.require(r);c.filename=o}else this.#e.set(r,{kind:"media",filename:o,bytes:i,url:s,blob:a});return t}require(e){return this.#e.require(e)}};var io=class n{videoTrack;options;#e;#t=new Map;#r=[0,0];constructor(e,t){this.videoTrack=e,this.options=t,this.#e=new yr(e,t.canvasSinkOptions)}static async init(e,t){let o=await new ne({formats:le,source:await me(e)}).getPrimaryVideoTrack();if(o)return new n(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.#a())}get frequency(){return this.options.frequency}#n([e,t],r=1){let o=t-e;return[e-o*r,t+o*r]}async#o(){let[e,t]=this.#r,r=new Set,o=await this.videoTrack.computeDuration();for(let i=Math.max(0,e);i<=t;i+=this.options.frequency)i>=0&&i<=o&&r.add(i);this.options.onPlaceholders?.([...r])}async#c(){let[e,t]=this.#r,r=new Set,o=await this.videoTrack.computeDuration();for(let c=Math.max(0,e);c<=t;c+=this.options.frequency)c>=0&&c<=o&&r.add(c);let i=[...r].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())r.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,r]=e,o=r-t,[i,s]=this.#r,a=i+o,c=s-o,l=t<a,u=r>c;!l&&!u||(this.#r=this.#n(e,2),this.#a())}#i=null;#s=!1;async#a(){if(this.#o(),this.#i){this.#s=!0;return}this.#i=this.#c(),await this.#i,this.#i=null,this.#s&&(this.#s=!1,await this.#a())}getThumbnail(e){return this.#t.get(e)}};function oe(n,e,t,r){return new(t||(t=Promise))((function(o,i){function s(l){try{c(r.next(l))}catch(u){i(u)}}function a(l){try{c(r.throw(l))}catch(u){i(u)}}function c(l){var u;l.done?o(l.value):(u=l.value,u instanceof t?u:new t((function(d){d(u)}))).then(s,a)}c((r=r.apply(n,e||[])).next())}))}var yt=class{constructor(){this.listeners={}}on(e,t,r){if(this.listeners[e]||(this.listeners[e]=new Set),r?.once){let o=(...i)=>{this.un(e,o),t(...i)};return this.listeners[e].add(o),()=>this.un(e,o)}return this.listeners[e].add(t),()=>this.un(e,t)}un(e,t){var r;(r=this.listeners[e])===null||r===void 0||r.delete(t)}once(e,t){return this.on(e,t,{once:!0})}unAll(){this.listeners={}}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach((r=>r(...t)))}},so={decode:function(n,e){return oe(this,void 0,void 0,(function*(){let t=new AudioContext({sampleRate:e});try{return yield t.decodeAudioData(n)}finally{t.close()}}))},createBuffer:function(n,e){if(!n||n.length===0)throw new Error("channelData must be a non-empty array");if(e<=0)throw new Error("duration must be greater than 0");if(typeof n[0]=="number"&&(n=[n]),!n[0]||n[0].length===0)throw new Error("channelData must contain non-empty channel arrays");(function(r){let o=r[0];if(o.some((i=>i>1||i<-1))){let i=o.length,s=0;for(let a=0;a<i;a++){let c=Math.abs(o[a]);c>s&&(s=c)}for(let a of r)for(let c=0;c<i;c++)a[c]/=s}})(n);let t=n.map((r=>r instanceof Float32Array?r:Float32Array.from(r)));return{duration:e,length:t[0].length,sampleRate:t[0].length/e,numberOfChannels:t.length,getChannelData:r=>{let o=t[r];if(!o)throw new Error(`Channel ${r} not found`);return o},copyFromChannel:AudioBuffer.prototype.copyFromChannel,copyToChannel:AudioBuffer.prototype.copyToChannel}}};function Qa(n,e){let t=e.xmlns?document.createElementNS(e.xmlns,n):document.createElement(n);for(let[r,o]of Object.entries(e))if(r==="children"&&o)for(let[i,s]of Object.entries(o))s instanceof Node?t.appendChild(s):typeof s=="string"?t.appendChild(document.createTextNode(s)):t.appendChild(Qa(i,s));else r==="style"?Object.assign(t.style,o):r==="textContent"?t.textContent=o:t.setAttribute(r,o.toString());return t}function ja(n,e,t){let r=Qa(n,e||{});return t?.appendChild(r),r}var pl=Object.freeze({__proto__:null,createElement:ja,default:ja}),hl={fetchBlob:function(n,e,t){return oe(this,void 0,void 0,(function*(){let r=yield fetch(n,t);if(r.status>=400)throw new Error(`Failed to fetch ${n}: ${r.status} (${r.statusText})`);return(function(o,i){oe(this,void 0,void 0,(function*(){if(!o.body||!o.headers)return;let s=o.body.getReader(),a=Number(o.headers.get("Content-Length"))||0,c=0,l=u=>{c+=u?.length||0;let d=Math.round(c/a*100);i(d)};try{for(;;){let u=yield s.read();if(u.done)break;l(u.value)}}catch(u){console.warn("Progress tracking error:",u)}}))})(r.clone(),e),r.blob()}))}};function q(n){let e=n,t=new Set;return{get value(){return e},set(r){Object.is(e,r)||(e=r,t.forEach((o=>o(e))))},update(r){this.set(r(e))},subscribe:r=>(t.add(r),()=>t.delete(r))}}function bt(n,e){let t=q(n());return e.forEach((r=>r.subscribe((()=>{let o=n();Object.is(t.value,o)||t.set(o)})))),{get value(){return t.value},subscribe:r=>t.subscribe(r)}}function Qe(n,e){let t,r=()=>{t&&(t(),t=void 0),t=n()},o=e.map((i=>i.subscribe(r)));return r(),()=>{t&&(t(),t=void 0),o.forEach((i=>i()))}}var Di=class extends yt{get isPlayingSignal(){return this._isPlaying}get currentTimeSignal(){return this._currentTime}get durationSignal(){return this._duration}get volumeSignal(){return this._volume}get mutedSignal(){return this._muted}get playbackRateSignal(){return this._playbackRate}get seekingSignal(){return this._seeking}constructor(e){super(),this.isExternalMedia=!1,this.reactiveMediaEventCleanups=[],e.media?(this.media=e.media,this.isExternalMedia=!0):this.media=document.createElement("audio"),this._isPlaying=q(!1),this._currentTime=q(0),this._duration=q(0),this._volume=q(this.media.volume),this._muted=q(this.media.muted),this._playbackRate=q(this.media.playbackRate||1),this._seeking=q(!1),this.setupReactiveMediaEvents(),e.mediaControls&&(this.media.controls=!0),e.autoplay&&(this.media.autoplay=!0),e.playbackRate!=null&&this.onMediaEvent("canplay",(()=>{e.playbackRate!=null&&(this.media.playbackRate=e.playbackRate)}),{once:!0})}setupReactiveMediaEvents(){this.reactiveMediaEventCleanups.push(this.onMediaEvent("play",(()=>{this._isPlaying.set(!0)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("pause",(()=>{this._isPlaying.set(!1)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("ended",(()=>{this._isPlaying.set(!1)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("timeupdate",(()=>{this._currentTime.set(this.media.currentTime)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("durationchange",(()=>{this._duration.set(this.media.duration||0)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("loadedmetadata",(()=>{this._duration.set(this.media.duration||0)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("seeking",(()=>{this._seeking.set(!0)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("seeked",(()=>{this._seeking.set(!1)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("volumechange",(()=>{this._volume.set(this.media.volume),this._muted.set(this.media.muted)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("ratechange",(()=>{this._playbackRate.set(this.media.playbackRate)})))}onMediaEvent(e,t,r){return this.media.addEventListener(e,t,r),()=>this.media.removeEventListener(e,t,r)}getSrc(){return this.media.currentSrc||this.media.src||""}revokeSrc(){let e=this.getSrc();e.startsWith("blob:")&&URL.revokeObjectURL(e)}canPlayType(e){return this.media.canPlayType(e)!==""}setSrc(e,t){let r=this.getSrc();if(e&&r===e)return;this.revokeSrc();let o=t instanceof Blob&&(this.canPlayType(t.type)||!e)?URL.createObjectURL(t):e;if(r&&this.media.removeAttribute("src"),o||e)try{this.media.src=o}catch{this.media.src=e}}destroy(){this.reactiveMediaEventCleanups.forEach((e=>e())),this.reactiveMediaEventCleanups=[],this.isExternalMedia||(this.media.pause(),this.revokeSrc(),this.media.removeAttribute("src"),this.media.load(),this.media.remove())}setMediaElement(e){this.reactiveMediaEventCleanups.forEach((t=>t())),this.reactiveMediaEventCleanups=[],this.media=e,this.setupReactiveMediaEvents()}play(){return oe(this,void 0,void 0,(function*(){try{return yield this.media.play()}catch(e){if(e instanceof DOMException&&e.name==="AbortError")return;throw e}}))}pause(){this.media.pause()}isPlaying(){return!this.media.paused&&!this.media.ended}setTime(e){this.media.currentTime=Math.max(0,Math.min(e,this.getDuration()))}getDuration(){return this.media.duration}getCurrentTime(){return this.media.currentTime}getVolume(){return this.media.volume}setVolume(e){this.media.volume=e}getMuted(){return this.media.muted}setMuted(e){this.media.muted=e}getPlaybackRate(){return this.media.playbackRate}isSeeking(){return this.media.seeking}setPlaybackRate(e,t){t!=null&&(this.media.preservesPitch=t),this.media.playbackRate=e}getMediaElement(){return this.media}setSinkId(e){return this.media.setSinkId(e)}};function gl({maxTop:n,maxBottom:e,halfHeight:t,vScale:r,barMinHeight:o=0,barAlign:i}){let s=Math.round(n*t*r),a=s+Math.round(e*t*r)||1;return a<o&&(a=o,i||(s=a/2)),{topHeight:s,totalHeight:a}}function xl({barAlign:n,halfHeight:e,topHeight:t,totalHeight:r,canvasHeight:o}){return n==="top"?0:n==="bottom"?o-r:e-t}function $a(n,e,t){let r=e-n.left,o=t-n.top;return[r/n.width,o/n.height]}function Ya(n){return!!(n.barWidth||n.barGap||n.barAlign)}function Xa(n,e){if(!Ya(e))return n;let t=e.barWidth||.5,r=t+(e.barGap||t/2);return r===0?n:Math.floor(n/r)*r}function Ka({scrollLeft:n,totalWidth:e,numCanvases:t}){if(e===0)return[0];let r=n/e,o=Math.floor(r*t);return[o-1,o,o+1]}function Za(n){let e=n._cleanup;typeof e=="function"&&e()}function bl(n){let e=q({scrollLeft:n.scrollLeft,scrollWidth:n.scrollWidth,clientWidth:n.clientWidth}),t=bt((()=>(function(i){let{scrollLeft:s,scrollWidth:a,clientWidth:c}=i;if(a===0)return{startX:0,endX:1};let l=s/a,u=(s+c)/a;return{startX:Math.max(0,Math.min(1,l)),endX:Math.max(0,Math.min(1,u))}})(e.value)),[e]),r=bt((()=>(function(i){return{left:i.scrollLeft,right:i.scrollLeft+i.clientWidth}})(e.value)),[e]),o=()=>{e.set({scrollLeft:n.scrollLeft,scrollWidth:n.scrollWidth,clientWidth:n.clientWidth})};return n.addEventListener("scroll",o,{passive:!0}),{scrollData:e,percentages:t,bounds:r,cleanup:()=>{n.removeEventListener("scroll",o),Za(e)}}}var Ri=class extends yt{constructor(e,t){super(),this.timeouts=[],this.isScrollable=!1,this.audioData=null,this.resizeObserver=null,this.lastContainerWidth=0,this.isDragging=!1,this.subscriptions=[],this.unsubscribeOnScroll=[],this.dragStream=null,this.scrollStream=null,this.subscriptions=[],this.options=e;let r=this.parentFromOptionsContainer(e.container);this.parent=r;let[o,i]=this.initHtml();r.appendChild(o),this.container=o,this.scrollContainer=i.querySelector(".scroll"),this.wrapper=i.querySelector(".wrapper"),this.canvasWrapper=i.querySelector(".canvases"),this.progressWrapper=i.querySelector(".progress"),this.cursor=i.querySelector(".cursor"),t&&i.appendChild(t),this.initEvents()}parentFromOptionsContainer(e){let t;if(typeof e=="string"?t=document.querySelector(e):e instanceof HTMLElement&&(t=e),!t)throw new Error("Container not found");return t}initEvents(){this.wrapper.addEventListener("click",(t=>{let r=this.wrapper.getBoundingClientRect(),[o,i]=$a(r,t.clientX,t.clientY);this.emit("click",o,i)})),this.wrapper.addEventListener("dblclick",(t=>{let r=this.wrapper.getBoundingClientRect(),[o,i]=$a(r,t.clientX,t.clientY);this.emit("dblclick",o,i)})),this.options.dragToSeek!==!0&&typeof this.options.dragToSeek!="object"||this.initDrag(),this.scrollStream=bl(this.scrollContainer);let e=Qe((()=>{let{startX:t,endX:r}=this.scrollStream.percentages.value,{left:o,right:i}=this.scrollStream.bounds.value;this.emit("scroll",t,r,o,i)}),[this.scrollStream.percentages,this.scrollStream.bounds]);if(this.subscriptions.push(e),typeof ResizeObserver=="function"){let t=this.createDelay(100);this.resizeObserver=new ResizeObserver((()=>{t().then((()=>this.onContainerResize())).catch((()=>{}))})),this.resizeObserver.observe(this.scrollContainer)}}onContainerResize(){let e=this.parent.clientWidth;e===this.lastContainerWidth&&this.options.height!=="auto"||(this.lastContainerWidth=e,this.reRender(),this.emit("resize"))}initDrag(){if(this.dragStream)return;this.dragStream=(function(t,r={}){let{threshold:o=3,mouseButton:i=0,touchDelay:s=100}=r,a=q(null),c=new Map,l=matchMedia("(pointer: coarse)").matches,u=()=>{},d=m=>{if(m.button!==i||(c.set(m.pointerId,m),c.size>1))return;let f=m.clientX,p=m.clientY,h=!1,g=Date.now(),y=t.getBoundingClientRect(),{left:x,top:v}=y,T=A=>{if(A.defaultPrevented||c.size>1||l&&Date.now()-g<s)return;let R=A.clientX,D=A.clientY,L=R-f,Y=D-p;(h||Math.abs(L)>o||Math.abs(Y)>o)&&(A.preventDefault(),A.stopPropagation(),h||(a.set({type:"start",x:f-x,y:p-v}),h=!0),a.set({type:"move",x:R-x,y:D-v,deltaX:L,deltaY:Y}),f=R,p=D)},S=A=>{if(c.delete(A.pointerId),h){let R=A.clientX,D=A.clientY;a.set({type:"end",x:R-x,y:D-v})}u()},k=A=>{c.delete(A.pointerId),A.relatedTarget&&A.relatedTarget!==document.documentElement||S(A)},I=A=>{h&&(A.stopPropagation(),A.preventDefault())},C=A=>{A.defaultPrevented||c.size>1||h&&A.preventDefault()};document.addEventListener("pointermove",T),document.addEventListener("pointerup",S),document.addEventListener("pointerout",k),document.addEventListener("pointercancel",k),document.addEventListener("touchmove",C,{passive:!1}),document.addEventListener("click",I,{capture:!0}),u=()=>{document.removeEventListener("pointermove",T),document.removeEventListener("pointerup",S),document.removeEventListener("pointerout",k),document.removeEventListener("pointercancel",k),document.removeEventListener("touchmove",C),setTimeout((()=>{document.removeEventListener("click",I,{capture:!0})}),10)}};return t.addEventListener("pointerdown",d),{signal:a,cleanup:()=>{u(),t.removeEventListener("pointerdown",d),c.clear(),Za(a)}}})(this.wrapper);let e=Qe((()=>{let t=this.dragStream.signal.value;if(!t)return;let r=this.wrapper.getBoundingClientRect().width,o=(i=t.x/r)<0?0:i>1?1:i;var i;t.type==="start"?(this.isDragging=!0,this.emit("dragstart",o)):t.type==="move"?this.emit("drag",o):t.type==="end"&&(this.isDragging=!1,this.emit("dragend",o))}),[this.dragStream.signal]);this.subscriptions.push(e)}initHtml(){let e=document.createElement("div"),t=e.attachShadow({mode:"open"}),r=this.options.cspNonce&&typeof this.options.cspNonce=="string"?this.options.cspNonce.replace(/"/g,""):"";return t.innerHTML=`
|
|
2415
|
+
`;function qa({name:n,renderer:e}){let t=Wa.default.find(c=>c.name===n),r=new wt,o=new er,i=new Br({}),s=new Br({}),a=new Po({glProgram:new So({vertex:Va,fragment:Ha(t.glsl)}),resources:{from:i,to:s,uniforms:{...Fi.basics,...Fi.custom(t)}}});return r.filters=[a],{render({width:c,height:l,from:u,to:d,progress:m}){return(r.width!==c||r.height!==l)&&(r.setSize({width:c,height:l}),o.source.resize(c,l)),i.resource=u,s.resource=d,i.update(),s.update(),a.resources.uniforms.uniforms.progress=m,e.render({container:r,target:o,clear:!1,width:c,height:l}),o}}}var eo=class{pixi;static async setup(){let e=await Ei({width:1920,height:1080,preference:"webgl",background:"black",preferWebGLVersion:2}),t=new ko;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:r}=this.pixi;this.#l(this.#a(e));let{dispose:o}=await this.#r(e,t);r.render(t);let i=new VideoFrame(r.canvas,{timestamp:0,duration:0});return o(),i}async#r(e,t){if(Array.isArray(e)){e.reverse();let r=[];for(let o of e){let i=await this.#r(o,t);r.push(i.dispose)}return{dispose:()=>r.forEach(o=>o())}}switch(e.kind){case"text":return this.#n(e,t);case"image":return this.#o(e,t);case"transition":return this.#c(e,t);case"gap":return this.pixi?.renderer.clear(),{dispose:()=>{}};default:return console.warn("Unknown layer kind",e.kind),{dispose:()=>{}}}}#n(e,t){let r=this.#s(e);return this.#i(r,e.matrix),t.addChild(r),{dispose:()=>{}}}#o(e,t){let r=er.from(e.frame),o=this.#s(e);return o.texture=r,this.#i(o,e.matrix),t.addChild(o),{dispose:()=>{r.destroy(!0),e.frame.close()}}}#c({from:e,to:t,progress:r,name:o},i){let a=(this.#e.get(o)??(this.#e.set(o,qa({name:"circle",renderer:this.pixi.renderer})),this.#e.get(o))).render({from:e,to:t,progress:r,width:e.displayWidth,height:e.displayHeight}),c=new wt(a);return i.addChild(c),{dispose:()=>c.destroy(!1)}}#i(e,t){if(!t)return;let r=Oa(t);e.setFromMatrix(r)}#s(e){let t=this.#t.get(e.id);if(t)return t;switch(e.kind){case"text":{let r=new Fr({text:e.content,style:e.style});return r.onmouseenter=()=>console.log("enter text"),this.#t.set(e.id,r).get(e.id)}case"image":{let r=new wt;return r.onmouseenter=()=>console.log("enter"),this.#t.set(e.id,r).get(e.id)}}}#a(e){let t=new Set,r=o=>{if(Array.isArray(o))for(let i of o)r(i);else t.add(o.id)};return r(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 Ga=n=>en.host(e=>({async world(){n.count++}}));async function me(n){return n instanceof Blob?new _r(n):new Er(n)}var to=class{machina;thread;compositor;static async setup(e){let t=new Qn,r=await en.thread({label:"OmnitoolDriver",workerUrl:e?.workerUrl??"/node_modules/@omnimedia/omnitool/x/driver/driver.worker.bundle.min.js",setupHost:Ga(t)}),o=await eo.setup();return new this(t,r,o)}constructor(e,t,r){this.machina=e,this.thread=t,this.compositor=r}async hello(){return this.thread.work.hello()}async getAudioDuration(e){let r=await new ne({source:await me(e),formats:le}).getPrimaryAudioTrack();if(!r)throw new Error("primary audio track not found");return await r.computeDuration()}async getVideoDuration(e){return await(await new ne({source:await me(e),formats:le}).getPrimaryVideoTrack())?.computeDuration()}decodeVideo(e){let t=null,r=new TransformStream({async transform(o,i){let s=await e.onFrame?.(o)??o;t?.close(),i.enqueue(s),t=s}});return this.thread.work.decodeVideo[Pt]({transfer:[r.writable]})({source:e.source,video:r.writable,start:e.start,end:e.end}),r.readable}decodeAudio(e){let t=new TransformStream;return this.thread.work.decodeAudio[Pt]({transfer:[t.writable]})({source:e.source,audio:t.writable,start:e.start,end:e.end}),t.readable}encode({audio:e,video:t,config:r}){let{readable:o,writable:i}=new TransformStream,s=[e,t,i].filter(Nr.happy),a=this.thread.work.encode[Pt]({transfer:s})({audio:e,video:t,config:r,writable:i});return{readable:o,done:a}}async composite(e){return await this.compositor.composite(e)}};var B;(function(n){n[n.Sequence=0]="Sequence",n[n.Stack=1]="Stack",n[n.Video=2]="Video",n[n.Audio=3]="Audio",n[n.Text=4]="Text",n[n.Gap=5]="Gap",n[n.Spatial=6]="Spatial",n[n.Transition=7]="Transition",n[n.TextStyle=8]="TextStyle"})(B||(B={}));var ro;(function(n){n[n.Crossfade=0]="Crossfade"})(ro||(ro={}));var no=class{datafile;duration=0;hasVideo=!1;hasAudio=!1;constructor(e){this.datafile=e}static async analyze(e){let t=new this(e),r=await this.duration(e.url)*1e3;t.duration=r;let{video:o,audio:i}=await this.#e(e.url);return t.hasAudio=i,t.hasVideo=o,t}static async duration(e){let r=await new ne({formats:le,source:await me(e)}).computeDuration();return Number(r.toFixed(5))}static async#e(e){let t=new ne({formats:le,source:await me(e)});return{audio:!!await t.getPrimaryAudioTrack(),video:!!await t.getPrimaryVideoTrack()}}};var oo=class{#e=new Ur;async store(e){let t=await no.analyze(e),{hash:r}=t.datafile.checksum,{filename:o,bytes:i,url:s,blob:a}=t.datafile;if(this.#e.has(r)){let c=this.#e.require(r);c.filename=o}else this.#e.set(r,{kind:"media",filename:o,bytes:i,url:s,blob:a});return t}require(e){return this.#e.require(e)}};var io=class n{videoTrack;options;#e;#t=new Map;#r=[0,0];constructor(e,t){this.videoTrack=e,this.options=t,this.#e=new yr(e,t.canvasSinkOptions)}static async init(e,t){let o=await new ne({formats:le,source:await me(e)}).getPrimaryVideoTrack();if(o)return new n(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.#a())}get frequency(){return this.options.frequency}#n([e,t],r=1){let o=t-e;return[e-o*r,t+o*r]}async#o(){let[e,t]=this.#r,r=new Set,o=await this.videoTrack.computeDuration();for(let i=Math.max(0,e);i<=t;i+=this.options.frequency)i>=0&&i<=o&&r.add(i);this.options.onPlaceholders?.([...r])}async#c(){let[e,t]=this.#r,r=new Set,o=await this.videoTrack.computeDuration();for(let c=Math.max(0,e);c<=t;c+=this.options.frequency)c>=0&&c<=o&&r.add(c);let i=[...r].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())r.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,r]=e,o=r-t,[i,s]=this.#r,a=i+o,c=s-o,l=t<a,u=r>c;!l&&!u||(this.#r=this.#n(e,2),this.#a())}#i=null;#s=!1;async#a(){if(this.#o(),this.#i){this.#s=!0;return}this.#i=this.#c(),await this.#i,this.#i=null,this.#s&&(this.#s=!1,await this.#a())}getThumbnail(e){return this.#t.get(e)}};function oe(n,e,t,r){return new(t||(t=Promise))((function(o,i){function s(l){try{c(r.next(l))}catch(u){i(u)}}function a(l){try{c(r.throw(l))}catch(u){i(u)}}function c(l){var u;l.done?o(l.value):(u=l.value,u instanceof t?u:new t((function(d){d(u)}))).then(s,a)}c((r=r.apply(n,e||[])).next())}))}var bt=class{constructor(){this.listeners={}}on(e,t,r){if(this.listeners[e]||(this.listeners[e]=new Set),r?.once){let o=(...i)=>{this.un(e,o),t(...i)};return this.listeners[e].add(o),()=>this.un(e,o)}return this.listeners[e].add(t),()=>this.un(e,t)}un(e,t){var r;(r=this.listeners[e])===null||r===void 0||r.delete(t)}once(e,t){return this.on(e,t,{once:!0})}unAll(){this.listeners={}}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach((r=>r(...t)))}},so={decode:function(n,e){return oe(this,void 0,void 0,(function*(){let t=new AudioContext({sampleRate:e});try{return yield t.decodeAudioData(n)}finally{t.close()}}))},createBuffer:function(n,e){if(!n||n.length===0)throw new Error("channelData must be a non-empty array");if(e<=0)throw new Error("duration must be greater than 0");if(typeof n[0]=="number"&&(n=[n]),!n[0]||n[0].length===0)throw new Error("channelData must contain non-empty channel arrays");(function(r){let o=r[0];if(o.some((i=>i>1||i<-1))){let i=o.length,s=0;for(let a=0;a<i;a++){let c=Math.abs(o[a]);c>s&&(s=c)}for(let a of r)for(let c=0;c<i;c++)a[c]/=s}})(n);let t=n.map((r=>r instanceof Float32Array?r:Float32Array.from(r)));return{duration:e,length:t[0].length,sampleRate:t[0].length/e,numberOfChannels:t.length,getChannelData:r=>{let o=t[r];if(!o)throw new Error(`Channel ${r} not found`);return o},copyFromChannel:AudioBuffer.prototype.copyFromChannel,copyToChannel:AudioBuffer.prototype.copyToChannel}}};function Qa(n,e){let t=e.xmlns?document.createElementNS(e.xmlns,n):document.createElement(n);for(let[r,o]of Object.entries(e))if(r==="children"&&o)for(let[i,s]of Object.entries(o))s instanceof Node?t.appendChild(s):typeof s=="string"?t.appendChild(document.createTextNode(s)):t.appendChild(Qa(i,s));else r==="style"?Object.assign(t.style,o):r==="textContent"?t.textContent=o:t.setAttribute(r,o.toString());return t}function ja(n,e,t){let r=Qa(n,e||{});return t?.appendChild(r),r}var pl=Object.freeze({__proto__:null,createElement:ja,default:ja}),hl={fetchBlob:function(n,e,t){return oe(this,void 0,void 0,(function*(){let r=yield fetch(n,t);if(r.status>=400)throw new Error(`Failed to fetch ${n}: ${r.status} (${r.statusText})`);return(function(o,i){oe(this,void 0,void 0,(function*(){if(!o.body||!o.headers)return;let s=o.body.getReader(),a=Number(o.headers.get("Content-Length"))||0,c=0,l=u=>{c+=u?.length||0;let d=Math.round(c/a*100);i(d)};try{for(;;){let u=yield s.read();if(u.done)break;l(u.value)}}catch(u){console.warn("Progress tracking error:",u)}}))})(r.clone(),e),r.blob()}))}};function q(n){let e=n,t=new Set;return{get value(){return e},set(r){Object.is(e,r)||(e=r,t.forEach((o=>o(e))))},update(r){this.set(r(e))},subscribe:r=>(t.add(r),()=>t.delete(r))}}function xt(n,e){let t=q(n());return e.forEach((r=>r.subscribe((()=>{let o=n();Object.is(t.value,o)||t.set(o)})))),{get value(){return t.value},subscribe:r=>t.subscribe(r)}}function Ke(n,e){let t,r=()=>{t&&(t(),t=void 0),t=n()},o=e.map((i=>i.subscribe(r)));return r(),()=>{t&&(t(),t=void 0),o.forEach((i=>i()))}}var Di=class extends bt{get isPlayingSignal(){return this._isPlaying}get currentTimeSignal(){return this._currentTime}get durationSignal(){return this._duration}get volumeSignal(){return this._volume}get mutedSignal(){return this._muted}get playbackRateSignal(){return this._playbackRate}get seekingSignal(){return this._seeking}constructor(e){super(),this.isExternalMedia=!1,this.reactiveMediaEventCleanups=[],e.media?(this.media=e.media,this.isExternalMedia=!0):this.media=document.createElement("audio"),this._isPlaying=q(!1),this._currentTime=q(0),this._duration=q(0),this._volume=q(this.media.volume),this._muted=q(this.media.muted),this._playbackRate=q(this.media.playbackRate||1),this._seeking=q(!1),this.setupReactiveMediaEvents(),e.mediaControls&&(this.media.controls=!0),e.autoplay&&(this.media.autoplay=!0),e.playbackRate!=null&&this.onMediaEvent("canplay",(()=>{e.playbackRate!=null&&(this.media.playbackRate=e.playbackRate)}),{once:!0})}setupReactiveMediaEvents(){this.reactiveMediaEventCleanups.push(this.onMediaEvent("play",(()=>{this._isPlaying.set(!0)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("pause",(()=>{this._isPlaying.set(!1)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("ended",(()=>{this._isPlaying.set(!1)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("timeupdate",(()=>{this._currentTime.set(this.media.currentTime)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("durationchange",(()=>{this._duration.set(this.media.duration||0)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("loadedmetadata",(()=>{this._duration.set(this.media.duration||0)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("seeking",(()=>{this._seeking.set(!0)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("seeked",(()=>{this._seeking.set(!1)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("volumechange",(()=>{this._volume.set(this.media.volume),this._muted.set(this.media.muted)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("ratechange",(()=>{this._playbackRate.set(this.media.playbackRate)})))}onMediaEvent(e,t,r){return this.media.addEventListener(e,t,r),()=>this.media.removeEventListener(e,t,r)}getSrc(){return this.media.currentSrc||this.media.src||""}revokeSrc(){let e=this.getSrc();e.startsWith("blob:")&&URL.revokeObjectURL(e)}canPlayType(e){return this.media.canPlayType(e)!==""}setSrc(e,t){let r=this.getSrc();if(e&&r===e)return;this.revokeSrc();let o=t instanceof Blob&&(this.canPlayType(t.type)||!e)?URL.createObjectURL(t):e;if(r&&this.media.removeAttribute("src"),o||e)try{this.media.src=o}catch{this.media.src=e}}destroy(){this.reactiveMediaEventCleanups.forEach((e=>e())),this.reactiveMediaEventCleanups=[],this.isExternalMedia||(this.media.pause(),this.revokeSrc(),this.media.removeAttribute("src"),this.media.load(),this.media.remove())}setMediaElement(e){this.reactiveMediaEventCleanups.forEach((t=>t())),this.reactiveMediaEventCleanups=[],this.media=e,this.setupReactiveMediaEvents()}play(){return oe(this,void 0,void 0,(function*(){try{return yield this.media.play()}catch(e){if(e instanceof DOMException&&e.name==="AbortError")return;throw e}}))}pause(){this.media.pause()}isPlaying(){return!this.media.paused&&!this.media.ended}setTime(e){this.media.currentTime=Math.max(0,Math.min(e,this.getDuration()))}getDuration(){return this.media.duration}getCurrentTime(){return this.media.currentTime}getVolume(){return this.media.volume}setVolume(e){this.media.volume=e}getMuted(){return this.media.muted}setMuted(e){this.media.muted=e}getPlaybackRate(){return this.media.playbackRate}isSeeking(){return this.media.seeking}setPlaybackRate(e,t){t!=null&&(this.media.preservesPitch=t),this.media.playbackRate=e}getMediaElement(){return this.media}setSinkId(e){return this.media.setSinkId(e)}};function gl({maxTop:n,maxBottom:e,halfHeight:t,vScale:r,barMinHeight:o=0,barAlign:i}){let s=Math.round(n*t*r),a=s+Math.round(e*t*r)||1;return a<o&&(a=o,i||(s=a/2)),{topHeight:s,totalHeight:a}}function xl({barAlign:n,halfHeight:e,topHeight:t,totalHeight:r,canvasHeight:o}){return n==="top"?0:n==="bottom"?o-r:e-t}function $a(n,e,t){let r=e-n.left,o=t-n.top;return[r/n.width,o/n.height]}function Ya(n){return!!(n.barWidth||n.barGap||n.barAlign)}function Xa(n,e){if(!Ya(e))return n;let t=e.barWidth||.5,r=t+(e.barGap||t/2);return r===0?n:Math.floor(n/r)*r}function Ka({scrollLeft:n,totalWidth:e,numCanvases:t}){if(e===0)return[0];let r=n/e,o=Math.floor(r*t);return[o-1,o,o+1]}function Za(n){let e=n._cleanup;typeof e=="function"&&e()}function bl(n){let e=q({scrollLeft:n.scrollLeft,scrollWidth:n.scrollWidth,clientWidth:n.clientWidth}),t=xt((()=>(function(i){let{scrollLeft:s,scrollWidth:a,clientWidth:c}=i;if(a===0)return{startX:0,endX:1};let l=s/a,u=(s+c)/a;return{startX:Math.max(0,Math.min(1,l)),endX:Math.max(0,Math.min(1,u))}})(e.value)),[e]),r=xt((()=>(function(i){return{left:i.scrollLeft,right:i.scrollLeft+i.clientWidth}})(e.value)),[e]),o=()=>{e.set({scrollLeft:n.scrollLeft,scrollWidth:n.scrollWidth,clientWidth:n.clientWidth})};return n.addEventListener("scroll",o,{passive:!0}),{scrollData:e,percentages:t,bounds:r,cleanup:()=>{n.removeEventListener("scroll",o),Za(e)}}}var Ri=class extends bt{constructor(e,t){super(),this.timeouts=[],this.isScrollable=!1,this.audioData=null,this.resizeObserver=null,this.lastContainerWidth=0,this.isDragging=!1,this.subscriptions=[],this.unsubscribeOnScroll=[],this.dragStream=null,this.scrollStream=null,this.subscriptions=[],this.options=e;let r=this.parentFromOptionsContainer(e.container);this.parent=r;let[o,i]=this.initHtml();r.appendChild(o),this.container=o,this.scrollContainer=i.querySelector(".scroll"),this.wrapper=i.querySelector(".wrapper"),this.canvasWrapper=i.querySelector(".canvases"),this.progressWrapper=i.querySelector(".progress"),this.cursor=i.querySelector(".cursor"),t&&i.appendChild(t),this.initEvents()}parentFromOptionsContainer(e){let t;if(typeof e=="string"?t=document.querySelector(e):e instanceof HTMLElement&&(t=e),!t)throw new Error("Container not found");return t}initEvents(){this.wrapper.addEventListener("click",(t=>{let r=this.wrapper.getBoundingClientRect(),[o,i]=$a(r,t.clientX,t.clientY);this.emit("click",o,i)})),this.wrapper.addEventListener("dblclick",(t=>{let r=this.wrapper.getBoundingClientRect(),[o,i]=$a(r,t.clientX,t.clientY);this.emit("dblclick",o,i)})),this.options.dragToSeek!==!0&&typeof this.options.dragToSeek!="object"||this.initDrag(),this.scrollStream=bl(this.scrollContainer);let e=Ke((()=>{let{startX:t,endX:r}=this.scrollStream.percentages.value,{left:o,right:i}=this.scrollStream.bounds.value;this.emit("scroll",t,r,o,i)}),[this.scrollStream.percentages,this.scrollStream.bounds]);if(this.subscriptions.push(e),typeof ResizeObserver=="function"){let t=this.createDelay(100);this.resizeObserver=new ResizeObserver((()=>{t().then((()=>this.onContainerResize())).catch((()=>{}))})),this.resizeObserver.observe(this.scrollContainer)}}onContainerResize(){let e=this.parent.clientWidth;e===this.lastContainerWidth&&this.options.height!=="auto"||(this.lastContainerWidth=e,this.reRender(),this.emit("resize"))}initDrag(){if(this.dragStream)return;this.dragStream=(function(t,r={}){let{threshold:o=3,mouseButton:i=0,touchDelay:s=100}=r,a=q(null),c=new Map,l=matchMedia("(pointer: coarse)").matches,u=()=>{},d=m=>{if(m.button!==i||(c.set(m.pointerId,m),c.size>1))return;let f=m.clientX,p=m.clientY,h=!1,g=Date.now(),y=t.getBoundingClientRect(),{left:x,top:v}=y,T=A=>{if(A.defaultPrevented||c.size>1||l&&Date.now()-g<s)return;let R=A.clientX,D=A.clientY,L=R-f,Y=D-p;(h||Math.abs(L)>o||Math.abs(Y)>o)&&(A.preventDefault(),A.stopPropagation(),h||(a.set({type:"start",x:f-x,y:p-v}),h=!0),a.set({type:"move",x:R-x,y:D-v,deltaX:L,deltaY:Y}),f=R,p=D)},S=A=>{if(c.delete(A.pointerId),h){let R=A.clientX,D=A.clientY;a.set({type:"end",x:R-x,y:D-v})}u()},k=A=>{c.delete(A.pointerId),A.relatedTarget&&A.relatedTarget!==document.documentElement||S(A)},I=A=>{h&&(A.stopPropagation(),A.preventDefault())},C=A=>{A.defaultPrevented||c.size>1||h&&A.preventDefault()};document.addEventListener("pointermove",T),document.addEventListener("pointerup",S),document.addEventListener("pointerout",k),document.addEventListener("pointercancel",k),document.addEventListener("touchmove",C,{passive:!1}),document.addEventListener("click",I,{capture:!0}),u=()=>{document.removeEventListener("pointermove",T),document.removeEventListener("pointerup",S),document.removeEventListener("pointerout",k),document.removeEventListener("pointercancel",k),document.removeEventListener("touchmove",C),setTimeout((()=>{document.removeEventListener("click",I,{capture:!0})}),10)}};return t.addEventListener("pointerdown",d),{signal:a,cleanup:()=>{u(),t.removeEventListener("pointerdown",d),c.clear(),Za(a)}}})(this.wrapper);let e=Ke((()=>{let t=this.dragStream.signal.value;if(!t)return;let r=this.wrapper.getBoundingClientRect().width,o=(i=t.x/r)<0?0:i>1?1:i;var i;t.type==="start"?(this.isDragging=!0,this.emit("dragstart",o)):t.type==="move"?this.emit("drag",o):t.type==="end"&&(this.isDragging=!1,this.emit("dragend",o))}),[this.dragStream.signal]);this.subscriptions.push(e)}initHtml(){let e=document.createElement("div"),t=e.attachShadow({mode:"open"}),r=this.options.cspNonce&&typeof this.options.cspNonce=="string"?this.options.cspNonce.replace(/"/g,""):"";return t.innerHTML=`
|
|
2416
2416
|
<style${r?` nonce="${r}"`:""}>
|
|
2417
2417
|
:host {
|
|
2418
2418
|
user-select: none;
|
|
@@ -2485,7 +2485,7 @@ vec4 transition(vec2 uv) {
|
|
|
2485
2485
|
<div class="cursor" part="cursor"></div>
|
|
2486
2486
|
</div>
|
|
2487
2487
|
</div>
|
|
2488
|
-
`,[e,t]}setOptions(e){if(this.options.container!==e.container){let t=this.parentFromOptionsContainer(e.container);t.appendChild(this.container),this.parent=t}e.dragToSeek!==!0&&typeof this.options.dragToSeek!="object"||this.initDrag(),this.options=e,this.reRender()}getWrapper(){return this.wrapper}getWidth(){return this.scrollContainer.clientWidth}getScroll(){return this.scrollContainer.scrollLeft}setScroll(e){this.scrollContainer.scrollLeft=e}setScrollPercentage(e){let{scrollWidth:t}=this.scrollContainer,r=t*e;this.setScroll(r)}destroy(){var e;this.subscriptions.forEach((t=>t())),this.container.remove(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),(e=this.unsubscribeOnScroll)===null||e===void 0||e.forEach((t=>t())),this.unsubscribeOnScroll=[],this.dragStream&&(this.dragStream.cleanup(),this.dragStream=null),this.scrollStream&&(this.scrollStream.cleanup(),this.scrollStream=null)}createDelay(e=10){let t,r,o=()=>{t&&(clearTimeout(t),t=void 0),r&&(r(),r=void 0)};return this.timeouts.push(o),()=>new Promise(((i,s)=>{o(),r=s,t=setTimeout((()=>{t=void 0,r=void 0,i()}),e)}))}getHeight(e,t){var r;let o=((r=this.audioData)===null||r===void 0?void 0:r.numberOfChannels)||1;return(function({optionsHeight:i,optionsSplitChannels:s,parentHeight:a,numberOfChannels:c,defaultHeight:l=128}){if(i==null)return l;let u=Number(i);if(!isNaN(u))return u;if(i==="auto"){let d=a||l;return s?.every((m=>!m.overlay))?d/c:d}return l})({optionsHeight:e,optionsSplitChannels:t,parentHeight:this.parent.clientHeight,numberOfChannels:o,defaultHeight:128})}convertColorValues(e,t){return(function(r,o,i){if(!Array.isArray(r))return r||"";if(r.length===0)return"#999";if(r.length<2)return r[0]||"";let s=document.createElement("canvas"),a=s.getContext("2d"),c=i??s.height*o,l=a.createLinearGradient(0,0,0,c||o),u=1/(r.length-1);return r.forEach(((d,m)=>{l.addColorStop(m*u,d)})),l})(e,this.getPixelRatio(),t?.canvas.height)}getPixelRatio(){return e=window.devicePixelRatio,Math.max(1,e||1);var e}renderBarWaveform(e,t,r,o){let{width:i,height:s}=r.canvas,{halfHeight:a,barWidth:c,barRadius:l,barIndexScale:u,barSpacing:d,barMinHeight:m}=(function({width:p,height:h,length:g,options:y,pixelRatio:x}){let v=h/2,T=y.barWidth?y.barWidth*x:1,S=y.barGap?y.barGap*x:y.barWidth?T/2:0,k=T+S||1;return{halfHeight:v,barWidth:T,barGap:S,barRadius:y.barRadius||0,barMinHeight:y.barMinHeight?y.barMinHeight*x:0,barIndexScale:g>0?p/k/g:0,barSpacing:k}})({width:i,height:s,length:(e[0]||[]).length,options:t,pixelRatio:this.getPixelRatio()}),f=(function({channelData:p,barIndexScale:h,barSpacing:g,barWidth:y,halfHeight:x,vScale:v,canvasHeight:T,barAlign:S,barMinHeight:k}){let I=p[0]||[],C=p[1]||I,A=I.length,R=[],D=0,L=0,Y=0;for(let U=0;U<=A;U++){let Ne=Math.round(U*h);if(Ne>D){let{topHeight:wc,totalHeight:Li}=gl({maxTop:L,maxBottom:Y,halfHeight:x,vScale:v,barMinHeight:k,barAlign:S}),kc=xl({barAlign:S,halfHeight:x,topHeight:wc,totalHeight:Li,canvasHeight:T});R.push({x:D*g,y:kc,width:y,height:Li}),D=Ne,L=0,Y=0}let Ni=Math.abs(I[U]||0),Ui=Math.abs(C[U]||0);Ni>L&&(L=Ni),Ui>Y&&(Y=Ui)}return R})({channelData:e,barIndexScale:u,barSpacing:d,barWidth:c,halfHeight:a,vScale:o,canvasHeight:s,barAlign:t.barAlign,barMinHeight:m});r.beginPath();for(let p of f)l&&"roundRect"in r?r.roundRect(p.x,p.y,p.width,p.height,l):r.rect(p.x,p.y,p.width,p.height);r.fill(),r.closePath()}renderLineWaveform(e,t,r,o){let{width:i,height:s}=r.canvas,a=(function({channelData:c,width:l,height:u,vScale:d}){let m=u/2,f=c[0]||[];return[f,c[1]||f].map(((p,h)=>{let g=p.length,y=g?l/g:0,x=m,v=h===0?-1:1,T=[{x:0,y:x}],S=0,k=0;for(let I=0;I<=g;I++){let C=Math.round(I*y);if(C>S){let R=x+(Math.round(k*m*d)||1)*v;T.push({x:S,y:R}),S=C,k=0}let A=Math.abs(p[I]||0);A>k&&(k=A)}return T.push({x:S,y:x}),T}))})({channelData:e,width:i,height:s,vScale:o});r.beginPath();for(let c of a)if(c.length){r.moveTo(c[0].x,c[0].y);for(let l=1;l<c.length;l++){let u=c[l];r.lineTo(u.x,u.y)}}r.fill(),r.closePath()}renderWaveform(e,t,r){if(r.fillStyle=this.convertColorValues(t.waveColor,r),t.renderFunction)return void t.renderFunction(e,r);let o=(function({channelData:i,barHeight:s,normalize:a,maxPeak:c}){var l;let u=s||1;if(!a)return u;let d=i[0];if(!d||d.length===0)return u;let m=c??0;if(!c)for(let f=0;f<d.length;f++){let p=(l=d[f])!==null&&l!==void 0?l:0,h=Math.abs(p);h>m&&(m=h)}return m?u/m:u})({channelData:e,barHeight:t.barHeight,normalize:t.normalize,maxPeak:t.maxPeak});Ya(t)?this.renderBarWaveform(e,t,r,o):this.renderLineWaveform(e,t,r,o)}renderSingleCanvas(e,t,r,o,i,s,a){let c=this.getPixelRatio(),l=document.createElement("canvas");l.width=Math.round(r*c),l.height=Math.round(o*c),l.style.width=`${r}px`,l.style.height=`${o}px`,l.style.left=`${Math.round(i)}px`,s.appendChild(l);let u=l.getContext("2d");if(t.renderFunction?(u.fillStyle=this.convertColorValues(t.waveColor,u),t.renderFunction(e,u)):this.renderWaveform(e,t,u),l.width>0&&l.height>0){let d=l.cloneNode(),m=d.getContext("2d");m.drawImage(l,0,0),m.globalCompositeOperation="source-in",m.fillStyle=this.convertColorValues(t.progressColor,m),m.fillRect(0,0,l.width,l.height),a.appendChild(d)}}renderMultiCanvas(e,t,r,o,i,s){let a=this.getPixelRatio(),{clientWidth:c}=this.scrollContainer,l=r/a,u=(function({clientWidth:p,totalWidth:h,options:g}){return Xa(Math.min(8e3,p,h),g)})({clientWidth:c,totalWidth:l,options:t}),d={};if(u===0)return;let m=p=>{if(p<0||p>=f||d[p])return;d[p]=!0;let h=p*u,g=Math.min(l-h,u);if(g=Xa(g,t),g<=0)return;let y=(function({channelData:x,offset:v,clampedWidth:T,totalWidth:S}){return x.map((k=>{let I=Math.floor(v/S*k.length),C=Math.floor((v+T)/S*k.length);return k.slice(I,C)}))})({channelData:e,offset:h,clampedWidth:g,totalWidth:l});this.renderSingleCanvas(y,t,g,o,h,i,s)},f=Math.ceil(l/u);if(!this.isScrollable){for(let p=0;p<f;p++)m(p);return}if(Ka({scrollLeft:this.scrollContainer.scrollLeft,totalWidth:l,numCanvases:f}).forEach((p=>m(p))),f>1){let p=this.on("scroll",(()=>{let{scrollLeft:h}=this.scrollContainer;Object.keys(d).length>10&&(i.innerHTML="",s.innerHTML="",d={}),Ka({scrollLeft:h,totalWidth:l,numCanvases:f}).forEach((g=>m(g)))}));this.unsubscribeOnScroll.push(p)}}renderChannel(e,t,r,o){var{overlay:i}=t,s=(function(u,d){var m={};for(var f in u)Object.prototype.hasOwnProperty.call(u,f)&&d.indexOf(f)<0&&(m[f]=u[f]);if(u!=null&&typeof Object.getOwnPropertySymbols=="function"){var p=0;for(f=Object.getOwnPropertySymbols(u);p<f.length;p++)d.indexOf(f[p])<0&&Object.prototype.propertyIsEnumerable.call(u,f[p])&&(m[f[p]]=u[f[p]])}return m})(t,["overlay"]);let a=document.createElement("div"),c=this.getHeight(s.height,s.splitChannels);a.style.height=`${c}px`,i&&o>0&&(a.style.marginTop=`-${c}px`),this.canvasWrapper.style.minHeight=`${c}px`,this.canvasWrapper.appendChild(a);let l=a.cloneNode();this.progressWrapper.appendChild(l),this.renderMultiCanvas(e,s,r,c,a,l)}render(e){return oe(this,void 0,void 0,(function*(){var t;this.timeouts.forEach((l=>l())),this.timeouts=[],this.canvasWrapper.innerHTML="",this.progressWrapper.innerHTML="",this.options.width!=null&&(this.scrollContainer.style.width=typeof this.options.width=="number"?`${this.options.width}px`:this.options.width);let r=this.getPixelRatio(),o=this.scrollContainer.clientWidth,{scrollWidth:i,isScrollable:s,useParentWidth:a,width:c}=(function({duration:l,minPxPerSec:u=0,parentWidth:d,fillParent:m,pixelRatio:f}){let p=Math.ceil(l*u),h=p>d,g=!!(m&&!h);return{scrollWidth:p,isScrollable:h,useParentWidth:g,width:(g?d:p)*f}})({duration:e.duration,minPxPerSec:this.options.minPxPerSec||0,parentWidth:o,fillParent:this.options.fillParent,pixelRatio:r});if(this.isScrollable=s,this.wrapper.style.width=a?"100%":`${i}px`,this.scrollContainer.style.overflowX=this.isScrollable?"auto":"hidden",this.scrollContainer.classList.toggle("noScrollbar",!!this.options.hideScrollbar),this.cursor.style.backgroundColor=`${this.options.cursorColor||this.options.progressColor}`,this.cursor.style.width=`${this.options.cursorWidth}px`,this.audioData=e,this.emit("render"),this.options.splitChannels)for(let l=0;l<e.numberOfChannels;l++){let u=Object.assign(Object.assign({},this.options),(t=this.options.splitChannels)===null||t===void 0?void 0:t[l]);this.renderChannel([e.getChannelData(l)],u,c,l)}else{let l=[e.getChannelData(0)];e.numberOfChannels>1&&l.push(e.getChannelData(1)),this.renderChannel(l,this.options,c,0)}Promise.resolve().then((()=>this.emit("rendered")))}))}reRender(){if(this.unsubscribeOnScroll.forEach((r=>r())),this.unsubscribeOnScroll=[],!this.audioData)return;let{scrollWidth:e}=this.scrollContainer,{right:t}=this.progressWrapper.getBoundingClientRect();if(this.render(this.audioData),this.isScrollable&&e!==this.scrollContainer.scrollWidth){let{right:r}=this.progressWrapper.getBoundingClientRect(),o=(function(i){let s=2*i;return(s<0?Math.floor(s):Math.ceil(s))/2})(r-t);this.scrollContainer.scrollLeft+=o}}zoom(e){this.options.minPxPerSec=e,this.reRender()}scrollIntoView(e,t=!1){let{scrollLeft:r,scrollWidth:o,clientWidth:i}=this.scrollContainer,s=e*o,a=r,c=r+i,l=i/2;if(this.isDragging)s+30>c?this.scrollContainer.scrollLeft+=30:s-30<a&&(this.scrollContainer.scrollLeft-=30);else{(s<a||s>c)&&(this.scrollContainer.scrollLeft=s-(this.options.autoCenter?l:0));let u=s-r-l;t&&this.options.autoCenter&&u>0&&(this.scrollContainer.scrollLeft+=u)}}renderProgress(e,t){if(isNaN(e))return;let r=100*e;this.canvasWrapper.style.clipPath=`polygon(${r}% 0%, 100% 0%, 100% 100%, ${r}% 100%)`,this.progressWrapper.style.width=`${r}%`,this.cursor.style.left=`${r}%`,this.cursor.style.transform=this.options.cursorWidth?`translateX(-${e*this.options.cursorWidth}px)`:"",this.isScrollable&&this.options.autoScroll&&this.audioData&&this.audioData.duration>0&&this.scrollIntoView(e,t)}exportImage(e,t,r){return oe(this,void 0,void 0,(function*(){let o=this.canvasWrapper.querySelectorAll("canvas");if(!o.length)throw new Error("No waveform data");if(r==="dataURL"){let i=Array.from(o).map((s=>s.toDataURL(e,t)));return Promise.resolve(i)}return Promise.all(Array.from(o).map((i=>new Promise(((s,a)=>{i.toBlob((c=>{c?s(c):a(new Error("Could not export image"))}),e,t)})))))}))}},Mi=class extends yt{constructor(){super(...arguments),this.animationFrameId=null,this.isRunning=!1}start(){if(this.isRunning)return;this.isRunning=!0;let e=()=>{this.isRunning&&(this.emit("tick"),this.animationFrameId=requestAnimationFrame(e))};e()}stop(){this.isRunning=!1,this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}destroy(){this.stop()}},Dr=class extends yt{constructor(e=new AudioContext){super(),this.bufferNode=null,this.playStartTime=0,this.playedDuration=0,this._muted=!1,this._playbackRate=1,this._duration=void 0,this.buffer=null,this.currentSrc="",this.paused=!0,this.crossOrigin=null,this.seeking=!1,this.autoplay=!1,this.addEventListener=this.on,this.removeEventListener=this.un,this.audioContext=e,this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination)}load(){return oe(this,void 0,void 0,(function*(){}))}get src(){return this.currentSrc}set src(e){if(this.currentSrc=e,this._duration=void 0,!e)return this.buffer=null,void this.emit("emptied");fetch(e).then((t=>{if(t.status>=400)throw new Error(`Failed to fetch ${e}: ${t.status} (${t.statusText})`);return t.arrayBuffer()})).then((t=>this.currentSrc!==e?null:this.audioContext.decodeAudioData(t))).then((t=>{this.currentSrc===e&&(this.buffer=t,this.emit("loadedmetadata"),this.emit("canplay"),this.autoplay&&this.play())})).catch((t=>{console.error("WebAudioPlayer load error:",t)}))}_play(){if(!this.paused)return;this.paused=!1,this.bufferNode&&(this.bufferNode.onended=null,this.bufferNode.disconnect()),this.bufferNode=this.audioContext.createBufferSource(),this.buffer&&(this.bufferNode.buffer=this.buffer),this.bufferNode.playbackRate.value=this._playbackRate,this.bufferNode.connect(this.gainNode);let e=this.playedDuration*this._playbackRate;(e>=this.duration||e<0)&&(e=0,this.playedDuration=0),this.bufferNode.start(this.audioContext.currentTime,e),this.playStartTime=this.audioContext.currentTime,this.bufferNode.onended=()=>{this.currentTime>=this.duration&&(this.pause(),this.emit("ended"))}}_pause(){var e;this.paused=!0,(e=this.bufferNode)===null||e===void 0||e.stop(),this.playedDuration+=this.audioContext.currentTime-this.playStartTime}play(){return oe(this,void 0,void 0,(function*(){this.paused&&(this._play(),this.emit("play"))}))}pause(){this.paused||(this._pause(),this.emit("pause"))}stopAt(e){let t=e-this.currentTime,r=this.bufferNode;r?.stop(this.audioContext.currentTime+t),r?.addEventListener("ended",(()=>{r===this.bufferNode&&(this.bufferNode=null,this.pause())}),{once:!0})}setSinkId(e){return oe(this,void 0,void 0,(function*(){return this.audioContext.setSinkId(e)}))}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e,this.bufferNode&&(this.bufferNode.playbackRate.value=e)}get currentTime(){return(this.paused?this.playedDuration:this.playedDuration+(this.audioContext.currentTime-this.playStartTime))*this._playbackRate}set currentTime(e){let t=!this.paused;t&&this._pause(),this.playedDuration=e/this._playbackRate,t&&this._play(),this.emit("seeking"),this.emit("timeupdate")}get duration(){var e,t;return(e=this._duration)!==null&&e!==void 0?e:((t=this.buffer)===null||t===void 0?void 0:t.duration)||0}set duration(e){this._duration=e}get volume(){return this.gainNode.gain.value}set volume(e){this.gainNode.gain.value=e,this.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted!==e&&(this._muted=e,this._muted?this.gainNode.disconnect():this.gainNode.connect(this.audioContext.destination))}canPlayType(e){return/^(audio|video)\//.test(e)}getGainNode(){return this.gainNode}getChannelData(){let e=[];if(!this.buffer)return e;let t=this.buffer.numberOfChannels;for(let r=0;r<t;r++)e.push(this.buffer.getChannelData(r));return e}removeAttribute(e){switch(e){case"src":this.src="";break;case"playbackRate":this.playbackRate=0;break;case"currentTime":this.currentTime=0;break;case"duration":this.duration=0;break;case"volume":this.volume=0;break;case"muted":this.muted=!1}}},yl={waveColor:"#999",progressColor:"#555",cursorWidth:1,minPxPerSec:0,fillParent:!0,interact:!0,dragToSeek:!1,autoScroll:!0,autoCenter:!0,sampleRate:8e3},Qt=class n extends Di{static create(e){return new n(e)}getState(){return this.wavesurferState}getRenderer(){return this.renderer}constructor(e){let t=e.media||(e.backend==="WebAudio"?new Dr:void 0);super({media:t,mediaControls:e.mediaControls,autoplay:e.autoplay,playbackRate:e.audioRate}),this.plugins=[],this.decodedData=null,this.stopAtPosition=null,this.subscriptions=[],this.mediaSubscriptions=[],this.abortController=null,this.reactiveCleanups=[],this.options=Object.assign({},yl,e);let{state:r,actions:o}=(function(a){var c,l,u,d,m,f;let p=(c=a?.currentTime)!==null&&c!==void 0?c:q(0),h=(l=a?.duration)!==null&&l!==void 0?l:q(0),g=(u=a?.isPlaying)!==null&&u!==void 0?u:q(!1),y=(d=a?.isSeeking)!==null&&d!==void 0?d:q(!1),x=(m=a?.volume)!==null&&m!==void 0?m:q(1),v=(f=a?.playbackRate)!==null&&f!==void 0?f:q(1),T=q(null),S=q(null),k=q(""),I=q(0),C=q(0),A=bt((()=>!g.value),[g]),R=bt((()=>T.value!==null),[T]),D=bt((()=>R.value&&h.value>0),[R,h]),L=bt((()=>p.value),[p]),Y=bt((()=>h.value>0?p.value/h.value:0),[p,h]);return{state:{currentTime:p,duration:h,isPlaying:g,isPaused:A,isSeeking:y,volume:x,playbackRate:v,audioBuffer:T,peaks:S,url:k,zoom:I,scrollPosition:C,canPlay:R,isReady:D,progress:L,progressPercent:Y},actions:{setCurrentTime:U=>{let Ne=Math.max(0,Math.min(h.value||1/0,U));p.set(Ne)},setDuration:U=>{h.set(Math.max(0,U))},setPlaying:U=>{g.set(U)},setSeeking:U=>{y.set(U)},setVolume:U=>{let Ne=Math.max(0,Math.min(1,U));x.set(Ne)},setPlaybackRate:U=>{let Ne=Math.max(.1,Math.min(16,U));v.set(Ne)},setAudioBuffer:U=>{T.set(U),U&&h.set(U.duration)},setPeaks:U=>{S.set(U)},setUrl:U=>{k.set(U)},setZoom:U=>{I.set(Math.max(0,U))},setScrollPosition:U=>{C.set(Math.max(0,U))}}}})({isPlaying:this.isPlayingSignal,currentTime:this.currentTimeSignal,duration:this.durationSignal,volume:this.volumeSignal,playbackRate:this.playbackRateSignal,isSeeking:this.seekingSignal});this.wavesurferState=r,this.wavesurferActions=o,this.timer=new Mi;let i=t?void 0:this.getMediaElement();this.renderer=new Ri(this.options,i),this.initPlayerEvents(),this.initRendererEvents(),this.initTimerEvents(),this.initReactiveState(),this.initPlugins();let s=this.options.url||this.getSrc()||"";Promise.resolve().then((()=>{this.emit("init");let{peaks:a,duration:c}=this.options;(s||a&&c)&&this.load(s,a,c).catch((l=>{this.emit("error",l instanceof Error?l:new Error(String(l)))}))}))}updateProgress(e=this.getCurrentTime()){return this.renderer.renderProgress(e/this.getDuration(),this.isPlaying()),e}initTimerEvents(){this.subscriptions.push(this.timer.on("tick",(()=>{if(!this.isSeeking()){let e=this.updateProgress();this.emit("timeupdate",e),this.emit("audioprocess",e),this.stopAtPosition!=null&&this.isPlaying()&&e>=this.stopAtPosition&&this.pause()}})))}initReactiveState(){this.reactiveCleanups.push((function(e,t){let r=[];r.push(Qe((()=>{let s=e.isPlaying.value;t.emit(s?"play":"pause")}),[e.isPlaying])),r.push(Qe((()=>{let s=e.currentTime.value;t.emit("timeupdate",s),e.isPlaying.value&&t.emit("audioprocess",s)}),[e.currentTime,e.isPlaying])),r.push(Qe((()=>{e.isSeeking.value&&t.emit("seeking",e.currentTime.value)}),[e.isSeeking,e.currentTime]));let o=!1;r.push(Qe((()=>{e.isReady.value&&!o&&(o=!0,t.emit("ready",e.duration.value))}),[e.isReady,e.duration]));let i=!1;return r.push(Qe((()=>{let s=e.isPlaying.value,a=e.currentTime.value,c=e.duration.value,l=c>0&&a>=c;i&&!s&&l&&t.emit("finish"),i=s&&l}),[e.isPlaying,e.currentTime,e.duration])),r.push(Qe((()=>{let s=e.zoom.value;s>0&&t.emit("zoom",s)}),[e.zoom])),()=>{r.forEach((s=>s()))}})(this.wavesurferState,{emit:this.emit.bind(this)}))}initPlayerEvents(){this.isPlaying()&&(this.emit("play"),this.timer.start()),this.mediaSubscriptions.push(this.onMediaEvent("timeupdate",(()=>{let e=this.updateProgress();this.emit("timeupdate",e)})),this.onMediaEvent("play",(()=>{this.emit("play"),this.timer.start()})),this.onMediaEvent("pause",(()=>{this.emit("pause"),this.timer.stop(),this.stopAtPosition=null})),this.onMediaEvent("emptied",(()=>{this.timer.stop(),this.stopAtPosition=null})),this.onMediaEvent("ended",(()=>{this.emit("timeupdate",this.getDuration()),this.emit("finish"),this.stopAtPosition=null})),this.onMediaEvent("seeking",(()=>{this.emit("seeking",this.getCurrentTime())})),this.onMediaEvent("error",(()=>{var e;this.emit("error",(e=this.getMediaElement().error)!==null&&e!==void 0?e:new Error("Media error")),this.stopAtPosition=null})))}initRendererEvents(){this.subscriptions.push(this.renderer.on("click",((e,t)=>{this.options.interact&&(this.seekTo(e),this.emit("interaction",e*this.getDuration()),this.emit("click",e,t))})),this.renderer.on("dblclick",((e,t)=>{this.emit("dblclick",e,t)})),this.renderer.on("scroll",((e,t,r,o)=>{let i=this.getDuration();this.emit("scroll",e*i,t*i,r,o)})),this.renderer.on("render",(()=>{this.emit("redraw")})),this.renderer.on("rendered",(()=>{this.emit("redrawcomplete")})),this.renderer.on("dragstart",(e=>{this.emit("dragstart",e)})),this.renderer.on("dragend",(e=>{this.emit("dragend",e)})),this.renderer.on("resize",(()=>{this.emit("resize")})));{let e,t=this.renderer.on("drag",(r=>{var o;if(!this.options.interact)return;this.renderer.renderProgress(r),clearTimeout(e);let i=0,s=this.options.dragToSeek;this.isPlaying()?i=0:s===!0?i=200:s&&typeof s=="object"&&(i=(o=s.debounceTime)!==null&&o!==void 0?o:200),e=setTimeout((()=>{this.seekTo(r)}),i),this.emit("interaction",r*this.getDuration()),this.emit("drag",r)}));this.subscriptions.push((()=>{clearTimeout(e),t()}))}}initPlugins(){var e;!((e=this.options.plugins)===null||e===void 0)&&e.length&&this.options.plugins.forEach((t=>{this.registerPlugin(t)}))}unsubscribePlayerEvents(){this.mediaSubscriptions.forEach((e=>e())),this.mediaSubscriptions=[]}setOptions(e){this.options=Object.assign({},this.options,e),e.duration&&!e.peaks&&(this.decodedData=so.createBuffer(this.exportPeaks(),e.duration)),e.peaks&&e.duration&&(this.decodedData=so.createBuffer(e.peaks,e.duration)),this.renderer.setOptions(this.options),e.audioRate&&this.setPlaybackRate(e.audioRate),e.mediaControls!=null&&(this.getMediaElement().controls=e.mediaControls)}registerPlugin(e){if(this.plugins.includes(e))return e;e._init(this),this.plugins.push(e);let t=e.once("destroy",(()=>{this.plugins=this.plugins.filter((r=>r!==e)),this.subscriptions=this.subscriptions.filter((r=>r!==t))}));return this.subscriptions.push(t),e}unregisterPlugin(e){this.plugins=this.plugins.filter((t=>t!==e)),e.destroy()}getWrapper(){return this.renderer.getWrapper()}getWidth(){return this.renderer.getWidth()}getScroll(){return this.renderer.getScroll()}setScroll(e){return this.renderer.setScroll(e)}setScrollTime(e){let t=e/this.getDuration();this.renderer.setScrollPercentage(t)}getActivePlugins(){return this.plugins}loadAudio(e,t,r,o){return oe(this,void 0,void 0,(function*(){var i;if(this.emit("load",e),!this.options.media&&this.isPlaying()&&this.pause(),this.decodedData=null,this.stopAtPosition=null,(i=this.abortController)===null||i===void 0||i.abort(),this.abortController=null,!t&&!r){let a=this.options.fetchParams||{};window.AbortController&&!a.signal&&(this.abortController=new AbortController,a.signal=this.abortController.signal);let c=u=>this.emit("loading",u);t=yield hl.fetchBlob(e,c,a);let l=this.options.blobMimeType;l&&(t=new Blob([t],{type:l}))}this.setSrc(e,t);let s=yield new Promise((a=>{let c=o||this.getDuration();c?a(c):this.mediaSubscriptions.push(this.onMediaEvent("loadedmetadata",(()=>a(this.getDuration())),{once:!0}))}));if(!e&&!t){let a=this.getMediaElement();a instanceof Dr&&(a.duration=s)}if(r)this.decodedData=so.createBuffer(r,s||0);else if(t){let a=yield t.arrayBuffer();this.decodedData=yield so.decode(a,this.options.sampleRate)}this.decodedData&&(this.emit("decode",this.getDuration()),this.renderer.render(this.decodedData)),this.emit("ready",this.getDuration())}))}load(e,t,r){return oe(this,void 0,void 0,(function*(){try{return yield this.loadAudio(e,void 0,t,r)}catch(o){throw this.emit("error",o),o}}))}loadBlob(e,t,r){return oe(this,void 0,void 0,(function*(){try{return yield this.loadAudio("",e,t,r)}catch(o){throw this.emit("error",o),o}}))}zoom(e){if(!this.decodedData)throw new Error("No audio loaded");this.renderer.zoom(e),this.emit("zoom",e)}getDecodedData(){return this.decodedData}exportPeaks({channels:e=2,maxLength:t=8e3,precision:r=1e4}={}){if(!this.decodedData)throw new Error("The audio has not been decoded yet");let o=Math.min(e,this.decodedData.numberOfChannels),i=[];for(let s=0;s<o;s++){let a=this.decodedData.getChannelData(s),c=[],l=a.length/t;for(let u=0;u<t;u++){let d=a.slice(Math.floor(u*l),Math.ceil((u+1)*l)),m=0;for(let f=0;f<d.length;f++){let p=d[f];Math.abs(p)>Math.abs(m)&&(m=p)}c.push(Math.round(m*r)/r)}i.push(c)}return i}getDuration(){let e=super.getDuration()||0;return e!==0&&e!==1/0||!this.decodedData||(e=this.decodedData.duration),e}toggleInteraction(e){this.options.interact=e}setTime(e){this.stopAtPosition=null,super.setTime(e),this.updateProgress(e),this.emit("timeupdate",e)}seekTo(e){let t=this.getDuration()*e;this.setTime(t)}play(e,t){let r=Object.create(null,{play:{get:()=>super.play}});return oe(this,void 0,void 0,(function*(){e!=null&&this.setTime(e);let o=yield r.play.call(this);return t!=null&&(this.media instanceof Dr?this.media.stopAt(t):this.stopAtPosition=t),o}))}playPause(){return oe(this,void 0,void 0,(function*(){return this.isPlaying()?this.pause():this.play()}))}stop(){this.pause(),this.setTime(0)}skip(e){this.setTime(this.getCurrentTime()+e)}empty(){this.load("",[[0]],.001)}setMediaElement(e){this.unsubscribePlayerEvents(),super.setMediaElement(e),this.initPlayerEvents()}exportImage(){return oe(this,arguments,void 0,(function*(e="image/png",t=1,r="dataURL"){return this.renderer.exportImage(e,t,r)}))}destroy(){var e;this.emit("destroy"),(e=this.abortController)===null||e===void 0||e.abort(),this.plugins.forEach((t=>t.destroy())),this.subscriptions.forEach((t=>t())),this.unsubscribePlayerEvents(),this.reactiveCleanups.forEach((t=>t())),this.reactiveCleanups=[],this.timer.destroy(),this.renderer.destroy(),super.destroy()}};Qt.BasePlugin=class extends yt{constructor(n){super(),this.subscriptions=[],this.isDestroyed=!1,this.options=n}onInit(){}_init(n){this.isDestroyed&&(this.subscriptions=[],this.isDestroyed=!1),this.wavesurfer=n,this.onInit()}destroy(){this.emit("destroy"),this.subscriptions.forEach((n=>n())),this.subscriptions=[],this.isDestroyed=!0,this.wavesurfer=void 0}},Qt.dom=pl;var ao=class n{wavesurfer;constructor(e,t,r){this.wavesurfer=Qt.create({container:t,waveColor:"rgb(200, 0, 200)",progressColor:"rgb(100, 0, 100)",barWidth:10,barRadius:10,barGap:2,peaks:[e],duration:r})}static async init(e,t,r){let o=e.decodeAudio({source:t}).getReader(),i=[],s=[],a=1024,c=await e.getAudioDuration(t);for(;;){let{done:l,value:u}=await o.read();if(l)break;let d=u.numberOfFrames,m=new Float32Array(d);u.copyTo(m,{planeIndex:0});for(let f=0;f<m.length;f++)if(s.push(m[f]),s.length>=a){let p=s.splice(0,a),h=Math.min(...p),g=Math.max(...p);i.push(h,g)}u.close()}return new n(i,r,c??0)}set width(e){this.wavesurfer.setOptions({width:e})}};var N=n=>n;var Yt=n=>n;var Ja=()=>{let n=!1,e=Yt(60),t=1e3/e,r=0,o=0,i=Ue(),s=null,a=l=>{if(requestAnimationFrame(a),!!n)for(r=l;l-o>=t;)o+=t,s?.(),s=null,i()};async function*c(){for(r=performance.now(),o=r,requestAnimationFrame(a);;)await new Promise(l=>s=l),yield}return{play(){n||(n=!0,r=performance.now(),o=r)},pause(){n=!1},setFPS(l){e=l,t=1e3/e},isPlaying(){return n},ticks:c,onTick:i}},ec=async(n,e)=>{let t=N(1e3/n.fps),r=n.duration/1e3,o=Math.ceil(r*n.fps);for(let i=0;i<o;i++){let s=N(i*t);await e(s,i)}};var Rr=n=>n;function rc(n){return"duration"in n}function nc(n){let e=[],t=new Map(n.timeline.items.map(r=>[r.id,r]));return Bi(n.timeline.rootId,t,n.from,{sequence:()=>{},stack:()=>{},video:(r,o,i)=>e.push({item:r,localTime:o,ancestors:i}),text:(r,o,i)=>e.push({item:r,localTime:o,ancestors:i}),audio:(r,o,i)=>e.push({item:r,localTime:o,ancestors:i})}),e}function oc(n,e,t){let r=Na;for(let o of e)r=tc(n,o,r);return tc(n,t,r)}function tc(n,e,t){if("spatialId"in e&&e.spatialId){let r=n.get(e.spatialId);if(r?.enabled){let o=Ba(r.transform);return za(o,t)}}return t}function Bi(n,e,t,r,o=[]){let i=e.get(n);if(i)switch(i.kind){case B.Stack:r.stack(i,t,o);for(let s of i.childrenIds)Bi(s,e,t,r,[...o,i]);break;case B.Sequence:{r.sequence(i,t,o);let s=N(0);for(let a of i.childrenIds){let c=e.get(a);if(!c||!rc(c))continue;let l=N(s+c.duration);if(t>=l){s=l;continue}let u=N(Math.max(0,t-s));Bi(a,e,u,r,[...o,i]),s=l}break}case B.Video:r.video(i,t,o);break;case B.Text:r.text(i,t,o);break;case B.Audio:r.audio(i,t,o);break}}function be(n,e){let t=e.items.find(r=>r.id===n);if(!t)return N(0);switch(t.kind){case B.Sequence:{let r=t.childrenIds.map(i=>e.items.find(s=>s.id===i)).filter(Boolean),o=N(0);for(let i=0;i<r.length;i++){let s=r[i];if(s.kind===B.Transition){let a=r[i-1],c=r[i+1];if(a&&c&&a.kind!==B.Transition&&c.kind!==B.Transition){let l=be(a.id,e),u=be(c.id,e),d=Math.max(0,Math.min(s.duration,l,u));o=N(o-d)}continue}o=N(o+be(s.id,e))}return o}case B.Stack:{let r=N(0);for(let o of t.childrenIds){let i=be(o,e);i>r&&(r=i)}return r}default:return rc(t)?t.duration:N(0)}}async function ic(n,e,t){return(await Promise.all(e.map(async({item:o,localTime:i})=>{if(o.kind!==B.Audio)return;let s=await n.getSink(o.mediaHash);if(!s)return;let a=o.start+i,c=Rr((t-a)/1e3),l=s.samples(a/1e3),u=await l.next();if(u.done)return;let d=u.value,m=l.next();return{offset:c,gain:o.gain??1,get currentSample(){return d},timelineTime:()=>Rr(c+d.timestamp),output:()=>({sample:d,timestamp:c+d.timestamp,gain:o.gain??1}),advance:async()=>{let f=await m;return f.done?!1:(d=f.value,m=l.next(),!0)}}}))).filter(o=>!!o)}var co=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 r=new ne({formats:le,source:await me(this.resolveMedia(e))}),o=await r.getPrimaryAudioTrack(),s=!!o&&await o.canDecode()&&o?new vr(o):null;return this.#e.set(e,{input:r,sink:s}),s}};function sc(n){let e={index:0,stream:n[0],time:n[0].timelineTime()};for(let[t,r]of n.entries()){let o=r.timelineTime();o<e.time&&(e={time:o,stream:r,index:t})}return e}function lo(n){let e=new co(n);return{async*sampleAudio(t,r){let o=nc({timeline:t,from:r}),i=await ic(e,o,r);for(;i.length>0;){let{stream:s,index:a}=sc(i);yield s.output(),await s.advance()||i.splice(a,1)}}}}var uo=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 r=new ne({formats:le,source:await me(this.resolveMedia(e))}),o=await r.getPrimaryVideoTrack(),s=!!o&&await o.canDecode()&&o?new Rt(o):null;return this.#e.set(e,{input:r,sink:s}),s}};async function ac(n,e,t,r){let[o,i]=await Promise.all([t,r]),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:n.id,kind:"transition",name:"circle",progress:e,from:s,to:a},...c]:c}async function cc(n,e,t,r){let o=vl(n,e,t);if(!o)return[];let i=[...r,e];return o.isTransitioning?ac(o.transition,o.progress,vt(n,o.outgoing,o.outgoingTime,i),vt(n,o.incoming,o.incomingTime,i)):vt(n,o.item,o.localTime,i)}function vl(n,e,t){let r=e.childrenIds.map(i=>n.items.get(i)).filter(i=>!!i),o=N(0);for(let i=0;i<r.length;i++){let s=r[i];if(s.kind===B.Transition)continue;let a=o,c=be(s.id,n.timeline),l=N(a+c),u=r[i+1];if(!(u?.kind===B.Transition)){if(t<l)return{isTransitioning:!1,item:s,localTime:N(t-a)};o=l;continue}let m=u,f=r[i+2];if(!f||f.kind===B.Transition){o=l;continue}let p=be(f.id,n.timeline),h=Math.max(0,Math.min(m.duration,c,p)),g=N(l-h);if(t<g)return{isTransitioning:!1,item:s,localTime:N(t-a)};if(t<l){let y=N(t-g),x=N(t-a);return{isTransitioning:!0,incoming:f,outgoing:s,outgoingTime:x,incomingTime:y,progress:h>0?y/h:1,transition:m}}o=g,i++}return null}async function vt(n,e,t,r){let o=oc(n.items,r,e);switch(e.kind){case B.Stack:{let i=[...r,e];return(await Promise.all(e.childrenIds.map(a=>n.items.get(a)).filter(a=>!!a).map(a=>vt(n,a,t,i)))).flat()}case B.Sequence:return cc(n,e,t,r);case B.Video:{if(t<0||t>=e.duration)return[];let i=await n.videoSampler(e,t);return i?[{kind:"image",frame:i,matrix:o,id:e.id}]:[]}case B.Text:{if(t<0||t>=e.duration)return[];let i=e.styleId?n.items.get(e.styleId)?.style:void 0;return[{id:e.id,kind:"text",content:e.content,style:i,matrix:o}]}case B.Gap:return[{id:e.id,kind:"gap"}];default:return[]}}function lc(n){return async(e,t)=>{let o=await(await n.getSink(e.mediaHash))?.getSample(t/1e3),i=o?.toVideoFrame();return o?.close(),i??void 0}}function mo(n,e){let t=new uo(n),r=e??lc(t);return{async sample(o,i){let s=new Map(o.items.map(c=>[c.id,c])),a=s.get(o.rootId);return a?vt({videoSampler:r,timeline:o,items:s},a,i,[]):[]}}}var fo=class{timeline;resolveMedia;visualSampler;audioSampler;#e=N(0);#t=null;#r=Ja();onTick=this.#r.onTick;onSeek=Ue();audioContext=new AudioContext({sampleRate:48e3});audioGain=this.audioContext.createGain();audioNodes=new Set;#n=null;constructor(e,t){this.timeline=e,this.resolveMedia=t,this.audioGain.connect(this.audioContext.destination),this.audioGain.gain.value=.7**2,this.visualSampler=mo(this.resolveMedia),this.audioSampler=lo(this.resolveMedia)}async*samples(){for await(let e of this.#r.ticks())yield this.visualSampler.sample(this.timeline,this.currentTime)}async seek(e){return this.pause(),this.#e=e,this.onSeek.publish(),await this.visualSampler.sample(this.timeline,e)}async start(e){this.timeline=e,await this.audioContext.resume(),this.#e=this.currentTime,this.#t=this.audioContext.currentTime,this.#n?.abort(),this.#n=new AbortController;for(let t of this.audioNodes)t.stop();this.audioNodes.clear(),this.#r.play(),this.#o(this.#n.signal,Rr(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()}get currentTime(){if(!this.#r.isPlaying()||this.#t===null)return this.#e;let e=(this.audioContext.currentTime-this.#t)*1e3;return N(this.#e+e)}setFps(e){this.#r.setFPS(e)}async#o(e,t){let r=this.audioContext;if(this.#t!==null)for await(let{sample:o,timestamp:i}of this.audioSampler.sampleAudio(this.timeline,N(t*1e3))){if(e.aborted||!this.#r.isPlaying())return;for(;i-(r.currentTime-this.#t+t)>.75;)await new Promise(c=>setTimeout(c,25));let s=r.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>=r.currentTime?s.start(a):s.start(r.currentTime,r.currentTime-a)}}};var po=class{driver;timeline;canvas;playback;constructor(e,t,r){this.driver=e,this.timeline=r,this.playback=new fo(r,t),this.canvas=e.compositor.pixi.renderer.canvas}async play(){await this.playback.start(this.timeline);for await(let e of this.playback.samples())(await this.driver.composite(e)).close(),this.currentTime>=this.duration&&this.pause()}pause(){this.playback.pause()}async seek(e){let t=await this.playback.seek(N(e));(await this.driver.composite(t)).close()}setFPS(e){this.playback.setFps(Yt(e))}get duration(){return be(this.timeline.rootId,this.timeline)}get currentTime(){return this.playback.currentTime}async update(e){this.timeline=e}};var Tt=class{state;constructor(e){this.state=e}require(e){return e===void 0?void 0:this.state.timeline.items.find(r=>r.id===e)}get timeline(){return this.state.timeline}#e(){return ye.toInteger(ye.random())}#t(e){this.state.timeline=e(this.state.timeline)}register(e){this.#t(t=>({...t,items:[...t.items,e]}))}textStyle=e=>{let t={id:this.#e(),kind:B.TextStyle,style:e};return this.register(t),t};spatial=e=>{let t={id:this.#e(),kind:B.Spatial,transform:e,enabled:!0};return this.register(t),t};sequence=(...e)=>{let t={id:this.#e(),kind:B.Sequence,childrenIds:e.map(r=>r.id)};return this.register(t),t};stack=(...e)=>{let t={kind:B.Stack,id:this.#e(),childrenIds:e.map(r=>r.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 r={kind:B.Video,id:this.#e(),mediaHash:e.datafile.checksum.hash,start:t?.start??0,duration:t?.duration??e.duration};return this.register(r),r};audio=(e,t)=>{if(!e.hasAudio)throw new Error(`Audio clip error: media "${e.datafile.filename}" has no audio track.`);let r={kind:B.Audio,id:this.#e(),mediaHash:e.datafile.checksum.hash,start:t?.start??0,duration:t?.duration??e.duration,gain:t?.gain??1};return this.register(r),r};text=(e,t)=>{let r={id:this.#e(),content:e,kind:B.Text,duration:t?.duration??2e3};return t?.styles&&(r.styleId=this.textStyle(t.styles).id),this.register(r),r};gap=e=>{let t={id:this.#e(),kind:B.Gap,duration:e};return this.register(t),t};transition={crossfade:e=>{let t={id:this.#e(),kind:B.Transition,effect:ro.Crossfade,duration:e};return this.register(t),t}};transform=e=>{let t=[e?.position?.[0]??0,e?.position?.[1]??0],r=[e?.scale?.[0]??1,e?.scale?.[1]??1],o=e?.rotation??0;return[t,r,o]};addChildren(e,...t){this.#t(r=>(r.items.find(({id:i})=>i===e.id).childrenIds.push(...t.map(i=>i.id)),r))}set=(e,t)=>{this.#t(r=>({...r,items:r.items.map(o=>o.id===e?{...o,...t}:o)}))}};var ho=class{#e;#t;constructor(e={}){this.#e=e.chunkFrames??1024,this.#t=e.clamp??!0}async*mix(e){let t=this.#e,r=null,o=null,i=[],s=0,a=0;for await(let c of e){if(o===null)o=c.planes.length,r=c.sampleRate;else{if(c.planes.length!==o)throw new Error("Channel count changed");if(c.sampleRate!==r)throw new Error("Sample rate changed")}let l=Math.round(c.timestamp*r),u=c.planes[0]?.length??0;for(;s+t<=l;)yield this.#r(i,s,o,r),s+=t;i.push({startFrame:l,endFrame:l+u,data:c.planes}),a=Math.max(a,l+u)}if(o!==null&&r!==null)for(;s<a;)yield this.#r(i,s,o,r),s+=t}#r(e,t,r,o){let i=this.#e,s=new Float32Array(r*i),a=t+i;for(let c=0;c<r;c++){let l=c*i,u=s.subarray(l,l+i);for(let d of e){let m=d.data[c];if(!m)continue;let f=Math.max(t,d.startFrame),p=Math.min(a,d.endFrame);if(f>=p)continue;let h=f-t,g=f-d.startFrame,y=p-f;for(let x=0;x<y;x++)u[h+x]+=m[g+x]}if(this.#t)for(let d=0;d<i;d++){let m=u[d];u[d]=m<-1?-1:m>1?1:m}}for(let c=e.length-1;c>=0;c--)e[c].endFrame<=a&&e.splice(c,1);return{planar:s,sampleRate:o,channels:r,frames:i,startFrame:t}}};var Tl=(n,e,t)=>{if(e===t)return n;let r=t/e,o=Math.max(1,Math.round(n.length*r)),i=new Float32Array(o);for(let s=0;s<o;s++){let a=s/r,c=Math.floor(a),l=Math.min(c+1,n.length-1),u=a-c;i[s]=n[c]*(1-u)+n[l]*u}return i},uc=(n,e)=>{let t=n.numberOfChannels,r=new Array(t),o=0;for(let i=0;i<t;i++){let s=new Float32Array(n.numberOfFrames);n.copyTo(s,{planeIndex:i,format:"f32-planar"});let a=Tl(s,n.sampleRate,e);r[i]=a,o=a.length}return{data:r,frames:o}};var dc=(n,e)=>{if(e!==1)for(let t of n)for(let r=0;r<t.length;r++)t[r]*=e};function mc({timeline:n,resolveMedia:e}){let t=new ho,r=wl(n,e),o=new TransformStream,i=o.writable.getWriter();async function s(){for await(let a of t.mix(r)){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*wl(n,e){let t=lo(e);for await(let{sample:r,timestamp:o,gain:i}of t.sampleAudio(n,N(0))){let{data:s}=uc(r,48e3);dc(s,i),yield{planes:s,sampleRate:48e3,timestamp:o},r.close()}}var go=class{driver;resolveMedia;#e;#t=new Map;constructor(e,t){this.driver=e,this.resolveMedia=t,this.#e=mo(t,(r,o)=>{let i=kl(N(r.start+o));return this.#r(r).next(i)})}cursor(e){let t=Number.NEGATIVE_INFINITY;return{next:r=>{if(r<t)throw new Error(`CursorVisualSampler is forward-only: requested ${r}ms after ${t}ms`);return t=r,this.#e.sample(e,r)},cancel:()=>this.#n()}}#r(e){let t=this.#t.get(e.id);if(t)return t;let r=this.resolveMedia(e.mediaHash),o=this.driver.decodeVideo({source:r}),i=this.#o(o.getReader());return this.#t.set(e.id,i),i}async#n(){await Promise.all([...this.#t.values()].map(e=>e.cancel())),this.#t.clear()}#o(e){return{async next(t){let r=null;for(;;){let{done:o,value:i}=await e.read();if(o){let a=r?new VideoFrame(r):void 0;return r?.close(),a}let s=i.timestamp??0;if(s>=t){let a=r?.timestamp??Number.NEGATIVE_INFINITY,c=!!r&&Math.abs(a-t)<Math.abs(s-t),l=c?r:i,u=c?i:r,d=new VideoFrame(l);return l.close(),u?.close(),d}r?.close(),r=i}},cancel:async()=>await e.cancel()}}},kl=n=>Math.round(n*1e3);function fc({timeline:n,fps:e,driver:t,resolveMedia:r}){let o=new TransformStream,i=o.writable.getWriter(),a=new go(t,r).cursor(n),c=1/e,l=be(n.rootId,n);async function u(){await ec({fps:e,duration:l},async(d,m)=>{let f=await a.next(d),p=await t.composite(f),h=new VideoFrame(p,{timestamp:Math.round(m*c*1e6),duration:Math.round(c*1e6)});await i.write(h),p.close()}),await i.close()}return u(),o.readable}function pc(n){let e=mc({...n}),t=fc({...n});return n.driver.encode({video:t,audio:e,config:{audio:{codec:"opus",bitrate:128e3},video:{codec:"vp9",bitrate:1e6}}})}var xo=class{driver;resources=new oo;constructor(e){this.driver=e}load=async e=>Object.fromEntries(await Promise.all(Object.entries(e).map(async([t,r])=>[t,await this.resources.store(await r)])));timeline=e=>{let t=new Tt({timeline:{format:"timeline",info:"https://omniclip.app/",version:0,items:[],rootId:0}}),r=e(t);return t.timeline.rootId=r.id,t.timeline};playback=async e=>new po(this.driver,t=>this.resources.require(t).url,e);render=async(e,t=30)=>pc({timeline:e,fps:Yt(t),driver:this.driver,resolveMedia:r=>this.resources.require(r).url})};var bo=class{data;bytes;hash;nickname;constructor(e,t,r,o){this.data=e,this.bytes=t,this.hash=r,this.nickname=o}static async make(e){let t=new Uint8Array(e),r=new Uint8Array(await crypto.subtle.digest("SHA-256",t)),o=zr.fromBytes(r),i=Xi.sigil.fromBytes(r);return new this(e,r,o,i)}};var yo=class{url;bytes;blob;filename;checksum;constructor(e,t,r,o,i){this.url=e,this.bytes=t,this.blob=r,this.filename=o,this.checksum=i}static async make(e,t){let r=await e.arrayBuffer(),o=new Uint8Array(r),i=await bo.make(o),s=t??i.nickname,a=URL.createObjectURL(e);return new this(a,o,e,s,i)}static async load(e){}};async function gc(n,e,t){let r=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 Tt({timeline:n}),u=await e.playback(n);c.replaceChildren(u.canvas),r.disabled=!1,o.disabled=!1,r.addEventListener("click",()=>u.play()),o.addEventListener("click",()=>u.pause()),i.max=String(Math.ceil(u.duration));let d=!1,m=null,f=!1;u.playback.onTick.on(()=>g(u.currentTime,u.duration));let p=async y=>{if(m=y,!f){for(f=!0;m;){let x=m;m=null,await u.seek(x)}f=!1}},h=(y,x)=>{a.textContent=`${hc(y)} / ${hc(x)}`};i.addEventListener("input",async()=>{d=!0;let y=Math.max(0,Math.min(+i.value,u.duration));h(y,u.duration),await p(y)}),i.addEventListener("change",async()=>{d=!1;let y=Math.max(0,Math.min(+i.value,u.duration));await p(y)});let g=(y,x)=>{let v=Math.max(0,Math.min(y,x));d||(i.value=String(Math.round(v)));let T=x?v/x*100:0;s.style.left=`${T}%`,h(v,x)};u.update(l.timeline)}function hc(n){let e=Math.max(0,n),t=Math.floor(e/1e3),r=Math.floor(t/60),o=t%60,i=Math.floor(e%1e3);return`${r}:${String(o).padStart(2,"0")}.${String(i).padStart(3,"0")}`}async function xc(n,e,t){let r=t.querySelector(".waveform-canvas"),o=t.querySelector(".width");r.replaceChildren();let i=await ao.init(n,e,r);o.oninput=()=>{let s=+o.value;i.width=s}}async function Oi(n,e){let t=new xo(n),{videoA:r}=await t.load({videoA:yo.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(r,{duration:3e3,start:1e3}),i.audio(r,{duration:1e3})),i.gap(500),i.video(r,{duration:7e3,start:5e3}))}),omni:t}}async function bc(n,e){let t=e.querySelector(".range"),r=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 u=await io.init(n,{onChange(d){let m=d.sort((f,p)=>f.time-p.time);a.replaceChildren(...m.map(({time:f,canvas:p})=>Sl(f,p.canvas)))},frequency:c,canvasSinkOptions:{width:80,height:50,fit:"fill"}});o.oninput=()=>{l=+o.value;let d=+t.value,m=d+l;u.range=[d,m],r.textContent=`visible time range: [${d}, ${m}]`},t.oninput=()=>{let d=+t.value,m=d+l;u.range=[d,m],r.textContent=`visible time range: [${d}, ${m}]`},i.oninput=()=>{u.frequency=1/+i.value,s.textContent=`frame every ${u.frequency.toFixed(3)} second (${i.value} frames per second)`},u.range=[10,10.5]}function Sl(n,e){let t=document.createElement("div");t.style.position="relative",t.style.display="inline-block",t.style.marginRight="4px",t.appendChild(e);let r=document.createElement("div");return r.textContent=`${n.toFixed(2)}s`,r.style.position="absolute",r.style.top="2px",r.style.right="4px",r.style.fontSize="10px",r.style.color="white",r.style.background="rgba(0,0,0,0.6)",r.style.padding="2px 4px",r.style.borderRadius="4px",r.style.pointerEvents="none",t.appendChild(r),t}function yc(n,e){let t={width:1920,height:1080},r=document.createElement("canvas");r.width=t.width,r.height=t.height;let o=r.getContext("2d");async function i(){let s=n.decodeVideo({source:e,async onFrame(m){let f=await n.composite([{id:0,kind:"image",frame:m},{id:1,kind:"text",content:"omnitool",style:{fontSize:50,fill:"green"}}]);return m.close(),o?.drawImage(f,0,0),f}}),a=n.decodeAudio({source:e}),{readable:c,done:l}=n.encode({video:s,audio:a,config:{audio:{codec:"opus",bitrate:128e3},video:{codec:"vp9",bitrate:1e6}}}),d=await(await window.showSaveFilePicker()).createWritable();await Promise.all([c.pipeTo(d),l])}return{canvas:r,run:i}}var Zt=await to.setup({workerUrl:new URL("../driver/driver.worker.bundle.min.js",import.meta.url)}),Cl=document.querySelector("[data-demo='transcode']"),Pl=document.querySelector("[data-demo='filmstrip']"),Il=document.querySelector("[data-demo='waveform']"),vc=document.querySelector("[data-demo='playback']"),wt=document.querySelector("[data-demo='export']"),Tc=wt.querySelector("[data-action='export']"),vo=null;await Zt.thread.work.hello(),Zt.machina.count===1?console.log("\u2705 driver works"):console.error("\u274C FAIL driver call didn't work");var Jt=(n,e)=>{let t=n.querySelector(".progress"),r=n.querySelector(".status");e==="running"?(t.removeAttribute("value"),r.textContent="running"):e==="done"?(t.value=1,r.textContent="done"):(t.value=0,r.textContent="idle")},zi=(n,e)=>{let t=n.querySelector("input[type='file']"),r=n.querySelector("[data-action='run']");r.disabled=!0,t.addEventListener("input",()=>{r.disabled=!t.files?.length}),r.addEventListener("click",async()=>{let o=t.files?.[0];if(o){r.disabled=!0,Jt(n,"running");try{await e(o,n),Jt(n,"done")}finally{r.disabled=!1}}})};zi(Cl,async(n,e)=>{let t=e.querySelector(".demo-preview"),r=yc(Zt,n);t.replaceChildren(r.canvas),await r.run()});zi(Pl,async(n,e)=>{await bc(n,e)});zi(Il,async(n,e)=>{await xc(Zt,n,e)});{let n=vc.querySelector("input[type='file']");n.addEventListener("input",async()=>{let e=n.files?.[0];if(!e)return;let{timeline:t,omni:r}=await Oi(Zt,e);await gc(t,r,vc)})}{let n=wt.querySelector("input[type='file']");n.addEventListener("input",async()=>{let e=n.files?.[0];if(!e)return;Jt(wt,"running");let{timeline:t,omni:r}=await Oi(Zt,e);vo={timeline:t,omni:r},Tc.disabled=!1;let o=wt.querySelector(".demo-preview"),i=await r.playback(t);await i.seek(0),o.replaceChildren(i.canvas),Jt(wt,"done")})}Tc.addEventListener("click",async()=>{vo&&(Jt(wt,"running"),await vo.omni.render(vo.timeline),Jt(wt,"done"))});
|
|
2488
|
+
`,[e,t]}setOptions(e){if(this.options.container!==e.container){let t=this.parentFromOptionsContainer(e.container);t.appendChild(this.container),this.parent=t}e.dragToSeek!==!0&&typeof this.options.dragToSeek!="object"||this.initDrag(),this.options=e,this.reRender()}getWrapper(){return this.wrapper}getWidth(){return this.scrollContainer.clientWidth}getScroll(){return this.scrollContainer.scrollLeft}setScroll(e){this.scrollContainer.scrollLeft=e}setScrollPercentage(e){let{scrollWidth:t}=this.scrollContainer,r=t*e;this.setScroll(r)}destroy(){var e;this.subscriptions.forEach((t=>t())),this.container.remove(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),(e=this.unsubscribeOnScroll)===null||e===void 0||e.forEach((t=>t())),this.unsubscribeOnScroll=[],this.dragStream&&(this.dragStream.cleanup(),this.dragStream=null),this.scrollStream&&(this.scrollStream.cleanup(),this.scrollStream=null)}createDelay(e=10){let t,r,o=()=>{t&&(clearTimeout(t),t=void 0),r&&(r(),r=void 0)};return this.timeouts.push(o),()=>new Promise(((i,s)=>{o(),r=s,t=setTimeout((()=>{t=void 0,r=void 0,i()}),e)}))}getHeight(e,t){var r;let o=((r=this.audioData)===null||r===void 0?void 0:r.numberOfChannels)||1;return(function({optionsHeight:i,optionsSplitChannels:s,parentHeight:a,numberOfChannels:c,defaultHeight:l=128}){if(i==null)return l;let u=Number(i);if(!isNaN(u))return u;if(i==="auto"){let d=a||l;return s?.every((m=>!m.overlay))?d/c:d}return l})({optionsHeight:e,optionsSplitChannels:t,parentHeight:this.parent.clientHeight,numberOfChannels:o,defaultHeight:128})}convertColorValues(e,t){return(function(r,o,i){if(!Array.isArray(r))return r||"";if(r.length===0)return"#999";if(r.length<2)return r[0]||"";let s=document.createElement("canvas"),a=s.getContext("2d"),c=i??s.height*o,l=a.createLinearGradient(0,0,0,c||o),u=1/(r.length-1);return r.forEach(((d,m)=>{l.addColorStop(m*u,d)})),l})(e,this.getPixelRatio(),t?.canvas.height)}getPixelRatio(){return e=window.devicePixelRatio,Math.max(1,e||1);var e}renderBarWaveform(e,t,r,o){let{width:i,height:s}=r.canvas,{halfHeight:a,barWidth:c,barRadius:l,barIndexScale:u,barSpacing:d,barMinHeight:m}=(function({width:p,height:h,length:g,options:y,pixelRatio:x}){let v=h/2,T=y.barWidth?y.barWidth*x:1,S=y.barGap?y.barGap*x:y.barWidth?T/2:0,k=T+S||1;return{halfHeight:v,barWidth:T,barGap:S,barRadius:y.barRadius||0,barMinHeight:y.barMinHeight?y.barMinHeight*x:0,barIndexScale:g>0?p/k/g:0,barSpacing:k}})({width:i,height:s,length:(e[0]||[]).length,options:t,pixelRatio:this.getPixelRatio()}),f=(function({channelData:p,barIndexScale:h,barSpacing:g,barWidth:y,halfHeight:x,vScale:v,canvasHeight:T,barAlign:S,barMinHeight:k}){let I=p[0]||[],C=p[1]||I,A=I.length,R=[],D=0,L=0,Y=0;for(let U=0;U<=A;U++){let Ne=Math.round(U*h);if(Ne>D){let{topHeight:wc,totalHeight:Li}=gl({maxTop:L,maxBottom:Y,halfHeight:x,vScale:v,barMinHeight:k,barAlign:S}),kc=xl({barAlign:S,halfHeight:x,topHeight:wc,totalHeight:Li,canvasHeight:T});R.push({x:D*g,y:kc,width:y,height:Li}),D=Ne,L=0,Y=0}let Ni=Math.abs(I[U]||0),Ui=Math.abs(C[U]||0);Ni>L&&(L=Ni),Ui>Y&&(Y=Ui)}return R})({channelData:e,barIndexScale:u,barSpacing:d,barWidth:c,halfHeight:a,vScale:o,canvasHeight:s,barAlign:t.barAlign,barMinHeight:m});r.beginPath();for(let p of f)l&&"roundRect"in r?r.roundRect(p.x,p.y,p.width,p.height,l):r.rect(p.x,p.y,p.width,p.height);r.fill(),r.closePath()}renderLineWaveform(e,t,r,o){let{width:i,height:s}=r.canvas,a=(function({channelData:c,width:l,height:u,vScale:d}){let m=u/2,f=c[0]||[];return[f,c[1]||f].map(((p,h)=>{let g=p.length,y=g?l/g:0,x=m,v=h===0?-1:1,T=[{x:0,y:x}],S=0,k=0;for(let I=0;I<=g;I++){let C=Math.round(I*y);if(C>S){let R=x+(Math.round(k*m*d)||1)*v;T.push({x:S,y:R}),S=C,k=0}let A=Math.abs(p[I]||0);A>k&&(k=A)}return T.push({x:S,y:x}),T}))})({channelData:e,width:i,height:s,vScale:o});r.beginPath();for(let c of a)if(c.length){r.moveTo(c[0].x,c[0].y);for(let l=1;l<c.length;l++){let u=c[l];r.lineTo(u.x,u.y)}}r.fill(),r.closePath()}renderWaveform(e,t,r){if(r.fillStyle=this.convertColorValues(t.waveColor,r),t.renderFunction)return void t.renderFunction(e,r);let o=(function({channelData:i,barHeight:s,normalize:a,maxPeak:c}){var l;let u=s||1;if(!a)return u;let d=i[0];if(!d||d.length===0)return u;let m=c??0;if(!c)for(let f=0;f<d.length;f++){let p=(l=d[f])!==null&&l!==void 0?l:0,h=Math.abs(p);h>m&&(m=h)}return m?u/m:u})({channelData:e,barHeight:t.barHeight,normalize:t.normalize,maxPeak:t.maxPeak});Ya(t)?this.renderBarWaveform(e,t,r,o):this.renderLineWaveform(e,t,r,o)}renderSingleCanvas(e,t,r,o,i,s,a){let c=this.getPixelRatio(),l=document.createElement("canvas");l.width=Math.round(r*c),l.height=Math.round(o*c),l.style.width=`${r}px`,l.style.height=`${o}px`,l.style.left=`${Math.round(i)}px`,s.appendChild(l);let u=l.getContext("2d");if(t.renderFunction?(u.fillStyle=this.convertColorValues(t.waveColor,u),t.renderFunction(e,u)):this.renderWaveform(e,t,u),l.width>0&&l.height>0){let d=l.cloneNode(),m=d.getContext("2d");m.drawImage(l,0,0),m.globalCompositeOperation="source-in",m.fillStyle=this.convertColorValues(t.progressColor,m),m.fillRect(0,0,l.width,l.height),a.appendChild(d)}}renderMultiCanvas(e,t,r,o,i,s){let a=this.getPixelRatio(),{clientWidth:c}=this.scrollContainer,l=r/a,u=(function({clientWidth:p,totalWidth:h,options:g}){return Xa(Math.min(8e3,p,h),g)})({clientWidth:c,totalWidth:l,options:t}),d={};if(u===0)return;let m=p=>{if(p<0||p>=f||d[p])return;d[p]=!0;let h=p*u,g=Math.min(l-h,u);if(g=Xa(g,t),g<=0)return;let y=(function({channelData:x,offset:v,clampedWidth:T,totalWidth:S}){return x.map((k=>{let I=Math.floor(v/S*k.length),C=Math.floor((v+T)/S*k.length);return k.slice(I,C)}))})({channelData:e,offset:h,clampedWidth:g,totalWidth:l});this.renderSingleCanvas(y,t,g,o,h,i,s)},f=Math.ceil(l/u);if(!this.isScrollable){for(let p=0;p<f;p++)m(p);return}if(Ka({scrollLeft:this.scrollContainer.scrollLeft,totalWidth:l,numCanvases:f}).forEach((p=>m(p))),f>1){let p=this.on("scroll",(()=>{let{scrollLeft:h}=this.scrollContainer;Object.keys(d).length>10&&(i.innerHTML="",s.innerHTML="",d={}),Ka({scrollLeft:h,totalWidth:l,numCanvases:f}).forEach((g=>m(g)))}));this.unsubscribeOnScroll.push(p)}}renderChannel(e,t,r,o){var{overlay:i}=t,s=(function(u,d){var m={};for(var f in u)Object.prototype.hasOwnProperty.call(u,f)&&d.indexOf(f)<0&&(m[f]=u[f]);if(u!=null&&typeof Object.getOwnPropertySymbols=="function"){var p=0;for(f=Object.getOwnPropertySymbols(u);p<f.length;p++)d.indexOf(f[p])<0&&Object.prototype.propertyIsEnumerable.call(u,f[p])&&(m[f[p]]=u[f[p]])}return m})(t,["overlay"]);let a=document.createElement("div"),c=this.getHeight(s.height,s.splitChannels);a.style.height=`${c}px`,i&&o>0&&(a.style.marginTop=`-${c}px`),this.canvasWrapper.style.minHeight=`${c}px`,this.canvasWrapper.appendChild(a);let l=a.cloneNode();this.progressWrapper.appendChild(l),this.renderMultiCanvas(e,s,r,c,a,l)}render(e){return oe(this,void 0,void 0,(function*(){var t;this.timeouts.forEach((l=>l())),this.timeouts=[],this.canvasWrapper.innerHTML="",this.progressWrapper.innerHTML="",this.options.width!=null&&(this.scrollContainer.style.width=typeof this.options.width=="number"?`${this.options.width}px`:this.options.width);let r=this.getPixelRatio(),o=this.scrollContainer.clientWidth,{scrollWidth:i,isScrollable:s,useParentWidth:a,width:c}=(function({duration:l,minPxPerSec:u=0,parentWidth:d,fillParent:m,pixelRatio:f}){let p=Math.ceil(l*u),h=p>d,g=!!(m&&!h);return{scrollWidth:p,isScrollable:h,useParentWidth:g,width:(g?d:p)*f}})({duration:e.duration,minPxPerSec:this.options.minPxPerSec||0,parentWidth:o,fillParent:this.options.fillParent,pixelRatio:r});if(this.isScrollable=s,this.wrapper.style.width=a?"100%":`${i}px`,this.scrollContainer.style.overflowX=this.isScrollable?"auto":"hidden",this.scrollContainer.classList.toggle("noScrollbar",!!this.options.hideScrollbar),this.cursor.style.backgroundColor=`${this.options.cursorColor||this.options.progressColor}`,this.cursor.style.width=`${this.options.cursorWidth}px`,this.audioData=e,this.emit("render"),this.options.splitChannels)for(let l=0;l<e.numberOfChannels;l++){let u=Object.assign(Object.assign({},this.options),(t=this.options.splitChannels)===null||t===void 0?void 0:t[l]);this.renderChannel([e.getChannelData(l)],u,c,l)}else{let l=[e.getChannelData(0)];e.numberOfChannels>1&&l.push(e.getChannelData(1)),this.renderChannel(l,this.options,c,0)}Promise.resolve().then((()=>this.emit("rendered")))}))}reRender(){if(this.unsubscribeOnScroll.forEach((r=>r())),this.unsubscribeOnScroll=[],!this.audioData)return;let{scrollWidth:e}=this.scrollContainer,{right:t}=this.progressWrapper.getBoundingClientRect();if(this.render(this.audioData),this.isScrollable&&e!==this.scrollContainer.scrollWidth){let{right:r}=this.progressWrapper.getBoundingClientRect(),o=(function(i){let s=2*i;return(s<0?Math.floor(s):Math.ceil(s))/2})(r-t);this.scrollContainer.scrollLeft+=o}}zoom(e){this.options.minPxPerSec=e,this.reRender()}scrollIntoView(e,t=!1){let{scrollLeft:r,scrollWidth:o,clientWidth:i}=this.scrollContainer,s=e*o,a=r,c=r+i,l=i/2;if(this.isDragging)s+30>c?this.scrollContainer.scrollLeft+=30:s-30<a&&(this.scrollContainer.scrollLeft-=30);else{(s<a||s>c)&&(this.scrollContainer.scrollLeft=s-(this.options.autoCenter?l:0));let u=s-r-l;t&&this.options.autoCenter&&u>0&&(this.scrollContainer.scrollLeft+=u)}}renderProgress(e,t){if(isNaN(e))return;let r=100*e;this.canvasWrapper.style.clipPath=`polygon(${r}% 0%, 100% 0%, 100% 100%, ${r}% 100%)`,this.progressWrapper.style.width=`${r}%`,this.cursor.style.left=`${r}%`,this.cursor.style.transform=this.options.cursorWidth?`translateX(-${e*this.options.cursorWidth}px)`:"",this.isScrollable&&this.options.autoScroll&&this.audioData&&this.audioData.duration>0&&this.scrollIntoView(e,t)}exportImage(e,t,r){return oe(this,void 0,void 0,(function*(){let o=this.canvasWrapper.querySelectorAll("canvas");if(!o.length)throw new Error("No waveform data");if(r==="dataURL"){let i=Array.from(o).map((s=>s.toDataURL(e,t)));return Promise.resolve(i)}return Promise.all(Array.from(o).map((i=>new Promise(((s,a)=>{i.toBlob((c=>{c?s(c):a(new Error("Could not export image"))}),e,t)})))))}))}},Mi=class extends bt{constructor(){super(...arguments),this.animationFrameId=null,this.isRunning=!1}start(){if(this.isRunning)return;this.isRunning=!0;let e=()=>{this.isRunning&&(this.emit("tick"),this.animationFrameId=requestAnimationFrame(e))};e()}stop(){this.isRunning=!1,this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}destroy(){this.stop()}},Dr=class extends bt{constructor(e=new AudioContext){super(),this.bufferNode=null,this.playStartTime=0,this.playedDuration=0,this._muted=!1,this._playbackRate=1,this._duration=void 0,this.buffer=null,this.currentSrc="",this.paused=!0,this.crossOrigin=null,this.seeking=!1,this.autoplay=!1,this.addEventListener=this.on,this.removeEventListener=this.un,this.audioContext=e,this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination)}load(){return oe(this,void 0,void 0,(function*(){}))}get src(){return this.currentSrc}set src(e){if(this.currentSrc=e,this._duration=void 0,!e)return this.buffer=null,void this.emit("emptied");fetch(e).then((t=>{if(t.status>=400)throw new Error(`Failed to fetch ${e}: ${t.status} (${t.statusText})`);return t.arrayBuffer()})).then((t=>this.currentSrc!==e?null:this.audioContext.decodeAudioData(t))).then((t=>{this.currentSrc===e&&(this.buffer=t,this.emit("loadedmetadata"),this.emit("canplay"),this.autoplay&&this.play())})).catch((t=>{console.error("WebAudioPlayer load error:",t)}))}_play(){if(!this.paused)return;this.paused=!1,this.bufferNode&&(this.bufferNode.onended=null,this.bufferNode.disconnect()),this.bufferNode=this.audioContext.createBufferSource(),this.buffer&&(this.bufferNode.buffer=this.buffer),this.bufferNode.playbackRate.value=this._playbackRate,this.bufferNode.connect(this.gainNode);let e=this.playedDuration*this._playbackRate;(e>=this.duration||e<0)&&(e=0,this.playedDuration=0),this.bufferNode.start(this.audioContext.currentTime,e),this.playStartTime=this.audioContext.currentTime,this.bufferNode.onended=()=>{this.currentTime>=this.duration&&(this.pause(),this.emit("ended"))}}_pause(){var e;this.paused=!0,(e=this.bufferNode)===null||e===void 0||e.stop(),this.playedDuration+=this.audioContext.currentTime-this.playStartTime}play(){return oe(this,void 0,void 0,(function*(){this.paused&&(this._play(),this.emit("play"))}))}pause(){this.paused||(this._pause(),this.emit("pause"))}stopAt(e){let t=e-this.currentTime,r=this.bufferNode;r?.stop(this.audioContext.currentTime+t),r?.addEventListener("ended",(()=>{r===this.bufferNode&&(this.bufferNode=null,this.pause())}),{once:!0})}setSinkId(e){return oe(this,void 0,void 0,(function*(){return this.audioContext.setSinkId(e)}))}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e,this.bufferNode&&(this.bufferNode.playbackRate.value=e)}get currentTime(){return(this.paused?this.playedDuration:this.playedDuration+(this.audioContext.currentTime-this.playStartTime))*this._playbackRate}set currentTime(e){let t=!this.paused;t&&this._pause(),this.playedDuration=e/this._playbackRate,t&&this._play(),this.emit("seeking"),this.emit("timeupdate")}get duration(){var e,t;return(e=this._duration)!==null&&e!==void 0?e:((t=this.buffer)===null||t===void 0?void 0:t.duration)||0}set duration(e){this._duration=e}get volume(){return this.gainNode.gain.value}set volume(e){this.gainNode.gain.value=e,this.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted!==e&&(this._muted=e,this._muted?this.gainNode.disconnect():this.gainNode.connect(this.audioContext.destination))}canPlayType(e){return/^(audio|video)\//.test(e)}getGainNode(){return this.gainNode}getChannelData(){let e=[];if(!this.buffer)return e;let t=this.buffer.numberOfChannels;for(let r=0;r<t;r++)e.push(this.buffer.getChannelData(r));return e}removeAttribute(e){switch(e){case"src":this.src="";break;case"playbackRate":this.playbackRate=0;break;case"currentTime":this.currentTime=0;break;case"duration":this.duration=0;break;case"volume":this.volume=0;break;case"muted":this.muted=!1}}},yl={waveColor:"#999",progressColor:"#555",cursorWidth:1,minPxPerSec:0,fillParent:!0,interact:!0,dragToSeek:!1,autoScroll:!0,autoCenter:!0,sampleRate:8e3},Qt=class n extends Di{static create(e){return new n(e)}getState(){return this.wavesurferState}getRenderer(){return this.renderer}constructor(e){let t=e.media||(e.backend==="WebAudio"?new Dr:void 0);super({media:t,mediaControls:e.mediaControls,autoplay:e.autoplay,playbackRate:e.audioRate}),this.plugins=[],this.decodedData=null,this.stopAtPosition=null,this.subscriptions=[],this.mediaSubscriptions=[],this.abortController=null,this.reactiveCleanups=[],this.options=Object.assign({},yl,e);let{state:r,actions:o}=(function(a){var c,l,u,d,m,f;let p=(c=a?.currentTime)!==null&&c!==void 0?c:q(0),h=(l=a?.duration)!==null&&l!==void 0?l:q(0),g=(u=a?.isPlaying)!==null&&u!==void 0?u:q(!1),y=(d=a?.isSeeking)!==null&&d!==void 0?d:q(!1),x=(m=a?.volume)!==null&&m!==void 0?m:q(1),v=(f=a?.playbackRate)!==null&&f!==void 0?f:q(1),T=q(null),S=q(null),k=q(""),I=q(0),C=q(0),A=xt((()=>!g.value),[g]),R=xt((()=>T.value!==null),[T]),D=xt((()=>R.value&&h.value>0),[R,h]),L=xt((()=>p.value),[p]),Y=xt((()=>h.value>0?p.value/h.value:0),[p,h]);return{state:{currentTime:p,duration:h,isPlaying:g,isPaused:A,isSeeking:y,volume:x,playbackRate:v,audioBuffer:T,peaks:S,url:k,zoom:I,scrollPosition:C,canPlay:R,isReady:D,progress:L,progressPercent:Y},actions:{setCurrentTime:U=>{let Ne=Math.max(0,Math.min(h.value||1/0,U));p.set(Ne)},setDuration:U=>{h.set(Math.max(0,U))},setPlaying:U=>{g.set(U)},setSeeking:U=>{y.set(U)},setVolume:U=>{let Ne=Math.max(0,Math.min(1,U));x.set(Ne)},setPlaybackRate:U=>{let Ne=Math.max(.1,Math.min(16,U));v.set(Ne)},setAudioBuffer:U=>{T.set(U),U&&h.set(U.duration)},setPeaks:U=>{S.set(U)},setUrl:U=>{k.set(U)},setZoom:U=>{I.set(Math.max(0,U))},setScrollPosition:U=>{C.set(Math.max(0,U))}}}})({isPlaying:this.isPlayingSignal,currentTime:this.currentTimeSignal,duration:this.durationSignal,volume:this.volumeSignal,playbackRate:this.playbackRateSignal,isSeeking:this.seekingSignal});this.wavesurferState=r,this.wavesurferActions=o,this.timer=new Mi;let i=t?void 0:this.getMediaElement();this.renderer=new Ri(this.options,i),this.initPlayerEvents(),this.initRendererEvents(),this.initTimerEvents(),this.initReactiveState(),this.initPlugins();let s=this.options.url||this.getSrc()||"";Promise.resolve().then((()=>{this.emit("init");let{peaks:a,duration:c}=this.options;(s||a&&c)&&this.load(s,a,c).catch((l=>{this.emit("error",l instanceof Error?l:new Error(String(l)))}))}))}updateProgress(e=this.getCurrentTime()){return this.renderer.renderProgress(e/this.getDuration(),this.isPlaying()),e}initTimerEvents(){this.subscriptions.push(this.timer.on("tick",(()=>{if(!this.isSeeking()){let e=this.updateProgress();this.emit("timeupdate",e),this.emit("audioprocess",e),this.stopAtPosition!=null&&this.isPlaying()&&e>=this.stopAtPosition&&this.pause()}})))}initReactiveState(){this.reactiveCleanups.push((function(e,t){let r=[];r.push(Ke((()=>{let s=e.isPlaying.value;t.emit(s?"play":"pause")}),[e.isPlaying])),r.push(Ke((()=>{let s=e.currentTime.value;t.emit("timeupdate",s),e.isPlaying.value&&t.emit("audioprocess",s)}),[e.currentTime,e.isPlaying])),r.push(Ke((()=>{e.isSeeking.value&&t.emit("seeking",e.currentTime.value)}),[e.isSeeking,e.currentTime]));let o=!1;r.push(Ke((()=>{e.isReady.value&&!o&&(o=!0,t.emit("ready",e.duration.value))}),[e.isReady,e.duration]));let i=!1;return r.push(Ke((()=>{let s=e.isPlaying.value,a=e.currentTime.value,c=e.duration.value,l=c>0&&a>=c;i&&!s&&l&&t.emit("finish"),i=s&&l}),[e.isPlaying,e.currentTime,e.duration])),r.push(Ke((()=>{let s=e.zoom.value;s>0&&t.emit("zoom",s)}),[e.zoom])),()=>{r.forEach((s=>s()))}})(this.wavesurferState,{emit:this.emit.bind(this)}))}initPlayerEvents(){this.isPlaying()&&(this.emit("play"),this.timer.start()),this.mediaSubscriptions.push(this.onMediaEvent("timeupdate",(()=>{let e=this.updateProgress();this.emit("timeupdate",e)})),this.onMediaEvent("play",(()=>{this.emit("play"),this.timer.start()})),this.onMediaEvent("pause",(()=>{this.emit("pause"),this.timer.stop(),this.stopAtPosition=null})),this.onMediaEvent("emptied",(()=>{this.timer.stop(),this.stopAtPosition=null})),this.onMediaEvent("ended",(()=>{this.emit("timeupdate",this.getDuration()),this.emit("finish"),this.stopAtPosition=null})),this.onMediaEvent("seeking",(()=>{this.emit("seeking",this.getCurrentTime())})),this.onMediaEvent("error",(()=>{var e;this.emit("error",(e=this.getMediaElement().error)!==null&&e!==void 0?e:new Error("Media error")),this.stopAtPosition=null})))}initRendererEvents(){this.subscriptions.push(this.renderer.on("click",((e,t)=>{this.options.interact&&(this.seekTo(e),this.emit("interaction",e*this.getDuration()),this.emit("click",e,t))})),this.renderer.on("dblclick",((e,t)=>{this.emit("dblclick",e,t)})),this.renderer.on("scroll",((e,t,r,o)=>{let i=this.getDuration();this.emit("scroll",e*i,t*i,r,o)})),this.renderer.on("render",(()=>{this.emit("redraw")})),this.renderer.on("rendered",(()=>{this.emit("redrawcomplete")})),this.renderer.on("dragstart",(e=>{this.emit("dragstart",e)})),this.renderer.on("dragend",(e=>{this.emit("dragend",e)})),this.renderer.on("resize",(()=>{this.emit("resize")})));{let e,t=this.renderer.on("drag",(r=>{var o;if(!this.options.interact)return;this.renderer.renderProgress(r),clearTimeout(e);let i=0,s=this.options.dragToSeek;this.isPlaying()?i=0:s===!0?i=200:s&&typeof s=="object"&&(i=(o=s.debounceTime)!==null&&o!==void 0?o:200),e=setTimeout((()=>{this.seekTo(r)}),i),this.emit("interaction",r*this.getDuration()),this.emit("drag",r)}));this.subscriptions.push((()=>{clearTimeout(e),t()}))}}initPlugins(){var e;!((e=this.options.plugins)===null||e===void 0)&&e.length&&this.options.plugins.forEach((t=>{this.registerPlugin(t)}))}unsubscribePlayerEvents(){this.mediaSubscriptions.forEach((e=>e())),this.mediaSubscriptions=[]}setOptions(e){this.options=Object.assign({},this.options,e),e.duration&&!e.peaks&&(this.decodedData=so.createBuffer(this.exportPeaks(),e.duration)),e.peaks&&e.duration&&(this.decodedData=so.createBuffer(e.peaks,e.duration)),this.renderer.setOptions(this.options),e.audioRate&&this.setPlaybackRate(e.audioRate),e.mediaControls!=null&&(this.getMediaElement().controls=e.mediaControls)}registerPlugin(e){if(this.plugins.includes(e))return e;e._init(this),this.plugins.push(e);let t=e.once("destroy",(()=>{this.plugins=this.plugins.filter((r=>r!==e)),this.subscriptions=this.subscriptions.filter((r=>r!==t))}));return this.subscriptions.push(t),e}unregisterPlugin(e){this.plugins=this.plugins.filter((t=>t!==e)),e.destroy()}getWrapper(){return this.renderer.getWrapper()}getWidth(){return this.renderer.getWidth()}getScroll(){return this.renderer.getScroll()}setScroll(e){return this.renderer.setScroll(e)}setScrollTime(e){let t=e/this.getDuration();this.renderer.setScrollPercentage(t)}getActivePlugins(){return this.plugins}loadAudio(e,t,r,o){return oe(this,void 0,void 0,(function*(){var i;if(this.emit("load",e),!this.options.media&&this.isPlaying()&&this.pause(),this.decodedData=null,this.stopAtPosition=null,(i=this.abortController)===null||i===void 0||i.abort(),this.abortController=null,!t&&!r){let a=this.options.fetchParams||{};window.AbortController&&!a.signal&&(this.abortController=new AbortController,a.signal=this.abortController.signal);let c=u=>this.emit("loading",u);t=yield hl.fetchBlob(e,c,a);let l=this.options.blobMimeType;l&&(t=new Blob([t],{type:l}))}this.setSrc(e,t);let s=yield new Promise((a=>{let c=o||this.getDuration();c?a(c):this.mediaSubscriptions.push(this.onMediaEvent("loadedmetadata",(()=>a(this.getDuration())),{once:!0}))}));if(!e&&!t){let a=this.getMediaElement();a instanceof Dr&&(a.duration=s)}if(r)this.decodedData=so.createBuffer(r,s||0);else if(t){let a=yield t.arrayBuffer();this.decodedData=yield so.decode(a,this.options.sampleRate)}this.decodedData&&(this.emit("decode",this.getDuration()),this.renderer.render(this.decodedData)),this.emit("ready",this.getDuration())}))}load(e,t,r){return oe(this,void 0,void 0,(function*(){try{return yield this.loadAudio(e,void 0,t,r)}catch(o){throw this.emit("error",o),o}}))}loadBlob(e,t,r){return oe(this,void 0,void 0,(function*(){try{return yield this.loadAudio("",e,t,r)}catch(o){throw this.emit("error",o),o}}))}zoom(e){if(!this.decodedData)throw new Error("No audio loaded");this.renderer.zoom(e),this.emit("zoom",e)}getDecodedData(){return this.decodedData}exportPeaks({channels:e=2,maxLength:t=8e3,precision:r=1e4}={}){if(!this.decodedData)throw new Error("The audio has not been decoded yet");let o=Math.min(e,this.decodedData.numberOfChannels),i=[];for(let s=0;s<o;s++){let a=this.decodedData.getChannelData(s),c=[],l=a.length/t;for(let u=0;u<t;u++){let d=a.slice(Math.floor(u*l),Math.ceil((u+1)*l)),m=0;for(let f=0;f<d.length;f++){let p=d[f];Math.abs(p)>Math.abs(m)&&(m=p)}c.push(Math.round(m*r)/r)}i.push(c)}return i}getDuration(){let e=super.getDuration()||0;return e!==0&&e!==1/0||!this.decodedData||(e=this.decodedData.duration),e}toggleInteraction(e){this.options.interact=e}setTime(e){this.stopAtPosition=null,super.setTime(e),this.updateProgress(e),this.emit("timeupdate",e)}seekTo(e){let t=this.getDuration()*e;this.setTime(t)}play(e,t){let r=Object.create(null,{play:{get:()=>super.play}});return oe(this,void 0,void 0,(function*(){e!=null&&this.setTime(e);let o=yield r.play.call(this);return t!=null&&(this.media instanceof Dr?this.media.stopAt(t):this.stopAtPosition=t),o}))}playPause(){return oe(this,void 0,void 0,(function*(){return this.isPlaying()?this.pause():this.play()}))}stop(){this.pause(),this.setTime(0)}skip(e){this.setTime(this.getCurrentTime()+e)}empty(){this.load("",[[0]],.001)}setMediaElement(e){this.unsubscribePlayerEvents(),super.setMediaElement(e),this.initPlayerEvents()}exportImage(){return oe(this,arguments,void 0,(function*(e="image/png",t=1,r="dataURL"){return this.renderer.exportImage(e,t,r)}))}destroy(){var e;this.emit("destroy"),(e=this.abortController)===null||e===void 0||e.abort(),this.plugins.forEach((t=>t.destroy())),this.subscriptions.forEach((t=>t())),this.unsubscribePlayerEvents(),this.reactiveCleanups.forEach((t=>t())),this.reactiveCleanups=[],this.timer.destroy(),this.renderer.destroy(),super.destroy()}};Qt.BasePlugin=class extends bt{constructor(n){super(),this.subscriptions=[],this.isDestroyed=!1,this.options=n}onInit(){}_init(n){this.isDestroyed&&(this.subscriptions=[],this.isDestroyed=!1),this.wavesurfer=n,this.onInit()}destroy(){this.emit("destroy"),this.subscriptions.forEach((n=>n())),this.subscriptions=[],this.isDestroyed=!0,this.wavesurfer=void 0}},Qt.dom=pl;var ao=class n{wavesurfer;constructor(e,t,r){this.wavesurfer=Qt.create({container:t,waveColor:"rgb(200, 0, 200)",progressColor:"rgb(100, 0, 100)",barWidth:10,barRadius:10,barGap:2,peaks:[e],duration:r})}static async init(e,t,r){let o=e.decodeAudio({source:t}).getReader(),i=[],s=[],a=1024,c=await e.getAudioDuration(t);for(;;){let{done:l,value:u}=await o.read();if(l)break;let d=u.numberOfFrames,m=new Float32Array(d);u.copyTo(m,{planeIndex:0});for(let f=0;f<m.length;f++)if(s.push(m[f]),s.length>=a){let p=s.splice(0,a),h=Math.min(...p),g=Math.max(...p);i.push(h,g)}u.close()}return new n(i,r,c??0)}set width(e){this.wavesurfer.setOptions({width:e})}};var N=n=>n;var Yt=n=>n;var Ja=()=>{let n=!1,e=Yt(60),t=1e3/e,r=0,o=0,i=St(),s=null,a=l=>{if(requestAnimationFrame(a),!!n)for(r=l;l-o>=t;)o+=t,s?.(),s=null,i()};async function*c(){for(r=performance.now(),o=r,requestAnimationFrame(a);;)await new Promise(l=>s=l),yield}return{play(){n||(n=!0,r=performance.now(),o=r)},pause(){n=!1},setFPS(l){e=l,t=1e3/e},isPlaying(){return n},ticks:c,onTick:i}},ec=async(n,e)=>{let t=N(1e3/n.fps),r=n.duration/1e3,o=Math.ceil(r*n.fps);for(let i=0;i<o;i++){let s=N(i*t);await e(s,i)}};var Rr=n=>n;function rc(n){return"duration"in n}function nc(n){let e=[],t=new Map(n.timeline.items.map(r=>[r.id,r]));return Bi(n.timeline.rootId,t,n.from,{sequence:()=>{},stack:()=>{},video:(r,o,i)=>e.push({item:r,localTime:o,ancestors:i}),text:(r,o,i)=>e.push({item:r,localTime:o,ancestors:i}),audio:(r,o,i)=>e.push({item:r,localTime:o,ancestors:i})}),e}function oc(n,e,t){let r=Na;for(let o of e)r=tc(n,o,r);return tc(n,t,r)}function tc(n,e,t){if("spatialId"in e&&e.spatialId){let r=n.get(e.spatialId);if(r?.enabled){let o=Ba(r.transform);return za(o,t)}}return t}function Bi(n,e,t,r,o=[]){let i=e.get(n);if(i)switch(i.kind){case B.Stack:r.stack(i,t,o);for(let s of i.childrenIds)Bi(s,e,t,r,[...o,i]);break;case B.Sequence:{r.sequence(i,t,o);let s=N(0);for(let a of i.childrenIds){let c=e.get(a);if(!c||!rc(c))continue;let l=N(s+c.duration);if(t>=l){s=l;continue}let u=N(Math.max(0,t-s));Bi(a,e,u,r,[...o,i]),s=l}break}case B.Video:r.video(i,t,o);break;case B.Text:r.text(i,t,o);break;case B.Audio:r.audio(i,t,o);break}}function be(n,e){let t=e.items.find(r=>r.id===n);if(!t)return N(0);switch(t.kind){case B.Sequence:{let r=t.childrenIds.map(i=>e.items.find(s=>s.id===i)).filter(Boolean),o=N(0);for(let i=0;i<r.length;i++){let s=r[i];if(s.kind===B.Transition){let a=r[i-1],c=r[i+1];if(a&&c&&a.kind!==B.Transition&&c.kind!==B.Transition){let l=be(a.id,e),u=be(c.id,e),d=Math.max(0,Math.min(s.duration,l,u));o=N(o-d)}continue}o=N(o+be(s.id,e))}return o}case B.Stack:{let r=N(0);for(let o of t.childrenIds){let i=be(o,e);i>r&&(r=i)}return r}default:return rc(t)?t.duration:N(0)}}async function ic(n,e,t){return(await Promise.all(e.map(async({item:o,localTime:i})=>{if(o.kind!==B.Audio)return;let s=await n.getSink(o.mediaHash);if(!s)return;let a=o.start+i,c=Rr((t-a)/1e3),l=s.samples(a/1e3),u=await l.next();if(u.done)return;let d=u.value,m=l.next();return{offset:c,gain:o.gain??1,get currentSample(){return d},timelineTime:()=>Rr(c+d.timestamp),output:()=>({sample:d,timestamp:c+d.timestamp,gain:o.gain??1}),advance:async()=>{let f=await m;return f.done?!1:(d=f.value,m=l.next(),!0)}}}))).filter(o=>!!o)}var co=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 r=new ne({formats:le,source:await me(this.resolveMedia(e))}),o=await r.getPrimaryAudioTrack(),s=!!o&&await o.canDecode()&&o?new vr(o):null;return this.#e.set(e,{input:r,sink:s}),s}};function sc(n){let e={index:0,stream:n[0],time:n[0].timelineTime()};for(let[t,r]of n.entries()){let o=r.timelineTime();o<e.time&&(e={time:o,stream:r,index:t})}return e}function lo(n){let e=new co(n);return{async*sampleAudio(t,r){let o=nc({timeline:t,from:r}),i=await ic(e,o,r);for(;i.length>0;){let{stream:s,index:a}=sc(i);yield s.output(),await s.advance()||i.splice(a,1)}}}}var uo=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 r=new ne({formats:le,source:await me(this.resolveMedia(e))}),o=await r.getPrimaryVideoTrack(),s=!!o&&await o.canDecode()&&o?new Rt(o):null;return this.#e.set(e,{input:r,sink:s}),s}};async function ac(n,e,t,r){let[o,i]=await Promise.all([t,r]),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:n.id,kind:"transition",name:"circle",progress:e,from:s,to:a},...c]:c}async function cc(n,e,t,r){let o=vl(n,e,t);if(!o)return[];let i=[...r,e];return o.isTransitioning?ac(o.transition,o.progress,yt(n,o.outgoing,o.outgoingTime,i),yt(n,o.incoming,o.incomingTime,i)):yt(n,o.item,o.localTime,i)}function vl(n,e,t){let r=e.childrenIds.map(i=>n.items.get(i)).filter(i=>!!i),o=N(0);for(let i=0;i<r.length;i++){let s=r[i];if(s.kind===B.Transition)continue;let a=o,c=be(s.id,n.timeline),l=N(a+c),u=r[i+1];if(!(u?.kind===B.Transition)){if(t<l)return{isTransitioning:!1,item:s,localTime:N(t-a)};o=l;continue}let m=u,f=r[i+2];if(!f||f.kind===B.Transition){o=l;continue}let p=be(f.id,n.timeline),h=Math.max(0,Math.min(m.duration,c,p)),g=N(l-h);if(t<g)return{isTransitioning:!1,item:s,localTime:N(t-a)};if(t<l){let y=N(t-g),x=N(t-a);return{isTransitioning:!0,incoming:f,outgoing:s,outgoingTime:x,incomingTime:y,progress:h>0?y/h:1,transition:m}}o=g,i++}return null}async function yt(n,e,t,r){let o=oc(n.items,r,e);switch(e.kind){case B.Stack:{let i=[...r,e];return(await Promise.all(e.childrenIds.map(a=>n.items.get(a)).filter(a=>!!a).map(a=>yt(n,a,t,i)))).flat()}case B.Sequence:return cc(n,e,t,r);case B.Video:{if(t<0||t>=e.duration)return[];let i=await n.videoSampler(e,t);return i?[{kind:"image",frame:i,matrix:o,id:e.id}]:[]}case B.Text:{if(t<0||t>=e.duration)return[];let i=e.styleId?n.items.get(e.styleId)?.style:void 0;return[{id:e.id,kind:"text",content:e.content,style:i,matrix:o}]}case B.Gap:return[{id:e.id,kind:"gap"}];default:return[]}}function lc(n){return async(e,t)=>{let o=await(await n.getSink(e.mediaHash))?.getSample(t/1e3),i=o?.toVideoFrame();return o?.close(),i??void 0}}function mo(n,e){let t=new uo(n),r=e??lc(t);return{async sample(o,i){let s=new Map(o.items.map(c=>[c.id,c])),a=s.get(o.rootId);return a?yt({videoSampler:r,timeline:o,items:s},a,i,[]):[]}}}var fo=class{timeline;resolveMedia;visualSampler;audioSampler;#e=N(0);#t=null;#r=Ja();onTick=this.#r.onTick;audioContext=new AudioContext({sampleRate:48e3});audioGain=this.audioContext.createGain();audioNodes=new Set;#n=null;constructor(e,t){this.timeline=e,this.resolveMedia=t,this.audioGain.connect(this.audioContext.destination),this.audioGain.gain.value=.7**2,this.visualSampler=mo(this.resolveMedia),this.audioSampler=lo(this.resolveMedia)}async*samples(){for await(let e of this.#r.ticks())yield this.visualSampler.sample(this.timeline,this.currentTime)}async seek(e){return this.pause(),this.#e=e,await this.visualSampler.sample(this.timeline,e)}async start(e){this.timeline=e,await this.audioContext.resume(),this.#e=this.currentTime,this.#t=this.audioContext.currentTime,this.#n?.abort(),this.#n=new AbortController;for(let t of this.audioNodes)t.stop();this.audioNodes.clear(),this.#r.play(),this.#o(this.#n.signal,Rr(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()}get currentTime(){if(!this.#r.isPlaying()||this.#t===null)return this.#e;let e=(this.audioContext.currentTime-this.#t)*1e3;return N(this.#e+e)}setFps(e){this.#r.setFPS(e)}async#o(e,t){let r=this.audioContext;if(this.#t!==null)for await(let{sample:o,timestamp:i}of this.audioSampler.sampleAudio(this.timeline,N(t*1e3))){if(e.aborted||!this.#r.isPlaying())return;for(;i-(r.currentTime-this.#t+t)>.75;)await new Promise(c=>setTimeout(c,25));let s=r.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>=r.currentTime?s.start(a):s.start(r.currentTime,r.currentTime-a)}}};var po=class{driver;timeline;canvas;playback;constructor(e,t,r){this.driver=e,this.timeline=r,this.playback=new fo(r,t),this.canvas=e.compositor.pixi.renderer.canvas}async play(){await this.playback.start(this.timeline);for await(let e of this.playback.samples())(await this.driver.composite(e)).close(),this.currentTime>=this.duration&&this.pause()}pause(){this.playback.pause()}async seek(e){let t=await this.playback.seek(N(e));(await this.driver.composite(t)).close()}setFPS(e){this.playback.setFps(Yt(e))}get duration(){return be(this.timeline.rootId,this.timeline)}get currentTime(){return this.playback.currentTime}async update(e){this.timeline=e}};var vt=class{state;constructor(e){this.state=e}require(e){return e===void 0?void 0:this.state.timeline.items.find(r=>r.id===e)}get timeline(){return this.state.timeline}#e(){return ye.toInteger(ye.random())}#t(e){this.state.timeline=e(this.state.timeline)}register(e){this.#t(t=>({...t,items:[...t.items,e]}))}textStyle=e=>{let t={id:this.#e(),kind:B.TextStyle,style:e};return this.register(t),t};spatial=e=>{let t={id:this.#e(),kind:B.Spatial,transform:e,enabled:!0};return this.register(t),t};sequence=(...e)=>{let t={id:this.#e(),kind:B.Sequence,childrenIds:e.map(r=>r.id)};return this.register(t),t};stack=(...e)=>{let t={kind:B.Stack,id:this.#e(),childrenIds:e.map(r=>r.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 r={kind:B.Video,id:this.#e(),mediaHash:e.datafile.checksum.hash,start:t?.start??0,duration:t?.duration??e.duration};return this.register(r),r};audio=(e,t)=>{if(!e.hasAudio)throw new Error(`Audio clip error: media "${e.datafile.filename}" has no audio track.`);let r={kind:B.Audio,id:this.#e(),mediaHash:e.datafile.checksum.hash,start:t?.start??0,duration:t?.duration??e.duration,gain:t?.gain??1};return this.register(r),r};text=(e,t)=>{let r={id:this.#e(),content:e,kind:B.Text,duration:t?.duration??2e3};return t?.styles&&(r.styleId=this.textStyle(t.styles).id),this.register(r),r};gap=e=>{let t={id:this.#e(),kind:B.Gap,duration:e};return this.register(t),t};transition={crossfade:e=>{let t={id:this.#e(),kind:B.Transition,effect:ro.Crossfade,duration:e};return this.register(t),t}};transform=e=>{let t=[e?.position?.[0]??0,e?.position?.[1]??0],r=[e?.scale?.[0]??1,e?.scale?.[1]??1],o=e?.rotation??0;return[t,r,o]};addChildren(e,...t){this.#t(r=>(r.items.find(({id:i})=>i===e.id).childrenIds.push(...t.map(i=>i.id)),r))}set=(e,t)=>{this.#t(r=>({...r,items:r.items.map(o=>o.id===e?{...o,...t}:o)}))}};var ho=class{#e;#t;constructor(e={}){this.#e=e.chunkFrames??1024,this.#t=e.clamp??!0}async*mix(e){let t=this.#e,r=null,o=null,i=[],s=0,a=0;for await(let c of e){if(o===null)o=c.planes.length,r=c.sampleRate;else{if(c.planes.length!==o)throw new Error("Channel count changed");if(c.sampleRate!==r)throw new Error("Sample rate changed")}let l=Math.round(c.timestamp*r),u=c.planes[0]?.length??0;for(;s+t<=l;)yield this.#r(i,s,o,r),s+=t;i.push({startFrame:l,endFrame:l+u,data:c.planes}),a=Math.max(a,l+u)}if(o!==null&&r!==null)for(;s<a;)yield this.#r(i,s,o,r),s+=t}#r(e,t,r,o){let i=this.#e,s=new Float32Array(r*i),a=t+i;for(let c=0;c<r;c++){let l=c*i,u=s.subarray(l,l+i);for(let d of e){let m=d.data[c];if(!m)continue;let f=Math.max(t,d.startFrame),p=Math.min(a,d.endFrame);if(f>=p)continue;let h=f-t,g=f-d.startFrame,y=p-f;for(let x=0;x<y;x++)u[h+x]+=m[g+x]}if(this.#t)for(let d=0;d<i;d++){let m=u[d];u[d]=m<-1?-1:m>1?1:m}}for(let c=e.length-1;c>=0;c--)e[c].endFrame<=a&&e.splice(c,1);return{planar:s,sampleRate:o,channels:r,frames:i,startFrame:t}}};var Tl=(n,e,t)=>{if(e===t)return n;let r=t/e,o=Math.max(1,Math.round(n.length*r)),i=new Float32Array(o);for(let s=0;s<o;s++){let a=s/r,c=Math.floor(a),l=Math.min(c+1,n.length-1),u=a-c;i[s]=n[c]*(1-u)+n[l]*u}return i},uc=(n,e)=>{let t=n.numberOfChannels,r=new Array(t),o=0;for(let i=0;i<t;i++){let s=new Float32Array(n.numberOfFrames);n.copyTo(s,{planeIndex:i,format:"f32-planar"});let a=Tl(s,n.sampleRate,e);r[i]=a,o=a.length}return{data:r,frames:o}};var dc=(n,e)=>{if(e!==1)for(let t of n)for(let r=0;r<t.length;r++)t[r]*=e};function mc({timeline:n,resolveMedia:e}){let t=new ho,r=wl(n,e),o=new TransformStream,i=o.writable.getWriter();async function s(){for await(let a of t.mix(r)){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*wl(n,e){let t=lo(e);for await(let{sample:r,timestamp:o,gain:i}of t.sampleAudio(n,N(0))){let{data:s}=uc(r,48e3);dc(s,i),yield{planes:s,sampleRate:48e3,timestamp:o},r.close()}}var go=class{driver;resolveMedia;#e;#t=new Map;constructor(e,t){this.driver=e,this.resolveMedia=t,this.#e=mo(t,(r,o)=>{let i=kl(N(r.start+o));return this.#r(r).next(i)})}cursor(e){let t=Number.NEGATIVE_INFINITY;return{next:r=>{if(r<t)throw new Error(`CursorVisualSampler is forward-only: requested ${r}ms after ${t}ms`);return t=r,this.#e.sample(e,r)},cancel:()=>this.#n()}}#r(e){let t=this.#t.get(e.id);if(t)return t;let r=this.resolveMedia(e.mediaHash),o=this.driver.decodeVideo({source:r}),i=this.#o(o.getReader());return this.#t.set(e.id,i),i}async#n(){await Promise.all([...this.#t.values()].map(e=>e.cancel())),this.#t.clear()}#o(e){return{async next(t){let r=null;for(;;){let{done:o,value:i}=await e.read();if(o){let a=r?new VideoFrame(r):void 0;return r?.close(),a}let s=i.timestamp??0;if(s>=t){let a=r?.timestamp??Number.NEGATIVE_INFINITY,c=!!r&&Math.abs(a-t)<Math.abs(s-t),l=c?r:i,u=c?i:r,d=new VideoFrame(l);return l.close(),u?.close(),d}r?.close(),r=i}},cancel:async()=>await e.cancel()}}},kl=n=>Math.round(n*1e3);function fc({timeline:n,fps:e,driver:t,resolveMedia:r}){let o=new TransformStream,i=o.writable.getWriter(),a=new go(t,r).cursor(n),c=1/e,l=be(n.rootId,n);async function u(){await ec({fps:e,duration:l},async(d,m)=>{let f=await a.next(d),p=await t.composite(f),h=new VideoFrame(p,{timestamp:Math.round(m*c*1e6),duration:Math.round(c*1e6)});await i.write(h),p.close()}),await i.close()}return u(),o.readable}function pc(n){let e=mc({...n}),t=fc({...n});return n.driver.encode({video:t,audio:e,config:{audio:{codec:"opus",bitrate:128e3},video:{codec:"vp9",bitrate:1e6}}})}var xo=class{driver;resources=new oo;constructor(e){this.driver=e}load=async e=>Object.fromEntries(await Promise.all(Object.entries(e).map(async([t,r])=>[t,await this.resources.store(await r)])));timeline=e=>{let t=new vt({timeline:{format:"timeline",info:"https://omniclip.app/",version:0,items:[],rootId:0}}),r=e(t);return t.timeline.rootId=r.id,t.timeline};playback=async e=>new po(this.driver,t=>this.resources.require(t).url,e);render=async(e,t=30)=>pc({timeline:e,fps:Yt(t),driver:this.driver,resolveMedia:r=>this.resources.require(r).url})};var bo=class{data;bytes;hash;nickname;constructor(e,t,r,o){this.data=e,this.bytes=t,this.hash=r,this.nickname=o}static async make(e){let t=new Uint8Array(e),r=new Uint8Array(await crypto.subtle.digest("SHA-256",t)),o=zr.fromBytes(r),i=Xi.sigil.fromBytes(r);return new this(e,r,o,i)}};var yo=class{url;bytes;blob;filename;checksum;constructor(e,t,r,o,i){this.url=e,this.bytes=t,this.blob=r,this.filename=o,this.checksum=i}static async make(e,t){let r=await e.arrayBuffer(),o=new Uint8Array(r),i=await bo.make(o),s=t??i.nickname,a=URL.createObjectURL(e);return new this(a,o,e,s,i)}static async load(e){}};async function gc(n,e,t){let r=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 vt({timeline:n}),u=await e.playback(n);c.replaceChildren(u.canvas),r.disabled=!1,o.disabled=!1,r.addEventListener("click",()=>u.play()),o.addEventListener("click",()=>u.pause()),i.max=String(Math.ceil(u.duration));let d=!1,m=null,f=!1;u.playback.onTick.on(()=>g(u.currentTime,u.duration));let p=async y=>{if(m=y,!f){for(f=!0;m;){let x=m;m=null,await u.seek(x)}f=!1}},h=(y,x)=>{a.textContent=`${hc(y)} / ${hc(x)}`};i.addEventListener("input",async()=>{d=!0;let y=Math.max(0,Math.min(+i.value,u.duration));h(y,u.duration),await p(y)}),i.addEventListener("change",async()=>{d=!1;let y=Math.max(0,Math.min(+i.value,u.duration));await p(y)});let g=(y,x)=>{let v=Math.max(0,Math.min(y,x));d||(i.value=String(Math.round(v)));let T=x?v/x*100:0;s.style.left=`${T}%`,h(v,x)};u.update(l.timeline)}function hc(n){let e=Math.max(0,n),t=Math.floor(e/1e3),r=Math.floor(t/60),o=t%60,i=Math.floor(e%1e3);return`${r}:${String(o).padStart(2,"0")}.${String(i).padStart(3,"0")}`}async function xc(n,e,t){let r=t.querySelector(".waveform-canvas"),o=t.querySelector(".width");r.replaceChildren();let i=await ao.init(n,e,r);o.oninput=()=>{let s=+o.value;i.width=s}}async function Oi(n,e){let t=new xo(n),{videoA:r}=await t.load({videoA:yo.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(r,{duration:3e3,start:1e3}),i.audio(r,{duration:1e3})),i.gap(500),i.video(r,{duration:7e3,start:5e3}))}),omni:t}}async function bc(n,e){let t=e.querySelector(".range"),r=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 u=await io.init(n,{onChange(d){let m=d.sort((f,p)=>f.time-p.time);a.replaceChildren(...m.map(({time:f,canvas:p})=>Sl(f,p.canvas)))},frequency:c,canvasSinkOptions:{width:80,height:50,fit:"fill"}});o.oninput=()=>{l=+o.value;let d=+t.value,m=d+l;u.range=[d,m],r.textContent=`visible time range: [${d}, ${m}]`},t.oninput=()=>{let d=+t.value,m=d+l;u.range=[d,m],r.textContent=`visible time range: [${d}, ${m}]`},i.oninput=()=>{u.frequency=1/+i.value,s.textContent=`frame every ${u.frequency.toFixed(3)} second (${i.value} frames per second)`},u.range=[10,10.5]}function Sl(n,e){let t=document.createElement("div");t.style.position="relative",t.style.display="inline-block",t.style.marginRight="4px",t.appendChild(e);let r=document.createElement("div");return r.textContent=`${n.toFixed(2)}s`,r.style.position="absolute",r.style.top="2px",r.style.right="4px",r.style.fontSize="10px",r.style.color="white",r.style.background="rgba(0,0,0,0.6)",r.style.padding="2px 4px",r.style.borderRadius="4px",r.style.pointerEvents="none",t.appendChild(r),t}function yc(n,e){let t={width:1920,height:1080},r=document.createElement("canvas");r.width=t.width,r.height=t.height;let o=r.getContext("2d");async function i(){let s=n.decodeVideo({source:e,async onFrame(m){let f=await n.composite([{id:0,kind:"image",frame:m},{id:1,kind:"text",content:"omnitool",style:{fontSize:50,fill:"green"}}]);return m.close(),o?.drawImage(f,0,0),f}}),a=n.decodeAudio({source:e}),{readable:c,done:l}=n.encode({video:s,audio:a,config:{audio:{codec:"opus",bitrate:128e3},video:{codec:"vp9",bitrate:1e6}}}),d=await(await window.showSaveFilePicker()).createWritable();await Promise.all([c.pipeTo(d),l])}return{canvas:r,run:i}}var Zt=await to.setup({workerUrl:new URL("../driver/driver.worker.bundle.min.js",import.meta.url)}),Cl=document.querySelector("[data-demo='transcode']"),Pl=document.querySelector("[data-demo='filmstrip']"),Il=document.querySelector("[data-demo='waveform']"),vc=document.querySelector("[data-demo='playback']"),Tt=document.querySelector("[data-demo='export']"),Tc=Tt.querySelector("[data-action='export']"),vo=null;await Zt.thread.work.hello(),Zt.machina.count===1?console.log("\u2705 driver works"):console.error("\u274C FAIL driver call didn't work");var Jt=(n,e)=>{let t=n.querySelector(".progress"),r=n.querySelector(".status");e==="running"?(t.removeAttribute("value"),r.textContent="running"):e==="done"?(t.value=1,r.textContent="done"):(t.value=0,r.textContent="idle")},zi=(n,e)=>{let t=n.querySelector("input[type='file']"),r=n.querySelector("[data-action='run']");r.disabled=!0,t.addEventListener("input",()=>{r.disabled=!t.files?.length}),r.addEventListener("click",async()=>{let o=t.files?.[0];if(o){r.disabled=!0,Jt(n,"running");try{await e(o,n),Jt(n,"done")}finally{r.disabled=!1}}})};zi(Cl,async(n,e)=>{let t=e.querySelector(".demo-preview"),r=yc(Zt,n);t.replaceChildren(r.canvas),await r.run()});zi(Pl,async(n,e)=>{await bc(n,e)});zi(Il,async(n,e)=>{await xc(Zt,n,e)});{let n=vc.querySelector("input[type='file']");n.addEventListener("input",async()=>{let e=n.files?.[0];if(!e)return;let{timeline:t,omni:r}=await Oi(Zt,e);await gc(t,r,vc)})}{let n=Tt.querySelector("input[type='file']");n.addEventListener("input",async()=>{let e=n.files?.[0];if(!e)return;Jt(Tt,"running");let{timeline:t,omni:r}=await Oi(Zt,e);vo={timeline:t,omni:r},Tc.disabled=!1;let o=Tt.querySelector(".demo-preview"),i=await r.playback(t);await i.seek(0),o.replaceChildren(i.canvas),Jt(Tt,"done")})}Tc.addEventListener("click",async()=>{vo&&(Jt(Tt,"running"),await vo.omni.render(vo.timeline),Jt(Tt,"done"))});
|
|
2489
2489
|
/*! Bundled license information:
|
|
2490
2490
|
|
|
2491
2491
|
mediabunny/dist/modules/src/misc.js:
|