@omnimedia/omnitool 1.1.0-96 → 1.1.0-98

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.
@@ -1,4 +1,4 @@
1
- import"./chunk-FZ5BYF63.js";import{c as Qt,j as Ca,k as ka,l as Ri,n as Mi,u as Jt}from"./chunk-PSLUOGTZ.js";import"./chunk-CUYOGHWU.js";import"./chunk-ZWCPT5FR.js";import"./chunk-OJ3FPXW7.js";import{b as An,e as Bi}from"./chunk-VLCVEIFU.js";import{Ca as k,F as zi,G as Di,J as ne,K as Q,P as Oi,S as wa,T as qr,V as $t,a as Gd,b as qd,c as Hd,d as _n,e as Ta,fa as P,g as Y,h as Ge,ha as A,i as Fi,j as Ei,k as Vr,m as Gr,o as U,qa as Zt,sa as In}from"./chunk-KWN4NNES.js";var Zm=Gd((b4,Qm)=>{Qm.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
1
+ import"./chunk-FZ5BYF63.js";import{c as Jt,j as Ca,k as ka,l as Ri,n as Mi,u as tr}from"./chunk-PSLUOGTZ.js";import"./chunk-CUYOGHWU.js";import"./chunk-ZWCPT5FR.js";import"./chunk-OJ3FPXW7.js";import{b as An,e as Bi}from"./chunk-VLCVEIFU.js";import{Ca as k,F as zi,G as Di,J as ne,K as Q,P as Oi,S as wa,T as Hr,V as Zt,a as Gd,b as qd,c as Hd,d as _n,e as Ta,fa as P,g as Y,h as Ge,ha as A,i as Fi,j as Ei,k as Gr,m as qr,o as U,qa as er,sa as In}from"./chunk-KWN4NNES.js";var Zm=Gd((b4,Qm)=>{Qm.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 er=Object.freeze({eq(r,e){if(r.length!==e.length)return!1;for(let t=0;t<=r.length;t++)if(r.at(t)!==e.at(t))return!1;return!0},random(r){return crypto.getRandomValues(new Uint8Array(r))}});var ue=class{lexicon;static lexicons=Object.freeze({base2:{characters:"01"},hex:{characters:"0123456789abcdef"},base36:{characters:"0123456789abcdefghijklmnopqrstuvwxyz"},base58:{characters:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"},base62:{characters:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"},base64url:{negativePrefix:"~",characters:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"},base64:{characters:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",padding:{character:"=",size:4}}});lookup;negativePrefix;constructor(e){this.lexicon=e,this.lookup=Object.fromEntries([...e.characters].map((t,n)=>[t,n])),this.negativePrefix=e.negativePrefix??"-"}toBytes(e){let t=Math.log2(this.lexicon.characters.length);if(Number.isInteger(t)){let a=0,c=0,l=[];for(let f of e){if(f===this.lexicon.padding?.character)continue;let u=this.lookup[f];if(u===void 0)throw new Error(`Invalid character: ${f}`);for(a=a<<t|u,c+=t;c>=8;)c-=8,l.push(a>>c&255)}return new Uint8Array(l)}let n=0n,o=BigInt(this.lexicon.characters.length),i=!1;e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),i=!0);for(let a of e){let c=this.lookup[a];if(c===void 0)throw new Error(`Invalid character: ${a}`);n=n*o+BigInt(c)}let s=[];for(;n>0n;)s.unshift(Number(n%256n)),n=n/256n;return new Uint8Array(s)}fromBytes(e){let t=Math.log2(this.lexicon.characters.length);if(Number.isInteger(t)){let s=0,a=0,c="";for(let l of e)for(s=s<<8|l,a+=8;a>=t;){a-=t;let f=s>>a&(1<<t)-1;c+=this.lexicon.characters[f]}if(a>0){let l=s<<t-a&(1<<t)-1;c+=this.lexicon.characters[l]}if(this.lexicon.padding)for(;c.length%this.lexicon.padding.size!==0;)c+=this.lexicon.padding.character;return c}let n=0n;for(let s of e)n=(n<<8n)+BigInt(s);if(n===0n)return this.lexicon.characters[0];let o=BigInt(this.lexicon.characters.length),i="";for(;n>0n;)i=this.lexicon.characters[Number(n%o)]+i,n=n/o;return i}toInteger(e){if(!e)return 0;let t=0n,n=!1,o=BigInt(this.lexicon.characters.length);e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),n=!0);for(let i of e){let s=this.lookup[i];if(s===void 0)throw new Error(`Invalid character: ${i}`);t=t*o+BigInt(s)}return Number(n?-t:t)}fromInteger(e){e=Math.floor(e);let t=e<0,n=BigInt(t?-e:e);if(n===0n)return this.lexicon.characters[0];let o=BigInt(this.lexicon.characters.length),i="";for(;n>0n;)i=this.lexicon.characters[Number(n%o)]+i,n=n/o;return t?`${this.negativePrefix}${i}`:i}random(e=32){return this.fromBytes(er.random(e))}};var ze=new ue(ue.lexicons.hex),z0=new ue(ue.lexicons.base2),D0=new ue(ue.lexicons.base36),Ui=new ue(ue.lexicons.base58),O0=new ue(ue.lexicons.base62),R0=new ue(ue.lexicons.base64),M0=new ue(ue.lexicons.base64url);var Ni=["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 Li=["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 qe={defaults:{groupSize:4,wordSeparator:".",groupSeparator:" "},random(r,e){let t=er.random(r);return this.fromBytes(t,e)},fromBytes(r,e={}){let{groupSize:t=qe.defaults.groupSize,wordSeparator:n=qe.defaults.wordSeparator,groupSeparator:o=qe.defaults.groupSeparator}=e,i=[],s=[];r.forEach((c,l)=>{let f=l%2===0?Ni:Li;s.push(f[c]),s.length===2&&(i.push(s.join("")),s=[])}),s.length&&i.push(s.join(""));let a=[];for(let c=0;c<i.length;c+=t)a.push(i.slice(c,c+t).join(n));return a.join(o)},toBytes(r){let e=r.toLowerCase().replace(/[^a-z]/g,"");if(e.length/3%1!==0)throw new Error(`invalid triplet count, ${e.length} does not divide into triplets`);let n=[];for(let o=0;o<e.length;o+=3)n.push(e.slice(o,o+3));return new Uint8Array(n.map((o,i)=>{let a=(i%2===0?Ni:Li).findIndex(c=>c===o);if(a===-1)throw new Error(`unknown triplet ${o}`);return a}))},toHex(r){return ze.fromBytes(qe.toBytes(r))},fromHex(r,e){return qe.fromBytes(ze.toBytes(r),e)}};var De={defaults:{delimiter:".",sigilBytes:4,previewBytes:8},toBytes(r){r=r.trim();let e=r.split(/[^a-zA-Z0-9]+/m).filter(Boolean).map(o=>o.trim());if(e.length<2)return qe.toBytes(e.join(""));let t=e.pop(),n=e.join("");return new Uint8Array([...qe.toBytes(n),...Ui.toBytes(t)])},parse(r,e){let t=De.toBytes(r);return De.build.fromBytes(t,e)},build:{fromBytes(r,e={}){let{delimiter:t,previewBytes:n,sigilBytes:o}={...De.defaults,...e},i=f=>r.length>0?qe.fromBytes(r.slice(0,f),{wordSeparator:t,groupSeparator:t}):"",s=i(o),a=i(n),c=r.length>n?Ui.fromBytes(r.slice(n)):"",l=[a,c].filter(f=>f.length>0).join(t);return{raw:r,full:l,preview:a,bulk:c,sigil:s,bytes:r,thumbprint:l}},fromHex(r,e){let t=ze.toBytes(r);return De.build.fromBytes(t,e)}},toHex(r){let e=De.toBytes(r);return ze.fromBytes(e)},fromBytes(r,e){return De.build.fromBytes(r,e).full},fromHex(r,e){return De.fromBytes(ze.toBytes(r),e)},sigil:{fromHex(r,e){return De.build.fromHex(r,e).sigil},fromBytes(r,e){return De.build.fromBytes(r,e).sigil}}},Pa=De;var Fn=Object.freeze({fromBytes(r){return[...r].map(e=>e.toString(16).padStart(2,"0")).join("")},toBytes(r){if(r.length%2!==0)throw new Error("must have even number of hex characters");let e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)e[t/2]=parseInt(r.slice(t,t+2),16);return e},random(r=32){return this.fromBytes(er.random(r))},string(r){return Fn.fromBytes(r)},bytes(r){return Fn.toBytes(r)}});function Oe(){let r,e,t=new Promise((o,i)=>{r=o,e=i});function n(o){return o.then(r).catch(e),t}return{promise:t,resolve:r,reject:e,entangle:n}}var En=Object.freeze({happy:r=>r!=null,sad:r=>r==null,boolean:r=>typeof r=="boolean",number:r=>typeof r=="number",string:r=>typeof r=="string",bigint:r=>typeof r=="bigint",object:r=>typeof r=="object"&&r!==null,array:r=>Array.isArray(r),fn:r=>typeof r=="function",symbol:r=>typeof r=="symbol"});var zn=class r extends Map{static require(e,t){if(e.has(t))return e.get(t);throw new Error(`required key not found: "${t}"`)}static guarantee(e,t,n){if(e.has(t))return e.get(t);{let o=n();return e.set(t,o),o}}array(){return[...this]}require(e){return r.require(this,e)}guarantee(e,t){return r.guarantee(this,e,t)}};function _a(r){let e=Promise.resolve();return(...t)=>{let n=()=>r(...t),o=e.then(n);return e=o.catch(()=>{}),o}}function Ia(...r){return(...e)=>r.forEach(t=>t(...e))}var Hr=class extends Error{milliseconds;name=this.constructor.name;constructor(e){super(`deadline exceeded (${(e/1e3).toFixed(1)} seconds)`),this.milliseconds=e}};function Aa(r,e){return r<=0||r===1/0?e():new Promise((t,n)=>{let o=setTimeout(()=>n(new Hr(r)),r);e().then(t).catch(n).finally(()=>clearTimeout(o))})}function Dn(){let r=[];function e(){for(let t of r)t();r=[]}return e.schedule=(...t)=>(r.push(...t),e),e}function Fa(r,e){let t=r;for(let n of e)if(t=t[n],En.sad(t))break;return t}function Ea(){let r=new Set;async function e(...c){await Promise.all([...r].map(l=>l(...c)))}function t(c){return r.add(c),()=>{r.delete(c)}}async function n(...c){return e(...c)}function o(c){return t(c)}async function i(c){let{promise:l,resolve:f}=Oe(),u=o(async(...m)=>{c&&await c(...m),f(m),u()});return l}function s(){r.clear()}let a={pub:n,sub:o,publish:e,subscribe:t,on:t,next:i,clear:s};return Object.assign(o,a),Object.assign(n,a),a}function Vi(r){let e=Ea();return r&&e.sub(r),e.sub}function ke(r){let e=Ea();return r&&e.sub(r),e.pub}function Gi(r,e){return{error:t=>r.error({...e,...t}),rpcRequest:t=>r.rpcRequest({...e,...t}),rpcError:t=>r.rpcError({...e,...t})}}var On=()=>r=>({plain:r.none,errMessage:r.mix(r.brightRed,r.bold),errName:r.red,errStack:r.mix(r.red,r.dim),timestamp:r.blue,timestampErr:r.red});function za(){return On()}var ot=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 Rn=()=>({none:r=>r,uncolor:jd,mix:Xd,hex:Kd,rgb:Da,bgRgb:Yd});function jd(r){return r.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"")}function Xd(...r){return e=>{for(let t of r)e=t(e);return e}}function Kd(r){r=r.replace(/^#/,"");let e,t,n,o;if(r.length===3)e=parseInt(r.split("").map(i=>i+i).join(""),16);else if(r.length===6)e=parseInt(r,16);else throw new Error("Invalid hex color");return t=e>>16&255,n=e>>8&255,o=e&255,Da(t,n,o)}function Da(r,e,t){let n=`\x1B[38;2;${r};${e};${t}m`;return o=>`${n}${o}${ot.reset}`}function Yd(r,e,t){let n=`\x1B[48;2;${r};${e};${t}m`;return o=>`${n}${o}${ot.reset}`}var Wr={...Object.fromEntries(Object.entries(ot).map(([r])=>[r,e=>e])),...Rn()};var jr={...Object.fromEntries(Object.entries(ot).map(([r,e])=>[r,t=>`${e}${t}${ot.reset}`])),...Rn()};function qi(){return typeof Deno<"u"&&typeof Deno.version<"u"}function Hi(){return typeof process<"u"&&process.versions&&process.versions.node}function Oa(){return Hi()?process.env.FORCE_COLOR||process.stdout.isTTY&&process.env.TERM!=="dumb":qi()?Deno.env.get("FORCE_COLOR")||Deno.isatty(Deno.stdout.rid)&&Deno.env.get("TERM")!=="dumb":!1}var Wi=()=>Oa()?jr:Wr;var Mn=()=>({colors:r,theme:e})=>{let t=e(r);function n(s){let a=s.stack?`
2334
+ `,author:"Jake Nelson",license:"MIT",createdAt:"Wed, 1 Nov 2017 15:24:36 -0500",updatedAt:"Thu, 2 Nov 2017 18:37:42 -0500"}]});var rr=Object.freeze({eq(r,e){if(r.length!==e.length)return!1;for(let t=0;t<=r.length;t++)if(r.at(t)!==e.at(t))return!1;return!0},random(r){return crypto.getRandomValues(new Uint8Array(r))}});var ue=class{lexicon;static lexicons=Object.freeze({base2:{characters:"01"},hex:{characters:"0123456789abcdef"},base36:{characters:"0123456789abcdefghijklmnopqrstuvwxyz"},base58:{characters:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"},base62:{characters:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"},base64url:{negativePrefix:"~",characters:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"},base64:{characters:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",padding:{character:"=",size:4}}});lookup;negativePrefix;constructor(e){this.lexicon=e,this.lookup=Object.fromEntries([...e.characters].map((t,n)=>[t,n])),this.negativePrefix=e.negativePrefix??"-"}toBytes(e){let t=Math.log2(this.lexicon.characters.length);if(Number.isInteger(t)){let a=0,c=0,l=[];for(let f of e){if(f===this.lexicon.padding?.character)continue;let u=this.lookup[f];if(u===void 0)throw new Error(`Invalid character: ${f}`);for(a=a<<t|u,c+=t;c>=8;)c-=8,l.push(a>>c&255)}return new Uint8Array(l)}let n=0n,o=BigInt(this.lexicon.characters.length),i=!1;e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),i=!0);for(let a of e){let c=this.lookup[a];if(c===void 0)throw new Error(`Invalid character: ${a}`);n=n*o+BigInt(c)}let s=[];for(;n>0n;)s.unshift(Number(n%256n)),n=n/256n;return new Uint8Array(s)}fromBytes(e){let t=Math.log2(this.lexicon.characters.length);if(Number.isInteger(t)){let s=0,a=0,c="";for(let l of e)for(s=s<<8|l,a+=8;a>=t;){a-=t;let f=s>>a&(1<<t)-1;c+=this.lexicon.characters[f]}if(a>0){let l=s<<t-a&(1<<t)-1;c+=this.lexicon.characters[l]}if(this.lexicon.padding)for(;c.length%this.lexicon.padding.size!==0;)c+=this.lexicon.padding.character;return c}let n=0n;for(let s of e)n=(n<<8n)+BigInt(s);if(n===0n)return this.lexicon.characters[0];let o=BigInt(this.lexicon.characters.length),i="";for(;n>0n;)i=this.lexicon.characters[Number(n%o)]+i,n=n/o;return i}toInteger(e){if(!e)return 0;let t=0n,n=!1,o=BigInt(this.lexicon.characters.length);e.startsWith(this.negativePrefix)&&(e=e.slice(this.negativePrefix.length),n=!0);for(let i of e){let s=this.lookup[i];if(s===void 0)throw new Error(`Invalid character: ${i}`);t=t*o+BigInt(s)}return Number(n?-t:t)}fromInteger(e){e=Math.floor(e);let t=e<0,n=BigInt(t?-e:e);if(n===0n)return this.lexicon.characters[0];let o=BigInt(this.lexicon.characters.length),i="";for(;n>0n;)i=this.lexicon.characters[Number(n%o)]+i,n=n/o;return t?`${this.negativePrefix}${i}`:i}random(e=32){return this.fromBytes(rr.random(e))}};var ze=new ue(ue.lexicons.hex),z0=new ue(ue.lexicons.base2),D0=new ue(ue.lexicons.base36),Ui=new ue(ue.lexicons.base58),O0=new ue(ue.lexicons.base62),R0=new ue(ue.lexicons.base64),M0=new ue(ue.lexicons.base64url);var Ni=["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 Li=["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 qe={defaults:{groupSize:4,wordSeparator:".",groupSeparator:" "},random(r,e){let t=rr.random(r);return this.fromBytes(t,e)},fromBytes(r,e={}){let{groupSize:t=qe.defaults.groupSize,wordSeparator:n=qe.defaults.wordSeparator,groupSeparator:o=qe.defaults.groupSeparator}=e,i=[],s=[];r.forEach((c,l)=>{let f=l%2===0?Ni:Li;s.push(f[c]),s.length===2&&(i.push(s.join("")),s=[])}),s.length&&i.push(s.join(""));let a=[];for(let c=0;c<i.length;c+=t)a.push(i.slice(c,c+t).join(n));return a.join(o)},toBytes(r){let e=r.toLowerCase().replace(/[^a-z]/g,"");if(e.length/3%1!==0)throw new Error(`invalid triplet count, ${e.length} does not divide into triplets`);let n=[];for(let o=0;o<e.length;o+=3)n.push(e.slice(o,o+3));return new Uint8Array(n.map((o,i)=>{let a=(i%2===0?Ni:Li).findIndex(c=>c===o);if(a===-1)throw new Error(`unknown triplet ${o}`);return a}))},toHex(r){return ze.fromBytes(qe.toBytes(r))},fromHex(r,e){return qe.fromBytes(ze.toBytes(r),e)}};var De={defaults:{delimiter:".",sigilBytes:4,previewBytes:8},toBytes(r){r=r.trim();let e=r.split(/[^a-zA-Z0-9]+/m).filter(Boolean).map(o=>o.trim());if(e.length<2)return qe.toBytes(e.join(""));let t=e.pop(),n=e.join("");return new Uint8Array([...qe.toBytes(n),...Ui.toBytes(t)])},parse(r,e){let t=De.toBytes(r);return De.build.fromBytes(t,e)},build:{fromBytes(r,e={}){let{delimiter:t,previewBytes:n,sigilBytes:o}={...De.defaults,...e},i=f=>r.length>0?qe.fromBytes(r.slice(0,f),{wordSeparator:t,groupSeparator:t}):"",s=i(o),a=i(n),c=r.length>n?Ui.fromBytes(r.slice(n)):"",l=[a,c].filter(f=>f.length>0).join(t);return{raw:r,full:l,preview:a,bulk:c,sigil:s,bytes:r,thumbprint:l}},fromHex(r,e){let t=ze.toBytes(r);return De.build.fromBytes(t,e)}},toHex(r){let e=De.toBytes(r);return ze.fromBytes(e)},fromBytes(r,e){return De.build.fromBytes(r,e).full},fromHex(r,e){return De.fromBytes(ze.toBytes(r),e)},sigil:{fromHex(r,e){return De.build.fromHex(r,e).sigil},fromBytes(r,e){return De.build.fromBytes(r,e).sigil}}},Pa=De;var Fn=Object.freeze({fromBytes(r){return[...r].map(e=>e.toString(16).padStart(2,"0")).join("")},toBytes(r){if(r.length%2!==0)throw new Error("must have even number of hex characters");let e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)e[t/2]=parseInt(r.slice(t,t+2),16);return e},random(r=32){return this.fromBytes(rr.random(r))},string(r){return Fn.fromBytes(r)},bytes(r){return Fn.toBytes(r)}});function Oe(){let r,e,t=new Promise((o,i)=>{r=o,e=i});function n(o){return o.then(r).catch(e),t}return{promise:t,resolve:r,reject:e,entangle:n}}var En=Object.freeze({happy:r=>r!=null,sad:r=>r==null,boolean:r=>typeof r=="boolean",number:r=>typeof r=="number",string:r=>typeof r=="string",bigint:r=>typeof r=="bigint",object:r=>typeof r=="object"&&r!==null,array:r=>Array.isArray(r),fn:r=>typeof r=="function",symbol:r=>typeof r=="symbol"});var zn=class r extends Map{static require(e,t){if(e.has(t))return e.get(t);throw new Error(`required key not found: "${t}"`)}static guarantee(e,t,n){if(e.has(t))return e.get(t);{let o=n();return e.set(t,o),o}}array(){return[...this]}require(e){return r.require(this,e)}guarantee(e,t){return r.guarantee(this,e,t)}};function _a(r){let e=Promise.resolve();return(...t)=>{let n=()=>r(...t),o=e.then(n);return e=o.catch(()=>{}),o}}function Ia(...r){return(...e)=>r.forEach(t=>t(...e))}var Wr=class extends Error{milliseconds;name=this.constructor.name;constructor(e){super(`deadline exceeded (${(e/1e3).toFixed(1)} seconds)`),this.milliseconds=e}};function Aa(r,e){return r<=0||r===1/0?e():new Promise((t,n)=>{let o=setTimeout(()=>n(new Wr(r)),r);e().then(t).catch(n).finally(()=>clearTimeout(o))})}function Dn(){let r=[];function e(){for(let t of r)t();r=[]}return e.schedule=(...t)=>(r.push(...t),e),e}function Fa(r,e){let t=r;for(let n of e)if(t=t[n],En.sad(t))break;return t}function Ea(){let r=new Set;async function e(...c){await Promise.all([...r].map(l=>l(...c)))}function t(c){return r.add(c),()=>{r.delete(c)}}async function n(...c){return e(...c)}function o(c){return t(c)}async function i(c){let{promise:l,resolve:f}=Oe(),u=o(async(...m)=>{c&&await c(...m),f(m),u()});return l}function s(){r.clear()}let a={pub:n,sub:o,publish:e,subscribe:t,on:t,next:i,clear:s};return Object.assign(o,a),Object.assign(n,a),a}function Vi(r){let e=Ea();return r&&e.sub(r),e.sub}function ke(r){let e=Ea();return r&&e.sub(r),e.pub}function Gi(r,e){return{error:t=>r.error({...e,...t}),rpcRequest:t=>r.rpcRequest({...e,...t}),rpcError:t=>r.rpcError({...e,...t})}}var On=()=>r=>({plain:r.none,errMessage:r.mix(r.brightRed,r.bold),errName:r.red,errStack:r.mix(r.red,r.dim),timestamp:r.blue,timestampErr:r.red});function za(){return On()}var ot=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 Rn=()=>({none:r=>r,uncolor:jd,mix:Xd,hex:Kd,rgb:Da,bgRgb:Yd});function jd(r){return r.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"")}function Xd(...r){return e=>{for(let t of r)e=t(e);return e}}function Kd(r){r=r.replace(/^#/,"");let e,t,n,o;if(r.length===3)e=parseInt(r.split("").map(i=>i+i).join(""),16);else if(r.length===6)e=parseInt(r,16);else throw new Error("Invalid hex color");return t=e>>16&255,n=e>>8&255,o=e&255,Da(t,n,o)}function Da(r,e,t){let n=`\x1B[38;2;${r};${e};${t}m`;return o=>`${n}${o}${ot.reset}`}function Yd(r,e,t){let n=`\x1B[48;2;${r};${e};${t}m`;return o=>`${n}${o}${ot.reset}`}var jr={...Object.fromEntries(Object.entries(ot).map(([r])=>[r,e=>e])),...Rn()};var Xr={...Object.fromEntries(Object.entries(ot).map(([r,e])=>[r,t=>`${e}${t}${ot.reset}`])),...Rn()};function qi(){return typeof Deno<"u"&&typeof Deno.version<"u"}function Hi(){return typeof process<"u"&&process.versions&&process.versions.node}function Oa(){return Hi()?process.env.FORCE_COLOR||process.stdout.isTTY&&process.env.TERM!=="dumb":qi()?Deno.env.get("FORCE_COLOR")||Deno.isatty(Deno.stdout.rid)&&Deno.env.get("TERM")!=="dumb":!1}var Wi=()=>Oa()?Xr:jr;var Mn=()=>({colors:r,theme:e})=>{let t=e(r);function n(s){let a=s.stack?`
2335
2335
  `+s.stack+`
2336
- `:"";return[t.errName(s.name+":"),t.errMessage(s.message)].join(" ")+t.errStack(a)}function o(s){return s&&s instanceof Error?n(s):s}function i(s){return s&&s instanceof Error?n(s):t.errMessage(s)}return{stdout:s=>s.map(o),stderr:s=>s.map(i)}};function Xr(...r){return e=>({stdout:t=>{for(let n of r)t=n(e).stdout(t);return t},stderr:t=>{for(let n of r)t=n(e).stderr(t);return t}})}function $d(){return{icon:"\u{1F6A8}",now:()=>Date.now()}}var Bn=r=>({colors:e,theme:t})=>{let n={...$d(),...r},o=t(e),i=new Date(n.now()),s=i.getUTCFullYear().toString().padStart(4,"0"),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),c=i.getUTCDate().toString().padStart(2,"0"),l=`${s}-${a}-${c}`,f=i.getUTCHours().toString().padStart(2,"0"),u=i.getUTCMinutes().toString().padStart(2,"0"),m=i.getUTCSeconds().toString().padStart(2,"0"),d=i.getUTCMilliseconds().toString().padStart(3,"0"),p=`${f}:${u}:${m}.${d}`,h=`${l}::${p}`;return{stdout:x=>[o.timestamp(h),...x],stderr:x=>[o.timestampErr(h),...[n.icon].filter(Boolean),...x]}};function Ra(){return Xr(Mn(),Bn())}var Un=()=>({stdout:async r=>{await Deno.stdout.write(new TextEncoder().encode(r+`
2336
+ `:"";return[t.errName(s.name+":"),t.errMessage(s.message)].join(" ")+t.errStack(a)}function o(s){return s&&s instanceof Error?n(s):s}function i(s){return s&&s instanceof Error?n(s):t.errMessage(s)}return{stdout:s=>s.map(o),stderr:s=>s.map(i)}};function Kr(...r){return e=>({stdout:t=>{for(let n of r)t=n(e).stdout(t);return t},stderr:t=>{for(let n of r)t=n(e).stderr(t);return t}})}function $d(){return{icon:"\u{1F6A8}",now:()=>Date.now()}}var Bn=r=>({colors:e,theme:t})=>{let n={...$d(),...r},o=t(e),i=new Date(n.now()),s=i.getUTCFullYear().toString().padStart(4,"0"),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),c=i.getUTCDate().toString().padStart(2,"0"),l=`${s}-${a}-${c}`,f=i.getUTCHours().toString().padStart(2,"0"),u=i.getUTCMinutes().toString().padStart(2,"0"),m=i.getUTCSeconds().toString().padStart(2,"0"),d=i.getUTCMilliseconds().toString().padStart(3,"0"),p=`${f}:${u}:${m}.${d}`,h=`${l}::${p}`;return{stdout:x=>[o.timestamp(h),...x],stderr:x=>[o.timestampErr(h),...[n.icon].filter(Boolean),...x]}};function Ra(){return Kr(Mn(),Bn())}var Un=()=>({stdout:async r=>{await Deno.stdout.write(new TextEncoder().encode(r+`
2337
2337
  `))},stderr:async r=>{await Deno.stderr.write(new TextEncoder().encode(r+`
2338
2338
  `))}});var Nn=()=>({stdout:async r=>{process.stdout.write(r+`
2339
2339
  `)},stderr:async r=>{process.stderr.write(r+`
2340
- `)}});var Ln=()=>({stdout:async r=>console.log(r),stderr:async r=>console.error(r)});var Ma=()=>qi()?Un():Hi()?Nn():Ln();var Ba=()=>({stdout:async()=>{},stderr:async()=>{}});function Ua(){return()=>({stdout:r=>r,stderr:r=>r})}var tr=class r{static writers={auto:Ma,void:Ba,deno:Un,node:Nn,console:Ln};static colors={auto:Wi,colorful:()=>jr,colorless:()=>Wr};static themes={auto:za,basic:On};static shapers={auto:Ra,none:Ua,errors:Mn,timestamp:Bn};writer=r.writers.auto();colors=r.colors.auto();theme=r.themes.auto();shaper=r.shapers.auto();async log(...e){await this.writer.stdout(this.shaper(this).stdout(e).join(" "))}async error(...e){await this.writer.stderr(this.shaper(this).stderr(e).join(" "))}setWriter(e){return this.writer=e,this}setColors(e){return this.colors=e,this}setTheme(e){return this.theme=e,this}setShaper(...e){return this.shaper=Xr(...e),this}};var Kr=class extends tr{static dummy(){return new this().setWriter(tr.writers.void())}rpcRequest=async({request:e,...t})=>{let n=this.colors.none;this.log(...this.#e(t),n(`${e.method}()`))};rpcError=async({request:e,error:t,...n})=>{this.error(...this.#e(n),`${e.method}()`,t)};#e({meta:e,label:t,remote:n}){let o=this.colors.mix(this.colors.blue,this.colors.dim),i=this.colors.mix(this.colors.cyan,this.colors.dim);return[e?this.#t(e):void 0,t||void 0,n===void 0?void 0:n?o("<-"):i("->")].filter(Boolean)}#t(e){let{headers:t}=e.request;return[this.colors.yellow(`[${e.ip}]`),this.colors.green(t.origin?t.origin:"(no-origin)")].join(" ")}};var Re=class extends Kr{rpcRequest=async()=>{}};var He;(function(r){r.version="2.0";function e(t){return"id"in t?t.id:null}r.getId=e,r.errorCodes={serverError:-32e3,unexposedError:-32001}})(He||(He={}));var Vn=class extends Error{name=this.constructor.name},vt=class extends Error{name=this.constructor.name};async function Na({tap:r,request:e,action:t}){let n=He.getId(e);try{let o=await t();return n===null?null:{id:n,result:o,jsonrpc:He.version}}catch(o){return r.rpcError({request:e,error:o}),n===null?null:{id:n,jsonrpc:He.version,error:o instanceof Vn?{code:He.errorCodes.serverError,message:o.message}:{code:He.errorCodes.unexposedError,message:"unexposed error"}}}}function Gn(r){let e=r.tap??new Re;return async t=>{let n=t.method.split("."),o=Fa(r.fns,n),i=async()=>await o(...t.params);return e.rpcRequest({request:t}),await Na({tap:e,request:t,action:i})}}var rr=Symbol("tune"),Qd=Symbol("query"),Zd=Symbol("notify"),Jd=Symbol("settings");function La(r){function e(t){let n={notify:void 0};return new Proxy((()=>{}),{apply:(o,i,s)=>r(t,s,n),get:(o,i)=>{if(i!=="then")return i===rr?s=>(...a)=>r(t,a,{...n,...s}):i===Zd?(...s)=>r(t,s,{...n,notify:!0}):i===Qd?(...s)=>r(t,s,{...n,notify:!1}):i===Jd?n:(o[i]||(o[i]=e([...t,i])),o[i])},set:(o,i,s)=>(o[i]=s,!0)})}return e([])}function yt(r){let{endpoint:e,tap:t=new Re}=r,n=1;return La(async(o,i,s)=>{let a=s.notify??r.notify??!1,c=s.transfer,l={jsonrpc:"2.0",method:o.join("."),params:i},f=a?l:{...l,id:n++};t.rpcRequest({request:f});let u=await e(f,{transfer:c});if(a&&!u)return null;if(!u)throw new vt("response was null, but shouldn't be, because the request was not a notification");if("error"in u)throw new vt(r.label?`${r.label}: ${u.error.message}`:u.error.message);return u.result})}function Yr(r){return yt({endpoint:Gn(r),tap:r.tap})}var bt=class{recv=ke();sendRequest=ke();sendResponse=ke();static makeEntangledPair({origin:e="example.e280.org"}={}){let t=new this,n=new this,o=[t.sendRequest.sub(s=>n.recv(s,{origin:e})),t.sendResponse.sub(s=>n.recv(s,{origin:e})),n.sendRequest.sub(s=>t.recv(s,{origin:e})),n.sendResponse.sub(s=>t.recv(s,{origin:e}))];return[t,n,()=>o.forEach(s=>s())]}};function qn(r,e){return r.addEventListener("message",e),()=>r.removeEventListener("message",e)}function Va(r,e){return async(t,{transfer:n}={})=>{if("id"in t){let o=Oe();return e(t,n,o.promise),r.wait(t.id,t.method).then(i=>(o.resolve(i),i))}else{let o=Promise.resolve(null);return e(t,n,o),o}}}function Ga(r){let e=[],t=[];for(let n of Array.isArray(r)?r:[r])"method"in n?e.push(n):t.push(n);return{requests:e,responses:t}}async function qa(r,e){let t=(await Promise.all(e.map(async n=>r(n)))).filter(n=>n!==null);return t.length===0?null:t.length===1?t[0]:t}var nr=class extends bt{dispose=Dn();constructor(e){super(),this.dispose.schedule(this.sendRequest.sub((t,n)=>e.postMessage(t,n)),this.sendResponse.sub((t,n)=>e.postMessage(t,n)),qn(e,t=>this.recv(t.data,t)))}};var Hn=class{remote;transfer;constructor(e){this.remote=e}};var ji=Object.freeze({timeout:6e4,maxRequestBytes:1e7});var Wn=class{timeout;pending=new Map;constructor(e){this.timeout=e}async wait(e,t){let n=Oe();return this.pending.set(e,{method:t,deferred:n}),await Aa(this.timeout,()=>n.promise).catch(o=>{throw o instanceof Hr&&(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 vt(e.error.message)):t.deferred.resolve(e))}};var St=class{options;remote;remoteEndpoint;dispose=Dn();#e;constructor(e){this.options=e;let{conduit:t,tap:n}=e;this.#e=new Wn(e.timeout??ji.timeout),this.remoteEndpoint=Va(this.#e,t.sendRequest.pub.bind(t.sendRequest)),this.remote=yt({endpoint:this.remoteEndpoint,tap:n&&Gi(n,{remote:!0})}),this.dispose.schedule(t.recv.sub(o=>this.recv(o)))}async recv(e){let t=new Hn(this.remote),{conduit:n,rpc:o,tap:i}=this.options,{requests:s,responses:a}=Ga(e);for(let u of a)this.#e.deliverResponse(u);if(!o)return;let c=await o(t),l=Gn({fns:c,tap:i&&Gi(i,{remote:!1})}),f=await qa(l,s);f&&await n.sendResponse(f,t.transfer)}};var We={derive:{host:r=>({host:r.remote.host,get transfer(){return r.transfer},set transfer(e){r.transfer=e}}),work:r=>({work:r.remote,get transfer(){return r.transfer},set transfer(e){r.transfer=e}})},mock:{host:()=>({host:void 0,transfer:void 0}),work:()=>({work:void 0,transfer:void 0})}};var je=new Re;async function Ha(r,e,t={}){let n=t.tap??je,o=new St({tap:n,timeout:t.timeout??1/0,conduit:new nr(r.getSelf()),rpc:async i=>e(We.derive.host(i))});return await o.remote.infra.ready(),o.remote.host}var or=class{worker;messenger;constructor(e,t){this.worker=e,this.messenger=t}static async make(e,t){let n=t.tap??je,o=t.label??"comrade",i=e.loadWorker(t.workerUrl,o),s=Oe(),a={async ready(){s.resolve()}},c=new St({tap:n,timeout:t.timeout??1/0,conduit:new nr(i),rpc:async l=>({infra:a,host:t.setupHost(We.derive.work(l))})});return await s.promise,new this(i,c)}get work(){return this.messenger.remote}terminate(){this.worker.terminate()}};var jn=class{threads;static async make(e,t){let n=t.workerCount??e.guessOptimalThreadCount(),o=await Promise.all([...Array(n)].map(async(i,s)=>or.make(e,{...t,label:t.label??`${t.label??"comrade"}_${s+1}`})));return new this(o,{tap:t.tap})}work;#e=new Set;#t=[];constructor(e,t={}){this.threads=e;let n=t.tap??je,o=async(i,s)=>this.#r({request:i,prom:Oe(),transfer:s?.transfer});this.work=yt({tap:n,endpoint:o}),e.forEach(i=>this.#e.add(i))}get threadCount(){return this.threads.length}terminate(){for(let e of this.threads)e.terminate()}#r(e){return this.#t.push(e),this.#n(),e.prom.promise}#n(){for(;this.#e.size>0&&this.#t.length>0;){let e=[...this.#e].pop();this.#e.delete(e);let t=this.#t.shift();this.#e.delete(e);let n=e.messenger.remoteEndpoint(t.request,{transfer:t.transfer});t.prom.entangle(n).finally(()=>{this.#e.add(e),this.#n()})}}};var Wa=r=>({thread:e=>or.make(r,e),cluster:e=>jn.make(r,e),worker:(e,t={})=>Ha(r,e,t),work:e=>e,host:e=>e,mocks(e){let{setupWork:t,setupHost:n,tap:o=je}=e,i=We.mock.host(),s=We.mock.work();return s.work=Yr({tap:o,fns:t(i)}),i.host=Yr({tap:o,fns:n(s)}),{workShell:s,hostShell:i,work:s.work,host:i.host}},mockWork(e,t=je){let n=We.mock.host(),o=We.mock.work();return o.work=Yr({tap:t,fns:e(n)}),{workShell:o,hostShell:n,work:o.work,mockHost:i=>(n.host=Yr({tap:t,fns:i(o)}),{workShell:o,hostShell:n,work:o.work,host:n.host})}}});var ja=()=>({getSelf(){return self},guessOptimalThreadCount(){let r=navigator.hardwareConcurrency??1;return Math.max(1,r-1)},loadWorker(r,e){return new window.Worker(r,{name:e,type:"module"})},async loadWasm(r){return WebAssembly.instantiateStreaming(fetch(r))}});var rp=ja(),ir=Wa(rp);function g(r){if(!r)throw new Error("Assertion failed.")}var Xn=r=>{let e=(r%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${r}.`)},de=r=>r&&r[r.length-1];var $=class r{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),o=(t&1<<n)>>n;return this.pos++,o}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let o=this.pos;o<n;o++){let i=Math.floor(o/8),s=this.bytes[i],a=7-(o&7);s&=~(1<<a),s|=(t&1<<n-o-1)>>n-o-1<<a,this.bytes[i]=s}this.pos=n}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new r(this.bytes);return e.pos=this.pos,e}},O=r=>{let e=0;for(;r.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+r.readBits(e)},Be=r=>{let e=O(r);return(e&1)===0?-(e>>1):e+1>>1};var Pe=r=>r.constructor===Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),j=r=>r.constructor===DataView?r:ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r),ce=new TextDecoder;var Qi=r=>Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),Zi={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Kn=Qi(Zi),Ji={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Yn=Qi(Ji),es={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},$n=Qi(es);var Qn=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r),Me=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e,t=new Promise(o=>{e=o}),n=this.currentPromise;return this.currentPromise=t,await n,e}},ts=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),rs=r=>(r=r>>1&1431655765|(r&1431655765)<<1,r=r>>2&858993459|(r&858993459)<<2,r=r>>4&252645135|(r&252645135)<<4,r=r>>8&16711935|(r&16711935)<<8,r=r>>16&65535|(r&65535)<<16,r>>>0),Tt=(r,e,t)=>{let n=0,o=r.length-1,i=-1;for(;n<=o;){let s=n+o>>1,a=t(r[s]);a===e?(i=s,o=s-1):a<e?n=s+1:o=s-1}return i},W=(r,e,t)=>{let n=0,o=r.length-1,i=-1;for(;n<=o;){let s=n+(o-n+1)/2|0;t(r[s])<=e?(i=s,n=s+1):o=s-1}return i},ns=(r,e,t)=>{let n=W(r,t(e),t);r.splice(n+1,0,e)},pe=()=>{let r,e;return{promise:new Promise((n,o)=>{r=n,e=o}),resolve:r,reject:e}};var os=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return r[t]},Zn=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1},Ka=async function*(r){Symbol.iterator in r?yield*r[Symbol.iterator]():yield*r[Symbol.asyncIterator]()},Ya=r=>{if(!(Symbol.iterator in r)&&!(Symbol.asyncIterator in r))throw new TypeError("Argument must be an iterable or async iterable.")},we=r=>{throw new Error(`Unexpected value: ${r}`)},wt=(r,e,t)=>{let n=r.getUint8(e),o=r.getUint8(e+1),i=r.getUint8(e+2);return t?n|o<<8|i<<16:n<<16|o<<8|i},$a=(r,e,t)=>wt(r,e,t)<<8>>8,Qa=(r,e,t,n)=>{t=t>>>0,t=t&16777215,n?(r.setUint8(e,t&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t>>>16&255)):(r.setUint8(e,t>>>16&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t&255))};var is=(r,e)=>({async next(){let t=await r.next();return t.done?{value:void 0,done:!0}:{value:e(t.value),done:!1}},return(){return r.return()},throw(t){return r.throw(t)},[Symbol.asyncIterator](){return this}}),Ct=(r,e,t)=>Math.max(e,Math.min(t,r)),le="und",kt=r=>{let e=Math.round(r);return Math.abs(r/e-1)<10*Number.EPSILON?e:r},Za=(r,e)=>Math.round(r/e)*e,Ja=r=>{let e=0;for(;r;)e++,r>>=1;return e},np=/^[a-z]{3}$/,Jn=r=>np.test(r),Ue=1e6*(1+Number.EPSILON),ss=(r,e)=>{let t={...r,...e};if(r.headers||e.headers){let n=r.headers?Xa(r.headers):{},o=e.headers?Xa(e.headers):{},i={...n};Object.entries(o).forEach(([s,a])=>{let c=Object.keys(i).find(l=>l.toLowerCase()===s.toLowerCase());c&&delete i[c],i[s]=a}),t.headers=i}return t},Xa=r=>{if(r instanceof Headers){let e={};return r.forEach((t,n)=>{e[n]=t}),e}if(Array.isArray(r)){let e={};return r.forEach(([t,n])=>{e[t]=n}),e}return r},as=async(r,e,t,n,o)=>{let i=0;for(;;)try{return await r(e,t)}catch(s){if(o())throw s;i++;let a=n(i,s,e);if(a===null)throw s;if(console.error("Retrying failed fetch. Error:",s),!Number.isFinite(a)||a<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(a>0&&await new Promise(c=>setTimeout(c,1e3*a)),o())throw s}};var $r=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},Xi=null,it=()=>Xi!==null?Xi:Xi=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),Ki=null,Qr=()=>Ki!==null?Ki:Ki=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),Yi=null,Zr=()=>Yi!==null?Yi:Yi=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),$i=null,ec=()=>{if($i!==null)return $i;if(typeof navigator>"u")return null;let r=/\bChrome\/(\d+)/.exec(navigator.userAgent);return r?$i=Number(r[1]):null},Pt=(r,e)=>r!==-1?r:e,eo=(r,e,t,n)=>r<=n&&t<=e;var tc=r=>{let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t};var to=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Jr=r=>typeof r=="number"&&!Number.isNaN(r);var st=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.")}},ro=class{constructor(e,t,n,o){if(this.data=e,this.mimeType=t,this.name=n,this.description=o,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!==void 0&&typeof t!="string")throw new TypeError("mimeType, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("name, when provided, must be a string.");if(o!==void 0&&typeof o!="string")throw new TypeError("description, when provided, must be a string.")}};var xe={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};var at=["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"],op=["aac","opus","mp3","vorbis","flac"],x1=[...op,...at];var _t=[{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 rc=".01.01.01.01.00",nc=".0.110.01.01.01.0";var no=r=>{let{codec:e,codecDescription:t,colorSpace:n,avcCodecInfo:o,hevcCodecInfo:i,vp9CodecInfo:s,av1CodecInfo:a}=r;if(e==="avc"){if(g(r.avcType!==null),o){let c=new Uint8Array([o.avcProfileIndication,o.profileCompatibility,o.avcLevelIndication]);return`avc${r.avcType}.${ts(c)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${r.avcType}.${ts(t.subarray(1,4))}`}else if(e==="hevc"){let c,l,f,u,m,d;if(i)c=i.generalProfileSpace,l=i.generalProfileIdc,f=rs(i.generalProfileCompatibilityFlags),u=i.generalTierFlag,m=i.generalLevelIdc,d=[...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=j(t),x=h.getUint8(1);c=x>>6&3,l=x&31,f=rs(h.getUint32(2)),u=x>>5&1,m=h.getUint8(12),d=[];for(let y=0;y<6;y++)d.push(h.getUint8(6+y))}let p="hev1.";for(p+=["","A","B","C"][c]+l,p+=".",p+=f.toString(16).toUpperCase(),p+=".",p+=u===0?"L":"H",p+=m;d.length>0&&d[d.length-1]===0;)d.pop();return d.length>0&&(p+=".",p+=d.map(h=>h.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!s){let y=r.width*r.height,v=de(_t).level;for(let S of _t)if(y<=S.maxPictureSize){v=S.level;break}return`vp09.00.${v.toString().padStart(2,"0")}.08`}let c=s.profile.toString().padStart(2,"0"),l=s.level.toString().padStart(2,"0"),f=s.bitDepth.toString().padStart(2,"0"),u=s.chromaSubsampling.toString().padStart(2,"0"),m=s.colourPrimaries.toString().padStart(2,"0"),d=s.transferCharacteristics.toString().padStart(2,"0"),p=s.matrixCoefficients.toString().padStart(2,"0"),h=s.videoFullRangeFlag.toString().padStart(2,"0"),x=`vp09.${c}.${l}.${f}.${u}`;return x+=`.${m}.${d}.${p}.${h}`,x.endsWith(rc)&&(x=x.slice(0,-rc.length)),x}else if(e==="av1"){if(!a){let S=r.width*r.height,C=de(_t).level;for(let _ of _t)if(S<=_.maxPictureSize){C=_.level;break}return`av01.0.${C.toString().padStart(2,"0")}M.08`}let c=a.profile,l=a.level.toString().padStart(2,"0"),f=a.tier?"H":"M",u=a.bitDepth.toString().padStart(2,"0"),m=a.monochrome?"1":"0",d=100*a.chromaSubsamplingX+10*a.chromaSubsamplingY+1*(a.chromaSubsamplingX&&a.chromaSubsamplingY?a.chromaSamplePosition:0),p=n?.primaries?Zi[n.primaries]:1,h=n?.transfer?Ji[n.transfer]:1,x=n?.matrix?es[n.matrix]:1,y=n?.fullRange?1:0,v=`av01.${c}.${l}${f}.${u}`;return v+=`.${m}.${d.toString().padStart(3,"0")}`,v+=`.${p.toString().padStart(2,"0")}`,v+=`.${h.toString().padStart(2,"0")}`,v+=`.${x.toString().padStart(2,"0")}`,v+=`.${y}`,v.endsWith(nc)&&(v=v.slice(0,-nc.length)),v}}throw new TypeError(`Unhandled codec '${e}'.`)};var oo=r=>{let{codec:e,codecDescription:t,aacCodecInfo:n}=r;if(e==="aac"){if(!n)throw new TypeError("AAC codec info must be provided.");return n.isMpeg2?"mp4a.67":`mp4a.40.${ls(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&&at.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},en=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],cs=[-1,1,2,3,4,5,6,8],ls=r=>{if(!r||r.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new $(r),t=e.readBits(5);t===31&&(t=32+e.readBits(6));let n=e.readBits(4),o=null;n===15?o=e.readBits(24):n<en.length&&(o=en[n]);let i=e.readBits(4),s=null;return i>=1&&i<=7&&(s=cs[i]),{objectType:t,frequencyIndex:n,sampleRate:o,channelConfiguration:i,numberOfChannels:s}};var It=48e3,ip=/^pcm-([usf])(\d+)+(be)?$/,io=r=>{if(g(at.includes(r)),r==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(r==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=ip.exec(r);g(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";let n=Number(e[2])/8,o=e[3]!=="be",i=r==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:n,littleEndian:o,silentValue:i}};var At;(function(r){r[r.IDR=5]="IDR",r[r.SEI=6]="SEI",r[r.SPS=7]="SPS",r[r.PPS=8]="PPS",r[r.SPS_EXT=13]="SPS_EXT"})(At||(At={}));var he;(function(r){r[r.RASL_N=8]="RASL_N",r[r.RASL_R=9]="RASL_R",r[r.BLA_W_LP=16]="BLA_W_LP",r[r.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",r[r.VPS_NUT=32]="VPS_NUT",r[r.SPS_NUT=33]="SPS_NUT",r[r.PPS_NUT=34]="PPS_NUT",r[r.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",r[r.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(he||(he={}));var ao=r=>{let e=[],t=0;for(;t<r.length;){let n=-1,o=0;for(let i=t;i<r.length-3;i++){if(r[i]===0&&r[i+1]===0&&r[i+2]===1){n=i,o=3;break}if(i<r.length-4&&r[i]===0&&r[i+1]===0&&r[i+2]===0&&r[i+3]===1){n=i,o=4;break}}if(n===-1)break;if(t>0&&n>t){let i=r.subarray(t,n);i.length>0&&e.push(i)}t=n+o}if(t<r.length){let n=r.subarray(t);n.length>0&&e.push(n)}return e},sc=(r,e)=>{let t=[],n=0,o=new DataView(r.buffer,r.byteOffset,r.byteLength);for(;n+e<=r.length;){let i;e===1?i=o.getUint8(n):e===2?i=o.getUint16(n,!1):e===3?i=wt(o,n,!1):e===4?i=o.getUint32(n,!1):(we(e),g(!1)),n+=e;let s=r.subarray(n,n+i);t.push(s),n+=i}return t},so=r=>{let e=[],t=r.length;for(let n=0;n<t;n++)n+2<t&&r[n]===0&&r[n+1]===0&&r[n+2]===3?(e.push(0,0),n+=2):e.push(r[n]);return new Uint8Array(e)},us=new Uint8Array([0,0,0,1]),ap=r=>{let e=r.reduce((o,i)=>o+us.byteLength+i.byteLength,0),t=new Uint8Array(e),n=0;for(let o of r)t.set(us,n),n+=us.byteLength,t.set(o,n),n+=o.byteLength;return t},cp=(r,e)=>{let t=r.reduce((i,s)=>i+e+s.byteLength,0),n=new Uint8Array(t),o=0;for(let i of r){let s=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(e){case 1:s.setUint8(o,i.byteLength);break;case 2:s.setUint16(o,i.byteLength,!1);break;case 3:Qa(s,o,i.byteLength,!1);break;case 4:s.setUint32(o,i.byteLength,!1);break}o+=e,n.set(i,o),o+=i.byteLength}return n},fs=(r,e)=>{if(e.description){let o=(Pe(e.description)[4]&3)+1;return sc(r,o)}else return ao(r)},ac=(r,e)=>{if(e.description){let o=(Pe(e.description)[4]&3)+1;return cp(r,o)}else return ap(r)},Ft=r=>r[0]&31,cc=r=>{try{let e=ao(r),t=e.filter(c=>Ft(c)===At.SPS),n=e.filter(c=>Ft(c)===At.PPS),o=e.filter(c=>Ft(c)===At.SPS_EXT);if(t.length===0||n.length===0)return null;let i=t[0],s=ms(i);g(s!==null);let a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:n,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?o:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}};var lc=r=>{try{let e=j(r),t=0,n=e.getUint8(t++),o=e.getUint8(t++),i=e.getUint8(t++),s=e.getUint8(t++),a=e.getUint8(t++)&3,c=e.getUint8(t++)&31,l=[];for(let d=0;d<c;d++){let p=e.getUint16(t,!1);t+=2,l.push(r.subarray(t,t+p)),t+=p}let f=e.getUint8(t++),u=[];for(let d=0;d<f;d++){let p=e.getUint16(t,!1);t+=2,u.push(r.subarray(t,t+p)),t+=p}let m={configurationVersion:n,avcProfileIndication:o,profileCompatibility:i,avcLevelIndication:s,lengthSizeMinusOne:a,sequenceParameterSets:l,pictureParameterSets:u,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((o===100||o===110||o===122||o===144)&&t+4<=r.length){let d=e.getUint8(t++)&3,p=e.getUint8(t++)&7,h=e.getUint8(t++)&7,x=e.getUint8(t++);m.chromaFormat=d,m.bitDepthLumaMinus8=p,m.bitDepthChromaMinus8=h;let y=[];for(let v=0;v<x;v++){let S=e.getUint16(t,!1);t+=2,y.push(r.subarray(t,t+S)),t+=S}m.sequenceParameterSetExt=y}return m}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}},ms=r=>{try{let e=new $(so(r));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let n=e.readAlignedByte(),o=e.readAlignedByte(),i=e.readAlignedByte();O(e);let s=null,a=null,c=null;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(s=O(e),s===3&&e.skipBits(1),a=O(e),c=O(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,x=8;for(let y=0;y<p;y++){if(x!==0){let v=Be(e);x=(h+v+256)%256}h=x===0?h:x}}}O(e);let l=O(e);if(l===0)O(e);else if(l===1){e.skipBits(1),Be(e),Be(e);let u=O(e);for(let m=0;m<u;m++)Be(e)}O(e),e.skipBits(1),O(e),O(e);let f=e.readBits(1);return{profileIdc:n,constraintFlags:o,levelIdc:i,frameMbsOnlyFlag:f,chromaFormatIdc:s,bitDepthLumaMinus8:a,bitDepthChromaMinus8:c}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},ds=(r,e)=>{if(e.description){let o=(Pe(e.description)[21]&3)+1;return sc(r,o)}else return ao(r)},Xe=r=>r[0]>>1&63,uc=r=>{try{let e=ao(r),t=e.filter(L=>Xe(L)===he.VPS_NUT),n=e.filter(L=>Xe(L)===he.SPS_NUT),o=e.filter(L=>Xe(L)===he.PPS_NUT),i=e.filter(L=>Xe(L)===he.PREFIX_SEI_NUT||Xe(L)===he.SUFFIX_SEI_NUT);if(n.length===0||o.length===0)return null;let s=n[0],a=new $(so(s));a.skipBits(16),a.readBits(4);let c=a.readBits(3),l=a.readBits(1),{general_profile_space:f,general_tier_flag:u,general_profile_idc:m,general_profile_compatibility_flags:d,general_constraint_indicator_flags:p,general_level_idc:h}=lp(a,c);O(a);let x=O(a);x===3&&a.skipBits(1),O(a),O(a),a.readBits(1)&&(O(a),O(a),O(a),O(a));let y=O(a),v=O(a);O(a);let C=a.readBits(1)?0:c;for(let L=C;L<=c;L++)O(a),O(a),O(a);O(a),O(a),O(a),O(a),O(a),O(a),a.readBits(1)&&a.readBits(1)&&up(a),a.skipBits(1),a.skipBits(1),a.readBits(1)&&(a.skipBits(4),a.skipBits(4),O(a),O(a),a.skipBits(1));let _=O(a);if(fp(a,_),a.readBits(1)){let L=O(a);for(let V=0;V<L;V++)O(a),a.skipBits(1)}a.skipBits(1),a.skipBits(1);let T=0;a.readBits(1)&&(T=dp(a,c));let E=0;if(o.length>0){let L=o[0],V=new $(so(L));V.skipBits(16),O(V),O(V),V.skipBits(1),V.skipBits(1),V.skipBits(3),V.skipBits(1),V.skipBits(1),O(V),O(V),Be(V),V.skipBits(1),V.skipBits(1),V.readBits(1)&&O(V),Be(V),Be(V),V.skipBits(1),V.skipBits(1),V.skipBits(1),V.skipBits(1);let te=V.readBits(1),Ee=V.readBits(1);!te&&!Ee?E=0:te&&!Ee?E=2:!te&&Ee?E=3:E=0}let I=[...t.length?[{arrayCompleteness:1,nalUnitType:he.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:he.SPS_NUT,nalUnits:n}]:[],...o.length?[{arrayCompleteness:1,nalUnitType:he.PPS_NUT,nalUnits:o}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Xe(i[0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:f,generalTierFlag:u,generalProfileIdc:m,generalProfileCompatibilityFlags:d,generalConstraintIndicatorFlags:p,generalLevelIdc:h,minSpatialSegmentationIdc:T,parallelismType:E,chromaFormatIdc:x,bitDepthLumaMinus8:y,bitDepthChromaMinus8:v,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:l,lengthSizeMinusOne:3,arrays:I}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},lp=(r,e)=>{let t=r.readBits(2),n=r.readBits(1),o=r.readBits(5),i=0;for(let f=0;f<32;f++)i=i<<1|r.readBits(1);let s=new Uint8Array(6);for(let f=0;f<6;f++)s[f]=r.readBits(8);let a=r.readBits(8),c=[],l=[];for(let f=0;f<e;f++)c.push(r.readBits(1)),l.push(r.readBits(1));if(e>0)for(let f=e;f<8;f++)r.skipBits(2);for(let f=0;f<e;f++)c[f]&&r.skipBits(88),l[f]&&r.skipBits(8);return{general_profile_space:t,general_tier_flag:n,general_profile_idc:o,general_profile_compatibility_flags:i,general_constraint_indicator_flags:s,general_level_idc:a}},up=r=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!r.readBits(1))O(r);else{let o=Math.min(64,1<<4+(e<<1));e>1&&Be(r);for(let i=0;i<o;i++)Be(r)}},fp=(r,e)=>{let t=[];for(let n=0;n<e;n++)t[n]=mp(r,n,e,t)},mp=(r,e,t,n)=>{let o=0,i=0,s=0;if(e!==0&&(i=r.readBits(1)),i){if(e===t){let c=O(r);s=e-(c+1)}else s=e-1;r.readBits(1),O(r);let a=n[s]??0;for(let c=0;c<=a;c++)r.readBits(1)||r.readBits(1);o=n[s]}else{let a=O(r),c=O(r);for(let l=0;l<a;l++)O(r),r.readBits(1);for(let l=0;l<c;l++)O(r),r.readBits(1);o=a+c}return o},dp=(r,e)=>{if(r.readBits(1)&&r.readBits(8)===255&&(r.readBits(16),r.readBits(16)),r.readBits(1)&&r.readBits(1),r.readBits(1)&&(r.readBits(3),r.readBits(1),r.readBits(1)&&(r.readBits(8),r.readBits(8),r.readBits(8))),r.readBits(1)&&(O(r),O(r)),r.readBits(1),r.readBits(1),r.readBits(1),r.readBits(1)&&(O(r),O(r),O(r),O(r)),r.readBits(1)&&(r.readBits(32),r.readBits(32),r.readBits(1)&&O(r),r.readBits(1)&&pp(r,!0,e)),r.readBits(1)){r.readBits(1),r.readBits(1),r.readBits(1);let t=O(r);return O(r),O(r),O(r),O(r),t}return 0},pp=(r,e,t)=>{let n=!1,o=!1,i=!1;e&&(n=r.readBits(1)===1,o=r.readBits(1)===1,(n||o)&&(i=r.readBits(1)===1,i&&(r.readBits(8),r.readBits(5),r.readBits(1),r.readBits(5)),r.readBits(4),r.readBits(4),i&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5)));for(let s=0;s<=t;s++){let a=r.readBits(1)===1,c=!0;a||(c=r.readBits(1)===1);let l=!1;c?O(r):l=r.readBits(1)===1;let f=1;l||(f=O(r)+1),n&&oc(r,f,i),o&&oc(r,f,i)}},oc=(r,e,t)=>{for(let n=0;n<e;n++)O(r),O(r),t&&(O(r),O(r)),r.readBits(1)};var co=r=>{let e=new $(r);if(e.readBits(2)!==2)return null;let n=e.readBits(1),i=(e.readBits(1)<<1)+n;if(i===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;i>=2&&(l=e.readBits(1)?12:10);let f=e.readBits(3),u=0,m=0;if(f!==7)if(m=e.readBits(1),i===1||i===3){let E=e.readBits(1),I=e.readBits(1);u=!E&&!I?3:E&&!I?2:1,e.skipBits(1)}else u=1;else u=3,m=1;let d=e.readBits(16),p=e.readBits(16),h=d+1,x=p+1,y=h*x,v=de(_t).level;for(let T of _t)if(y<=T.maxPictureSize){v=T.level;break}return{profile:i,level:v,bitDepth:l,chromaSubsampling:u,videoFullRangeFlag:m,colourPrimaries:f===2?1:f===1?6:2,transferCharacteristics:f===2?1:f===1?6:2,matrixCoefficients:f===7?0:f===2?1:f===1?6:2}},fc=function*(r){let e=new $(r),t=()=>{let n=0;for(let o=0;o<8;o++){let i=e.readAlignedByte();if(n|=(i&127)<<o*7,!(i&128))break;if(o===7&&i&128)return null}return n>=2**32-1?null:n};for(;e.getBitsLeft()>=8;){e.skipBits(1);let n=e.readBits(4),o=e.readBits(1),i=e.readBits(1);e.skipBits(1),o&&e.skipBits(8);let s;if(i){let a=t();if(a===null)return;s=a}else s=Math.floor(e.getBitsLeft()/8);g(e.pos%8===0),yield{type:n,data:r.subarray(e.pos/8,e.pos/8+s)},e.skipBits(s*8)}},lo=r=>{for(let{type:e,data:t}of fc(r)){if(e!==1)continue;let n=new $(t),o=n.readBits(3),i=n.readBits(1),s=n.readBits(1),a=0,c=0,l=0;if(s)a=n.readBits(5);else{if(n.readBits(1)&&(n.skipBits(32),n.skipBits(32),n.readBits(1)))return null;let T=n.readBits(1);T&&(l=n.readBits(5),n.skipBits(32),n.skipBits(5),n.skipBits(5));let E=n.readBits(5);for(let I=0;I<=E;I++){n.skipBits(12);let M=n.readBits(5);if(I===0&&(a=M),M>7){let V=n.readBits(1);I===0&&(c=V)}if(T&&n.readBits(1)){let te=l+1;n.skipBits(te),n.skipBits(te),n.skipBits(1)}n.readBits(1)&&n.skipBits(4)}}let f=n.readBits(4),u=n.readBits(4),m=f+1;n.skipBits(m);let d=u+1;n.skipBits(d);let p=0;if(s?p=0:p=n.readBits(1),p&&(n.skipBits(4),n.skipBits(3)),n.skipBits(1),n.skipBits(1),n.skipBits(1),!s){n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let _=n.readBits(1);_&&(n.skipBits(1),n.skipBits(1));let T=n.readBits(1),E=0;T?E=2:E=n.readBits(1),E>0&&(n.readBits(1)||n.skipBits(1)),_&&n.skipBits(3)}n.skipBits(1),n.skipBits(1),n.skipBits(1);let h=n.readBits(1),x=8;o===2&&h?x=n.readBits(1)?12:10:o<=2&&(x=h?10:8);let y=0;o!==1&&(y=n.readBits(1));let v=1,S=1,C=0;return y||(o===0?(v=1,S=1):o===1?(v=0,S=0):x===12&&(v=n.readBits(1),v&&(S=n.readBits(1))),v&&S&&(C=n.readBits(2))),{profile:o,level:a,tier:c,bitDepth:x,monochrome:y,chromaSubsamplingX:v,chromaSubsamplingY:S,chromaSamplePosition:C}}return null},mc=r=>{let e=j(r),t=e.getUint8(9),n=e.getUint16(10,!0),o=e.getUint32(12,!0),i=e.getInt16(16,!0),s=e.getUint8(18),a=null;return s&&(a=r.subarray(19,21+t)),{outputChannelCount:t,preSkip:n,inputSampleRate:o,outputGain:i,channelMappingFamily:s,channelMappingTable:a}},hp=[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],dc=r=>{let e=r[0]>>3;return{durationInSamples:hp[e]}},pc=r=>{if(r.length<7)throw new Error("Setup header is too short.");if(r[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...r.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let t=r.length,n=new Uint8Array(t);for(let u=0;u<t;u++)n[u]=r[t-1-u];let o=new $(n),i=0;for(;o.getBitsLeft()>97;)if(o.readBits(1)===1){i=o.pos;break}if(i===0)throw new Error("Invalid Setup header: framing bit not found.");let s=0,a=!1,c=0;for(;o.getBitsLeft()>=97;){let u=o.pos,m=o.readBits(8),d=o.readBits(16),p=o.readBits(16);if(m>63||d!==0||p!==0){o.pos=u;break}if(o.skipBits(1),s++,s>64)break;o.clone().readBits(6)+1===s&&(a=!0,c=s)}if(!a)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);let l=c;o.pos=0,o.skipBits(i);let f=Array(l).fill(0);for(let u=l-1;u>=0;u--)o.skipBits(40),f[u]=o.readBits(1);return{modeBlockflags:f}},uo=(r,e,t)=>{switch(r){case"avc":{let n=fs(t,e),o=n.some(i=>Ft(i)===At.IDR);if(!o&&(!Zr()||ec()>=144))for(let i of n){if(Ft(i)!==At.SEI)continue;let a=so(i),c=1;do{let l=0;for(;;){let m=a[c++];if(m===void 0||(l+=m,m<255))break}let f=0;for(;;){let m=a[c++];if(m===void 0||(f+=m,m<255))break}if(l===6){let m=new $(a);m.pos=8*c;let d=O(m),p=m.readBits(1);if(d===0&&p===1){o=!0;break}}c+=f}while(c<a.length-1)}return o?"key":"delta"}case"hevc":return ds(t,e).some(i=>{let s=Xe(i);return he.BLA_W_LP<=s&&s<=he.RSV_IRAP_VCL23})?"key":"delta";case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{let n=new $(t);if(n.readBits(2)!==2)return null;let o=n.readBits(1);return(n.readBits(1)<<1)+o===3&&n.skipBits(1),n.readBits(1)?null:n.readBits(1)===0?"key":"delta"}case"av1":{let n=!1;for(let{type:o,data:i}of fc(t))if(o===1){let s=new $(i);s.skipBits(4),n=!!s.readBits(1)}else if(o===3||o===6||o===7){if(n)return"key";let s=new $(i);return s.readBits(1)?null:s.readBits(2)===0?"key":"delta"}return null}default:we(r),g(!1)}},ct;(function(r){r[r.STREAMINFO=0]="STREAMINFO",r[r.VORBIS_COMMENT=4]="VORBIS_COMMENT",r[r.PICTURE=6]="PICTURE"})(ct||(ct={}));var tn=(r,e)=>{let t=j(r),n=0,o=t.getUint32(n,!0);n+=4;let i=ce.decode(r.subarray(n,n+o));n+=o,o>0&&(e.raw??={},e.raw.vendor??=i);let s=t.getUint32(n,!0);n+=4;for(let a=0;a<s;a++){let c=t.getUint32(n,!0);n+=4;let l=ce.decode(r.subarray(n,n+c));n+=c;let f=l.indexOf("=");if(f===-1)continue;let u=l.slice(0,f).toUpperCase(),m=l.slice(f+1);switch(e.raw??={},e.raw[u]??=m,u){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 d=m.split("/"),p=Number.parseInt(d[0],10),h=d[1]&&Number.parseInt(d[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),h&&Number.isInteger(h)&&h>0&&(e.tracksTotal??=h)}break;case"TRACKTOTAL":{let d=Number.parseInt(m,10);Number.isInteger(d)&&d>0&&(e.tracksTotal??=d)}break;case"DISCNUMBER":{let d=m.split("/"),p=Number.parseInt(d[0],10),h=d[1]&&Number.parseInt(d[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),h&&Number.isInteger(h)&&h>0&&(e.discsTotal??=h)}break;case"DISCTOTAL":{let d=Number.parseInt(m,10);Number.isInteger(d)&&d>0&&(e.discsTotal??=d)}break;case"DATE":{let d=new Date(m);Number.isNaN(d.getTime())||(e.date??=d)}break;case"GENRE":e.genre??=m;break;case"METADATA_BLOCK_PICTURE":{let d=tc(m),p=j(d),h=p.getUint32(0,!1),x=p.getUint32(4,!1),y=String.fromCharCode(...d.subarray(8,8+x)),v=p.getUint32(8+x,!1),S=ce.decode(d.subarray(12+x,12+x+v)),C=p.getUint32(x+v+28),_=d.subarray(x+v+32,x+v+32+C);e.images??=[],e.images.push({data:_,mimeType:y,kind:h===3?"coverFront":h===4?"coverBack":"unknown",name:void 0,description:S||void 0})}break}}};var me=class{constructor(e){this.input=e}};var fo=[],mo=[];var oe=new Uint8Array(0),Z=class r{constructor(e,t,n,o,i=-1,s,a){if(this.data=e,this.type=t,this.timestamp=n,this.duration=o,this.sequenceNumber=i,e===oe&&s===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(s===void 0&&(s=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(n))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(o)||o<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(i))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");if(a!==void 0&&(typeof a!="object"||!a))throw new TypeError("sideData, when provided, must be an object.");if(a?.alpha!==void 0&&!(a.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(a?.alphaByteLength!==void 0&&(!Number.isInteger(a.alphaByteLength)||a.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=a??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===oe}get microsecondTimestamp(){return Math.trunc(Ue*this.timestamp)}get microsecondDuration(){return Math.trunc(Ue*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let n=new Uint8Array(e.byteLength);return e.copyTo(n),new r(n,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");return new r(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}};var hc=r=>{let t=0,n=0,o=~r;o&128&&(o&=-129,t=-1),n=((o&240)>>4)+5;let i=(1<<n|(o&15)<<n-4|1<<n-5)-33;return t===0?i:-i};var gc=r=>{let e=0,t=0,n=r^85;n&128&&(n&=-129,e=-1),t=((n&240)>>4)+4;let o=0;return t!==4?o=1<<t|(n&15)<<t-4|1<<t-5:o=n<<1|1,e===0?o:-o};to();var xc=-1/0,vc=-1/0,on=null;typeof FinalizationRegistry<"u"&&(on=new FinalizationRegistry(r=>{let e=Date.now();r.type==="video"?(e-xc>=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."),xc=e),typeof VideoFrame<"u"&&r.data instanceof VideoFrame&&r.data.close()):(e-vc>=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."),vc=e),typeof AudioData<"u"&&r.data instanceof AudioData&&r.data.close())}));var bc=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],gp=new Set(bc),ar=class r{get displayWidth(){return this.rotation%180===0?this.codedWidth:this.codedHeight}get displayHeight(){return this.rotation%180===0?this.codedHeight:this.codedWidth}get microsecondTimestamp(){return Math.trunc(Ue*this.timestamp)}get microsecondDuration(){return Math.trunc(Ue*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||!gp.has(t.format))throw new TypeError("init.format must be one of: "+bc.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=Pe(e).slice(),this._layout=t.layout??xp(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 nn(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 nn(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new r(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Ue),duration:Math.trunc((t.duration??0)*Ue)||void 0}),t);let n=0,o=0;if("naturalWidth"in e?(n=e.naturalWidth,o=e.naturalHeight):"videoWidth"in e?(n=e.videoWidth,o=e.videoHeight):"width"in e&&(n=Number(e.width),o=Number(e.height)),!n||!o)throw new TypeError("Could not determine dimensions.");let i=new OffscreenCanvas(n,o),s=i.getContext("2d",{alpha:Qr(),willReadFrequently:!0});g(s),s.drawImage(e,0,0),this._data=i,this._layout=null,this.format="RGBX",this.codedWidth=n,this.codedHeight=o,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new nn({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");on?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return g(this._data!==null),Et(this._data)?new r(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(g(this._layout),new r(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})):new r(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){this._closed||(on?.unregister(this),Et(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(yc(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(g(this._data!==null),!Et(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let t=this.toVideoFrame(),n=t.allocationSize(e);return t.close(),n}return Et(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,t={}){if(!Qn(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(yc(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(g(this._data!==null),!Et(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){let n=this.toVideoFrame(),o=await n.copyTo(e,t);return n.close(),o}if(Et(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array)return g(this._layout),Pe(e).set(this._data),this._layout;{let o=this._data.getContext("2d");g(o);let i=o.getImageData(0,0,this.codedWidth,this.codedHeight);return Pe(e).set(i.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return g(this._data!==null),Et(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,n,o,i,s,a,c,l){let f=0,u=0,m=this.displayWidth,d=this.displayHeight,p=0,h=0,x=this.displayWidth,y=this.displayHeight;if(s!==void 0?(f=t,u=n,m=o,d=i,p=s,h=a,c!==void 0?(x=c,y=l):(x=m,y=d)):(p=t,h=n,o!==void 0&&(x=o,y=i)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(f))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))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(d)||d<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(x)||x<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:f,sy:u,sWidth:m,sHeight:d}=this._rotateSourceRegion(f,u,m,d,this.rotation));let v=this.toCanvasImageSource();e.save();let S=p+x/2,C=h+y/2;e.translate(S,C),e.rotate(this.rotation*Math.PI/180);let _=this.rotation%180===0?1:x/y;e.scale(1/_,_),e.drawImage(v,f,u,m,d,-x/2,-y/2,x,y),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");t.crop!==void 0&&gs(t.crop,"options.");let n=e.canvas.width,o=e.canvas.height,i=t.rotation??this.rotation,[s,a]=i%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];t.crop&&hs(t.crop,s,a);let c,l,f,u,{sx:m,sy:d,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,f=n,u=o;else{let[y,v]=t.crop?[t.crop.width,t.crop.height]:[s,a],S=t.fit==="contain"?Math.min(n/y,o/v):Math.max(n/y,o/v);f=y*S,u=v*S,c=(n-f)/2,l=(o-u)/2}e.save();let x=i%180===0?1:f/u;e.translate(n/2,o/2),e.rotate(i*Math.PI/180),e.scale(1/x,x),e.translate(-n/2,-o/2),e.drawImage(this.toCanvasImageSource(),m,d,p,h,c,l,f,u),e.restore()}_rotateSourceRegion(e,t,n,o,i){return i===90?[e,t,n,o]=[t,this.codedHeight-e-n,o,n]:i===180?[e,t]=[this.codedWidth-e-n,this.codedHeight-t-o]:i===270&&([e,t,n,o]=[this.codedWidth-t-o,e,o,n]),{sx:e,sy:t,sWidth:n,sHeight:o}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(g(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()}},nn=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}}},Et=r=>typeof VideoFrame<"u"&&r instanceof VideoFrame,hs=(r,e,t)=>{r.left=Math.min(r.left,e),r.top=Math.min(r.top,t),r.width=Math.min(r.width,e-r.left),r.height=Math.min(r.height,t-r.top),g(r.width>=0),g(r.height>=0)},gs=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},yc=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.colorSpace!==void 0&&!["display-p3","srgb"].includes(r.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(r.format!==void 0&&typeof r.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(r.layout!==void 0){if(!Array.isArray(r.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let e of r.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(r.rect!==void 0){if(!r.rect||typeof r.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(r.rect.x!==void 0&&(!Number.isInteger(r.rect.x)||r.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(r.rect.y!==void 0&&(!Number.isInteger(r.rect.y)||r.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(r.rect.width!==void 0&&(!Number.isInteger(r.rect.width)||r.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(r.rect.height!==void 0&&(!Number.isInteger(r.rect.height)||r.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},xp=(r,e,t)=>{let n=vp(r),o=[],i=0;for(let s of n){let a=Math.ceil(e/s.widthDivisor),c=Math.ceil(t/s.heightDivisor),l=a*s.sampleBytes,f=l*c;o.push({offset:i,stride:l}),i+=f}return o},vp=r=>{let e=(t,n,o,i,s)=>{let a=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:n,widthDivisor:o,heightDivisor:i},{sampleBytes:n,widthDivisor:o,heightDivisor:i}];return s&&a.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),a};switch(r){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:we(r),g(!1)}},ps=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),cr=class r{get microsecondTimestamp(){return Math.trunc(Ue*this.timestamp)}get microsecondDuration(){return Math.trunc(Ue*this.duration)}constructor(e){if(this._closed=!1,rn(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(!ps.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/(zt(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let n;if(e.data instanceof ArrayBuffer)n=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))n=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let o=this.numberOfFrames*this.numberOfChannels*zt(this.format);if(n.byteLength<o)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=n}on?.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&&!ps.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let t=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let o=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-n;if(o>this.numberOfFrames-n)throw new RangeError("frameCount out of range");let i=zt(t),s=sr(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(!Qn(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&&!ps.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{planeIndex:n,format:o,frameCount:i,frameOffset:s}=t,a=this.format,c=o??this.format;if(!c)throw new Error("Destination format not determined");let l=this.numberOfFrames,f=this.numberOfChannels,u=s??0;if(u>=l)throw new RangeError("frameOffset out of range");let m=i!==void 0?i:l-u;if(m>l-u)throw new RangeError("frameCount out of range");let d=zt(c),p=sr(c);if(p&&n>=f)throw new RangeError("planeIndex out of range");if(!p&&n!==0)throw new RangeError("planeIndex out of range");let x=(p?m:m*f)*d;if(e.byteLength<x)throw new RangeError("Destination buffer is too small");let y=j(e),v=Tc(c);if(rn(this._data))it()&&f>2&&c!==a?yp(this._data,y,a,c,f,n,u,m):this._data.copyTo(e,{planeIndex:n,frameOffset:u,frameCount:m,format:c});else{let S=this._data,C=j(S),_=Sc(a),T=zt(a),E=sr(a);for(let I=0;I<m;I++)if(p){let M=I*d,L;E?L=(n*l+(I+u))*T:L=((I+u)*f+n)*T;let V=_(C,L);v(y,M,V)}else for(let M=0;M<f;M++){let V=(I*f+M)*d,te;E?te=(M*l+(I+u))*T:te=((I+u)*f+M)*T;let Ee=_(C,te);v(y,V,Ee)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(rn(this._data)){let e=new r(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new r({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(on?.unregister(this),rn(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(rn(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(sr(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(t,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{let e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(t,{planeIndex:n,format:"f32-planar"}),e.copyToChannel(t,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,o=e.numberOfChannels,i=e.sampleRate,s=e.length,a=Math.floor(n/o),c=0,l=s;for(;l>0;){let f=Math.min(a,l),u=new Float32Array(o*f);for(let m=0;m<o;m++)e.copyFromChannel(u.subarray(m*f,(m+1)*f),m,c);yield new r({format:"f32-planar",sampleRate:i,numberOfFrames:f,numberOfChannels:o,timestamp:t+c/i,data:u}),c+=f,l-=f}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,o=e.numberOfChannels,i=e.sampleRate,s=e.length,a=Math.floor(n/o),c=0,l=s,f=[];for(;l>0;){let u=Math.min(a,l),m=new Float32Array(o*u);for(let p=0;p<o;p++)e.copyFromChannel(m.subarray(p*u,(p+1)*u),p,c);let d=new r({format:"f32-planar",sampleRate:i,numberOfFrames:u,numberOfChannels:o,timestamp:t+c/i,data:m});f.push(d),c+=u,l-=u}return f}},zt=r=>{switch(r){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},sr=r=>{switch(r){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Sc=r=>{switch(r){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},Tc=r=>{switch(r){case"u8":case"u8-planar":return(e,t,n)=>e.setUint8(t,Ct((n+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,n)=>e.setInt16(t,Ct(Math.round(n*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,n)=>e.setInt32(t,Ct(Math.round(n*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,n)=>e.setFloat32(t,n,!0)}},rn=r=>typeof AudioData<"u"&&r instanceof AudioData,yp=(r,e,t,n,o,i,s,a)=>{let c=Sc(t),l=Tc(n),f=zt(t),u=zt(n),m=sr(t);if(sr(n))if(m){let p=new ArrayBuffer(a*f),h=j(p);r.copyTo(p,{planeIndex:i,frameOffset:s,frameCount:a,format:t});for(let x=0;x<a;x++){let y=x*f,v=x*u,S=c(h,y);l(e,v,S)}}else{let p=new ArrayBuffer(a*o*f),h=j(p);r.copyTo(p,{planeIndex:0,frameOffset:s,frameCount:a,format:t});for(let x=0;x<a;x++){let y=(x*o+i)*f,v=x*u,S=c(h,y);l(e,v,S)}}else if(m){let p=a*f,h=new ArrayBuffer(p),x=j(h);for(let y=0;y<o;y++){r.copyTo(h,{planeIndex:y,frameOffset:s,frameCount:a,format:t});for(let v=0;v<a;v++){let S=v*f,C=(v*o+y)*u,_=c(x,S);l(e,C,_)}}}else{let p=new ArrayBuffer(a*o*f),h=j(p);r.copyTo(p,{planeIndex:0,frameOffset:s,frameCount:a,format:t});for(let x=0;x<a;x++)for(let y=0;y<o;y++){let v=x*o+y,S=v*f,C=v*u,_=c(h,S);l(e,C,_)}}};var lr=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.metadataOnly!==void 0&&typeof r.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(r.verifyKeyPackets!==void 0&&typeof r.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(r.verifyKeyPackets&&r.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},lt=r=>{if(!Jr(r))throw new TypeError("timestamp must be a number.")},xs=(r,e,t)=>t.verifyKeyPackets?e.then(async n=>{if(!n||n.type==="delta")return n;let o=await r.determinePacketType(n);return o&&(n.type=o),n}):e,Dt=class{constructor(e){if(!(e instanceof ur))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(lr(e),this._track.input._disposed)throw new ie;return xs(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){if(lt(e),lr(t),this._track.input._disposed)throw new ie;return xs(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof Z))throw new TypeError("packet must be an EncodedPacket.");if(lr(t),this._track.input._disposed)throw new ie;return xs(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(lt(e),lr(t),this._track.input._disposed)throw new ie;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let n=await this._track._backing.getKeyPacket(e,t);return n&&(g(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getKeyPacket(n.timestamp-1/this._track.timeResolution,t):n)}async getNextKeyPacket(e,t={}){if(!(e instanceof Z))throw new TypeError("packet must be an EncodedPacket.");if(lr(t),this._track.input._disposed)throw new ie;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let n=await this._track._backing.getNextKeyPacket(e,t);return n&&(g(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getNextKeyPacket(n,t):n)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof Z))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof Z))throw new TypeError("endPacket must be an EncodedPacket.");if(lr(n),this._track.input._disposed)throw new ie;let o=[],{promise:i,resolve:s}=pe(),{promise:a,resolve:c}=pe(),l=!1,f=!1,u=null,m=[],d=()=>Math.max(2,m.length);(async()=>{let h=e??await this.getFirstPacket(n);for(;h&&!f&&!this._track.input._disposed&&!(t&&h.sequenceNumber>=t?.sequenceNumber);){if(o.length>d()){({promise:a,resolve:c}=pe()),await a;continue}o.push(h),s(),{promise:i,resolve:s}=pe(),h=await this.getNextPacket(h,n)}l=!0,s()})().catch(h=>{u||(u=h,s())});let p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new ie;if(f)return{value:void 0,done:!0};if(u)throw u;if(o.length>0){let h=o.shift(),x=performance.now();for(m.push(x);m.length>0&&x-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 f=!0,c(),s(),{value:void 0,done:!0}},async throw(h){throw h},[Symbol.asyncIterator](){return this}}}},sn=class{constructor(e,t){this.onSample=e,this.onError=t}},an=class{mediaSamplesInRange(e=0,t=1/0){lt(e),lt(t);let n=[],o=!1,i=null,{promise:s,resolve:a}=pe(),{promise:c,resolve:l}=pe(),f=!1,u=!1,m=!1,d=null;(async()=>{let x=await this._createDecoder(T=>{if(l(),T.timestamp>=t&&(u=!0),u){T.close();return}i&&(T.timestamp>e?(n.push(i),o=!0):i.close()),T.timestamp>=e&&(n.push(T),o=!0),i=o?null:T,n.length>0&&(a(),{promise:s,resolve:a}=pe())},T=>{d||(d=T,a())}),y=this._createPacketSink(),v=await y.getKeyPacket(e,{verifyKeyPackets:!0})??await y.getFirstPacket(),S=v,C;if(t<1/0){let T=await y.getPacket(t),E=T?T.type==="key"&&T.timestamp===t?T:await y.getNextKeyPacket(T,{verifyKeyPackets:!0}):null;E&&(C=E)}let _=y.packets(v??void 0,C);for(await _.next();S&&!u&&!this._track.input._disposed;){let T=wc(n.length);if(n.length+x.getDecodeQueueSize()>T){({promise:c,resolve:l}=pe()),await c;continue}x.decode(S);let E=await _.next();if(E.done)break;S=E.value}await _.return(),!m&&!this._track.input._disposed&&await x.flush(),x.close(),!o&&i&&n.push(i),f=!0,a()})().catch(x=>{d||(d=x,a())});let p=this._track,h=()=>{i?.close();for(let x of n)x.close()};return{async next(){for(;;){if(p.input._disposed)throw h(),new ie;if(m)return{value:void 0,done:!0};if(d)throw h(),d;if(n.length>0){let x=n.shift();return l(),{value:x,done:!1}}else if(!f)await s;else return{value:void 0,done:!0}}},async return(){return m=!0,u=!0,l(),a(),h(),{value:void 0,done:!0}},async throw(x){throw x},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){Ya(e);let t=Ka(e),n=[],o=[],{promise:i,resolve:s}=pe(),{promise:a,resolve:c}=pe(),l=!1,f=!1,u=null,m=h=>{o.push(h),s(),{promise:i,resolve:s}=pe()};(async()=>{let h=await this._createDecoder(T=>{if(c(),f){T.close();return}let E=0;for(;n.length>0&&T.timestamp-n[0]>-1e-10;)E++,n.shift();if(E>0)for(let I=0;I<E;I++)m(I<E-1?T.clone():T);else T.close()},T=>{u||(u=T,s())}),x=this._createPacketSink(),y=null,v=null,S=-1,C=async()=>{g(v);let T=v;for(h.decode(T);T.sequenceNumber<S;){let E=wc(o.length);for(;o.length+h.getDecodeQueueSize()>E&&!f;)({promise:a,resolve:c}=pe()),await a;if(f)break;let I=await x.getNextPacket(T);g(I),h.decode(I),T=I}S=-1},_=async()=>{await h.flush();for(let T=0;T<n.length;T++)m(null);n.length=0};for await(let T of t){if(lt(T),f||this._track.input._disposed)break;let E=await x.getPacket(T),I=E&&await x.getKeyPacket(T,{verifyKeyPackets:!0});if(!I){S!==-1&&(await C(),await _()),m(null),y=null;continue}y&&(I.sequenceNumber!==v.sequenceNumber||E.timestamp<y.timestamp)&&(await C(),await _()),n.push(E.timestamp),S=Math.max(E.sequenceNumber,S),y=E,v=I}!f&&!this._track.input._disposed&&(S!==-1&&await C(),await _()),h.close(),l=!0,s()})().catch(h=>{u||(u=h,s())});let d=this._track,p=()=>{for(let h of o)h?.close()};return{async next(){for(;;){if(d.input._disposed)throw p(),new ie;if(f)return{value:void 0,done:!0};if(u)throw p(),u;if(o.length>0){let h=o.shift();return g(h!==void 0),c(),{value:h,done:!1}}else if(!l)await i;else return{value:void 0,done:!0}}},async return(){return f=!0,c(),s(),p(),{value:void 0,done:!0}},async throw(h){throw h},[Symbol.asyncIterator](){return this}}}},wc=r=>r===0?40:8,vs=class extends sn{constructor(e,t,n,o,i,s){super(e,t),this.codec=n,this.decoderConfig=o,this.rotation=i,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new $r,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=fo.find(c=>c.supports(n,o));if(a)this.customDecoder=new a,this.customDecoder.codec=n,this.customDecoder.config=o,this.customDecoder.onSample=c=>{if(!(c instanceof ar))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=f=>{if(this.alphaQueue.length>0){let u=this.alphaQueue.shift();g(u!==void 0),this.mergeAlpha(f,u)}else this.colorQueue.push(f)};if(n==="avc"&&this.decoderConfig.description&&Zr()){let f=lc(Pe(this.decoderConfig.description));if(f&&f.sequenceParameterSets.length>0){let u=ms(f.sequenceParameterSets[0]);u&&u.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let l=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:f=>{try{c(f)}catch(u){this.onError(u)}},error:f=>{f.stack=l,this.onError(f)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(g(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(g(this.decoder),it()||ns(this.inputTimestamps,e.timestamp,t=>t),Zr()&&this.currentPacketIndex===0&&this.codec==="avc"){let n=fs(e.data,this.decoderConfig).filter(i=>{let s=Ft(i);return!(s>=20&&s<=31)}),o=ac(n,this.decoderConfig);e=new Z(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 ys}catch(n){console.error("Due to an error, only color data will be decoded.",n),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let n=i=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let s=this.colorQueue.shift();g(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();g(s!==void 0),this.mergeAlpha(s,null)}else this.alphaQueue.push(null)},o=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:i=>{try{n(i)}catch(s){this.onError(s)}},error:i=>{i.stack=o,this.onError(i)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=uo(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 ds(e,this.decoderConfig).some(n=>{let o=Xe(n);return o===he.RASL_N||o===he.RASL_R})}sampleHandler(e){if(it()){if(this.sampleQueue.length>0&&e.timestamp>=de(this.sampleQueue).timestamp){for(let t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}ns(this.sampleQueue,e,t=>t.timestamp)}else{let t=this.inputTimestamps.shift();g(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 ar(e);this.sampleHandler(i);return}g(this.merger),this.merger.update(e,t),e.close(),t.close();let n=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),o=new ar(n);this.sampleHandler(o)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(g(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),it()){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()):(g(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}},ys=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 Ln=()=>({stdout:async r=>console.log(r),stderr:async r=>console.error(r)});var Ma=()=>qi()?Un():Hi()?Nn():Ln();var Ba=()=>({stdout:async()=>{},stderr:async()=>{}});function Ua(){return()=>({stdout:r=>r,stderr:r=>r})}var nr=class r{static writers={auto:Ma,void:Ba,deno:Un,node:Nn,console:Ln};static colors={auto:Wi,colorful:()=>Xr,colorless:()=>jr};static themes={auto:za,basic:On};static shapers={auto:Ra,none:Ua,errors:Mn,timestamp:Bn};writer=r.writers.auto();colors=r.colors.auto();theme=r.themes.auto();shaper=r.shapers.auto();async log(...e){await this.writer.stdout(this.shaper(this).stdout(e).join(" "))}async error(...e){await this.writer.stderr(this.shaper(this).stderr(e).join(" "))}setWriter(e){return this.writer=e,this}setColors(e){return this.colors=e,this}setTheme(e){return this.theme=e,this}setShaper(...e){return this.shaper=Kr(...e),this}};var or=class extends nr{static dummy(){return new this().setWriter(nr.writers.void())}rpcRequest=async({request:e,...t})=>{let n=this.colors.none;this.log(...this.#e(t),n(`${e.method}()`))};rpcError=async({request:e,error:t,...n})=>{this.error(...this.#e(n),`${e.method}()`,t)};#e({meta:e,label:t,remote:n}){let o=this.colors.mix(this.colors.blue,this.colors.dim),i=this.colors.mix(this.colors.cyan,this.colors.dim);return[e?this.#t(e):void 0,t||void 0,n===void 0?void 0:n?o("<-"):i("->")].filter(Boolean)}#t(e){let{headers:t}=e.request;return[this.colors.yellow(`[${e.ip}]`),this.colors.green(t.origin?t.origin:"(no-origin)")].join(" ")}};var Re=class extends or{rpcRequest=async()=>{}};var He;(function(r){r.version="2.0";function e(t){return"id"in t?t.id:null}r.getId=e,r.errorCodes={serverError:-32e3,unexposedError:-32001}})(He||(He={}));var Vn=class extends Error{name=this.constructor.name},vt=class extends Error{name=this.constructor.name};async function Na({tap:r,request:e,action:t}){let n=He.getId(e);try{let o=await t();return n===null?null:{id:n,result:o,jsonrpc:He.version}}catch(o){return r.rpcError({request:e,error:o}),n===null?null:{id:n,jsonrpc:He.version,error:o instanceof Vn?{code:He.errorCodes.serverError,message:o.message}:{code:He.errorCodes.unexposedError,message:"unexposed error"}}}}function Gn(r){let e=r.tap??new Re;return async t=>{let n=t.method.split("."),o=Fa(r.fns,n),i=async()=>await o(...t.params);return e.rpcRequest({request:t}),await Na({tap:e,request:t,action:i})}}var yt=Symbol("tune"),Qd=Symbol("query"),Zd=Symbol("notify"),Jd=Symbol("settings");function La(r){function e(t){let n={notify:void 0};return new Proxy((()=>{}),{apply:(o,i,s)=>r(t,s,n),get:(o,i)=>{if(i!=="then")return i===yt?s=>(...a)=>r(t,a,{...n,...s}):i===Zd?(...s)=>r(t,s,{...n,notify:!0}):i===Qd?(...s)=>r(t,s,{...n,notify:!1}):i===Jd?n:(o[i]||(o[i]=e([...t,i])),o[i])},set:(o,i,s)=>(o[i]=s,!0)})}return e([])}function bt(r){let{endpoint:e,tap:t=new Re}=r,n=1;return La(async(o,i,s)=>{let a=s.notify??r.notify??!1,c=s.transfer,l={jsonrpc:"2.0",method:o.join("."),params:i},f=a?l:{...l,id:n++};t.rpcRequest({request:f});let u=await e(f,{transfer:c});if(a&&!u)return null;if(!u)throw new vt("response was null, but shouldn't be, because the request was not a notification");if("error"in u)throw new vt(r.label?`${r.label}: ${u.error.message}`:u.error.message);return u.result})}function Yr(r){return bt({endpoint:Gn(r),tap:r.tap})}var St=class{recv=ke();sendRequest=ke();sendResponse=ke();static makeEntangledPair({origin:e="example.e280.org"}={}){let t=new this,n=new this,o=[t.sendRequest.sub(s=>n.recv(s,{origin:e})),t.sendResponse.sub(s=>n.recv(s,{origin:e})),n.sendRequest.sub(s=>t.recv(s,{origin:e})),n.sendResponse.sub(s=>t.recv(s,{origin:e}))];return[t,n,()=>o.forEach(s=>s())]}};function qn(r,e){return r.addEventListener("message",e),()=>r.removeEventListener("message",e)}function Va(r,e){return async(t,{transfer:n}={})=>{if("id"in t){let o=Oe();return e(t,n,o.promise),r.wait(t.id,t.method).then(i=>(o.resolve(i),i))}else{let o=Promise.resolve(null);return e(t,n,o),o}}}function Ga(r){let e=[],t=[];for(let n of Array.isArray(r)?r:[r])"method"in n?e.push(n):t.push(n);return{requests:e,responses:t}}async function qa(r,e){let t=(await Promise.all(e.map(async n=>r(n)))).filter(n=>n!==null);return t.length===0?null:t.length===1?t[0]:t}var ir=class extends St{dispose=Dn();constructor(e){super(),this.dispose.schedule(this.sendRequest.sub((t,n)=>e.postMessage(t,n)),this.sendResponse.sub((t,n)=>e.postMessage(t,n)),qn(e,t=>this.recv(t.data,t)))}};var Hn=class{remote;transfer;constructor(e){this.remote=e}};var ji=Object.freeze({timeout:6e4,maxRequestBytes:1e7});var Wn=class{timeout;pending=new Map;constructor(e){this.timeout=e}async wait(e,t){let n=Oe();return this.pending.set(e,{method:t,deferred:n}),await Aa(this.timeout,()=>n.promise).catch(o=>{throw o instanceof Wr&&(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 vt(e.error.message)):t.deferred.resolve(e))}};var Tt=class{options;remote;remoteEndpoint;dispose=Dn();#e;constructor(e){this.options=e;let{conduit:t,tap:n}=e;this.#e=new Wn(e.timeout??ji.timeout),this.remoteEndpoint=Va(this.#e,t.sendRequest.pub.bind(t.sendRequest)),this.remote=bt({endpoint:this.remoteEndpoint,tap:n&&Gi(n,{remote:!0})}),this.dispose.schedule(t.recv.sub(o=>this.recv(o)))}async recv(e){let t=new Hn(this.remote),{conduit:n,rpc:o,tap:i}=this.options,{requests:s,responses:a}=Ga(e);for(let u of a)this.#e.deliverResponse(u);if(!o)return;let c=await o(t),l=Gn({fns:c,tap:i&&Gi(i,{remote:!1})}),f=await qa(l,s);f&&await n.sendResponse(f,t.transfer)}};var We={derive:{host:r=>({host:r.remote.host,get transfer(){return r.transfer},set transfer(e){r.transfer=e}}),work:r=>({work:r.remote,get transfer(){return r.transfer},set transfer(e){r.transfer=e}})},mock:{host:()=>({host:void 0,transfer:void 0}),work:()=>({work:void 0,transfer:void 0})}};var je=new Re;async function Ha(r,e,t={}){let n=t.tap??je,o=new Tt({tap:n,timeout:t.timeout??1/0,conduit:new ir(r.getSelf()),rpc:async i=>e(We.derive.host(i))});return await o.remote.infra.ready(),o.remote.host}var sr=class{worker;messenger;constructor(e,t){this.worker=e,this.messenger=t}static async make(e,t){let n=t.tap??je,o=t.label??"comrade",i=e.loadWorker(t.workerUrl,o),s=Oe(),a={async ready(){s.resolve()}},c=new Tt({tap:n,timeout:t.timeout??1/0,conduit:new ir(i),rpc:async l=>({infra:a,host:t.setupHost(We.derive.work(l))})});return await s.promise,new this(i,c)}get work(){return this.messenger.remote}terminate(){this.worker.terminate()}};var jn=class{threads;static async make(e,t){let n=t.workerCount??e.guessOptimalThreadCount(),o=await Promise.all([...Array(n)].map(async(i,s)=>sr.make(e,{...t,label:t.label??`${t.label??"comrade"}_${s+1}`})));return new this(o,{tap:t.tap})}work;#e=new Set;#t=[];constructor(e,t={}){this.threads=e;let n=t.tap??je,o=async(i,s)=>this.#r({request:i,prom:Oe(),transfer:s?.transfer});this.work=bt({tap:n,endpoint:o}),e.forEach(i=>this.#e.add(i))}get threadCount(){return this.threads.length}terminate(){for(let e of this.threads)e.terminate()}#r(e){return this.#t.push(e),this.#n(),e.prom.promise}#n(){for(;this.#e.size>0&&this.#t.length>0;){let e=[...this.#e].pop();this.#e.delete(e);let t=this.#t.shift();this.#e.delete(e);let n=e.messenger.remoteEndpoint(t.request,{transfer:t.transfer});t.prom.entangle(n).finally(()=>{this.#e.add(e),this.#n()})}}};var Wa=r=>({thread:e=>sr.make(r,e),cluster:e=>jn.make(r,e),worker:(e,t={})=>Ha(r,e,t),work:e=>e,host:e=>e,mocks(e){let{setupWork:t,setupHost:n,tap:o=je}=e,i=We.mock.host(),s=We.mock.work();return s.work=Yr({tap:o,fns:t(i)}),i.host=Yr({tap:o,fns:n(s)}),{workShell:s,hostShell:i,work:s.work,host:i.host}},mockWork(e,t=je){let n=We.mock.host(),o=We.mock.work();return o.work=Yr({tap:t,fns:e(n)}),{workShell:o,hostShell:n,work:o.work,mockHost:i=>(n.host=Yr({tap:t,fns:i(o)}),{workShell:o,hostShell:n,work:o.work,host:n.host})}}});var ja=()=>({getSelf(){return self},guessOptimalThreadCount(){let r=navigator.hardwareConcurrency??1;return Math.max(1,r-1)},loadWorker(r,e){return new window.Worker(r,{name:e,type:"module"})},async loadWasm(r){return WebAssembly.instantiateStreaming(fetch(r))}});var rp=ja(),wt=Wa(rp);function g(r){if(!r)throw new Error("Assertion failed.")}var Xn=r=>{let e=(r%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${r}.`)},de=r=>r&&r[r.length-1];var $=class r{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),o=(t&1<<n)>>n;return this.pos++,o}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let o=this.pos;o<n;o++){let i=Math.floor(o/8),s=this.bytes[i],a=7-(o&7);s&=~(1<<a),s|=(t&1<<n-o-1)>>n-o-1<<a,this.bytes[i]=s}this.pos=n}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new r(this.bytes);return e.pos=this.pos,e}},O=r=>{let e=0;for(;r.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+r.readBits(e)},Be=r=>{let e=O(r);return(e&1)===0?-(e>>1):e+1>>1};var Pe=r=>r.constructor===Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),j=r=>r.constructor===DataView?r:ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r),ce=new TextDecoder;var Qi=r=>Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),Zi={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Kn=Qi(Zi),Ji={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Yn=Qi(Ji),es={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},$n=Qi(es);var Qn=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r),Me=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e,t=new Promise(o=>{e=o}),n=this.currentPromise;return this.currentPromise=t,await n,e}},ts=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),rs=r=>(r=r>>1&1431655765|(r&1431655765)<<1,r=r>>2&858993459|(r&858993459)<<2,r=r>>4&252645135|(r&252645135)<<4,r=r>>8&16711935|(r&16711935)<<8,r=r>>16&65535|(r&65535)<<16,r>>>0),Ct=(r,e,t)=>{let n=0,o=r.length-1,i=-1;for(;n<=o;){let s=n+o>>1,a=t(r[s]);a===e?(i=s,o=s-1):a<e?n=s+1:o=s-1}return i},W=(r,e,t)=>{let n=0,o=r.length-1,i=-1;for(;n<=o;){let s=n+(o-n+1)/2|0;t(r[s])<=e?(i=s,n=s+1):o=s-1}return i},ns=(r,e,t)=>{let n=W(r,t(e),t);r.splice(n+1,0,e)},pe=()=>{let r,e;return{promise:new Promise((n,o)=>{r=n,e=o}),resolve:r,reject:e}};var os=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return r[t]},Zn=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1},Ka=async function*(r){Symbol.iterator in r?yield*r[Symbol.iterator]():yield*r[Symbol.asyncIterator]()},Ya=r=>{if(!(Symbol.iterator in r)&&!(Symbol.asyncIterator in r))throw new TypeError("Argument must be an iterable or async iterable.")},we=r=>{throw new Error(`Unexpected value: ${r}`)},kt=(r,e,t)=>{let n=r.getUint8(e),o=r.getUint8(e+1),i=r.getUint8(e+2);return t?n|o<<8|i<<16:n<<16|o<<8|i},$a=(r,e,t)=>kt(r,e,t)<<8>>8,Qa=(r,e,t,n)=>{t=t>>>0,t=t&16777215,n?(r.setUint8(e,t&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t>>>16&255)):(r.setUint8(e,t>>>16&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t&255))};var is=(r,e)=>({async next(){let t=await r.next();return t.done?{value:void 0,done:!0}:{value:e(t.value),done:!1}},return(){return r.return()},throw(t){return r.throw(t)},[Symbol.asyncIterator](){return this}}),Pt=(r,e,t)=>Math.max(e,Math.min(t,r)),le="und",_t=r=>{let e=Math.round(r);return Math.abs(r/e-1)<10*Number.EPSILON?e:r},Za=(r,e)=>Math.round(r/e)*e,Ja=r=>{let e=0;for(;r;)e++,r>>=1;return e},np=/^[a-z]{3}$/,Jn=r=>np.test(r),Ue=1e6*(1+Number.EPSILON),ss=(r,e)=>{let t={...r,...e};if(r.headers||e.headers){let n=r.headers?Xa(r.headers):{},o=e.headers?Xa(e.headers):{},i={...n};Object.entries(o).forEach(([s,a])=>{let c=Object.keys(i).find(l=>l.toLowerCase()===s.toLowerCase());c&&delete i[c],i[s]=a}),t.headers=i}return t},Xa=r=>{if(r instanceof Headers){let e={};return r.forEach((t,n)=>{e[n]=t}),e}if(Array.isArray(r)){let e={};return r.forEach(([t,n])=>{e[t]=n}),e}return r},as=async(r,e,t,n,o)=>{let i=0;for(;;)try{return await r(e,t)}catch(s){if(o())throw s;i++;let a=n(i,s,e);if(a===null)throw s;if(console.error("Retrying failed fetch. Error:",s),!Number.isFinite(a)||a<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(a>0&&await new Promise(c=>setTimeout(c,1e3*a)),o())throw s}};var $r=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},Xi=null,it=()=>Xi!==null?Xi:Xi=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),Ki=null,Qr=()=>Ki!==null?Ki:Ki=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),Yi=null,Zr=()=>Yi!==null?Yi:Yi=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),$i=null,ec=()=>{if($i!==null)return $i;if(typeof navigator>"u")return null;let r=/\bChrome\/(\d+)/.exec(navigator.userAgent);return r?$i=Number(r[1]):null},It=(r,e)=>r!==-1?r:e,eo=(r,e,t,n)=>r<=n&&t<=e;var tc=r=>{let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t};var to=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Jr=r=>typeof r=="number"&&!Number.isNaN(r);var st=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.")}},ro=class{constructor(e,t,n,o){if(this.data=e,this.mimeType=t,this.name=n,this.description=o,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!==void 0&&typeof t!="string")throw new TypeError("mimeType, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("name, when provided, must be a string.");if(o!==void 0&&typeof o!="string")throw new TypeError("description, when provided, must be a string.")}};var xe={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};var at=["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"],op=["aac","opus","mp3","vorbis","flac"],x1=[...op,...at];var At=[{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 rc=".01.01.01.01.00",nc=".0.110.01.01.01.0";var no=r=>{let{codec:e,codecDescription:t,colorSpace:n,avcCodecInfo:o,hevcCodecInfo:i,vp9CodecInfo:s,av1CodecInfo:a}=r;if(e==="avc"){if(g(r.avcType!==null),o){let c=new Uint8Array([o.avcProfileIndication,o.profileCompatibility,o.avcLevelIndication]);return`avc${r.avcType}.${ts(c)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${r.avcType}.${ts(t.subarray(1,4))}`}else if(e==="hevc"){let c,l,f,u,m,d;if(i)c=i.generalProfileSpace,l=i.generalProfileIdc,f=rs(i.generalProfileCompatibilityFlags),u=i.generalTierFlag,m=i.generalLevelIdc,d=[...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=j(t),x=h.getUint8(1);c=x>>6&3,l=x&31,f=rs(h.getUint32(2)),u=x>>5&1,m=h.getUint8(12),d=[];for(let y=0;y<6;y++)d.push(h.getUint8(6+y))}let p="hev1.";for(p+=["","A","B","C"][c]+l,p+=".",p+=f.toString(16).toUpperCase(),p+=".",p+=u===0?"L":"H",p+=m;d.length>0&&d[d.length-1]===0;)d.pop();return d.length>0&&(p+=".",p+=d.map(h=>h.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!s){let y=r.width*r.height,v=de(At).level;for(let S of At)if(y<=S.maxPictureSize){v=S.level;break}return`vp09.00.${v.toString().padStart(2,"0")}.08`}let c=s.profile.toString().padStart(2,"0"),l=s.level.toString().padStart(2,"0"),f=s.bitDepth.toString().padStart(2,"0"),u=s.chromaSubsampling.toString().padStart(2,"0"),m=s.colourPrimaries.toString().padStart(2,"0"),d=s.transferCharacteristics.toString().padStart(2,"0"),p=s.matrixCoefficients.toString().padStart(2,"0"),h=s.videoFullRangeFlag.toString().padStart(2,"0"),x=`vp09.${c}.${l}.${f}.${u}`;return x+=`.${m}.${d}.${p}.${h}`,x.endsWith(rc)&&(x=x.slice(0,-rc.length)),x}else if(e==="av1"){if(!a){let S=r.width*r.height,C=de(At).level;for(let _ of At)if(S<=_.maxPictureSize){C=_.level;break}return`av01.0.${C.toString().padStart(2,"0")}M.08`}let c=a.profile,l=a.level.toString().padStart(2,"0"),f=a.tier?"H":"M",u=a.bitDepth.toString().padStart(2,"0"),m=a.monochrome?"1":"0",d=100*a.chromaSubsamplingX+10*a.chromaSubsamplingY+1*(a.chromaSubsamplingX&&a.chromaSubsamplingY?a.chromaSamplePosition:0),p=n?.primaries?Zi[n.primaries]:1,h=n?.transfer?Ji[n.transfer]:1,x=n?.matrix?es[n.matrix]:1,y=n?.fullRange?1:0,v=`av01.${c}.${l}${f}.${u}`;return v+=`.${m}.${d.toString().padStart(3,"0")}`,v+=`.${p.toString().padStart(2,"0")}`,v+=`.${h.toString().padStart(2,"0")}`,v+=`.${x.toString().padStart(2,"0")}`,v+=`.${y}`,v.endsWith(nc)&&(v=v.slice(0,-nc.length)),v}}throw new TypeError(`Unhandled codec '${e}'.`)};var oo=r=>{let{codec:e,codecDescription:t,aacCodecInfo:n}=r;if(e==="aac"){if(!n)throw new TypeError("AAC codec info must be provided.");return n.isMpeg2?"mp4a.67":`mp4a.40.${ls(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&&at.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},en=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],cs=[-1,1,2,3,4,5,6,8],ls=r=>{if(!r||r.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new $(r),t=e.readBits(5);t===31&&(t=32+e.readBits(6));let n=e.readBits(4),o=null;n===15?o=e.readBits(24):n<en.length&&(o=en[n]);let i=e.readBits(4),s=null;return i>=1&&i<=7&&(s=cs[i]),{objectType:t,frequencyIndex:n,sampleRate:o,channelConfiguration:i,numberOfChannels:s}};var Ft=48e3,ip=/^pcm-([usf])(\d+)+(be)?$/,io=r=>{if(g(at.includes(r)),r==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(r==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=ip.exec(r);g(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";let n=Number(e[2])/8,o=e[3]!=="be",i=r==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:n,littleEndian:o,silentValue:i}};var Et;(function(r){r[r.IDR=5]="IDR",r[r.SEI=6]="SEI",r[r.SPS=7]="SPS",r[r.PPS=8]="PPS",r[r.SPS_EXT=13]="SPS_EXT"})(Et||(Et={}));var he;(function(r){r[r.RASL_N=8]="RASL_N",r[r.RASL_R=9]="RASL_R",r[r.BLA_W_LP=16]="BLA_W_LP",r[r.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",r[r.VPS_NUT=32]="VPS_NUT",r[r.SPS_NUT=33]="SPS_NUT",r[r.PPS_NUT=34]="PPS_NUT",r[r.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",r[r.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(he||(he={}));var ao=r=>{let e=[],t=0;for(;t<r.length;){let n=-1,o=0;for(let i=t;i<r.length-3;i++){if(r[i]===0&&r[i+1]===0&&r[i+2]===1){n=i,o=3;break}if(i<r.length-4&&r[i]===0&&r[i+1]===0&&r[i+2]===0&&r[i+3]===1){n=i,o=4;break}}if(n===-1)break;if(t>0&&n>t){let i=r.subarray(t,n);i.length>0&&e.push(i)}t=n+o}if(t<r.length){let n=r.subarray(t);n.length>0&&e.push(n)}return e},sc=(r,e)=>{let t=[],n=0,o=new DataView(r.buffer,r.byteOffset,r.byteLength);for(;n+e<=r.length;){let i;e===1?i=o.getUint8(n):e===2?i=o.getUint16(n,!1):e===3?i=kt(o,n,!1):e===4?i=o.getUint32(n,!1):(we(e),g(!1)),n+=e;let s=r.subarray(n,n+i);t.push(s),n+=i}return t},so=r=>{let e=[],t=r.length;for(let n=0;n<t;n++)n+2<t&&r[n]===0&&r[n+1]===0&&r[n+2]===3?(e.push(0,0),n+=2):e.push(r[n]);return new Uint8Array(e)},us=new Uint8Array([0,0,0,1]),ap=r=>{let e=r.reduce((o,i)=>o+us.byteLength+i.byteLength,0),t=new Uint8Array(e),n=0;for(let o of r)t.set(us,n),n+=us.byteLength,t.set(o,n),n+=o.byteLength;return t},cp=(r,e)=>{let t=r.reduce((i,s)=>i+e+s.byteLength,0),n=new Uint8Array(t),o=0;for(let i of r){let s=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(e){case 1:s.setUint8(o,i.byteLength);break;case 2:s.setUint16(o,i.byteLength,!1);break;case 3:Qa(s,o,i.byteLength,!1);break;case 4:s.setUint32(o,i.byteLength,!1);break}o+=e,n.set(i,o),o+=i.byteLength}return n},fs=(r,e)=>{if(e.description){let o=(Pe(e.description)[4]&3)+1;return sc(r,o)}else return ao(r)},ac=(r,e)=>{if(e.description){let o=(Pe(e.description)[4]&3)+1;return cp(r,o)}else return ap(r)},zt=r=>r[0]&31,cc=r=>{try{let e=ao(r),t=e.filter(c=>zt(c)===Et.SPS),n=e.filter(c=>zt(c)===Et.PPS),o=e.filter(c=>zt(c)===Et.SPS_EXT);if(t.length===0||n.length===0)return null;let i=t[0],s=ms(i);g(s!==null);let a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:n,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?o:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}};var lc=r=>{try{let e=j(r),t=0,n=e.getUint8(t++),o=e.getUint8(t++),i=e.getUint8(t++),s=e.getUint8(t++),a=e.getUint8(t++)&3,c=e.getUint8(t++)&31,l=[];for(let d=0;d<c;d++){let p=e.getUint16(t,!1);t+=2,l.push(r.subarray(t,t+p)),t+=p}let f=e.getUint8(t++),u=[];for(let d=0;d<f;d++){let p=e.getUint16(t,!1);t+=2,u.push(r.subarray(t,t+p)),t+=p}let m={configurationVersion:n,avcProfileIndication:o,profileCompatibility:i,avcLevelIndication:s,lengthSizeMinusOne:a,sequenceParameterSets:l,pictureParameterSets:u,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((o===100||o===110||o===122||o===144)&&t+4<=r.length){let d=e.getUint8(t++)&3,p=e.getUint8(t++)&7,h=e.getUint8(t++)&7,x=e.getUint8(t++);m.chromaFormat=d,m.bitDepthLumaMinus8=p,m.bitDepthChromaMinus8=h;let y=[];for(let v=0;v<x;v++){let S=e.getUint16(t,!1);t+=2,y.push(r.subarray(t,t+S)),t+=S}m.sequenceParameterSetExt=y}return m}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}},ms=r=>{try{let e=new $(so(r));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let n=e.readAlignedByte(),o=e.readAlignedByte(),i=e.readAlignedByte();O(e);let s=null,a=null,c=null;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(s=O(e),s===3&&e.skipBits(1),a=O(e),c=O(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,x=8;for(let y=0;y<p;y++){if(x!==0){let v=Be(e);x=(h+v+256)%256}h=x===0?h:x}}}O(e);let l=O(e);if(l===0)O(e);else if(l===1){e.skipBits(1),Be(e),Be(e);let u=O(e);for(let m=0;m<u;m++)Be(e)}O(e),e.skipBits(1),O(e),O(e);let f=e.readBits(1);return{profileIdc:n,constraintFlags:o,levelIdc:i,frameMbsOnlyFlag:f,chromaFormatIdc:s,bitDepthLumaMinus8:a,bitDepthChromaMinus8:c}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},ds=(r,e)=>{if(e.description){let o=(Pe(e.description)[21]&3)+1;return sc(r,o)}else return ao(r)},Xe=r=>r[0]>>1&63,uc=r=>{try{let e=ao(r),t=e.filter(L=>Xe(L)===he.VPS_NUT),n=e.filter(L=>Xe(L)===he.SPS_NUT),o=e.filter(L=>Xe(L)===he.PPS_NUT),i=e.filter(L=>Xe(L)===he.PREFIX_SEI_NUT||Xe(L)===he.SUFFIX_SEI_NUT);if(n.length===0||o.length===0)return null;let s=n[0],a=new $(so(s));a.skipBits(16),a.readBits(4);let c=a.readBits(3),l=a.readBits(1),{general_profile_space:f,general_tier_flag:u,general_profile_idc:m,general_profile_compatibility_flags:d,general_constraint_indicator_flags:p,general_level_idc:h}=lp(a,c);O(a);let x=O(a);x===3&&a.skipBits(1),O(a),O(a),a.readBits(1)&&(O(a),O(a),O(a),O(a));let y=O(a),v=O(a);O(a);let C=a.readBits(1)?0:c;for(let L=C;L<=c;L++)O(a),O(a),O(a);O(a),O(a),O(a),O(a),O(a),O(a),a.readBits(1)&&a.readBits(1)&&up(a),a.skipBits(1),a.skipBits(1),a.readBits(1)&&(a.skipBits(4),a.skipBits(4),O(a),O(a),a.skipBits(1));let _=O(a);if(fp(a,_),a.readBits(1)){let L=O(a);for(let V=0;V<L;V++)O(a),a.skipBits(1)}a.skipBits(1),a.skipBits(1);let T=0;a.readBits(1)&&(T=dp(a,c));let E=0;if(o.length>0){let L=o[0],V=new $(so(L));V.skipBits(16),O(V),O(V),V.skipBits(1),V.skipBits(1),V.skipBits(3),V.skipBits(1),V.skipBits(1),O(V),O(V),Be(V),V.skipBits(1),V.skipBits(1),V.readBits(1)&&O(V),Be(V),Be(V),V.skipBits(1),V.skipBits(1),V.skipBits(1),V.skipBits(1);let te=V.readBits(1),Ee=V.readBits(1);!te&&!Ee?E=0:te&&!Ee?E=2:!te&&Ee?E=3:E=0}let I=[...t.length?[{arrayCompleteness:1,nalUnitType:he.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:he.SPS_NUT,nalUnits:n}]:[],...o.length?[{arrayCompleteness:1,nalUnitType:he.PPS_NUT,nalUnits:o}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Xe(i[0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:f,generalTierFlag:u,generalProfileIdc:m,generalProfileCompatibilityFlags:d,generalConstraintIndicatorFlags:p,generalLevelIdc:h,minSpatialSegmentationIdc:T,parallelismType:E,chromaFormatIdc:x,bitDepthLumaMinus8:y,bitDepthChromaMinus8:v,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:l,lengthSizeMinusOne:3,arrays:I}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},lp=(r,e)=>{let t=r.readBits(2),n=r.readBits(1),o=r.readBits(5),i=0;for(let f=0;f<32;f++)i=i<<1|r.readBits(1);let s=new Uint8Array(6);for(let f=0;f<6;f++)s[f]=r.readBits(8);let a=r.readBits(8),c=[],l=[];for(let f=0;f<e;f++)c.push(r.readBits(1)),l.push(r.readBits(1));if(e>0)for(let f=e;f<8;f++)r.skipBits(2);for(let f=0;f<e;f++)c[f]&&r.skipBits(88),l[f]&&r.skipBits(8);return{general_profile_space:t,general_tier_flag:n,general_profile_idc:o,general_profile_compatibility_flags:i,general_constraint_indicator_flags:s,general_level_idc:a}},up=r=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!r.readBits(1))O(r);else{let o=Math.min(64,1<<4+(e<<1));e>1&&Be(r);for(let i=0;i<o;i++)Be(r)}},fp=(r,e)=>{let t=[];for(let n=0;n<e;n++)t[n]=mp(r,n,e,t)},mp=(r,e,t,n)=>{let o=0,i=0,s=0;if(e!==0&&(i=r.readBits(1)),i){if(e===t){let c=O(r);s=e-(c+1)}else s=e-1;r.readBits(1),O(r);let a=n[s]??0;for(let c=0;c<=a;c++)r.readBits(1)||r.readBits(1);o=n[s]}else{let a=O(r),c=O(r);for(let l=0;l<a;l++)O(r),r.readBits(1);for(let l=0;l<c;l++)O(r),r.readBits(1);o=a+c}return o},dp=(r,e)=>{if(r.readBits(1)&&r.readBits(8)===255&&(r.readBits(16),r.readBits(16)),r.readBits(1)&&r.readBits(1),r.readBits(1)&&(r.readBits(3),r.readBits(1),r.readBits(1)&&(r.readBits(8),r.readBits(8),r.readBits(8))),r.readBits(1)&&(O(r),O(r)),r.readBits(1),r.readBits(1),r.readBits(1),r.readBits(1)&&(O(r),O(r),O(r),O(r)),r.readBits(1)&&(r.readBits(32),r.readBits(32),r.readBits(1)&&O(r),r.readBits(1)&&pp(r,!0,e)),r.readBits(1)){r.readBits(1),r.readBits(1),r.readBits(1);let t=O(r);return O(r),O(r),O(r),O(r),t}return 0},pp=(r,e,t)=>{let n=!1,o=!1,i=!1;e&&(n=r.readBits(1)===1,o=r.readBits(1)===1,(n||o)&&(i=r.readBits(1)===1,i&&(r.readBits(8),r.readBits(5),r.readBits(1),r.readBits(5)),r.readBits(4),r.readBits(4),i&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5)));for(let s=0;s<=t;s++){let a=r.readBits(1)===1,c=!0;a||(c=r.readBits(1)===1);let l=!1;c?O(r):l=r.readBits(1)===1;let f=1;l||(f=O(r)+1),n&&oc(r,f,i),o&&oc(r,f,i)}},oc=(r,e,t)=>{for(let n=0;n<e;n++)O(r),O(r),t&&(O(r),O(r)),r.readBits(1)};var co=r=>{let e=new $(r);if(e.readBits(2)!==2)return null;let n=e.readBits(1),i=(e.readBits(1)<<1)+n;if(i===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;i>=2&&(l=e.readBits(1)?12:10);let f=e.readBits(3),u=0,m=0;if(f!==7)if(m=e.readBits(1),i===1||i===3){let E=e.readBits(1),I=e.readBits(1);u=!E&&!I?3:E&&!I?2:1,e.skipBits(1)}else u=1;else u=3,m=1;let d=e.readBits(16),p=e.readBits(16),h=d+1,x=p+1,y=h*x,v=de(At).level;for(let T of At)if(y<=T.maxPictureSize){v=T.level;break}return{profile:i,level:v,bitDepth:l,chromaSubsampling:u,videoFullRangeFlag:m,colourPrimaries:f===2?1:f===1?6:2,transferCharacteristics:f===2?1:f===1?6:2,matrixCoefficients:f===7?0:f===2?1:f===1?6:2}},fc=function*(r){let e=new $(r),t=()=>{let n=0;for(let o=0;o<8;o++){let i=e.readAlignedByte();if(n|=(i&127)<<o*7,!(i&128))break;if(o===7&&i&128)return null}return n>=2**32-1?null:n};for(;e.getBitsLeft()>=8;){e.skipBits(1);let n=e.readBits(4),o=e.readBits(1),i=e.readBits(1);e.skipBits(1),o&&e.skipBits(8);let s;if(i){let a=t();if(a===null)return;s=a}else s=Math.floor(e.getBitsLeft()/8);g(e.pos%8===0),yield{type:n,data:r.subarray(e.pos/8,e.pos/8+s)},e.skipBits(s*8)}},lo=r=>{for(let{type:e,data:t}of fc(r)){if(e!==1)continue;let n=new $(t),o=n.readBits(3),i=n.readBits(1),s=n.readBits(1),a=0,c=0,l=0;if(s)a=n.readBits(5);else{if(n.readBits(1)&&(n.skipBits(32),n.skipBits(32),n.readBits(1)))return null;let T=n.readBits(1);T&&(l=n.readBits(5),n.skipBits(32),n.skipBits(5),n.skipBits(5));let E=n.readBits(5);for(let I=0;I<=E;I++){n.skipBits(12);let M=n.readBits(5);if(I===0&&(a=M),M>7){let V=n.readBits(1);I===0&&(c=V)}if(T&&n.readBits(1)){let te=l+1;n.skipBits(te),n.skipBits(te),n.skipBits(1)}n.readBits(1)&&n.skipBits(4)}}let f=n.readBits(4),u=n.readBits(4),m=f+1;n.skipBits(m);let d=u+1;n.skipBits(d);let p=0;if(s?p=0:p=n.readBits(1),p&&(n.skipBits(4),n.skipBits(3)),n.skipBits(1),n.skipBits(1),n.skipBits(1),!s){n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let _=n.readBits(1);_&&(n.skipBits(1),n.skipBits(1));let T=n.readBits(1),E=0;T?E=2:E=n.readBits(1),E>0&&(n.readBits(1)||n.skipBits(1)),_&&n.skipBits(3)}n.skipBits(1),n.skipBits(1),n.skipBits(1);let h=n.readBits(1),x=8;o===2&&h?x=n.readBits(1)?12:10:o<=2&&(x=h?10:8);let y=0;o!==1&&(y=n.readBits(1));let v=1,S=1,C=0;return y||(o===0?(v=1,S=1):o===1?(v=0,S=0):x===12&&(v=n.readBits(1),v&&(S=n.readBits(1))),v&&S&&(C=n.readBits(2))),{profile:o,level:a,tier:c,bitDepth:x,monochrome:y,chromaSubsamplingX:v,chromaSubsamplingY:S,chromaSamplePosition:C}}return null},mc=r=>{let e=j(r),t=e.getUint8(9),n=e.getUint16(10,!0),o=e.getUint32(12,!0),i=e.getInt16(16,!0),s=e.getUint8(18),a=null;return s&&(a=r.subarray(19,21+t)),{outputChannelCount:t,preSkip:n,inputSampleRate:o,outputGain:i,channelMappingFamily:s,channelMappingTable:a}},hp=[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],dc=r=>{let e=r[0]>>3;return{durationInSamples:hp[e]}},pc=r=>{if(r.length<7)throw new Error("Setup header is too short.");if(r[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...r.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let t=r.length,n=new Uint8Array(t);for(let u=0;u<t;u++)n[u]=r[t-1-u];let o=new $(n),i=0;for(;o.getBitsLeft()>97;)if(o.readBits(1)===1){i=o.pos;break}if(i===0)throw new Error("Invalid Setup header: framing bit not found.");let s=0,a=!1,c=0;for(;o.getBitsLeft()>=97;){let u=o.pos,m=o.readBits(8),d=o.readBits(16),p=o.readBits(16);if(m>63||d!==0||p!==0){o.pos=u;break}if(o.skipBits(1),s++,s>64)break;o.clone().readBits(6)+1===s&&(a=!0,c=s)}if(!a)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);let l=c;o.pos=0,o.skipBits(i);let f=Array(l).fill(0);for(let u=l-1;u>=0;u--)o.skipBits(40),f[u]=o.readBits(1);return{modeBlockflags:f}},uo=(r,e,t)=>{switch(r){case"avc":{let n=fs(t,e),o=n.some(i=>zt(i)===Et.IDR);if(!o&&(!Zr()||ec()>=144))for(let i of n){if(zt(i)!==Et.SEI)continue;let a=so(i),c=1;do{let l=0;for(;;){let m=a[c++];if(m===void 0||(l+=m,m<255))break}let f=0;for(;;){let m=a[c++];if(m===void 0||(f+=m,m<255))break}if(l===6){let m=new $(a);m.pos=8*c;let d=O(m),p=m.readBits(1);if(d===0&&p===1){o=!0;break}}c+=f}while(c<a.length-1)}return o?"key":"delta"}case"hevc":return ds(t,e).some(i=>{let s=Xe(i);return he.BLA_W_LP<=s&&s<=he.RSV_IRAP_VCL23})?"key":"delta";case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{let n=new $(t);if(n.readBits(2)!==2)return null;let o=n.readBits(1);return(n.readBits(1)<<1)+o===3&&n.skipBits(1),n.readBits(1)?null:n.readBits(1)===0?"key":"delta"}case"av1":{let n=!1;for(let{type:o,data:i}of fc(t))if(o===1){let s=new $(i);s.skipBits(4),n=!!s.readBits(1)}else if(o===3||o===6||o===7){if(n)return"key";let s=new $(i);return s.readBits(1)?null:s.readBits(2)===0?"key":"delta"}return null}default:we(r),g(!1)}},ct;(function(r){r[r.STREAMINFO=0]="STREAMINFO",r[r.VORBIS_COMMENT=4]="VORBIS_COMMENT",r[r.PICTURE=6]="PICTURE"})(ct||(ct={}));var tn=(r,e)=>{let t=j(r),n=0,o=t.getUint32(n,!0);n+=4;let i=ce.decode(r.subarray(n,n+o));n+=o,o>0&&(e.raw??={},e.raw.vendor??=i);let s=t.getUint32(n,!0);n+=4;for(let a=0;a<s;a++){let c=t.getUint32(n,!0);n+=4;let l=ce.decode(r.subarray(n,n+c));n+=c;let f=l.indexOf("=");if(f===-1)continue;let u=l.slice(0,f).toUpperCase(),m=l.slice(f+1);switch(e.raw??={},e.raw[u]??=m,u){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 d=m.split("/"),p=Number.parseInt(d[0],10),h=d[1]&&Number.parseInt(d[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),h&&Number.isInteger(h)&&h>0&&(e.tracksTotal??=h)}break;case"TRACKTOTAL":{let d=Number.parseInt(m,10);Number.isInteger(d)&&d>0&&(e.tracksTotal??=d)}break;case"DISCNUMBER":{let d=m.split("/"),p=Number.parseInt(d[0],10),h=d[1]&&Number.parseInt(d[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),h&&Number.isInteger(h)&&h>0&&(e.discsTotal??=h)}break;case"DISCTOTAL":{let d=Number.parseInt(m,10);Number.isInteger(d)&&d>0&&(e.discsTotal??=d)}break;case"DATE":{let d=new Date(m);Number.isNaN(d.getTime())||(e.date??=d)}break;case"GENRE":e.genre??=m;break;case"METADATA_BLOCK_PICTURE":{let d=tc(m),p=j(d),h=p.getUint32(0,!1),x=p.getUint32(4,!1),y=String.fromCharCode(...d.subarray(8,8+x)),v=p.getUint32(8+x,!1),S=ce.decode(d.subarray(12+x,12+x+v)),C=p.getUint32(x+v+28),_=d.subarray(x+v+32,x+v+32+C);e.images??=[],e.images.push({data:_,mimeType:y,kind:h===3?"coverFront":h===4?"coverBack":"unknown",name:void 0,description:S||void 0})}break}}};var me=class{constructor(e){this.input=e}};var fo=[],mo=[];var oe=new Uint8Array(0),Z=class r{constructor(e,t,n,o,i=-1,s,a){if(this.data=e,this.type=t,this.timestamp=n,this.duration=o,this.sequenceNumber=i,e===oe&&s===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(s===void 0&&(s=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(n))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(o)||o<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(i))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");if(a!==void 0&&(typeof a!="object"||!a))throw new TypeError("sideData, when provided, must be an object.");if(a?.alpha!==void 0&&!(a.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(a?.alphaByteLength!==void 0&&(!Number.isInteger(a.alphaByteLength)||a.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=a??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===oe}get microsecondTimestamp(){return Math.trunc(Ue*this.timestamp)}get microsecondDuration(){return Math.trunc(Ue*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let n=new Uint8Array(e.byteLength);return e.copyTo(n),new r(n,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");return new r(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}};var hc=r=>{let t=0,n=0,o=~r;o&128&&(o&=-129,t=-1),n=((o&240)>>4)+5;let i=(1<<n|(o&15)<<n-4|1<<n-5)-33;return t===0?i:-i};var gc=r=>{let e=0,t=0,n=r^85;n&128&&(n&=-129,e=-1),t=((n&240)>>4)+4;let o=0;return t!==4?o=1<<t|(n&15)<<t-4|1<<t-5:o=n<<1|1,e===0?o:-o};to();var xc=-1/0,vc=-1/0,on=null;typeof FinalizationRegistry<"u"&&(on=new FinalizationRegistry(r=>{let e=Date.now();r.type==="video"?(e-xc>=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."),xc=e),typeof VideoFrame<"u"&&r.data instanceof VideoFrame&&r.data.close()):(e-vc>=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."),vc=e),typeof AudioData<"u"&&r.data instanceof AudioData&&r.data.close())}));var bc=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],gp=new Set(bc),cr=class r{get displayWidth(){return this.rotation%180===0?this.codedWidth:this.codedHeight}get displayHeight(){return this.rotation%180===0?this.codedHeight:this.codedWidth}get microsecondTimestamp(){return Math.trunc(Ue*this.timestamp)}get microsecondDuration(){return Math.trunc(Ue*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||!gp.has(t.format))throw new TypeError("init.format must be one of: "+bc.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=Pe(e).slice(),this._layout=t.layout??xp(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 nn(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 nn(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new r(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Ue),duration:Math.trunc((t.duration??0)*Ue)||void 0}),t);let n=0,o=0;if("naturalWidth"in e?(n=e.naturalWidth,o=e.naturalHeight):"videoWidth"in e?(n=e.videoWidth,o=e.videoHeight):"width"in e&&(n=Number(e.width),o=Number(e.height)),!n||!o)throw new TypeError("Could not determine dimensions.");let i=new OffscreenCanvas(n,o),s=i.getContext("2d",{alpha:Qr(),willReadFrequently:!0});g(s),s.drawImage(e,0,0),this._data=i,this._layout=null,this.format="RGBX",this.codedWidth=n,this.codedHeight=o,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new nn({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");on?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return g(this._data!==null),Dt(this._data)?new r(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(g(this._layout),new r(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})):new r(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){this._closed||(on?.unregister(this),Dt(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(yc(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(g(this._data!==null),!Dt(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let t=this.toVideoFrame(),n=t.allocationSize(e);return t.close(),n}return Dt(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,t={}){if(!Qn(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(yc(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(g(this._data!==null),!Dt(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){let n=this.toVideoFrame(),o=await n.copyTo(e,t);return n.close(),o}if(Dt(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array)return g(this._layout),Pe(e).set(this._data),this._layout;{let o=this._data.getContext("2d");g(o);let i=o.getImageData(0,0,this.codedWidth,this.codedHeight);return Pe(e).set(i.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return g(this._data!==null),Dt(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,n,o,i,s,a,c,l){let f=0,u=0,m=this.displayWidth,d=this.displayHeight,p=0,h=0,x=this.displayWidth,y=this.displayHeight;if(s!==void 0?(f=t,u=n,m=o,d=i,p=s,h=a,c!==void 0?(x=c,y=l):(x=m,y=d)):(p=t,h=n,o!==void 0&&(x=o,y=i)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(f))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))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(d)||d<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(x)||x<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:f,sy:u,sWidth:m,sHeight:d}=this._rotateSourceRegion(f,u,m,d,this.rotation));let v=this.toCanvasImageSource();e.save();let S=p+x/2,C=h+y/2;e.translate(S,C),e.rotate(this.rotation*Math.PI/180);let _=this.rotation%180===0?1:x/y;e.scale(1/_,_),e.drawImage(v,f,u,m,d,-x/2,-y/2,x,y),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");t.crop!==void 0&&gs(t.crop,"options.");let n=e.canvas.width,o=e.canvas.height,i=t.rotation??this.rotation,[s,a]=i%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];t.crop&&hs(t.crop,s,a);let c,l,f,u,{sx:m,sy:d,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,f=n,u=o;else{let[y,v]=t.crop?[t.crop.width,t.crop.height]:[s,a],S=t.fit==="contain"?Math.min(n/y,o/v):Math.max(n/y,o/v);f=y*S,u=v*S,c=(n-f)/2,l=(o-u)/2}e.save();let x=i%180===0?1:f/u;e.translate(n/2,o/2),e.rotate(i*Math.PI/180),e.scale(1/x,x),e.translate(-n/2,-o/2),e.drawImage(this.toCanvasImageSource(),m,d,p,h,c,l,f,u),e.restore()}_rotateSourceRegion(e,t,n,o,i){return i===90?[e,t,n,o]=[t,this.codedHeight-e-n,o,n]:i===180?[e,t]=[this.codedWidth-e-n,this.codedHeight-t-o]:i===270&&([e,t,n,o]=[this.codedWidth-t-o,e,o,n]),{sx:e,sy:t,sWidth:n,sHeight:o}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(g(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()}},nn=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}}},Dt=r=>typeof VideoFrame<"u"&&r instanceof VideoFrame,hs=(r,e,t)=>{r.left=Math.min(r.left,e),r.top=Math.min(r.top,t),r.width=Math.min(r.width,e-r.left),r.height=Math.min(r.height,t-r.top),g(r.width>=0),g(r.height>=0)},gs=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},yc=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.colorSpace!==void 0&&!["display-p3","srgb"].includes(r.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(r.format!==void 0&&typeof r.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(r.layout!==void 0){if(!Array.isArray(r.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let e of r.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(r.rect!==void 0){if(!r.rect||typeof r.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(r.rect.x!==void 0&&(!Number.isInteger(r.rect.x)||r.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(r.rect.y!==void 0&&(!Number.isInteger(r.rect.y)||r.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(r.rect.width!==void 0&&(!Number.isInteger(r.rect.width)||r.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(r.rect.height!==void 0&&(!Number.isInteger(r.rect.height)||r.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},xp=(r,e,t)=>{let n=vp(r),o=[],i=0;for(let s of n){let a=Math.ceil(e/s.widthDivisor),c=Math.ceil(t/s.heightDivisor),l=a*s.sampleBytes,f=l*c;o.push({offset:i,stride:l}),i+=f}return o},vp=r=>{let e=(t,n,o,i,s)=>{let a=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:n,widthDivisor:o,heightDivisor:i},{sampleBytes:n,widthDivisor:o,heightDivisor:i}];return s&&a.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),a};switch(r){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:we(r),g(!1)}},ps=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),lr=class r{get microsecondTimestamp(){return Math.trunc(Ue*this.timestamp)}get microsecondDuration(){return Math.trunc(Ue*this.duration)}constructor(e){if(this._closed=!1,rn(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(!ps.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/(Ot(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let n;if(e.data instanceof ArrayBuffer)n=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))n=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let o=this.numberOfFrames*this.numberOfChannels*Ot(this.format);if(n.byteLength<o)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=n}on?.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&&!ps.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let t=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let o=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-n;if(o>this.numberOfFrames-n)throw new RangeError("frameCount out of range");let i=Ot(t),s=ar(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(!Qn(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&&!ps.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{planeIndex:n,format:o,frameCount:i,frameOffset:s}=t,a=this.format,c=o??this.format;if(!c)throw new Error("Destination format not determined");let l=this.numberOfFrames,f=this.numberOfChannels,u=s??0;if(u>=l)throw new RangeError("frameOffset out of range");let m=i!==void 0?i:l-u;if(m>l-u)throw new RangeError("frameCount out of range");let d=Ot(c),p=ar(c);if(p&&n>=f)throw new RangeError("planeIndex out of range");if(!p&&n!==0)throw new RangeError("planeIndex out of range");let x=(p?m:m*f)*d;if(e.byteLength<x)throw new RangeError("Destination buffer is too small");let y=j(e),v=Tc(c);if(rn(this._data))it()&&f>2&&c!==a?yp(this._data,y,a,c,f,n,u,m):this._data.copyTo(e,{planeIndex:n,frameOffset:u,frameCount:m,format:c});else{let S=this._data,C=j(S),_=Sc(a),T=Ot(a),E=ar(a);for(let I=0;I<m;I++)if(p){let M=I*d,L;E?L=(n*l+(I+u))*T:L=((I+u)*f+n)*T;let V=_(C,L);v(y,M,V)}else for(let M=0;M<f;M++){let V=(I*f+M)*d,te;E?te=(M*l+(I+u))*T:te=((I+u)*f+M)*T;let Ee=_(C,te);v(y,V,Ee)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(rn(this._data)){let e=new r(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new r({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(on?.unregister(this),rn(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(rn(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(ar(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(t,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{let e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(t,{planeIndex:n,format:"f32-planar"}),e.copyToChannel(t,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,o=e.numberOfChannels,i=e.sampleRate,s=e.length,a=Math.floor(n/o),c=0,l=s;for(;l>0;){let f=Math.min(a,l),u=new Float32Array(o*f);for(let m=0;m<o;m++)e.copyFromChannel(u.subarray(m*f,(m+1)*f),m,c);yield new r({format:"f32-planar",sampleRate:i,numberOfFrames:f,numberOfChannels:o,timestamp:t+c/i,data:u}),c+=f,l-=f}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let n=48e3*5,o=e.numberOfChannels,i=e.sampleRate,s=e.length,a=Math.floor(n/o),c=0,l=s,f=[];for(;l>0;){let u=Math.min(a,l),m=new Float32Array(o*u);for(let p=0;p<o;p++)e.copyFromChannel(m.subarray(p*u,(p+1)*u),p,c);let d=new r({format:"f32-planar",sampleRate:i,numberOfFrames:u,numberOfChannels:o,timestamp:t+c/i,data:m});f.push(d),c+=u,l-=u}return f}},Ot=r=>{switch(r){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},ar=r=>{switch(r){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Sc=r=>{switch(r){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},Tc=r=>{switch(r){case"u8":case"u8-planar":return(e,t,n)=>e.setUint8(t,Pt((n+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,n)=>e.setInt16(t,Pt(Math.round(n*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,n)=>e.setInt32(t,Pt(Math.round(n*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,n)=>e.setFloat32(t,n,!0)}},rn=r=>typeof AudioData<"u"&&r instanceof AudioData,yp=(r,e,t,n,o,i,s,a)=>{let c=Sc(t),l=Tc(n),f=Ot(t),u=Ot(n),m=ar(t);if(ar(n))if(m){let p=new ArrayBuffer(a*f),h=j(p);r.copyTo(p,{planeIndex:i,frameOffset:s,frameCount:a,format:t});for(let x=0;x<a;x++){let y=x*f,v=x*u,S=c(h,y);l(e,v,S)}}else{let p=new ArrayBuffer(a*o*f),h=j(p);r.copyTo(p,{planeIndex:0,frameOffset:s,frameCount:a,format:t});for(let x=0;x<a;x++){let y=(x*o+i)*f,v=x*u,S=c(h,y);l(e,v,S)}}else if(m){let p=a*f,h=new ArrayBuffer(p),x=j(h);for(let y=0;y<o;y++){r.copyTo(h,{planeIndex:y,frameOffset:s,frameCount:a,format:t});for(let v=0;v<a;v++){let S=v*f,C=(v*o+y)*u,_=c(x,S);l(e,C,_)}}}else{let p=new ArrayBuffer(a*o*f),h=j(p);r.copyTo(p,{planeIndex:0,frameOffset:s,frameCount:a,format:t});for(let x=0;x<a;x++)for(let y=0;y<o;y++){let v=x*o+y,S=v*f,C=v*u,_=c(h,S);l(e,C,_)}}};var ur=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.metadataOnly!==void 0&&typeof r.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(r.verifyKeyPackets!==void 0&&typeof r.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(r.verifyKeyPackets&&r.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},lt=r=>{if(!Jr(r))throw new TypeError("timestamp must be a number.")},xs=(r,e,t)=>t.verifyKeyPackets?e.then(async n=>{if(!n||n.type==="delta")return n;let o=await r.determinePacketType(n);return o&&(n.type=o),n}):e,Rt=class{constructor(e){if(!(e instanceof fr))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(ur(e),this._track.input._disposed)throw new ie;return xs(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){if(lt(e),ur(t),this._track.input._disposed)throw new ie;return xs(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof Z))throw new TypeError("packet must be an EncodedPacket.");if(ur(t),this._track.input._disposed)throw new ie;return xs(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(lt(e),ur(t),this._track.input._disposed)throw new ie;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let n=await this._track._backing.getKeyPacket(e,t);return n&&(g(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getKeyPacket(n.timestamp-1/this._track.timeResolution,t):n)}async getNextKeyPacket(e,t={}){if(!(e instanceof Z))throw new TypeError("packet must be an EncodedPacket.");if(ur(t),this._track.input._disposed)throw new ie;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let n=await this._track._backing.getNextKeyPacket(e,t);return n&&(g(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getNextKeyPacket(n,t):n)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof Z))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof Z))throw new TypeError("endPacket must be an EncodedPacket.");if(ur(n),this._track.input._disposed)throw new ie;let o=[],{promise:i,resolve:s}=pe(),{promise:a,resolve:c}=pe(),l=!1,f=!1,u=null,m=[],d=()=>Math.max(2,m.length);(async()=>{let h=e??await this.getFirstPacket(n);for(;h&&!f&&!this._track.input._disposed&&!(t&&h.sequenceNumber>=t?.sequenceNumber);){if(o.length>d()){({promise:a,resolve:c}=pe()),await a;continue}o.push(h),s(),{promise:i,resolve:s}=pe(),h=await this.getNextPacket(h,n)}l=!0,s()})().catch(h=>{u||(u=h,s())});let p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new ie;if(f)return{value:void 0,done:!0};if(u)throw u;if(o.length>0){let h=o.shift(),x=performance.now();for(m.push(x);m.length>0&&x-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 f=!0,c(),s(),{value:void 0,done:!0}},async throw(h){throw h},[Symbol.asyncIterator](){return this}}}},sn=class{constructor(e,t){this.onSample=e,this.onError=t}},an=class{mediaSamplesInRange(e=0,t=1/0){lt(e),lt(t);let n=[],o=!1,i=null,{promise:s,resolve:a}=pe(),{promise:c,resolve:l}=pe(),f=!1,u=!1,m=!1,d=null;(async()=>{let x=await this._createDecoder(T=>{if(l(),T.timestamp>=t&&(u=!0),u){T.close();return}i&&(T.timestamp>e?(n.push(i),o=!0):i.close()),T.timestamp>=e&&(n.push(T),o=!0),i=o?null:T,n.length>0&&(a(),{promise:s,resolve:a}=pe())},T=>{d||(d=T,a())}),y=this._createPacketSink(),v=await y.getKeyPacket(e,{verifyKeyPackets:!0})??await y.getFirstPacket(),S=v,C;if(t<1/0){let T=await y.getPacket(t),E=T?T.type==="key"&&T.timestamp===t?T:await y.getNextKeyPacket(T,{verifyKeyPackets:!0}):null;E&&(C=E)}let _=y.packets(v??void 0,C);for(await _.next();S&&!u&&!this._track.input._disposed;){let T=wc(n.length);if(n.length+x.getDecodeQueueSize()>T){({promise:c,resolve:l}=pe()),await c;continue}x.decode(S);let E=await _.next();if(E.done)break;S=E.value}await _.return(),!m&&!this._track.input._disposed&&await x.flush(),x.close(),!o&&i&&n.push(i),f=!0,a()})().catch(x=>{d||(d=x,a())});let p=this._track,h=()=>{i?.close();for(let x of n)x.close()};return{async next(){for(;;){if(p.input._disposed)throw h(),new ie;if(m)return{value:void 0,done:!0};if(d)throw h(),d;if(n.length>0){let x=n.shift();return l(),{value:x,done:!1}}else if(!f)await s;else return{value:void 0,done:!0}}},async return(){return m=!0,u=!0,l(),a(),h(),{value:void 0,done:!0}},async throw(x){throw x},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){Ya(e);let t=Ka(e),n=[],o=[],{promise:i,resolve:s}=pe(),{promise:a,resolve:c}=pe(),l=!1,f=!1,u=null,m=h=>{o.push(h),s(),{promise:i,resolve:s}=pe()};(async()=>{let h=await this._createDecoder(T=>{if(c(),f){T.close();return}let E=0;for(;n.length>0&&T.timestamp-n[0]>-1e-10;)E++,n.shift();if(E>0)for(let I=0;I<E;I++)m(I<E-1?T.clone():T);else T.close()},T=>{u||(u=T,s())}),x=this._createPacketSink(),y=null,v=null,S=-1,C=async()=>{g(v);let T=v;for(h.decode(T);T.sequenceNumber<S;){let E=wc(o.length);for(;o.length+h.getDecodeQueueSize()>E&&!f;)({promise:a,resolve:c}=pe()),await a;if(f)break;let I=await x.getNextPacket(T);g(I),h.decode(I),T=I}S=-1},_=async()=>{await h.flush();for(let T=0;T<n.length;T++)m(null);n.length=0};for await(let T of t){if(lt(T),f||this._track.input._disposed)break;let E=await x.getPacket(T),I=E&&await x.getKeyPacket(T,{verifyKeyPackets:!0});if(!I){S!==-1&&(await C(),await _()),m(null),y=null;continue}y&&(I.sequenceNumber!==v.sequenceNumber||E.timestamp<y.timestamp)&&(await C(),await _()),n.push(E.timestamp),S=Math.max(E.sequenceNumber,S),y=E,v=I}!f&&!this._track.input._disposed&&(S!==-1&&await C(),await _()),h.close(),l=!0,s()})().catch(h=>{u||(u=h,s())});let d=this._track,p=()=>{for(let h of o)h?.close()};return{async next(){for(;;){if(d.input._disposed)throw p(),new ie;if(f)return{value:void 0,done:!0};if(u)throw p(),u;if(o.length>0){let h=o.shift();return g(h!==void 0),c(),{value:h,done:!1}}else if(!l)await i;else return{value:void 0,done:!0}}},async return(){return f=!0,c(),s(),p(),{value:void 0,done:!0}},async throw(h){throw h},[Symbol.asyncIterator](){return this}}}},wc=r=>r===0?40:8,vs=class extends sn{constructor(e,t,n,o,i,s){super(e,t),this.codec=n,this.decoderConfig=o,this.rotation=i,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new $r,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=fo.find(c=>c.supports(n,o));if(a)this.customDecoder=new a,this.customDecoder.codec=n,this.customDecoder.config=o,this.customDecoder.onSample=c=>{if(!(c instanceof cr))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=f=>{if(this.alphaQueue.length>0){let u=this.alphaQueue.shift();g(u!==void 0),this.mergeAlpha(f,u)}else this.colorQueue.push(f)};if(n==="avc"&&this.decoderConfig.description&&Zr()){let f=lc(Pe(this.decoderConfig.description));if(f&&f.sequenceParameterSets.length>0){let u=ms(f.sequenceParameterSets[0]);u&&u.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let l=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:f=>{try{c(f)}catch(u){this.onError(u)}},error:f=>{f.stack=l,this.onError(f)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(g(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(g(this.decoder),it()||ns(this.inputTimestamps,e.timestamp,t=>t),Zr()&&this.currentPacketIndex===0&&this.codec==="avc"){let n=fs(e.data,this.decoderConfig).filter(i=>{let s=zt(i);return!(s>=20&&s<=31)}),o=ac(n,this.decoderConfig);e=new Z(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 ys}catch(n){console.error("Due to an error, only color data will be decoded.",n),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let n=i=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let s=this.colorQueue.shift();g(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();g(s!==void 0),this.mergeAlpha(s,null)}else this.alphaQueue.push(null)},o=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:i=>{try{n(i)}catch(s){this.onError(s)}},error:i=>{i.stack=o,this.onError(i)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=uo(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 ds(e,this.decoderConfig).some(n=>{let o=Xe(n);return o===he.RASL_N||o===he.RASL_R})}sampleHandler(e){if(it()){if(this.sampleQueue.length>0&&e.timestamp>=de(this.sampleQueue).timestamp){for(let t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}ns(this.sampleQueue,e,t=>t.timestamp)}else{let t=this.inputTimestamps.shift();g(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 cr(e);this.sampleHandler(i);return}g(this.merger),this.merger.update(e,t),e.close(),t.close();let n=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),o=new cr(n);this.sampleHandler(o)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(g(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),it()){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()):(g(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}},ys=class{constructor(){typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");let e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
2341
2341
  in vec2 a_position;
2342
2342
  in vec2 a_texCoord;
2343
2343
  out vec2 v_texCoord;
@@ -2359,7 +2359,7 @@ vec4 transition(vec2 uv) {
2359
2359
  float alpha = texture(u_alphaTexture, v_texCoord).r;
2360
2360
  fragColor = vec4(color, alpha);
2361
2361
  }
2362
- `),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){let n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),n}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let o=this.gl.getAttribLocation(this.program,"a_position"),i=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(o),this.gl.vertexAttribPointer(o,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,t){(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}},ut=class extends an{constructor(e){if(!(e instanceof Ne))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=this._track.codec,o=this._track.rotation,i=await this._track.getDecoderConfig(),s=this._track.timeResolution;return g(n&&i),new vs(e,t,n,i,o,s)}_createPacketSink(){return new Dt(this._track)}async getSample(e){lt(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)}},cn=class{constructor(e,t={}){if(this._nextCanvasIndex=0,!(e instanceof Ne))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&&gs(t.crop,"options."),t.poolSize!==void 0&&(typeof t.poolSize!="number"||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");let n=t.rotation??e.rotation,[o,i]=n%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],s=t.crop;s&&hs(s,o,i);let[a,c]=s?[s.width,s.height]:[o,i],l=a/c;t.width!==void 0&&t.height===void 0?(a=t.width,c=Math.round(a/l)):t.width===void 0&&t.height!==void 0?(c=t.height,a=Math.round(c*l)):t.width!==void 0&&t.height!==void 0&&(a=t.width,c=t.height),this._videoTrack=e,this._alpha=t.alpha??!1,this._width=a,this._height=c,this._rotation=n,this._crop=s,this._fit=t.fit??"fill",this._videoSampleSink=new ut(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let t=this._canvasPool[this._nextCanvasIndex],n=!1;t||(typeof document<"u"?(t=document.createElement("canvas"),t.width=this._width,t.height=this._height):t=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=t),n=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let o=t.getContext("2d",{alpha:this._alpha||Qr()});g(o),o.resetTransform(),n||(!this._alpha&&Qr()?(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){lt(e);let t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return is(this._videoSampleSink.samples(e,t),n=>this._videoSampleToWrappedCanvas(n))}canvasesAtTimestamps(e){return is(this._videoSampleSink.samplesAtTimestamps(e),t=>t&&this._videoSampleToWrappedCanvas(t))}},bs=class extends sn{constructor(e,t,n,o){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new $r,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=mo.find(a=>a.supports(n,o));if(s)this.customDecoder=new s,this.customDecoder.codec=n,this.customDecoder.config=o,this.customDecoder.onSample=a=>{if(!(a instanceof cr))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 cr(c))}catch(l){this.onError(l)}},error:c=>{c.stack=a,this.onError(c)}}),this.decoder.configure(o)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(g(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(g(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(g(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(g(this.decoder),this.decoder.close())}},Ss=class extends sn{constructor(e,t,n){super(e,t),this.decoderConfig=n,this.currentTimestamp=null,g(at.includes(n.codec)),this.codec=n.codec;let{dataType:o,sampleSize:i,littleEndian:s}=io(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)=>hc(a.getUint8(c)):o==="alaw"?this.readInputValue=(a,c)=>gc(a.getUint8(c)):g(!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):g(!1);break;case 3:o==="unsigned"?this.readInputValue=(a,c)=>wt(a,c,s)-2**23:o==="signed"?this.readInputValue=(a,c)=>$a(a,c,s):g(!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):g(!1);break;case 8:o==="float"?this.readInputValue=(a,c)=>a.getFloat64(c,s):g(!1);break;default:we(i),g(!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:we(i),g(!1)}}getDecodeQueueSize(){return 0}decode(e){let t=j(e.data),n=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,o=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,i=new ArrayBuffer(o),s=new DataView(i);for(let f=0;f<n*this.decoderConfig.numberOfChannels;f++){let u=f*this.inputSampleSize,m=f*this.outputSampleSize,d=this.readInputValue(t,u);this.writeOutputValue(s,m,d)}let a=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=a)&&(this.currentTimestamp=e.timestamp);let c=this.currentTimestamp;this.currentTimestamp+=a;let l=new cr({format:this.outputFormat,data:i,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:c});this.onSample(l)}async flush(){}close(){}},ln=class extends an{constructor(e){if(!(e instanceof se))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=this._track.codec,o=await this._track.getDecoderConfig();return g(n&&o),at.includes(o.codec)?new Ss(e,t,o):new bs(e,t,n,o)}_createPacketSink(){return new Dt(this._track)}async getSample(e){lt(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 ur=class{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Ne}isAudioTrack(){return this instanceof se}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),n=1/0,o=-1/0,i=0,s=0;for await(let a of t.packets(void 0,void 0,{metadataOnly:!0})){if(i>=e&&a.timestamp>=o)break;n=Math.min(n,a.timestamp),o=Math.max(o,a.timestamp+a.duration),i++,s+=a.byteLength}return{packetCount:i,averagePacketRate:i?Number((i/(o-n)).toPrecision(16)):0,averageBitrate:i?Number((8*s/(o-n)).toPrecision(16)):0}}},Ne=class extends ur{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 g(t!==null),fo.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 Z))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 g(t),uo(this.codec,t,e.data)}},se=class extends ur{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 g(t!==null),mo.some(n=>n.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Z))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}};var Cc=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isQuickTime?"quicktime":"mp4");if(r.codecStrings.length>0){let n=[...new Set(r.codecStrings)];t+=`; codecs="${n.join(", ")}"`}return t};var Ot=8,fr=16,Ke=r=>{let e=F(r),t=J(r,4),n=8;e===1&&(e=Se(r),n=16);let i=e-n;return i<0?null:{name:t,totalSize:e,headerSize:n,contentSize:i}},ft=r=>Ye(r)/65536,po=r=>Ye(r)/1073741824,ho=r=>{let e=0;for(let t=0;t<4;t++){e<<=7;let n=R(r);if(e|=n&127,(n&128)===0)break}return e},_e=r=>{let e=ae(r);return r.skip(2),e=Math.min(e,r.remainingLength),ce.decode(B(r,e))},kc=r=>{let e=Ke(r);if(!e||e.name!=="data"||r.remainingLength<8)return null;let t=F(r);r.skip(4);let n=B(r,e.contentSize-8);switch(t){case 1:return ce.decode(n);case 2:return new TextDecoder("utf-16be").decode(n);case 13:return new st(n,"image/jpeg");case 14:return new st(n,"image/png");case 27:return new st(n,"image/bmp");default:return n}};var go=class extends me{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(t=>t.inputTrack.getCodecParameterString()));return Cc({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,Ot,fr);if(t instanceof Promise&&(t=await t),!t)break;let n=e,o=Ke(t);if(!o)break;if(o.name==="ftyp"){let i=J(t,4);this.isQuickTime=i==="qt "}else if(o.name==="moov"){let i=this.reader.requestSlice(t.filePos,o.contentSize);if(i instanceof Promise&&(i=await i),!i)break;this.moovSlice=i,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((s,a)=>Number(a.disposition.default)-Number(s.disposition.default));for(let s of this.tracks){let a=s.editListPreviousSegmentDurations/this.movieTimescale;s.editListOffset-=Math.round(a*s.timescale)}break}e=n+o.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let t=this.reader.requestSlice(this.reader.fileSize-4,4);t instanceof Promise&&(t=await t),g(t);let n=F(t),o=this.reader.fileSize-n;if(o>=0&&o<=this.reader.fileSize-fr){let i=this.reader.requestSliceRange(o,Ot,fr);if(i instanceof Promise&&(i=await i),i){let s=Ke(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,g(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&at.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){g(e.info?.type==="audio");let i=io(e.info.codec),s=[],a=[];for(let c=0;c<t.sampleToChunk.length;c++){let l=t.sampleToChunk[c],f=t.sampleToChunk[c+1],u=(f?f.startChunkIndex:t.chunkOffsets.length)-l.startChunkIndex;for(let m=0;m<u;m++){let d=l.startSampleIndex+m*l.samplesPerChunk,p=d+l.samplesPerChunk,h=W(t.sampleTimingEntries,d,I=>I.startIndex),x=t.sampleTimingEntries[h],y=W(t.sampleTimingEntries,p,I=>I.startIndex),v=t.sampleTimingEntries[y],S=x.startDecodeTimestamp+(d-x.startIndex)*x.delta,_=v.startDecodeTimestamp+(p-v.startIndex)*v.delta-S,T=de(s);T&&T.delta===_?T.count++:s.push({startIndex:l.startChunkIndex+m,startDecodeTimestamp:S,count:1,delta:_});let E=l.samplesPerChunk*i.sampleSize*e.info.numberOfChannels;a.push(E)}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,Ot,fr);t instanceof Promise&&(t=await t),g(t);let n=Ke(t);g(n?.name==="moof");let o=this.reader.requestSlice(e,n.totalSize);o instanceof Promise&&(o=await o),g(o),this.traverseBox(o);let i=this.lastReadFragment;g(i&&i.moofOffset===e);for(let[,s]of i.trackData){let a=s.track,{fragmentPositionCache:c}=a;if(!s.startTimestampIsFinal){let f=a.fragmentLookupTable.find(u=>u.moofOffset===i.moofOffset);if(f)Ts(s,f.timestamp);else{let u=W(c,i.moofOffset-1,m=>m.moofOffset);if(u!==-1){let m=c[u];Ts(s,m.endTimestamp)}}s.startTimestampIsFinal=!0}let l=W(c,s.startTimestamp,f=>f.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-Ot&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-Ot;){let n=e.filePos,o=Ke(e);if(!o)break;yield{boxInfo:o,slice:e},e.filePos=n+o.totalSize}}traverseBox(e){let t=e.filePos,n=Ke(e);if(!n)return!1;let o=e.filePos,i=t+n.totalSize;switch(n.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"mvhd":{let s=R(e);e.skip(3),s===1?(e.skip(16),this.movieTimescale=F(e),this.movieDurationInTimescale=Se(e)):(e.skip(8),this.movieTimescale=F(e),this.movieDurationInTimescale=F(e))}break;case"trak":{let s={id:-1,demuxer:this,inputTrack:null,disposition:{...xe},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:le,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=s,this.readContiguousBoxes(e.slice(o,n.contentSize)),s.id!==-1&&s.timescale!==-1&&s.info!==null){if(s.info.type==="video"&&s.info.width!==-1){let a=s;s.inputTrack=new Ne(this.input,new ws(a)),this.tracks.push(s)}else if(s.info.type==="audio"&&s.info.numberOfChannels!==-1){let a=s;s.inputTrack=new se(this.input,new Cs(a)),this.tracks.push(s)}}this.currentTrack=null}break;case"tkhd":{let s=this.currentTrack;if(!s)break;let a=R(e),l=!!(mt(e)&1);if(s.disposition.default=l,a===0)e.skip(8),s.id=F(e),e.skip(4),s.durationInMovieTimescale=F(e);else if(a===1)e.skip(16),s.id=F(e),e.skip(4),s.durationInMovieTimescale=Se(e);else throw new Error(`Incorrect track header version ${a}.`);e.skip(16);let f=[ft(e),ft(e),po(e),ft(e),ft(e),po(e),ft(e),ft(e),po(e)],u=Xn(Za(wp(f),90));g(u===0||u===90||u===180||u===270),s.rotation=u}break;case"elst":{let s=this.currentTrack;if(!s)break;let a=R(e);e.skip(3);let c=!1,l=0,f=F(e);for(let u=0;u<f;u++){let m=a===1?Se(e):F(e),d=a===1?_c(e):Ye(e),p=ft(e);if(m!==0){if(c){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(d===-1){l+=m;continue}if(p!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}s.editListPreviousSegmentDurations=l,s.editListOffset=d,c=!0}}}break;case"mdhd":{let s=this.currentTrack;if(!s)break;let a=R(e);e.skip(3),a===0?(e.skip(8),s.timescale=F(e),s.durationInMediaTimescale=F(e)):a===1&&(e.skip(16),s.timescale=F(e),s.durationInMediaTimescale=Se(e));let c=ae(e);if(c>0){s.languageCode="";for(let l=0;l<3;l++)s.languageCode=String.fromCharCode(96+(c&31))+s.languageCode,c>>=5;Jn(s.languageCode)||(s.languageCode=le)}}break;case"hdlr":{let s=this.currentTrack;if(!s)break;e.skip(8);let a=J(e,4);a==="vide"?s.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:a==="soun"&&(s.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{let s=this.currentTrack;if(!s)break;s.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(o,n.contentSize))}break;case"stsd":{let s=this.currentTrack;if(!s||s.info===null||s.sampleTable)break;let a=R(e);e.skip(3);let c=F(e);for(let l=0;l<c;l++){let f=e.filePos,u=Ke(e);if(!u)break;s.internalCodecId=u.name;let m=u.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 '${u.name}').`),e.skip(24),s.info.width=ae(e),s.info.height=ae(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,f+u.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 '${u.name}').`))),e.skip(8);let d=ae(e);e.skip(6);let p=ae(e),h=ae(e);e.skip(4);let x=F(e)/65536;if(a===0&&d>0){if(d===1)e.skip(4),h=8*F(e),e.skip(8);else if(d===2){e.skip(4),x=vo(e),p=F(e),e.skip(4),h=F(e);let y=F(e);if(e.skip(8),m==="lpcm"){let v=h+7>>3,S=!!(y&1),C=!!(y&2),_=y&4?-1:0;h>0&&h<=64&&(S?h===32&&(s.info.codec=C?"pcm-f32be":"pcm-f32"):_&1<<v-1?v===1?s.info.codec="pcm-s8":v===2?s.info.codec=C?"pcm-s16be":"pcm-s16":v===3?s.info.codec=C?"pcm-s24be":"pcm-s24":v===4&&(s.info.codec=C?"pcm-s32be":"pcm-s32"):v===1&&(s.info.codec="pcm-u8")),s.info.codec===null&&console.warn("Unsupported PCM format.")}}}s.info.codec==="opus"&&(x=It),s.info.numberOfChannels=p,s.info.sampleRate=x,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,f+u.totalSize-e.filePos))}}}break;case"avcC":{let s=this.currentTrack;if(!s)break;g(s.info),s.info.codecDescription=B(e,n.contentSize)}break;case"hvcC":{let s=this.currentTrack;if(!s)break;g(s.info),s.info.codecDescription=B(e,n.contentSize)}break;case"vpcC":{let s=this.currentTrack;if(!s)break;g(s.info?.type==="video"),e.skip(4);let a=R(e),c=R(e),l=R(e),f=l>>4,u=l>>1&7,m=l&1,d=R(e),p=R(e),h=R(e);s.info.vp9CodecInfo={profile:a,level:c,bitDepth:f,chromaSubsampling:u,videoFullRangeFlag:m,colourPrimaries:d,transferCharacteristics:p,matrixCoefficients:h}}break;case"av1C":{let s=this.currentTrack;if(!s)break;g(s.info?.type==="video"),e.skip(1);let a=R(e),c=a>>5,l=a&31,f=R(e),u=f>>7,m=f>>6&1,d=f>>5&1,p=f>>4&1,h=f>>3&1,x=f>>2&1,y=f&3,v=c===2&&m?d?12:10:m?10:8;s.info.av1CodecInfo={profile:c,level:l,tier:u,bitDepth:v,monochrome:p,chromaSubsamplingX:h,chromaSubsamplingY:x,chromaSamplePosition:y}}break;case"colr":{let s=this.currentTrack;if(!s||(g(s.info?.type==="video"),J(e,4)!=="nclx"))break;let c=ae(e),l=ae(e),f=ae(e),u=!!(R(e)&128);s.info.colorSpace={primaries:Kn[c],transfer:Yn[l],matrix:$n[f],fullRange:u}}break;case"wave":this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"esds":{let s=this.currentTrack;if(!s)break;g(s.info?.type==="audio"),e.skip(4);let a=R(e);g(a===3),ho(e),e.skip(2);let c=R(e),l=(c&128)!==0,f=(c&64)!==0,u=(c&32)!==0;if(l&&e.skip(2),f){let x=R(e);e.skip(x)}u&&e.skip(2);let m=R(e);g(m===4);let d=ho(e),p=e.filePos,h=R(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),d>e.filePos-p){let x=R(e);g(x===5);let y=ho(e);if(s.info.codecDescription=B(e,y),s.info.codec==="aac"){let v=ls(s.info.codecDescription);v.numberOfChannels!==null&&(s.info.numberOfChannels=v.numberOfChannels),v.sampleRate!==null&&(s.info.sampleRate=v.sampleRate)}}}break;case"enda":{let s=this.currentTrack;if(!s)break;g(s.info?.type==="audio"),ae(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;g(s.info?.type==="audio"),e.skip(4);let c=!!(R(e)&1),l=R(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;g(s.info?.type==="audio"),e.skip(1);let a=R(e),c=ae(e),l=F(e),f=un(e),u=R(e),m;u!==0?m=B(e,2+a):m=new Uint8Array(0);let d=new Uint8Array(19+m.byteLength),p=new DataView(d.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,f,!0),p.setUint8(18,u),d.set(m,19),s.info.codecDescription=d,s.info.numberOfChannels=a}break;case"dfLa":{let s=this.currentTrack;if(!s)break;g(s.info?.type==="audio"),e.skip(4);let a=127,c=128,l=e.filePos;for(;e.filePos<i;){let p=R(e),h=mt(e);if((p&a)===ct.STREAMINFO){e.skip(10);let y=F(e),v=y>>>12,S=(y>>9&7)+1;s.info.sampleRate=v,s.info.numberOfChannels=S,e.skip(20)}else e.skip(h);if(p&c)break}let f=e.filePos;e.filePos=l;let u=B(e,f-l),m=new Uint8Array(4+u.byteLength);new DataView(m.buffer).setUint32(0,1716281667,!1),m.set(u,4),s.info.codecDescription=m}break;case"stts":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=F(e),c=0,l=0;for(let f=0;f<a;f++){let u=F(e),m=F(e);s.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:l,count:u,delta:m}),c+=u,l+=u*m}}break;case"ctts":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=F(e),c=0;for(let l=0;l<a;l++){let f=F(e),u=Ye(e);s.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:f,offset:u}),c+=f}}break;case"stsz":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=F(e),c=F(e);if(a===0)for(let l=0;l<c;l++){let f=F(e);s.sampleTable.sampleSizes.push(f)}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=R(e),c=F(e),l=B(e,Math.ceil(c*a/8)),f=new $(l);for(let u=0;u<c;u++){let m=f.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=F(e);for(let c=0;c<a;c++){let l=F(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=F(e);for(let l=0;l<a;l++){let f=F(e)-1,u=F(e),m=F(e);s.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:f,samplesPerChunk:u,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 u=s.sampleTable.sampleToChunk[l+1].startChunkIndex-s.sampleTable.sampleToChunk[l].startChunkIndex;c+=u*s.sampleTable.sampleToChunk[l].samplesPerChunk}}break;case"stco":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=F(e);for(let c=0;c<a;c++){let l=F(e);s.sampleTable.chunkOffsets.push(l)}}break;case"co64":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=F(e);for(let c=0;c<a;c++){let l=Se(e);s.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"mehd":{let s=R(e);e.skip(3);let a=s===1?Se(e):F(e);this.movieDurationInTimescale=a}break;case"trex":{e.skip(4);let s=F(e),a=F(e),c=F(e),l=F(e),f=F(e);this.fragmentTrackDefaults.push({trackId:s,defaultSampleDescriptionIndex:a,defaultSampleDuration:c,defaultSampleSize:l,defaultSampleFlags:f})}break;case"tfra":{let s=R(e);e.skip(3);let a=F(e),c=this.tracks.find(v=>v.id===a);if(!c)break;let l=F(e),f=(l&48)>>4,u=(l&12)>>2,m=l&3,d=[R,ae,mt,F],p=d[f],h=d[u],x=d[m],y=F(e);for(let v=0;v<y;v++){let S=s===1?Se(e):F(e),C=s===1?Se(e):F(e);p(e),h(e),x(e),c.fragmentLookupTable.push({timestamp:S,moofOffset:C})}c.fragmentLookupTable.sort((v,S)=>v.timestamp-S.timestamp);for(let v=0;v<c.fragmentLookupTable.length-1;v++){let S=c.fragmentLookupTable[v],C=c.fragmentLookupTable[v+1];S.timestamp===C.timestamp&&(c.fragmentLookupTable.splice(v+1,1),v--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:n.totalSize,implicitBaseDataOffset:t,trackData:new Map},this.readContiguousBoxes(e.slice(o,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(g(this.currentFragment),this.readContiguousBoxes(e.slice(o,n.contentSize)),this.currentTrack){let s=this.currentFragment.trackData.get(this.currentTrack.id);if(s){let{currentFragmentState:a}=this.currentTrack;g(a),a.startTimestamp!==null&&(Ts(s,a.startTimestamp),s.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{g(this.currentFragment),e.skip(1);let s=mt(e),a=!!(s&1),c=!!(s&2),l=!!(s&8),f=!!(s&16),u=!!(s&32),m=!!(s&65536),d=!!(s&131072),p=F(e),h=this.tracks.find(y=>y.id===p);if(!h)break;let x=this.fragmentTrackDefaults.find(y=>y.trackId===p);this.currentTrack=h,h.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:x?.defaultSampleDescriptionIndex??null,defaultSampleDuration:x?.defaultSampleDuration??null,defaultSampleSize:x?.defaultSampleSize??null,defaultSampleFlags:x?.defaultSampleFlags??null,startTimestamp:null},a?h.currentFragmentState.baseDataOffset=Se(e):d&&(h.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(h.currentFragmentState.sampleDescriptionIndex=F(e)),l&&(h.currentFragmentState.defaultSampleDuration=F(e)),f&&(h.currentFragmentState.defaultSampleSize=F(e)),u&&(h.currentFragmentState.defaultSampleFlags=F(e)),m&&(h.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let s=this.currentTrack;if(!s)break;g(s.currentFragmentState);let a=R(e);e.skip(3);let c=a===0?F(e):Se(e);s.currentFragmentState.startTimestamp=c}break;case"trun":{let s=this.currentTrack;if(!s)break;if(g(this.currentFragment),g(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=R(e),c=mt(e),l=!!(c&1),f=!!(c&4),u=!!(c&256),m=!!(c&512),d=!!(c&1024),p=!!(c&2048),h=F(e),x=s.currentFragmentState.baseDataOffset;l&&(x+=Ye(e));let y=null;f&&(y=F(e));let v=x;if(h===0){this.currentFragment.implicitBaseDataOffset=v;break}let S=0,C={track:s,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(s.id,C);for(let E=0;E<h;E++){let I;u?I=F(e):(g(s.currentFragmentState.defaultSampleDuration!==null),I=s.currentFragmentState.defaultSampleDuration);let M;m?M=F(e):(g(s.currentFragmentState.defaultSampleSize!==null),M=s.currentFragmentState.defaultSampleSize);let L;d?L=F(e):(g(s.currentFragmentState.defaultSampleFlags!==null),L=s.currentFragmentState.defaultSampleFlags),E===0&&y!==null&&(L=y);let V=0;p&&(a===0?V=F(e):V=Ye(e));let te=!(L&65536);C.samples.push({presentationTimestamp:S+V,duration:I,byteOffset:v,byteSize:M,isKeyFrame:te}),v+=M,S+=I}C.presentationTimestamps=C.samples.map((E,I)=>({presentationTimestamp:E.presentationTimestamp,sampleIndex:I})).sort((E,I)=>E.presentationTimestamp-I.presentationTimestamp);for(let E=0;E<C.presentationTimestamps.length;E++){let I=C.presentationTimestamps[E],M=C.samples[I.sampleIndex];if(C.firstKeyFrameTimestamp===null&&M.isKeyFrame&&(C.firstKeyFrameTimestamp=M.presentationTimestamp),E<C.presentationTimestamps.length-1){let L=C.presentationTimestamps[E+1];M.duration=L.presentationTimestamp-I.presentationTimestamp}}let _=C.samples[C.presentationTimestamps[0].sampleIndex],T=C.samples[de(C.presentationTimestamps).sampleIndex];C.startTimestamp=_.presentationTimestamp,C.endTimestamp=T.presentationTimestamp+T.duration,this.currentFragment.implicitBaseDataOffset=v}break;case"udta":{let s=this.iterateContiguousBoxes(e.slice(o,n.contentSize));for(let{boxInfo:a,slice:c}of s){if(a.name!=="meta"&&!this.currentTrack){let l=c.filePos;this.metadataTags.raw??={},a.name[0]==="\xA9"?this.metadataTags.raw[a.name]??=_e(c):this.metadataTags.raw[a.name]??=B(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=ce.decode(B(c,a.contentSize)):this.metadataTags.title??=_e(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=_e(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=_e(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=_e(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=_e(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=_e(c));break;case"\xA9day":if(!this.currentTrack){let l=new Date(_e(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=_e(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=_e(c));break}}}break;case"meta":{if(this.currentTrack)break;let a=F(e)!==0;this.currentMetadataKeys=new Map,a?this.readContiguousBoxes(e.slice(o,n.contentSize)):this.readContiguousBoxes(e.slice(o+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let s=F(e);for(let a=0;a<s;a++){let c=F(e);e.skip(4);let l=ce.decode(B(e,c-8));this.currentMetadataKeys.set(a+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let s=this.iterateContiguousBoxes(e.slice(o,n.contentSize));for(let{boxInfo:a,slice:c}of s){let l=a.name,f=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(f)&&(l=this.currentMetadataKeys.get(f));let u=kc(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=u,l){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof u=="string"&&(this.metadataTags.title??=u);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof u=="string"&&(this.metadataTags.description??=u);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof u=="string"&&(this.metadataTags.artist??=u);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof u=="string"&&(this.metadataTags.album??=u);break;case"aART":case"album_artist":typeof u=="string"&&(this.metadataTags.albumArtist??=u);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof u=="string"&&(this.metadataTags.comment??=u);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof u=="string"&&(this.metadataTags.genre??=u);break;case"\xA9lyr":case"lyrics":typeof u=="string"&&(this.metadataTags.lyrics??=u);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof u=="string"){let m=new Date(u);Number.isNaN(m.getTime())||(this.metadataTags.date??=m)}break;case"covr":case"com.apple.quicktime.artwork":u instanceof st?(this.metadataTags.images??=[],this.metadataTags.images.push({data:u.data,kind:"coverFront",mimeType:u.mimeType})):u instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:u,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof u=="string"){let m=u.split("/"),d=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(d)&&d>0&&(this.metadataTags.trackNumber??=d),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(u instanceof Uint8Array&&u.length>=6){let m=j(u),d=m.getUint16(2,!1),p=m.getUint16(4,!1);d>0&&(this.metadataTags.trackNumber??=d),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(u instanceof Uint8Array&&u.length>=6){let m=j(u),d=m.getUint16(2,!1),p=m.getUint16(4,!1);d>0&&(this.metadataTags.discNumber??=d),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=i,!0}},xo=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,n=>n.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return kt(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),o=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=ks(o,n),s=await this.fetchPacketForSampleIndex(i,t);return!Pc(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=W(c.presentationTimestamps,n,m=>m.presentationTimestamp),f=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,u=l!==-1&&n<c.endTimestamp;return{sampleIndex:f,correctSampleFound:u}},n,n,t)}async getNextPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,t);let o=this.packetToFragmentLocation.get(e);if(o===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(o.fragment,i=>{if(i===o.fragment){let s=i.trackData.get(this.internalTrack.id);if(o.sampleIndex+1<s.samples.length)return{sampleIndex:o.sampleIndex+1,correctSampleFound:!0}}else if(i.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.mapTimestampIntoTimescale(e),o=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=bp(o,n),s=await this.fetchPacketForSampleIndex(i,t);return!Pc(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=Zn(c.presentationTimestamps,m=>c.samples[m.sampleIndex].isKeyFrame&&m.presentationTimestamp<=n),f=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,u=l!==-1&&n<c.endTimestamp;return{sampleIndex:f,correctSampleFound:u}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Tp(i,n);return this.fetchPacketForSampleIndex(s,t)}let o=this.packetToFragmentLocation.get(e);if(o===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(o.fragment,i=>{if(i===o.fragment){let a=i.trackData.get(this.internalTrack.id).samples.findIndex((c,l)=>c.isKeyFrame&&l>o.sampleIndex);if(a!==-1)return{sampleIndex:a,correctSampleFound:!0}}else{let s=i.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){let a=s.samples.findIndex(c=>c.isKeyFrame);return g(a!==-1),{sampleIndex:a,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),o=Sp(n,e);if(!o)return null;let i;if(t.metadataOnly)i=oe;else{let l=this.internalTrack.demuxer.reader.requestSlice(o.sampleOffset,o.sampleSize);l instanceof Promise&&(l=await l),g(l),i=B(l,o.sampleSize)}let s=(o.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=o.duration/this.internalTrack.timescale,c=new Z(i,o.isKeyFrame?"key":"delta",s,a,e,o.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,n){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).samples[t];g(i);let s;if(n.metadataOnly)s=oe;else{let f=this.internalTrack.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);f instanceof Promise&&(f=await f),g(f),s=B(f,i.byteSize)}let a=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=i.duration/this.internalTrack.timescale,l=new Z(s,i.isKeyFrame?"key":"delta",a,c,e.moofOffset+t,i.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:t}),l}async performFragmentedLookup(e,t,n,o,i){let s=this.internalTrack.demuxer,a=null,c=null,l=-1;if(e){let{sampleIndex:x,correctSampleFound:y}=t(e);if(y)return this.fetchPacketInFragment(e,x,i);x!==-1&&(c=e,l=x)}let f=W(this.internalTrack.fragmentLookupTable,n,x=>x.timestamp),u=f!==-1?this.internalTrack.fragmentLookupTable[f]:null,m=W(this.internalTrack.fragmentPositionCache,n,x=>x.startTimestamp),d=m!==-1?this.internalTrack.fragmentPositionCache[m]:null,p=Math.max(u?.moofOffset??0,d?.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 S=a.trackData.get(this.internalTrack.id);if(S&&S.startTimestamp>o)break}let x=s.reader.requestSliceRange(h,Ot,fr);if(x instanceof Promise&&(x=await x),!x)break;let y=h,v=Ke(x);if(!v)break;if(v.name==="moof"){a=await s.readFragment(y);let{sampleIndex:S,correctSampleFound:C}=t(a);if(C)return this.fetchPacketInFragment(a,S,i);S!==-1&&(c=a,l=S)}h=y+v.totalSize}if(u&&(!c||c.moofOffset<u.moofOffset)){let x=this.internalTrack.fragmentLookupTable[f-1];g(!x||x.timestamp<u.timestamp);let y=x?.timestamp??-1/0;return this.performFragmentedLookup(null,t,y,o,i)}return c?this.fetchPacketInFragment(c,l,i):null}},ws=class extends xo{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&&co(e.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&lo(e.data)}return{codec:no(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}},Cs=class extends xo{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:oo(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},ks=(r,e)=>{if(r.presentationTimestamps){let t=W(r.presentationTimestamps,e,n=>n.presentationTimestamp);return t===-1?-1:r.presentationTimestamps[t].sampleIndex}else{let t=W(r.sampleTimingEntries,e,o=>o.startDecodeTimestamp);if(t===-1)return-1;let n=r.sampleTimingEntries[t];return n.startIndex+Math.min(Math.floor((e-n.startDecodeTimestamp)/n.delta),n.count-1)}},bp=(r,e)=>{if(!r.keySampleIndices)return ks(r,e);if(r.presentationTimestamps){let t=W(r.presentationTimestamps,e,n=>n.presentationTimestamp);if(t===-1)return-1;for(let n=t;n>=0;n--){let o=r.presentationTimestamps[n].sampleIndex;if(Tt(r.keySampleIndices,o,s=>s)!==-1)return o}return-1}else{let t=ks(r,e),n=W(r.keySampleIndices,t,o=>o);return r.keySampleIndices[n]??-1}},Sp=(r,e)=>{let t=W(r.sampleTimingEntries,e,y=>y.startIndex),n=r.sampleTimingEntries[t];if(!n||n.startIndex+n.count<=e)return null;let i=n.startDecodeTimestamp+(e-n.startIndex)*n.delta,s=W(r.sampleCompositionTimeOffsets,e,y=>y.startIndex),a=r.sampleCompositionTimeOffsets[s];a&&e-a.startIndex<a.count&&(i+=a.offset);let c=r.sampleSizes[Math.min(e,r.sampleSizes.length-1)],l=W(r.sampleToChunk,e,y=>y.startSampleIndex),f=r.sampleToChunk[l];g(f);let u=f.startChunkIndex+Math.floor((e-f.startSampleIndex)/f.samplesPerChunk),m=r.chunkOffsets[u],d=f.startSampleIndex+(u-f.startChunkIndex)*f.samplesPerChunk,p=0,h=m;if(r.sampleSizes.length===1)h+=c*(e-d),p+=c*f.samplesPerChunk;else for(let y=d;y<d+f.samplesPerChunk;y++){let v=r.sampleSizes[y];y<e&&(h+=v),p+=v}let x=n.delta;if(r.presentationTimestamps){let y=r.presentationTimestampIndexMap[e];g(y!==void 0),y<r.presentationTimestamps.length-1&&(x=r.presentationTimestamps[y+1].presentationTimestamp-i)}return{presentationTimestamp:i,duration:x,sampleOffset:h,sampleSize:c,chunkOffset:m,chunkSize:p,isKeyFrame:r.keySampleIndices?Tt(r.keySampleIndices,e,y=>y)!==-1:!0}},Tp=(r,e)=>{if(!r.keySampleIndices)return e+1;let t=W(r.keySampleIndices,e,n=>n);return r.keySampleIndices[t+1]??-1},Ts=(r,e)=>{r.startTimestamp+=e,r.endTimestamp+=e;for(let t of r.samples)t.presentationTimestamp+=e;for(let t of r.presentationTimestamps)t.presentationTimestamp+=e},wp=r=>{let[e,,,t]=r,n=Math.hypot(e,t),o=e/n,i=t/n,s=-Math.atan2(i,o)*(180/Math.PI);return Number.isFinite(s)?s:0},Pc=r=>r.sampleSizes.length===0;var w;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Duration=17545]="Duration",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.MuxingApp=19840]="MuxingApp",r[r.WritingApp=22337]="WritingApp",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.TrackNumber=215]="TrackNumber",r[r.TrackUID=29637]="TrackUID",r[r.TrackType=131]="TrackType",r[r.FlagEnabled=185]="FlagEnabled",r[r.FlagDefault=136]="FlagDefault",r[r.FlagForced=21930]="FlagForced",r[r.FlagOriginal=21934]="FlagOriginal",r[r.FlagHearingImpaired=21931]="FlagHearingImpaired",r[r.FlagVisualImpaired=21932]="FlagVisualImpaired",r[r.FlagCommentary=21935]="FlagCommentary",r[r.FlagLacing=156]="FlagLacing",r[r.Name=21358]="Name",r[r.Language=2274716]="Language",r[r.LanguageBCP47=2274717]="LanguageBCP47",r[r.CodecID=134]="CodecID",r[r.CodecPrivate=25506]="CodecPrivate",r[r.CodecDelay=22186]="CodecDelay",r[r.SeekPreRoll=22203]="SeekPreRoll",r[r.DefaultDuration=2352003]="DefaultDuration",r[r.Video=224]="Video",r[r.PixelWidth=176]="PixelWidth",r[r.PixelHeight=186]="PixelHeight",r[r.AlphaMode=21440]="AlphaMode",r[r.Audio=225]="Audio",r[r.SamplingFrequency=181]="SamplingFrequency",r[r.Channels=159]="Channels",r[r.BitDepth=25188]="BitDepth",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.Block=161]="Block",r[r.BlockAdditions=30113]="BlockAdditions",r[r.BlockMore=166]="BlockMore",r[r.BlockAdditional=165]="BlockAdditional",r[r.BlockAddID=238]="BlockAddID",r[r.BlockDuration=155]="BlockDuration",r[r.ReferenceBlock=251]="ReferenceBlock",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.Colour=21936]="Colour",r[r.MatrixCoefficients=21937]="MatrixCoefficients",r[r.TransferCharacteristics=21946]="TransferCharacteristics",r[r.Primaries=21947]="Primaries",r[r.Range=21945]="Range",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPoseRoll=30325]="ProjectionPoseRoll",r[r.Attachments=423732329]="Attachments",r[r.AttachedFile=24999]="AttachedFile",r[r.FileDescription=18046]="FileDescription",r[r.FileName=18030]="FileName",r[r.FileMediaType=18016]="FileMediaType",r[r.FileData=18012]="FileData",r[r.FileUID=18094]="FileUID",r[r.Chapters=272869232]="Chapters",r[r.Tags=307544935]="Tags",r[r.Tag=29555]="Tag",r[r.Targets=25536]="Targets",r[r.TargetTypeValue=26826]="TargetTypeValue",r[r.TargetType=25546]="TargetType",r[r.TagTrackUID=25541]="TagTrackUID",r[r.TagEditionUID=25545]="TagEditionUID",r[r.TagChapterUID=25540]="TagChapterUID",r[r.TagAttachmentUID=25542]="TagAttachmentUID",r[r.SimpleTag=26568]="SimpleTag",r[r.TagName=17827]="TagName",r[r.TagLanguage=17530]="TagLanguage",r[r.TagString=17543]="TagString",r[r.TagBinary=17541]="TagBinary",r[r.ContentEncodings=28032]="ContentEncodings",r[r.ContentEncoding=25152]="ContentEncoding",r[r.ContentEncodingOrder=20529]="ContentEncodingOrder",r[r.ContentEncodingScope=20530]="ContentEncodingScope",r[r.ContentCompression=20532]="ContentCompression",r[r.ContentCompAlgo=16980]="ContentCompAlgo",r[r.ContentCompSettings=16981]="ContentCompSettings",r[r.ContentEncryption=20533]="ContentEncryption"})(w||(w={}));var Cp=[w.EBML,w.Segment],mr=[w.SeekHead,w.Info,w.Cluster,w.Tracks,w.Cues,w.Attachments,w.Chapters,w.Tags],fn=[...Cp,...mr];var Ps=8,Te=2,Ie=2*Ps,_s=r=>{let e=R(r);if(r.skip(-1),e===0)return null;let t=1,n=128;for(;(e&n)===0;)t++,n>>=1;return t},dr=r=>{let e=R(r);if(e===0)return null;let t=1,n=128;for(;(e&n)===0;)t++,n>>=1;let o=e&n-1;for(let i=1;i<t;i++)o*=256,o+=R(r);return o},q=(r,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let n=0;n<e;n++)t*=256,t+=R(r);return t},Ic=(r,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let t=0n;for(let n=0;n<e;n++)t<<=8n,t+=BigInt(R(r));return t};var yo=r=>{let e=_s(r);return e===null?null:q(r,e)},Is=r=>{let e=R(r);return e===255?e=null:(r.skip(-1),e=dr(r),e===72057594037927940&&(e=null)),e},Ae=r=>{let e=yo(r);if(e===null)return null;let t=Is(r);return{id:e,size:t}},dt=(r,e)=>{let t=B(r,e),n=0;for(;n<e&&t[n]!==0;)n+=1;return String.fromCharCode(...t.subarray(0,n))},pr=(r,e)=>{let t=B(r,e),n=0;for(;n<e&&t[n]!==0;)n+=1;return ce.decode(t.subarray(0,n))},bo=(r,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?Ac(r):vo(r)},So=async(r,e,t,n)=>{let o=new Set(t),i=e;for(;n===null||i<n;){let s=r.requestSliceRange(i,Te,Ie);if(s instanceof Promise&&(s=await s),!s)break;let a=Ae(s);if(!a)break;if(o.has(a.id))return{pos:i,found:!0};$e(a.size),i=s.filePos+a.size}return{pos:n!==null&&n>i?n:i,found:!1}},As=async(r,e,t,n)=>{let i=new Set(t),s=e;for(;s<n;){let a=r.requestSliceRange(s,0,Math.min(65536,n-s));if(a instanceof Promise&&(a=await a),!a||a.length<Ps)break;for(let c=0;c<a.length-Ps;c++){a.filePos=s;let l=yo(a);if(l!==null&&i.has(l))return s;s++}}return null},Fe={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 $e(r){if(r===null)throw new Error("Undefined element size is used in a place where it is not supported.")}var Fc=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isWebM?"webm":"x-matroska");if(r.codecStrings.length>0){let n=[...new Set(r.codecStrings.filter(Boolean))];t+=`; codecs="${n.join(", ")}"`}return t};var Qe;(function(r){r[r.None=0]="None",r[r.Xiph=1]="Xiph",r[r.FixedSize=2]="FixedSize",r[r.Ebml=3]="Ebml"})(Qe||(Qe={}));var To;(function(r){r[r.Block=1]="Block",r[r.Private=2]="Private",r[r.Next=4]="Next"})(To||(To={}));var mn;(function(r){r[r.Zlib=0]="Zlib",r[r.Bzlib=1]="Bzlib",r[r.lzo1x=2]="lzo1x",r[r.HeaderStripping=3]="HeaderStripping"})(mn||(mn={}));var Fs=[{id:w.SeekHead,flag:"seekHeadSeen"},{id:w.Info,flag:"infoSeen"},{id:w.Tracks,flag:"tracksSeen"},{id:w.Cues,flag:"cuesSeen"}],Ec=10*2**20,wo=class extends me{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(t=>t.inputTrack))}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),t=await Promise.all(e.map(n=>n.getCodecParameterString()));return Fc({isWebM:this.isWebM,hasVideo:this.segments.some(n=>n.tracks.some(o=>o.info?.type==="video")),hasAudio:this.segments.some(n=>n.tracks.some(o=>o.info?.type==="audio")),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let t of this.segments)t.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(let t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,Te,Ie);if(t instanceof Promise&&(t=await t),!t)break;let n=Ae(t);if(!n)break;let o=n.id,i=n.size,s=t.filePos;if(o===w.EBML){$e(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 So(this.reader,s,fn,this.reader.fileSize)).pos-s);let a=de(this.segments);a&&(a.elementEndPos=s+i)}$e(i),e=s+i}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===null?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let a=this.reader.requestSliceRange(n,Te,Ie);if(a instanceof Promise&&(a=await a),!a)break;let c=n,l=Ae(a);if(!l||!mr.includes(l.id)&&l.id!==w.Void){let p=await As(this.reader,c,mr,Math.min(this.currentSegment.elementEndPos??1/0,c+Ec));if(p){n=p;continue}else break}let{id:f,size:u}=l,m=a.filePos,d=Fs.findIndex(p=>p.id===f);if(d!==-1){let p=Fs[d].flag;this.currentSegment[p]=!0,$e(u);let h=this.reader.requestSlice(m,u);h instanceof Promise&&(h=await h),h&&this.readContiguousElements(h)}else if(f===w.Tags||f===w.Attachments){f===w.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,$e(u);let p=this.reader.requestSlice(m,u);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(f===w.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(u===null)break;n=m+u}if(this.currentSegment.seekEntries.sort((a,c)=>a.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(let a of this.currentSegment.seekEntries){let c=Fs.find(p=>p.id===a.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+a.segmentPosition,Te,Ie);if(l instanceof Promise&&(l=await l),!l)continue;let f=Ae(l);if(!f)continue;let{id:u,size:m}=f;if(u!==c.id)continue;$e(m),this.currentSegment[c.flag]=!0;let d=this.reader.requestSlice(l.filePos,m);d instanceof Promise&&(d=await d),d&&this.readContiguousElements(d)}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],f=a.cuePoints[c+1];l.time===f.time&&(a.cuePoints.splice(c+1,1),c--)}}let i=null,s=-1/0;for(let a of this.currentSegment.tracks)a.cuePoints.length>s&&(s=a.cuePoints.length,i=a);for(let a of this.currentSegment.tracks)a.cuePoints.length===0&&(a.cuePoints=i.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let n=this.reader.requestSliceRange(e,Te,Ie);n instanceof Promise&&(n=await n),g(n);let o=e,i=Ae(n);g(i);let s=i.id;g(s===w.Cluster);let a=i.size,c=n.filePos;a===null&&(a=(await So(this.reader,c,fn,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,a);l instanceof Promise&&(l=await l);let f={segment:t,elementStartPos:o,elementEndPos:c+a,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=f,l){let u=this.readContiguousElements(l,fn);f.elementEndPos=u}for(let[,u]of f.trackData){let m=u.track;g(u.blocks.length>0);let d=!1;for(let y=0;y<u.blocks.length;y++){let v=u.blocks[y];v.timestamp+=f.timestamp,d||=v.lacing!==Qe.None}u.presentationTimestamps=u.blocks.map((y,v)=>({timestamp:y.timestamp,blockIndex:v})).sort((y,v)=>y.timestamp-v.timestamp);for(let y=0;y<u.presentationTimestamps.length;y++){let v=u.presentationTimestamps[y],S=u.blocks[v.blockIndex];if(u.firstKeyFrameTimestamp===null&&S.isKeyFrame&&(u.firstKeyFrameTimestamp=S.timestamp),y<u.presentationTimestamps.length-1){let C=u.presentationTimestamps[y+1];S.duration=C.timestamp-S.timestamp}else S.duration===0&&m.defaultDuration!=null&&S.lacing===Qe.None&&(S.duration=m.defaultDuration)}d&&(this.expandLacedBlocks(u.blocks,m),u.presentationTimestamps=u.blocks.map((y,v)=>({timestamp:y.timestamp,blockIndex:v})).sort((y,v)=>y.timestamp-v.timestamp));let p=u.blocks[u.presentationTimestamps[0].blockIndex],h=u.blocks[de(u.presentationTimestamps).blockIndex];u.startTimestamp=p.timestamp,u.endTimestamp=h.timestamp+h.duration;let x=W(m.clusterPositionCache,u.startTimestamp,y=>y.startTimestamp);(x===-1||m.clusterPositionCache[x].elementStartPos!==o)&&m.clusterPositionCache.splice(x+1,0,{elementStartPos:f.elementStartPos,startTimestamp:u.startTimestamp})}return t.lastReadCluster=f,f}getTrackDataInCluster(e,t){let n=e.trackData.get(t);if(!n){let o=e.segment.tracks.find(i=>i.id===t);if(!o)return null;n={track:o,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,n)}return n}expandLacedBlocks(e,t){for(let n=0;n<e.length;n++){let o=e[n];if(o.lacing===Qe.None)continue;o.decoded||(o.data=this.decodeBlockData(t,o.data),o.decoded=!0);let i=hr.tempFromBytes(o.data),s=[],a=R(i)+1;switch(o.lacing){case Qe.Xiph:{let l=0;for(let f=0;f<a-1;f++){let u=0;for(;i.bufferPos<i.length;){let m=R(i);if(u+=m,m<255){s.push(u),l+=u;break}}}s.push(i.length-(i.bufferPos+l))}break;case Qe.FixedSize:{let l=i.length-1,f=Math.floor(l/a);for(let u=0;u<a;u++)s.push(f)}break;case Qe.Ebml:{let l=dr(i);g(l!==null);let f=l;s.push(f);let u=f;for(let m=1;m<a-1;m++){let d=i.bufferPos,p=dr(i);g(p!==null);let h=p,y=(1<<(i.bufferPos-d)*7-1)-1,v=h-y;f+=v,s.push(f),u+=f}s.push(i.length-(i.bufferPos+u))}break;default:g(!1)}g(s.length===a),e.splice(n,1);let c=o.duration||a*(t.defaultDuration??0);for(let l=0;l<a;l++){let f=s[l],u=B(i,f),m=o.timestamp+c*l/a,d=c/a;e.splice(n+l,0,{timestamp:m,duration:d,isKeyFrame:o.isKeyFrame,data:u,lacing:Qe.None,decoded:!0,mainAdditional:o.mainAdditional})}n+=a,n--}}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 n=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,Te,Ie);if(n instanceof Promise&&(n=await n),!n)continue;let o=Ae(n);if(!o||o.id!==t.id)continue;let{size:i}=o;$e(i),g(!this.currentSegment),this.currentSegment=e;let s=this.reader.requestSlice(n.filePos,i);s instanceof Promise&&(s=await s),s&&this.readContiguousElements(s),this.currentSegment=null,t.id===w.Tags?e.tagsSeen=!0:t.id===w.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){let n=e.filePos;for(;e.filePos-n<=e.length-Te;){let o=e.filePos;if(!this.traverseElement(e,t))return o}return e.filePos}traverseElement(e,t){let n=Ae(e);if(!n||t&&t.includes(n.id))return!1;let{id:o,size:i}=n,s=e.filePos;switch($e(i),o){case w.DocType:this.isWebM=dt(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=q(e,i)}break;case w.SeekPosition:{let a=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!a)break;a.segmentPosition=q(e,i)}break;case w.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=q(e,i),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case w.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=bo(e,i)}break;case w.TrackEntry:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...xe},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:le,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(s,i)),this.currentTrack.decodingInstructions.some(a=>a.data?.type!=="decompress"||a.scope!==To.Block||a.data.algorithm!==mn.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===Fe.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Fe.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Fe.vp8?this.currentTrack.info.codec="vp8":c===Fe.vp9?this.currentTrack.info.codec="vp9":c===Fe.av1&&(this.currentTrack.info.codec="av1");let l=this.currentTrack,f=new Ne(this.input,new Es(l));this.currentTrack.inputTrack=f,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){c===Fe.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===Fe.mp3?this.currentTrack.info.codec="mp3":c===Fe.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=It):c===Fe.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Fe.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,f=new se(this.input,new zs(l));this.currentTrack.inputTrack=f,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case w.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=q(e,i)}break;case w.TrackType:{if(!this.currentTrack)break;let a=q(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;q(e,i)||(this.currentSegment.tracks.pop(),this.currentTrack=null)}break;case w.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!q(e,i)}break;case w.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!q(e,i)}break;case w.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!q(e,i)}break;case w.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!q(e,i)}break;case w.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!q(e,i)}break;case w.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!q(e,i)}break;case w.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=dt(e,i)}break;case w.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=B(e,i)}break;case w.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*q(e,i)/1e9}break;case w.Name:{if(!this.currentTrack)break;this.currentTrack.name=pr(e,i)}break;case w.Language:{if(!this.currentTrack||this.currentTrack.languageCode!==le)break;this.currentTrack.languageCode=dt(e,i),Jn(this.currentTrack.languageCode)||(this.currentTrack.languageCode=le)}break;case w.LanguageBCP47:{if(!this.currentTrack)break;let c=dt(e,i).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=le}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=q(e,i)}break;case w.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=q(e,i)}break;case w.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=q(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=q(e,i),c=$n[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=q(e,i)===2}break;case w.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=q(e,i),c=Yn[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=q(e,i),c=Kn[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=-bo(e,i);try{this.currentTrack.info.rotation=Xn(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=bo(e,i)}break;case w.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=q(e,i)}break;case w.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=q(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=q(e,i);break;case w.CueTrackPositions:{if(this.currentCueTime===null)break;g(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=q(e,i)}break;case w.CueClusterPosition:{let a=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!a)break;g(this.currentSegment),a.clusterPosition=this.currentSegment.dataStartPos+q(e,i)}break;case w.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=q(e,i)}break;case w.SimpleBlock:{if(!this.currentCluster)break;let a=dr(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let l=un(e),f=R(e),u=f>>1&3,m=!!(f&128);c.track.info?.type==="audio"&&c.track.info.codec&&(m=!0);let d=B(e,i-(e.filePos-s)),p=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:m,data:d,lacing:u,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=dr(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let l=un(e),u=R(e)>>1&3,m=B(e,i-(e.filePos-s)),d=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:m,lacing:u,decoded:!d,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=B(e,i)}break;case w.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=q(e,i)}break;case w.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=q(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:q(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=pr(e,i);break;case w.TagString:{if(!this.currentSimpleTagName)break;let a=pr(e,i);this.processTagValue(this.currentSimpleTagName,a)}break;case w.TagBinary:{if(!this.currentSimpleTagName)break;let a=B(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 ro(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 f=c.toLowerCase();f.startsWith("cover.")?l="coverFront":f.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=Ic(e,i)}break;case w.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=pr(e,i)}break;case w.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=dt(e,i)}break;case w.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=B(e,i)}break;case w.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=pr(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:To.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=q(e,i)}break;case w.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=q(e,i)}break;case w.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:mn.Zlib,settings:null},this.readContiguousElements(e.slice(s,i))}break;case w.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=q(e,i)}break;case w.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=B(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){g(e.decodingInstructions.length>0);let n=t;for(let o of e.decodingInstructions)switch(g(o.data),o.data.type){case"decompress":switch(o.data.algorithm){case mn.HeaderStripping:if(o.data.settings&&o.data.settings.length>0){let i=o.data.settings,s=new Uint8Array(i.length+n.length);s.set(i,0),s.set(n,i.length),n=s}break;default:}break;default:}return n}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=t,typeof t=="string")switch(e.toLowerCase()){case"title":n.title??=t;break;case"description":n.description??=t;break;case"artist":n.artist??=t;break;case"album":n.album??=t;break;case"album_artist":n.albumArtist??=t;break;case"genre":n.genre??=t;break;case"comment":n.comment??=t;break;case"lyrics":n.lyrics??=t;break;case"date":{let o=new Date(t);Number.isNaN(o.getTime())||(n.date??=o)}break;case"track_number":case"part_number":{let o=t.split("/"),i=Number.parseInt(o[0],10),s=o[1]&&Number.parseInt(o[1],10);Number.isInteger(i)&&i>0&&(n.trackNumber??=i),s&&Number.isInteger(s)&&s>0&&(n.tracksTotal??=s)}break;case"disc_number":case"disc":{let o=t.split("/"),i=Number.parseInt(o[0],10),s=o[1]&&Number.parseInt(o[1],10);Number.isInteger(i)&&i>0&&(n.discNumber??=i),s&&Number.isInteger(s)&&s>0&&(n.discsTotal??=s)}break}}},Co=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 kt(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,o=>{let i=o.trackData.get(this.internalTrack.id);if(!i)return{blockIndex:-1,correctBlockFound:!1};let s=W(i.presentationTimestamps,n,l=>l.timestamp),a=s!==-1?i.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&n<i.endTimestamp;return{blockIndex:a,correctBlockFound:c}},n,n,t)}async getNextPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,o=>{if(o===n.cluster){let i=o.trackData.get(this.internalTrack.id);if(n.blockIndex+1<i.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(o.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,o=>{let i=o.trackData.get(this.internalTrack.id);if(!i)return{blockIndex:-1,correctBlockFound:!1};let s=Zn(i.presentationTimestamps,l=>i.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=n),a=s!==-1?i.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&n<i.endTimestamp;return{blockIndex:a,correctBlockFound:c}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,o=>{if(o===n.cluster){let s=o.trackData.get(this.internalTrack.id).blocks.findIndex((a,c)=>a.isKeyFrame&&c>n.blockIndex);if(s!==-1)return{blockIndex:s,correctBlockFound:!0}}else{let i=o.trackData.get(this.internalTrack.id);if(i&&i.firstKeyFrameTimestamp!==null){let s=i.blocks.findIndex(a=>a.isKeyFrame);return g(s!==-1),{blockIndex:s,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,n){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).blocks[t];g(i),i.decoded||(i.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,i.data),i.decoded=!0);let s=n.metadataOnly?oe:i.data,a=i.timestamp/this.internalTrack.segment.timestampFactor,c=i.duration/this.internalTrack.segment.timestampFactor,l={};i.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=n.metadataOnly?oe:i.mainAdditional,l.alphaByteLength=i.mainAdditional.byteLength);let f=new Z(s,i.isKeyFrame?"key":"delta",a,c,e.dataStartPos+t,i.data.byteLength,l);return this.packetToClusterLocation.set(f,{cluster:e,blockIndex:t}),f}async performClusterLookup(e,t,n,o,i){let{demuxer:s,segment:a}=this.internalTrack,c=null,l=null,f=-1;if(e){let{blockIndex:y,correctBlockFound:v}=t(e);if(v)return this.fetchPacketInCluster(e,y,i);y!==-1&&(l=e,f=y)}let u=W(this.internalTrack.cuePoints,n,y=>y.time),m=u!==-1?this.internalTrack.cuePoints[u]:null,d=W(this.internalTrack.clusterPositionCache,n,y=>y.startTimestamp),p=d!==-1?this.internalTrack.clusterPositionCache[d]:null,h=Math.max(m?.clusterPosition??0,p?.elementStartPos??0)||null,x;for(e?h===null||e.elementStartPos>=h?(x=e.elementEndPos,c=e):x=h:x=h??a.clusterSeekStartPos;a.elementEndPos===null||x<=a.elementEndPos-Te;){if(c){let I=c.trackData.get(this.internalTrack.id);if(I&&I.startTimestamp>o)break}let y=s.reader.requestSliceRange(x,Te,Ie);if(y instanceof Promise&&(y=await y),!y)break;let v=x,S=Ae(y);if(!S||!mr.includes(S.id)&&S.id!==w.Void){let I=await As(s.reader,v,mr,Math.min(a.elementEndPos??1/0,v+Ec));if(I){x=I;continue}else break}let C=S.id,_=S.size,T=y.filePos;if(C===w.Cluster){c=await s.readCluster(v,a),_=c.elementEndPos-T;let{blockIndex:I,correctBlockFound:M}=t(c);if(M)return this.fetchPacketInCluster(c,I,i);I!==-1&&(l=c,f=I)}_===null&&(g(C!==w.Cluster),_=(await So(s.reader,T,fn,a.elementEndPos)).pos-T);let E=T+_;if(a.elementEndPos===null){let I=s.reader.requestSliceRange(E,Te,Ie);if(I instanceof Promise&&(I=await I),!I)break;if(yo(I)===w.Segment){a.elementEndPos=E;break}}x=E}if(m&&(!l||l.elementStartPos<m.clusterPosition)){let y=this.internalTrack.cuePoints[u-1];g(!y||y.time<m.time);let v=y?.time??-1/0;return this.performClusterLookup(null,t,v,o,i)}return l?this.fetchPacketInCluster(l,f,i):null}},Es=class extends Co{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:no({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?cc(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?uc(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?co(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?lo(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}},zs=class extends Co{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:oo({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 kp=[44100,48e3,32e3],Pp=[-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],zc=1483304551,Dc=1231971951,_p=(r,e,t,n,o)=>e===0?0:e===1?Math.floor(144*t/(n<<r))+o:e===2?Math.floor(144*t/n)+o:(Math.floor(12*t/n)+o)*4,Oc=(r,e)=>r===3?e===3?21:36:e===3?13:21,Rc=(r,e)=>{let t=r>>>24,n=r>>>16&255,o=r>>>8&255,i=r&255;if(t!==255&&n!==255&&o!==255&&i!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((n&224)!==224)return{header:null,bytesAdvanced:1};let s=0,a=0;n&16?s=n&8?0:1:(s=1,a=1);let c=n>>3&3,l=n>>1&3,f=o>>4&15,u=(o>>2&3)%3,m=o>>1&1,d=i>>6&3,p=i>>4&3,h=i>>3&1,x=i>>2&1,y=i&3,v=Pp[s*16*4+l*16+f];if(v===-1)return{header:null,bytesAdvanced:1};let S=v*1e3,C=kp[u]>>s+a,_=_p(s,l,S,C,m);if(e!==null&&e<_)return{header:null,bytesAdvanced:1};let T;return c===3?T=l===3?384:1152:l===3?T=384:l===2?T=1152:T=576,{header:{totalSize:_,mpegVersionId:c,layer:l,bitrate:S,frequencyIndex:u,sampleRate:C,channel:d,modeExtension:p,copyright:h,original:x,emphasis:y,audioSamplesInFrame:T},bytesAdvanced:1}};var ko=r=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=r&e,e>>=8;return t};var xr;(function(r){r[r.Unsynchronisation=128]="Unsynchronisation",r[r.ExtendedHeader=64]="ExtendedHeader",r[r.ExperimentalIndicator=32]="ExperimentalIndicator",r[r.Footer=16]="Footer"})(xr||(xr={}));var vr;(function(r){r[r.ISO_8859_1=0]="ISO_8859_1",r[r.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",r[r.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",r[r.UTF_8=3]="UTF_8"})(vr||(vr={}));var dn=128,br=10,yr=["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"],Mc=(r,e)=>{let t=r.filePos;e.raw??={},e.raw.TAG??=B(r,dn-3),r.filePos=t;let n=gr(r,30);n&&(e.title??=n);let o=gr(r,30);o&&(e.artist??=o);let i=gr(r,30);i&&(e.album??=i);let s=gr(r,4),a=Number.parseInt(s,10);Number.isInteger(a)&&a>0&&(e.date??=new Date(a,0,1));let c=B(r,30),l;if(c[28]===0&&c[29]!==0){let u=c[29];u>0&&(e.trackNumber??=u),r.skip(-30),l=gr(r,28),r.skip(2)}else r.skip(-30),l=gr(r,30);l&&(e.comment??=l);let f=R(r);f<yr.length&&(e.genre??=yr[f])},gr=(r,e)=>{let t=B(r,e),n=Pt(t.indexOf(0),t.length),o=t.subarray(0,n),i="";for(let s=0;s<o.length;s++)i+=String.fromCharCode(o[s]);return i.trimEnd()},Rt=r=>{let e=r.filePos,t=J(r,3),n=R(r),o=R(r),i=R(r),s=F(r);if(t!=="ID3"||n===255||o===255||(s&2155905152)!==0)return r.filePos=e,null;let a=ko(s);return{majorVersion:n,revision:o,flags:i,size:a}},Po=(r,e,t)=>{if(![2,3,4].includes(e.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let n=B(r,e.size),o=new Ds(e,n);if(e.flags&xr.Footer&&o.removeFooter(),e.flags&xr.Unsynchronisation&&e.majorVersion===3&&o.ununsynchronizeAll(),e.flags&xr.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,f=!1;if(e.majorVersion===3?(c=!!(i.flags&64),l=!!(i.flags&128)):e.majorVersion===4&&(c=!!(i.flags&4),l=!!(i.flags&8),f=!!(i.flags&2)||!!(e.flags&xr.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(f&&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("/"),d=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(d)&&d>0&&(t.trackNumber??=d),p&&Number.isInteger(p)&&p>0&&(t.tracksTotal??=p)}break;case"TPOS":case"TPA":{let m=o.readId3V2EncodingAndText(a).split("/"),d=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(d)&&d>0&&(t.discNumber??=d),p&&Number.isInteger(p)&&p>0&&(t.discsTotal??=p)}break;case"TCON":case"TCO":{let u=o.readId3V2EncodingAndText(a),m=/^\((\d+)\)/.exec(u);if(m){let d=Number.parseInt(m[1]);if(yr[d]!==void 0){t.genre??=yr[d];break}}if(m=/^\d+$/.exec(u),m){let d=Number.parseInt(m[0]);if(yr[d]!==void 0){t.genre??=yr[d];break}}t.genre??=u}break;case"TDRC":case"TDAT":{let u=o.readId3V2EncodingAndText(a),m=new Date(u);Number.isNaN(m.getTime())||(t.date??=m)}break;case"TYER":case"TYE":{let u=o.readId3V2EncodingAndText(a),m=Number.parseInt(u,10);Number.isInteger(m)&&(t.date??=new Date(m,0,1))}break;case"USLT":case"ULT":{let u=o.readU8();o.pos+=3,o.readId3V2Text(u,a),t.lyrics??=o.readId3V2Text(u,a)}break;case"COMM":case"COM":{let u=o.readU8();o.pos+=3,o.readId3V2Text(u,a),t.comment??=o.readId3V2Text(u,a)}break;case"APIC":case"PIC":{let u=o.readId3V2TextEncoding(),m;if(e.majorVersion===2){let x=o.readAscii(3);m=x==="PNG"?"image/png":x==="JPG"?"image/jpeg":"image/*"}else m=o.readId3V2Text(u,a);let d=o.readU8(),p=o.readId3V2Text(u,a).trimEnd(),h=a-o.pos;if(h>=0){let x=o.readBytes(h);t.images||(t.images=[]),t.images.push({data:x,mimeType:m,kind:d===3?"coverFront":d===4?"coverBack":"unknown",description:p})}}break;default:o.pos+=i.size;break}o.pos=a}},Ds=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t<this.bytes.length;t++){let n=this.bytes[t];e.push(n),n===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let n=[];for(let s=e;s<t;s++){let a=this.bytes[s];n.push(a),a===255&&s!==t-1&&this.bytes[s+1]===0&&s++}let o=this.bytes.subarray(0,e),i=this.bytes.subarray(t);this.bytes=new Uint8Array(o.length+n.length+i.length),this.bytes.set(o,0),this.bytes.set(n,o.length),this.bytes.set(i,o.length+n.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-br),this.view=new DataView(this.bytes.buffer)}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+1);return this.pos+=3,e*256+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let n=0;n<e;n++)t+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);if(e==="\0\0\0")return null;let t=this.readU24();return{id:e,size:t,flags:0}}else{let e=this.readAscii(4);if(e==="\0\0\0\0")return null;let t=this.readU32(),n=this.header.majorVersion===4?ko(t):t,o=this.readU16(),i=this.pos,s=a=>{let c=this.pos+a;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=a;let l=this.readAscii(4);if(l!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(l))return!1}return!0};if(!s(n)){let a=this.header.majorVersion===4?t:ko(t);s(a)&&(n=a)}return this.pos=i,{id:e,size:n,flags:o}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let n=this.pos,o=this.readBytes(t-this.pos);switch(e){case vr.ISO_8859_1:{let i="";for(let s=0;s<o.length;s++){let a=o[s];if(a===0){this.pos=n+s+1;break}i+=String.fromCharCode(a)}return i}case vr.UTF_16_WITH_BOM:if(o[0]===255&&o[1]===254){let i=new TextDecoder("utf-16le"),s=Pt(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=n+Math.min(s+2,o.length),i.decode(o.subarray(2,s))}else if(o[0]===254&&o[1]===255){let i=new TextDecoder("utf-16be"),s=Pt(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=n+Math.min(s+2,o.length),i.decode(o.subarray(2,s))}else{let i=Pt(o.findIndex(s=>s===0),o.length);return this.pos=n+Math.min(i+1,o.length),ce.decode(o.subarray(0,i))}case vr.UTF_16_BE_NO_BOM:{let i=new TextDecoder("utf-16be"),s=Pt(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=n+Math.min(s+2,o.length),i.decode(o.subarray(0,s))}case vr.UTF_8:{let i=Pt(o.findIndex(s=>s===0),o.length);return this.pos=n+Math.min(i+1,o.length),ce.decode(o.subarray(0,i))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}};var pn=async(r,e,t)=>{let n=e;for(;t===null||n<t;){let o=r.requestSlice(n,4);if(o instanceof Promise&&(o=await o),!o)break;let i=F(o),s=Rc(i,r.fileSize!==null?r.fileSize-n:null);if(s.header)return{header:s.header,startPos:n};n+=s.bytesAdvanced}return null};var _o=class extends me{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new Me,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 se(this.input,new Os(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,br);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}let c=Rt(a);if(!c)break;this.lastLoadedPos=a.filePos+c.size}let e=await pn(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let n=Oc(t.mpegVersionId,t.channel),o=this.reader.requestSlice(e.startPos+n,4);if(o instanceof Promise&&(o=await o),o){let a=F(o);if(a===zc||a===Dc)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 g(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0,n=!1;for(;;){let o=this.reader.requestSlice(t,br);if(o instanceof Promise&&(o=await o),!o)break;let i=Rt(o);if(!i)break;n=!0;let s=this.reader.requestSlice(o.filePos,i.size);if(s instanceof Promise&&(s=await s),!s)break;Po(s,i,this.metadataTags),t=o.filePos+i.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=dn){let o=this.reader.requestSlice(this.reader.fileSize-dn,dn);o instanceof Promise&&(o=await o),g(o),J(o,3)==="TAG"&&Mc(o,this.metadataTags)}return this.metadataTags}finally{e()}}},Os=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return g(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 le}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return g(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return g(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...xe}}async getDecoderConfig(){return g(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let o;if(t.metadataOnly)o=oe;else{let i=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(i instanceof Promise&&(i=await i),!i)return null;o=B(i,n.dataSize)}return new Z(o,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let o=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{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let o=W(this.demuxer.loadedSamples,e,i=>i.timestamp);if(o===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(o,t);if(o>=0&&o+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(o,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Rs=1399285583,Ip=79764919,Uc=new Uint32Array(256);for(let r=0;r<256;r++){let e=r<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^Ip:e<<1;Uc[r]=e>>>0&4294967295}var Nc=r=>{let e=j(r),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let n=0;for(let o=0;o<r.length;o++){let i=r[o];n=(n<<8^Uc[n>>>24^i])>>>0}return e.setUint32(22,t,!0),n},Lc=(r,e,t)=>{let n=0,o=null;if(r.length>0)if(e.codec==="vorbis"){g(e.vorbisInfo);let i=e.vorbisInfo.modeBlockflags.length,a=(1<<Ja(i-1))-1<<1,c=(r[0]&a)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=t,f=e.vorbisInfo.modeBlockflags[c];if(o=e.vorbisInfo.blocksizes[f],f===1){let u=(a|1)+1,m=r[0]&u?1:0;l=e.vorbisInfo.blocksizes[m]}n=l!==null?l+o>>2:0}else e.codec==="opus"&&(n=dc(r).durationInSamples);return{durationInSamples:n,vorbisBlockSize:o}},Vc=r=>{let e="audio/ogg";if(r.codecStrings){let t=[...new Set(r.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};var pt=27,Bt=282,Gc=Bt+65025,Sr=r=>{let e=r.filePos;if(Mt(r)!==Rs)return null;r.skip(1);let n=R(r),o=Hc(r),i=Mt(r),s=Mt(r),a=Mt(r),c=R(r),l=new Uint8Array(c);for(let d=0;d<c;d++)l[d]=R(r);let f=27+c,u=l.reduce((d,p)=>d+p,0),m=f+u;return{headerStartPos:e,totalSize:m,dataStartPos:e+f,dataSize:u,headerType:n,granulePosition:o,serialNumber:i,sequenceNumber:s,checksum:a,lacingValues:l}},qc=(r,e)=>{for(;r.filePos<e-3;){let t=Mt(r),n=t&255,o=t>>>8&255,i=t>>>16&255,s=t>>>24&255,a=79;if(!(n!==a&&o!==a&&i!==a&&s!==a)){if(r.skip(-4),t===Rs)return!0;r.skip(1)}}return!1};var Io=class extends me{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,pt,Bt);if(t instanceof Promise&&(t=await t),!t)break;let n=Sr(t);if(!n||!!!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let t of this.bitstreams){let n=await this.readPacket(t.bosPage,0);n&&(n.data.byteLength>=7&&n.data[0]===1&&n.data[1]===118&&n.data[2]===111&&n.data[3]===114&&n.data[4]===98&&n.data[5]===105&&n.data[6]===115?await this.readVorbisMetadata(n,t):n.data.byteLength>=8&&n.data[0]===79&&n.data[1]===112&&n.data[2]===117&&n.data[3]===115&&n.data[4]===72&&n.data[5]===101&&n.data[6]===97&&n.data[7]===100&&await this.readOpusMetadata(n,t),t.codecInfo.codec!==null&&this.tracks.push(new se(this.input,new Ms(t,this))))}})()}async readVorbisMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let o=await this.readPacket(n.startPage,n.startSegmentIndex);if(!o||(n=await this.findNextPacketStart(o),!n))return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i||o.data[0]!==3||i.data[0]!==5)return;let s=[],a=u=>{for(;s.push(Math.min(255,u)),!(u<255);)u-=255};a(e.data.length),a(o.data.length);let c=new Uint8Array(1+s.length+e.data.length+o.data.length+i.data.length);c[0]=2,c.set(s,1),c.set(e.data,1+s.length),c.set(o.data,1+s.length+e.data.length),c.set(i.data,1+s.length+e.data.length+o.data.length),t.codecInfo.codec="vorbis",t.description=c,t.lastMetadataPacket=i;let l=j(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);let f=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(f&15),1<<(f>>4)],modeBlockflags:pc(i.data).modeBlockflags},tn(o.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let o=await this.readPacket(n.startPage,n.startSegmentIndex);if(!o)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=o;let i=mc(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=It,t.codecInfo.opusInfo={preSkip:i.preSkip},tn(o.data.subarray(8),this.metadataTags)}async readPacket(e,t){g(t<e.lacingValues.length);let n=0;for(let u=0;u<t;u++)n+=e.lacingValues[u];let o=e,i=n,s=t,a=[];e:for(;;){let u=this.reader.requestSlice(o.dataStartPos,o.dataSize);u instanceof Promise&&(u=await u),g(u);let m=B(u,o.dataSize);for(;;){if(s===o.lacingValues.length){a.push(m.subarray(n,i));break}let p=o.lacingValues[s];if(i+=p,p<255){a.push(m.subarray(n,i));break e}s++}let d=o.headerStartPos+o.totalSize;for(;;){let p=this.reader.requestSliceRange(d,pt,Bt);if(p instanceof Promise&&(p=await p),!p)return null;let h=Sr(p);if(!h)return null;if(o=h,o.serialNumber===e.serialNumber)break;d=o.headerStartPos+o.totalSize}n=0,i=0,s=0}let c=a.reduce((u,m)=>u+m.length,0),l=new Uint8Array(c),f=0;for(let u=0;u<a.length;u++){let m=a[u];l.set(m,f),f+=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 n=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let o=this.reader.requestSliceRange(n,pt,Bt);if(o instanceof Promise&&(o=await o),!o)return null;let i=Sr(o);if(!i)return null;if(i.serialNumber===e.endPage.serialNumber)return{startPage:i,startSegmentIndex:0};n=i.headerStartPos+i.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(t=>t.getCodecParameterString()));return Vc({codecStrings:e.filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...t)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Ms=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new Me,this.internalSampleRate=e.codecInfo.codec==="opus"?It: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 g(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 le}getDisposition(){return{...xe}}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"?(g(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,n){if(!e)return null;let{durationInSamples:o,vorbisBlockSize:i}=Lc(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Z(n.metadataOnly?oe: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){g(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let n=0;this.bitstream.codecInfo.codec==="opus"&&(g(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let o=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(o,{timestampInSamples:n,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let n=this.encodedPacketToMetadata.get(e);if(!n)throw new Error("Packet was not created from this track.");let o=await this.demuxer.findNextPacketStart(n.packet);if(!o)return null;let i=n.timestampInSamples+n.durationInSamples,s=await this.demuxer.readPacket(o.startPage,o.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:i,vorbisLastBlocksize:n.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let n=kt(e*this.internalSampleRate);if(n===0)return this.getFirstPacket(t);if(n<0)return null;g(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 v=i.headerStartPos,S=Math.floor((v+s)/2),C=S;for(;;){let _=Math.min(C+Gc,s-pt),T=this.demuxer.reader.requestSlice(C,_-C);if(T instanceof Promise&&(T=await T),g(T),!qc(T,_)){s=S+pt;continue e}let I=this.demuxer.reader.requestSliceRange(T.filePos,pt,Bt);I instanceof Promise&&(I=await I),g(I);let M=Sr(I);g(M);let L=!1;if(M.serialNumber===this.bitstream.serialNumber)L=!0;else{let te=this.demuxer.reader.requestSlice(M.headerStartPos,M.totalSize);te instanceof Promise&&(te=await te),g(te);let Ee=B(te,M.totalSize);L=Nc(Ee)===M.checksum}if(!L){C=M.headerStartPos+4;continue}if(L&&M.serialNumber!==this.bitstream.serialNumber){C=M.headerStartPos+M.totalSize;continue}if(M.granulePosition===-1){C=M.headerStartPos+M.totalSize;continue}this.granulePositionToTimestampInSamples(M.granulePosition)>n?s=M.headerStartPos:(i=M,a.push(M));continue e}}let c=o.startPage;for(let v of a){if(v.granulePosition===i.granulePosition)break;(!c||v.headerStartPos>c.headerStartPos)&&(c=v)}let l=c,f=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===i.granulePosition);){let v=l.headerStartPos+l.totalSize,S=this.demuxer.reader.requestSliceRange(v,pt,Bt);S instanceof Promise&&(S=await S),g(S);let C=Sr(S);g(C),l=C,l.serialNumber===this.bitstream.serialNumber&&f.push(l)}g(l.granulePosition!==-1);let u=null,m,d,p=l,h=0;if(l.headerStartPos===o.startPage.headerStartPos)m=this.granulePositionToTimestampInSamples(0),d=!0,u=0;else{m=0,d=!1;for(let C=l.lacingValues.length-1;C>=0;C--)if(l.lacingValues[C]<255){u=C+1;break}if(u===null)throw new Error("Invalid page with granule position: no packets end on this page.");h=u-1;let v={data:oe,endPage:p,endSegmentIndex:h};if(await this.demuxer.findNextPacketStart(v)){let C=jc(f,l,u);g(C);let _=Wc(f,C.page,C.segmentIndex);_&&(l=_.page,u=_.segmentIndex)}else for(;;){let C=jc(f,l,u);if(!C)break;let _=Wc(f,C.page,C.segmentIndex);if(!_)break;if(l=_.page,u=_.segmentIndex,C.page.headerStartPos!==p.headerStartPos){p=C.page,h=C.segmentIndex;break}}}let x=null,y=null;for(;l!==null;){g(u!==null);let v=await this.demuxer.readPacket(l,u);if(!v)break;if(!(l.headerStartPos===o.startPage.headerStartPos&&u<o.startSegmentIndex)){let _=this.createEncodedPacketFromOggPacket(v,{timestampInSamples:m,vorbisLastBlocksize:y?.vorbisBlockSize??null},t);g(_);let T=this.encodedPacketToMetadata.get(_);if(g(T),!d&&v.endPage.headerStartPos===p.headerStartPos&&v.endSegmentIndex===h?(m=this.granulePositionToTimestampInSamples(l.granulePosition),d=!0,_=this.createEncodedPacketFromOggPacket(v,{timestampInSamples:m-T.durationInSamples,vorbisLastBlocksize:y?.vorbisBlockSize??null},t),g(_),T=this.encodedPacketToMetadata.get(_),g(T)):m+=T.durationInSamples,x=_,y=T,d&&(Math.max(m,0)>n||Math.max(T.timestampInSamples,0)===n))break}let C=await this.demuxer.findNextPacketStart(v);if(!C)break;l=C.startPage,u=C.startSegmentIndex}return x}async getPacketSequential(e,t){let n=await this.sequentialScanMutex.acquire();try{let o=kt(e*this.internalSampleRate);e=o/this.internalSampleRate;let i=W(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);g(l),this.sequentialScanCache.length>0&&g(de(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return s}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},Wc=(r,e,t)=>{let n=e,o=t;e:for(;;){for(o--,o;o>=0;o--)if(n.lacingValues[o]<255){o++;break e}if(g(o===-1),!(n.headerType&1)){o=0;break}let s=os(r,a=>a.headerStartPos<n.headerStartPos);if(!s)return null;n=s,o=n.lacingValues.length}if(g(o!==-1),o===n.lacingValues.length){let i=r[r.indexOf(n)+1];g(i),n=i,o=0}return{page:n,segmentIndex:o}},jc=(r,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};let n=os(r,o=>o.headerStartPos<e.headerStartPos);return n?{page:n,segmentIndex:n.lacingValues.length-1}:null};var Ze;(function(r){r[r.PCM=1]="PCM",r[r.IEEE_FLOAT=3]="IEEE_FLOAT",r[r.ALAW=6]="ALAW",r[r.MULAW=7]="MULAW",r[r.EXTENSIBLE=65534]="EXTENSIBLE"})(Ze||(Ze={}));var Ao=class extends me{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),g(e);let t=J(e,4),n=t!=="RIFX",o=t==="RF64",i=Je(e,n),s=o?this.reader.fileSize:Math.min(i+8,this.reader.fileSize??1/0);if(J(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,f=e.filePos;for(;s===null||f<s;){let m=this.reader.requestSlice(f,8);if(m instanceof Promise&&(m=await m),!m)break;let d=J(m,4),p=Je(m,n),h=m.filePos;if(o&&c===0&&d!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(d==="fmt ")await this.parseFmtChunk(h,p,n);else if(d==="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(d==="ds64"){let x=this.reader.requestSlice(h,p);if(x instanceof Promise&&(x=await x),!x)break;let y=Us(x,n);l=Us(x,n),s=Math.min(y+8,this.reader.fileSize??1/0)}else d==="LIST"?await this.parseListChunk(h,p,n):(d==="ID3 "||d==="id3 ")&&await this.parseId3Chunk(h,p);f=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 u=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/u)*u,this.tracks.push(new se(this.input,new Bs(this)))})()}async parseFmtChunk(e,t,n){let o=this.reader.requestSlice(e,t);if(o instanceof Promise&&(o=await o),!o)return;let i=wr(o,n),s=wr(o,n),a=Je(o,n);o.skip(4);let c=wr(o,n),l;if(t===14?l=8:l=wr(o,n),t>=18&&i!==357){let f=wr(o,n),u=t-18;if(Math.min(u,f)>=22&&i===Ze.EXTENSIBLE){o.skip(6);let d=B(o,16);i=d[0]|d[1]<<8}}(i===Ze.MULAW||i===Ze.ALAW)&&(l=8),this.audioInfo={format:i,numberOfChannels:s,sampleRate:a,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}}async parseListChunk(e,t,n){let o=this.reader.requestSlice(e,t);if(o instanceof Promise&&(o=await o),!o)return;let i=J(o,4);if(i!=="INFO"&&i!=="INF0")return;let s=o.filePos;for(;s<=e+t-8;){o.filePos=s;let a=J(o,4),c=Je(o,n),l=B(o,c),f=0;for(let m=0;m<l.length&&l[m]!==0;m++)f++;let u=String.fromCharCode(...l.subarray(0,f));switch(this.metadataTags.raw??={},this.metadataTags.raw[a]=u,a){case"INAM":case"TITL":this.metadataTags.title??=u;break;case"TIT3":this.metadataTags.description??=u;break;case"IART":this.metadataTags.artist??=u;break;case"IPRD":this.metadataTags.album??=u;break;case"IPRT":case"ITRK":case"TRCK":{let m=u.split("/"),d=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(d)&&d>0&&(this.metadataTags.trackNumber??=d),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{let m=new Date(u);Number.isNaN(m.getTime())||(this.metadataTags.date??=m)}break;case"YEAR":{let m=Number.parseInt(u,10);Number.isInteger(m)&&m>0&&(this.metadataTags.date??=new Date(m,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=u;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=u;break}s+=8+c+(c&1)}}async parseId3Chunk(e,t){let n=this.reader.requestSlice(e,t);if(n instanceof Promise&&(n=await n),!n)return;let o=Rt(n);if(o){let i=n.slice(e+10,o.size);Po(i,o,this.metadataTags)}}getCodec(){if(g(this.audioInfo),this.audioInfo.format===Ze.MULAW)return"ulaw";if(this.audioInfo.format===Ze.ALAW)return"alaw";if(this.audioInfo.format===Ze.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}return this.audioInfo.format===Ze.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 g(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Tr=2048,Bs=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(g(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 g(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return le}getDisposition(){return{...xe}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){g(this.demuxer.audioInfo);let n=e*Tr*this.demuxer.audioInfo.blockSizeInBytes;if(n>=this.demuxer.dataSize)return null;let o=Math.min(Tr*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-n);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,o);if(c instanceof Promise&&(c=await c),!c)return null}let i;if(t.metadataOnly)i=oe;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,o);c instanceof Promise&&(c=await c),g(c),i=B(c,o)}let s=e*Tr/this.demuxer.audioInfo.sampleRate,a=o/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,s),new Z(i,"key",s,a,e,o)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){g(this.demuxer.audioInfo);let n=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Tr,(this.demuxer.dataSize-1)/(Tr*this.demuxer.audioInfo.blockSizeInBytes))),o=await this.getPacketAtIndex(n,t);if(o)return o;if(n===0)return null;g(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){g(this.demuxer.audioInfo);let n=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Tr);return this.getPacketAtIndex(n+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Cr=7,kr=9,hn=r=>{let e=r.filePos,t=B(r,9),n=new $(t);if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let s=n.readBits(1),a=n.readBits(2)+1,c=n.readBits(4);if(c===15)return null;n.skipBits(1);let l=n.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let f=n.readBits(13);n.skipBits(11);let u=n.readBits(2)+1;if(u!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let m=null;return s===1?r.filePos-=2:m=n.readBits(16),{objectType:a,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:f,numberOfAacFrames:u,crcCheck:m,startPos:e}};var Ns=1024,Fo=class extends me{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new Me,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();g(this.firstFrameHeader),this.tracks=[new se(this.input,new Ls(this))]})()}async advanceReader(){let e=this.reader.requestSliceRange(this.lastLoadedPos,Cr,kr);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=hn(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);let n=en[t.samplingFrequencyIndex];g(n!==void 0);let o=Ns/n,i=t.crcCheck?kr:Cr,s={timestamp:this.nextTimestampInSamples/n,duration:o,dataStart:t.startPos+i,dataSize:t.frameLength-i};this.loadedSamples.push(s),this.nextTimestampInSamples+=Ns,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 g(e),e.computeDuration()}async getMetadataTags(){return{}}},Ls=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/Ns}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return le}getCodec(){return"aac"}getInternalCodecId(){return g(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){g(this.demuxer.firstFrameHeader);let e=cs[this.demuxer.firstFrameHeader.channelConfiguration];return g(e!==void 0),e}getSampleRate(){g(this.demuxer.firstFrameHeader);let e=en[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return g(e!==void 0),e}getDisposition(){return{...xe}}async getDecoderConfig(){g(this.demuxer.firstFrameHeader);let e=new Uint8Array(3),t=new $(e),{objectType:n,samplingFrequencyIndex:o,channelConfiguration:i}=this.demuxer.firstFrameHeader;return n>31?(t.writeBits(5,31),t.writeBits(6,n-32)):t.writeBits(5,n),t.writeBits(4,o),t.writeBits(4,i),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:e.subarray(0,Math.ceil((t.pos-1)/8))}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let o;if(t.metadataOnly)o=oe;else{let i=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(i instanceof Promise&&(i=await i),!i)return null;o=B(i,n.dataSize)}return new Z(o,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let o=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{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let o=W(this.demuxer.loadedSamples,e,i=>i.timestamp);if(o===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(o,t);if(o>=0&&o+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(o,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Xc=r=>r===0?null:r===1?192:r>=2&&r<=5?144*2**r:r===6?"uncommon-u8":r===7?"uncommon-u16":r>=8&&r<=15?2**r:null,Kc=(r,e)=>{switch(r){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},Yc=r=>{let e=0,t=new $(B(r,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);let n=[],o=e-1,i=new $(B(r,o)),s=8-e-1;for(let c=0;c<s;c++)n.unshift(t.readBits(1));for(let c=0;c<o;c++)for(let l=0;l<8;l++){let f=i.readBits(1);l<2||n.unshift(f)}return n.reduce((c,l,f)=>c|l<<f,0)},$c=(r,e)=>{if(e==="uncommon-u16")return ae(r)+1;if(e==="uncommon-u8")return R(r)+1;if(typeof e=="number")return e;we(e),g(!1)},Qc=(r,e)=>e==="uncommon-u16"?ae(r):e==="uncommon-u16-10"?ae(r)*10:e==="uncommon-u8"?R(r):typeof e=="number"?e:null,Zc=r=>{let t=0;for(let n of r){t^=n;for(let o=0;o<8;o++)(t&128)!==0?t=t<<1^7:t<<=1,t&=255}return t};var Eo=class extends me{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 Me,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),g(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),g(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.`);g(t);let n=R(t),o=mt(t),i=(n&128)!==0;switch(n&127){case ct.STREAMINFO:{let a=this.reader.requestSlice(e,o);if(a instanceof Promise&&(a=await a),g(a),a===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let c=B(a,34),l=new $(c),f=l.readBits(16),u=l.readBits(16),m=l.readBits(24),d=l.readBits(24),p=l.readBits(20),h=l.readBits(3)+1;l.readBits(5);let x=l.readBits(36);l.skipBits(128);let y=new Uint8Array(42);y.set(new Uint8Array([102,76,97,67]),0),y.set(new Uint8Array([128,0,0,34]),4),y.set(c,8),this.audioInfo={numberOfChannels:h,sampleRate:p,totalSamples:x,minimumBlockSize:f,maximumBlockSize:u,minimumFrameSize:m,maximumFrameSize:d,description:y},this.track=new se(this.input,new Vs(this));break}case ct.VORBIS_COMMENT:{let a=this.reader.requestSlice(e,o);a instanceof Promise&&(a=await a),g(a),tn(B(a,o),this.metadataTags);break}case ct.PICTURE:{let a=this.reader.requestSlice(e,o);a instanceof Promise&&(a=await a),g(a);let c=F(a),l=F(a),f=ce.decode(B(a,l)),u=F(a),m=ce.decode(B(a,u));a.skip(16);let d=F(a),p=B(a,d);this.metadataTags.images??=[],this.metadataTags.images.push({data:p,mimeType:f,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}){g(this.audioInfo);let n=6,i=this.audioInfo.maximumFrameSize+16,s=await this.reader.requestSliceRange(e,this.audioInfo.minimumFrameSize,i);if(!s)return null;let a=this.readFlacFrameHeader({slice:s,isFirstPacket:t});if(!a)return null;for(s.filePos=e+this.audioInfo.minimumFrameSize;;){if(s.filePos>s.end-n)return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:s.end-e,isLastFrame:!0};if(R(s)===255){let l=s.filePos,f=R(s),u=this.blockingBit===1?249:248;if(f!==u){s.filePos=l;continue}s.skip(-2);let m=s.filePos-e,d=this.readFlacFrameHeader({slice:s,isFirstPacket:!1});if(!d){s.filePos=l;continue}if(this.blockingBit===0){if(d.num-a.num!==1){s.filePos=l;continue}}else if(d.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 n=e.filePos,o=B(e,4),i=new $(o);if(i.readBits(15)!==32764)return null;if(this.blockingBit===null){g(t);let x=i.readBits(1);this.blockingBit=x}else if(this.blockingBit===1){if(g(!t),i.readBits(1)!==1)return null}else if(this.blockingBit===0){if(g(!t),i.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");let a=Xc(i.readBits(4));if(!a)return null;g(this.audioInfo);let c=Kc(i.readBits(4),this.audioInfo.sampleRate);if(!c||(i.readBits(4),i.readBits(3),i.readBits(1)!==0))return null;let f=Yc(e),u=$c(e,a),m=Qc(e,c);if(m===null||m!==this.audioInfo.sampleRate)return null;let d=e.filePos-n,p=R(e);e.skip(-d),e.skip(-1);let h=Zc(B(e,d));return p!==h?null:{num:f,blockSize:u,sampleRate:m}}async advanceReader(){await this.readMetadata(),g(this.lastLoadedPos!==null),g(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],i={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(i),t.isLastFrame){this.lastSampleLoaded=!0;return}}},Vs=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return g(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 g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return le}getTimeResolution(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...xe}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return g(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(g(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");let n=await this.demuxer.readingMutex.acquire();try{for(;;){let o=W(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(o===-1){await this.demuxer.advanceReader();continue}let i=this.demuxer.loadedSamples[o],s=i.blockOffset/this.demuxer.audioInfo.sampleRate,a=i.blockSize/this.demuxer.audioInfo.sampleRate;if(s+a<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(o,t)}}finally{n()}}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let o=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&o>=this.demuxer.loadedSamples.length)return null;for(;o>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(o,t)}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let n=this.demuxer.loadedSamples[e];if(!n)return null;let o;if(t.metadataOnly)o=oe;else{let a=this.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(a instanceof Promise&&(a=await a),!a)return null;o=B(a,n.byteSize)}g(this.demuxer.audioInfo);let i=n.blockOffset/this.demuxer.audioInfo.sampleRate,s=n.blockSize/this.demuxer.audioInfo.sampleRate;return new Z(o,"key",i,s,e,n.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}};var Ce=class{},gn=class extends Ce{async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);return t instanceof Promise&&(t=await t),!t||(t.skip(4),J(t,4)!=="ftyp")?null:J(t,4)}_createDemuxer(e){return new go(e)}},zo=class extends gn{async _canReadInput(e){let t=await this._getMajorBrand(e);return!!t&&t!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},Do=class extends gn{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},xn=class extends Ce{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,Ie);if(n instanceof Promise&&(n=await n),!n)return!1;let o=_s(n);if(o===null||o<1||o>8||q(n,o)!==w.EBML)return!1;let s=Is(n);if(s===null)return!1;let a=e._reader.requestSlice(n.filePos,s);if(a instanceof Promise&&(a=await a),!a)return!1;let c=n.filePos;for(;a.filePos<=c+s-Te;){let l=Ae(a);if(!l)break;let{id:f,size:u}=l,m=a.filePos;if(u===null)return!1;switch(f){case w.EBMLVersion:if(q(a,u)!==1)return!1;break;case w.EBMLReadVersion:if(q(a,u)!==1)return!1;break;case w.DocType:if(dt(a,u)!==t)return!1;break;case w.DocTypeVersion:if(q(a,u)>4)return!1;break}a.filePos=m+u}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new wo(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},Oo=class extends xn{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},Ro=class extends Ce{async _canReadInput(e){let t=e._reader.requestSlice(0,10);if(t instanceof Promise&&(t=await t),!t)return!1;let n=0,o=!1;for(;;){let l=e._reader.requestSlice(n,br);if(l instanceof Promise&&(l=await l),!l)break;let f=Rt(l);if(!f)break;o=!0,n=l.filePos+f.size}let i=await pn(e._reader,n,n+4096);if(!i)return!1;if(o)return!0;n=i.startPos+i.header.totalSize;let s=await pn(e._reader,n,n+4);if(!s)return!1;let a=i.header,c=s.header;return!(a.channel!==c.channel||a.sampleRate!==c.sampleRate)}_createDemuxer(e){return new _o(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},Mo=class extends Ce{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let n=J(t,4);return n!=="RIFF"&&n!=="RIFX"&&n!=="RF64"?!1:(t.skip(4),J(t,4)==="WAVE")}_createDemuxer(e){return new Ao(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},Bo=class extends Ce{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?J(t,4)==="OggS":!1}_createDemuxer(e){return new Io(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},Uo=class extends Ce{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?J(t,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Eo(e)}},No=class extends Ce{async _canReadInput(e){let t=e._reader.requestSliceRange(0,Cr,kr);if(t instanceof Promise&&(t=await t),!t)return!1;let n=hn(t);if(!n||(t=e._reader.requestSliceRange(n.frameLength,Cr,kr),t instanceof Promise&&(t=await t),!t))return!1;let o=hn(t);return o?n.objectType===o.objectType&&n.samplingFrequencyIndex===o.samplingFrequencyIndex&&n.channelConfiguration===o.channelConfiguration:!1}_createDemuxer(e){return new Fo(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},Jc=new zo,el=new Do,tl=new xn,rl=new Oo,nl=new Ro,ol=new Mo,il=new Bo,sl=new No,al=new Uo,ge=[Jc,el,tl,rl,ol,il,al,nl,sl];var Ut=class{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new ie;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new ie;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}};var vn=class extends Ut{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&&(!Jr(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 Lo({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:ll.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&&!it()?t=this._blob.slice(e.currentPos).stream().getReader():t=null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){let{done:n,value:o}=await t.read();if(n)throw this._orchestrator.forgetWorker(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}else{let n=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+n.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(n))}e.running=!1,e.aborted&&await t?.cancel()}_dispose(){this._orchestrator.dispose()}},cl=.5*2**20,Ap=((r,e,t)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))){let o=null;try{typeof window<"u"&&typeof window.location<"u"&&(o=new URL(t instanceof Request?t.url:t,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&o!==null&&o!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(r-2),16)}),yn=class extends Ut{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&&(!Jr(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??Ap,this._orchestrator=new Lo({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:ll.network})}async _retrieveSize(){let e=new AbortController,t=await as(this._options.fetchFn??fetch,this._url,ss(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:e.signal}),this._getRetryDelay,()=>this._disposed);if(!t.ok)throw new Error(`Error fetching ${String(this._url)}: ${t.status} ${t.statusText}`);let n,o;if(t.status===206)o=this._getTotalLengthFromRangeResponse(t),n=this._orchestrator.createWorker(0,Math.min(o,cl));else{let i=t.headers.get("Content-Length");if(i)o=Number(i),n=this._orchestrator.createWorker(0,o),this._orchestrator.options.maxCacheSize=1/0,console.warn("HTTP server did not respond with 206 Partial Content, meaning the entire remote resource now has to be downloaded. For efficient media file streaming across a network, please make sure your server supports range requests.");else throw new Error(`HTTP response (status ${t.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=o,this._existingResponses.set(n,{response:t,abortController:e}),this._orchestrator.runWorker(n),o}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;;){let t=this._existingResponses.get(e);this._existingResponses.delete(e);let n=t?.abortController,o=t?.response;if(n||(n=new AbortController,o=await as(this._options.fetchFn??fetch,this._url,ss(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:n.signal}),this._getRetryDelay,()=>this._disposed)),g(o),!o.ok)throw new Error(`Error fetching ${String(this._url)}: ${o.status} ${o.statusText}`);if(e.currentPos>0&&o.status!==206)throw new Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!o.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let i=o.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){n.abort(),e.running=!1;return}let s;try{s=await i.read()}catch(l){if(this._disposed)throw l;let f=this._getRetryDelay(1,l,this._url);if(f!==null){console.error("Error while reading response stream. Attempting to resume.",l),await new Promise(u=>setTimeout(u,1e3*f));break}else throw l}if(e.aborted)continue;let{done:a,value:c}=s;if(a){if(e.currentPos>=e.targetPos){this._orchestrator.forgetWorker(e),e.running=!1;return}break}this.onread?.(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}}}_getTotalLengthFromRangeResponse(e){let t=e.headers.get("Content-Range");if(t){let o=/\/(\d+)/.exec(t);if(o)return Number(o[1])}let n=e.headers.get("Content-Length");if(n)return Number(n);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}};var ll={none:(r,e)=>({start:r,end:e}),fileSystem:(r,e)=>(r=Math.floor((r-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:r,end:e}),network:(r,e,t)=>{r=Math.max(0,Math.floor((r-65536)/65536)*65536);for(let o of t){let s=Math.max((o.startPos+o.targetPos)/2,o.targetPos-8388608);if(eo(r,e,s,o.targetPos)){let a=o.targetPos-o.startPos,c=Math.ceil((a+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(a+1)),f=Math.min(l,c);e=Math.max(e,o.startPos+f)}}return e=Math.max(e,r+cl),{start:r,end:e}}},Lo=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){g(this.fileSize!==null);let n=this.options.prefetchProfile(e,t,this.workers),o=Math.max(n.start,0),i=Math.min(n.end,this.fileSize);g(o<=e&&t<=i);let s=null,a=W(this.cache,e,v=>v.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=W(this.cache,o,v=>v.start),f=s?null:new Uint8Array(t-e),u=0,m=o,d=[];if(l!==-1){for(let v=l;v<this.cache.length;v++){let S=this.cache[v];if(S.start>=i)break;if(S.end<=o)continue;let C=Math.max(o,S.start),_=Math.min(i,S.end);if(g(C<=_),m<C&&d.push({start:m,end:C}),m=_,f){let T=Math.max(e,S.start),E=Math.min(t,S.end);if(T<E){let I=T-e;f.set(S.bytes.subarray(T-S.start,E-S.start),I),I===u&&(u=E-e)}}S.age=this.nextAge++}m<i&&d.push({start:m,end:i})}else d.push({start:o,end:i});if(f&&u>=f.length&&(s={bytes:f,view:j(f),offset:e}),d.length===0)return g(s),s;let{promise:p,resolve:h,reject:x}=pe(),y=[];for(let v of d){let S=Math.max(e,v.start),C=Math.min(t,v.end);S===v.start&&C===v.end?y.push(v):S<C&&y.push({start:S,end:C})}for(let v of d){let S=f&&{start:e,bytes:f,holes:y,resolve:h,reject:x},C=!1;for(let _ of this.workers)if(eo(v.start-131072,v.start,_.currentPos,_.targetPos)){_.targetPos=Math.max(_.targetPos,v.end),C=!0,S&&!_.pendingSlices.includes(S)&&_.pendingSlices.push(S),_.running||this.runWorker(_);break}if(!C){let _=this.createWorker(v.start,v.end);S&&(_.pendingSlices=[S]),this.runWorker(_)}}return s||(g(f),s=p.then(v=>({bytes:v,view:j(v),offset:e}))),s}createWorker(e,t){let n={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(n);this.workers.length>this.options.maxWorkerCount;){let o=0,i=this.workers[0];for(let s=1;s<this.workers.length;s++){let a=this.workers[s];a.age<i.age&&(o=s,i=a)}if(i.running&&i.pendingSlices.length>0)break;i.aborted=!0,this.workers.splice(o,1)}return n}runWorker(e){g(!e.running),g(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(n=>n.reject(t)),e.pendingSlices.length=0;else throw t})}supplyWorkerData(e,t){g(!e.aborted);let n=e.currentPos,o=n+t.length;this.insertIntoCache({start:n,end:o,bytes:t,view:j(t),age:this.nextAge++}),e.currentPos+=t.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let i=0;i<e.pendingSlices.length;i++){let s=e.pendingSlices[i],a=Math.max(n,s.start),c=Math.min(o,s.start+s.bytes.length);a<c&&s.bytes.set(t.subarray(a-n,c-n),a-s.start);for(let l=0;l<s.holes.length;l++){let f=s.holes[l];n<=f.start&&o>f.start&&(f.start=o),f.end<=f.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||eo(n,o,s.currentPos,s.targetPos)&&(this.workers.splice(i,1),i--)}}forgetWorker(e){let t=this.workers.indexOf(e);g(t!==-1),this.workers.splice(t,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=W(this.cache,e.start,n=>n.start)+1;if(t>0){let n=this.cache[t-1];if(n.end>=e.end)return;if(n.end>e.start){let o=new Uint8Array(e.end-n.start);o.set(n.bytes,0),o.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=o,n.view=j(o),n.end=e.end,t--,e=n}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let n=t+1;n<this.cache.length;n++){let o=this.cache[n];if(e.end<=o.start)break;if(e.end>=o.end){this.cache.splice(n,1),this.currentCacheSize-=o.bytes.length,n--;continue}let i=new Uint8Array(o.end-e.start);i.set(e.bytes,0),i.set(o.bytes,o.start-e.start),this.currentCacheSize-=e.end-o.start,e.bytes=i,e.view=j(i),e.end=o.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let n=0,o=this.cache[0];for(let i=1;i<this.cache.length;i++){let s=this.cache[i];s.age<o.age&&(n=i,o=s)}if(this.currentCacheSize-o.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(n,1),this.currentCacheSize-=o.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}};to();var fe=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 Ce)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Ut))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 Vo(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(),g(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()}},ie=class extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}};var Vo=class{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new ie;if(this.fileSize!==null&&e+t>this.fileSize)return null;let n=e+t,o=this.source._read(e,n);return o instanceof Promise?o.then(i=>i?new hr(i.bytes,i.view,i.offset,e,n):null):o?new hr(o.bytes,o.view,o.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new ie;if(this.fileSize!==null)return this.requestSlice(e,Ct(this.fileSize-e,t,n));{let o=this.requestSlice(e,n),i=s=>{if(s)return s;let a=l=>(g(l!==null),this.requestSlice(e,Ct(l-e,t,n))),c=this.source._retrieveSize();return c instanceof Promise?c.then(a):a(c)};return o instanceof Promise?o.then(i):i(o)}}},hr=class r{constructor(e,t,n,o,i){this.bytes=e,this.view=t,this.offset=n,this.start=o,this.end=i,this.bufferPos=o-n}static tempFromBytes(e){return new r(e,j(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new r(this.bytes,this.view,this.offset,e,e+t)}},ve=(r,e)=>{if(r.filePos<r.start||r.filePos+e>r.end)throw new RangeError(`Tried reading [${r.filePos}, ${r.filePos+e}), but slice is [${r.start}, ${r.end}). This is likely an internal error, please report it alongside the file that caused it.`)},B=(r,e)=>{ve(r,e);let t=r.bytes.subarray(r.bufferPos,r.bufferPos+e);return r.bufferPos+=e,t},R=r=>(ve(r,1),r.view.getUint8(r.bufferPos++)),wr=(r,e)=>{ve(r,2);let t=r.view.getUint16(r.bufferPos,e);return r.bufferPos+=2,t},ae=r=>{ve(r,2);let e=r.view.getUint16(r.bufferPos,!1);return r.bufferPos+=2,e},mt=r=>{ve(r,3);let e=wt(r.view,r.bufferPos,!1);return r.bufferPos+=3,e},un=r=>{ve(r,2);let e=r.view.getInt16(r.bufferPos,!1);return r.bufferPos+=2,e},Je=(r,e)=>{ve(r,4);let t=r.view.getUint32(r.bufferPos,e);return r.bufferPos+=4,t},F=r=>{ve(r,4);let e=r.view.getUint32(r.bufferPos,!1);return r.bufferPos+=4,e},Mt=r=>{ve(r,4);let e=r.view.getUint32(r.bufferPos,!0);return r.bufferPos+=4,e},Ye=r=>{ve(r,4);let e=r.view.getInt32(r.bufferPos,!1);return r.bufferPos+=4,e},Fp=r=>{ve(r,4);let e=r.view.getInt32(r.bufferPos,!0);return r.bufferPos+=4,e},Us=(r,e)=>{let t,n;return e?(t=Je(r,!0),n=Je(r,!0)):(n=Je(r,!1),t=Je(r,!1)),n*4294967296+t},Se=r=>{let e=F(r),t=F(r);return e*4294967296+t},_c=r=>{let e=Ye(r),t=F(r);return e*4294967296+t},Hc=r=>{let e=Mt(r);return Fp(r)*4294967296+e},Ac=r=>{ve(r,4);let e=r.view.getFloat32(r.bufferPos,!1);return r.bufferPos+=4,e},vo=r=>{ve(r,8);let e=r.view.getFloat64(r.bufferPos,!1);return r.bufferPos+=8,e},J=(r,e)=>{ve(r,e);let t="";for(let n=0;n<e;n++)t+=String.fromCharCode(r.bytes[r.bufferPos++]);return t};var Go=class{count=0};var ul={extension:{type:_n.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await import("./browserAll-PTRBXBRP.js")}};var fl={extension:{type:_n.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await import("./webworkerAll-JENRT6BT.js")}};var qo;function ml(r){return qo!==void 0||(qo=(()=>{let e={stencil:!0,failIfMajorPerformanceCaveat:r??An.defaultOptions.failIfMajorPerformanceCaveat};try{if(!qr.get().getWebGLRenderingContext())return!1;let n=qr.get().createCanvas().getContext("webgl",e),o=!!n?.getContextAttributes()?.stencil;if(n){let i=n.getExtension("WEBGL_lose_context");i&&i.loseContext()}return n=null,o}catch{return!1}})()),qo}var Ho;async function dl(r={}){return Ho!==void 0||(Ho=await(async()=>{let e=qr.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(r)).requestDevice(),!0}catch{return!1}})()),Ho}var pl=["webgl","webgpu","canvas"];async function Gs(r){let e=[];r.preference?(e.push(r.preference),pl.forEach(i=>{i!==r.preference&&e.push(i)})):e=pl.slice();let t,n={};for(let i=0;i<e.length;i++){let s=e[i];if(s==="webgpu"&&await dl()){let{WebGPURenderer:a}=await import("./WebGPURenderer-MGFAJCYY.js");t=a,n={...r,...r.webgpu};break}else if(s==="webgl"&&ml(r.failIfMajorPerformanceCaveat??An.defaultOptions.failIfMajorPerformanceCaveat)){let{WebGLRenderer:a}=await import("./WebGLRenderer-RSJAHIG2.js");t=a,n={...r,...r.webgl};break}else if(s==="canvas")throw n={...r},new Error("CanvasRenderer is not yet implemented")}if(delete n.webgpu,delete n.webgl,!t)throw new Error("No available renderer for the current environment");let o=new t;return await o.init(n),o}var hl=`
2362
+ `),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){let n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),n}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let o=this.gl.getAttribLocation(this.program,"a_position"),i=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(o),this.gl.vertexAttribPointer(o,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,t){(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}},ut=class extends an{constructor(e){if(!(e instanceof Ne))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=this._track.codec,o=this._track.rotation,i=await this._track.getDecoderConfig(),s=this._track.timeResolution;return g(n&&i),new vs(e,t,n,i,o,s)}_createPacketSink(){return new Rt(this._track)}async getSample(e){lt(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)}},cn=class{constructor(e,t={}){if(this._nextCanvasIndex=0,!(e instanceof Ne))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&&gs(t.crop,"options."),t.poolSize!==void 0&&(typeof t.poolSize!="number"||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");let n=t.rotation??e.rotation,[o,i]=n%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],s=t.crop;s&&hs(s,o,i);let[a,c]=s?[s.width,s.height]:[o,i],l=a/c;t.width!==void 0&&t.height===void 0?(a=t.width,c=Math.round(a/l)):t.width===void 0&&t.height!==void 0?(c=t.height,a=Math.round(c*l)):t.width!==void 0&&t.height!==void 0&&(a=t.width,c=t.height),this._videoTrack=e,this._alpha=t.alpha??!1,this._width=a,this._height=c,this._rotation=n,this._crop=s,this._fit=t.fit??"fill",this._videoSampleSink=new ut(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let t=this._canvasPool[this._nextCanvasIndex],n=!1;t||(typeof document<"u"?(t=document.createElement("canvas"),t.width=this._width,t.height=this._height):t=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=t),n=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let o=t.getContext("2d",{alpha:this._alpha||Qr()});g(o),o.resetTransform(),n||(!this._alpha&&Qr()?(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){lt(e);let t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return is(this._videoSampleSink.samples(e,t),n=>this._videoSampleToWrappedCanvas(n))}canvasesAtTimestamps(e){return is(this._videoSampleSink.samplesAtTimestamps(e),t=>t&&this._videoSampleToWrappedCanvas(t))}},bs=class extends sn{constructor(e,t,n,o){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new $r,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=mo.find(a=>a.supports(n,o));if(s)this.customDecoder=new s,this.customDecoder.codec=n,this.customDecoder.config=o,this.customDecoder.onSample=a=>{if(!(a instanceof lr))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 lr(c))}catch(l){this.onError(l)}},error:c=>{c.stack=a,this.onError(c)}}),this.decoder.configure(o)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(g(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(g(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(g(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(g(this.decoder),this.decoder.close())}},Ss=class extends sn{constructor(e,t,n){super(e,t),this.decoderConfig=n,this.currentTimestamp=null,g(at.includes(n.codec)),this.codec=n.codec;let{dataType:o,sampleSize:i,littleEndian:s}=io(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)=>hc(a.getUint8(c)):o==="alaw"?this.readInputValue=(a,c)=>gc(a.getUint8(c)):g(!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):g(!1);break;case 3:o==="unsigned"?this.readInputValue=(a,c)=>kt(a,c,s)-2**23:o==="signed"?this.readInputValue=(a,c)=>$a(a,c,s):g(!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):g(!1);break;case 8:o==="float"?this.readInputValue=(a,c)=>a.getFloat64(c,s):g(!1);break;default:we(i),g(!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:we(i),g(!1)}}getDecodeQueueSize(){return 0}decode(e){let t=j(e.data),n=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,o=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,i=new ArrayBuffer(o),s=new DataView(i);for(let f=0;f<n*this.decoderConfig.numberOfChannels;f++){let u=f*this.inputSampleSize,m=f*this.outputSampleSize,d=this.readInputValue(t,u);this.writeOutputValue(s,m,d)}let a=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=a)&&(this.currentTimestamp=e.timestamp);let c=this.currentTimestamp;this.currentTimestamp+=a;let l=new lr({format:this.outputFormat,data:i,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:c});this.onSample(l)}async flush(){}close(){}},ln=class extends an{constructor(e){if(!(e instanceof se))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");let n=this._track.codec,o=await this._track.getDecoderConfig();return g(n&&o),at.includes(o.codec)?new Ss(e,t,o):new bs(e,t,n,o)}_createPacketSink(){return new Rt(this._track)}async getSample(e){lt(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 fr=class{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Ne}isAudioTrack(){return this instanceof se}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 Rt(this),n=1/0,o=-1/0,i=0,s=0;for await(let a of t.packets(void 0,void 0,{metadataOnly:!0})){if(i>=e&&a.timestamp>=o)break;n=Math.min(n,a.timestamp),o=Math.max(o,a.timestamp+a.duration),i++,s+=a.byteLength}return{packetCount:i,averagePacketRate:i?Number((i/(o-n)).toPrecision(16)):0,averageBitrate:i?Number((8*s/(o-n)).toPrecision(16)):0}}},Ne=class extends fr{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 g(t!==null),fo.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 Z))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 g(t),uo(this.codec,t,e.data)}},se=class extends fr{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 g(t!==null),mo.some(n=>n.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Z))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}};var Cc=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isQuickTime?"quicktime":"mp4");if(r.codecStrings.length>0){let n=[...new Set(r.codecStrings)];t+=`; codecs="${n.join(", ")}"`}return t};var Mt=8,mr=16,Ke=r=>{let e=F(r),t=J(r,4),n=8;e===1&&(e=Se(r),n=16);let i=e-n;return i<0?null:{name:t,totalSize:e,headerSize:n,contentSize:i}},ft=r=>Ye(r)/65536,po=r=>Ye(r)/1073741824,ho=r=>{let e=0;for(let t=0;t<4;t++){e<<=7;let n=R(r);if(e|=n&127,(n&128)===0)break}return e},_e=r=>{let e=ae(r);return r.skip(2),e=Math.min(e,r.remainingLength),ce.decode(B(r,e))},kc=r=>{let e=Ke(r);if(!e||e.name!=="data"||r.remainingLength<8)return null;let t=F(r);r.skip(4);let n=B(r,e.contentSize-8);switch(t){case 1:return ce.decode(n);case 2:return new TextDecoder("utf-16be").decode(n);case 13:return new st(n,"image/jpeg");case 14:return new st(n,"image/png");case 27:return new st(n,"image/bmp");default:return n}};var go=class extends me{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(t=>t.inputTrack.getCodecParameterString()));return Cc({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,mr);if(t instanceof Promise&&(t=await t),!t)break;let n=e,o=Ke(t);if(!o)break;if(o.name==="ftyp"){let i=J(t,4);this.isQuickTime=i==="qt "}else if(o.name==="moov"){let i=this.reader.requestSlice(t.filePos,o.contentSize);if(i instanceof Promise&&(i=await i),!i)break;this.moovSlice=i,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((s,a)=>Number(a.disposition.default)-Number(s.disposition.default));for(let s of this.tracks){let a=s.editListPreviousSegmentDurations/this.movieTimescale;s.editListOffset-=Math.round(a*s.timescale)}break}e=n+o.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let t=this.reader.requestSlice(this.reader.fileSize-4,4);t instanceof Promise&&(t=await t),g(t);let n=F(t),o=this.reader.fileSize-n;if(o>=0&&o<=this.reader.fileSize-mr){let i=this.reader.requestSliceRange(o,Mt,mr);if(i instanceof Promise&&(i=await i),i){let s=Ke(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,g(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&at.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){g(e.info?.type==="audio");let i=io(e.info.codec),s=[],a=[];for(let c=0;c<t.sampleToChunk.length;c++){let l=t.sampleToChunk[c],f=t.sampleToChunk[c+1],u=(f?f.startChunkIndex:t.chunkOffsets.length)-l.startChunkIndex;for(let m=0;m<u;m++){let d=l.startSampleIndex+m*l.samplesPerChunk,p=d+l.samplesPerChunk,h=W(t.sampleTimingEntries,d,I=>I.startIndex),x=t.sampleTimingEntries[h],y=W(t.sampleTimingEntries,p,I=>I.startIndex),v=t.sampleTimingEntries[y],S=x.startDecodeTimestamp+(d-x.startIndex)*x.delta,_=v.startDecodeTimestamp+(p-v.startIndex)*v.delta-S,T=de(s);T&&T.delta===_?T.count++:s.push({startIndex:l.startChunkIndex+m,startDecodeTimestamp:S,count:1,delta:_});let E=l.samplesPerChunk*i.sampleSize*e.info.numberOfChannels;a.push(E)}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,mr);t instanceof Promise&&(t=await t),g(t);let n=Ke(t);g(n?.name==="moof");let o=this.reader.requestSlice(e,n.totalSize);o instanceof Promise&&(o=await o),g(o),this.traverseBox(o);let i=this.lastReadFragment;g(i&&i.moofOffset===e);for(let[,s]of i.trackData){let a=s.track,{fragmentPositionCache:c}=a;if(!s.startTimestampIsFinal){let f=a.fragmentLookupTable.find(u=>u.moofOffset===i.moofOffset);if(f)Ts(s,f.timestamp);else{let u=W(c,i.moofOffset-1,m=>m.moofOffset);if(u!==-1){let m=c[u];Ts(s,m.endTimestamp)}}s.startTimestampIsFinal=!0}let l=W(c,s.startTimestamp,f=>f.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 n=e.filePos,o=Ke(e);if(!o)break;yield{boxInfo:o,slice:e},e.filePos=n+o.totalSize}}traverseBox(e){let t=e.filePos,n=Ke(e);if(!n)return!1;let o=e.filePos,i=t+n.totalSize;switch(n.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"mvhd":{let s=R(e);e.skip(3),s===1?(e.skip(16),this.movieTimescale=F(e),this.movieDurationInTimescale=Se(e)):(e.skip(8),this.movieTimescale=F(e),this.movieDurationInTimescale=F(e))}break;case"trak":{let s={id:-1,demuxer:this,inputTrack:null,disposition:{...xe},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:le,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=s,this.readContiguousBoxes(e.slice(o,n.contentSize)),s.id!==-1&&s.timescale!==-1&&s.info!==null){if(s.info.type==="video"&&s.info.width!==-1){let a=s;s.inputTrack=new Ne(this.input,new ws(a)),this.tracks.push(s)}else if(s.info.type==="audio"&&s.info.numberOfChannels!==-1){let a=s;s.inputTrack=new se(this.input,new Cs(a)),this.tracks.push(s)}}this.currentTrack=null}break;case"tkhd":{let s=this.currentTrack;if(!s)break;let a=R(e),l=!!(mt(e)&1);if(s.disposition.default=l,a===0)e.skip(8),s.id=F(e),e.skip(4),s.durationInMovieTimescale=F(e);else if(a===1)e.skip(16),s.id=F(e),e.skip(4),s.durationInMovieTimescale=Se(e);else throw new Error(`Incorrect track header version ${a}.`);e.skip(16);let f=[ft(e),ft(e),po(e),ft(e),ft(e),po(e),ft(e),ft(e),po(e)],u=Xn(Za(wp(f),90));g(u===0||u===90||u===180||u===270),s.rotation=u}break;case"elst":{let s=this.currentTrack;if(!s)break;let a=R(e);e.skip(3);let c=!1,l=0,f=F(e);for(let u=0;u<f;u++){let m=a===1?Se(e):F(e),d=a===1?_c(e):Ye(e),p=ft(e);if(m!==0){if(c){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(d===-1){l+=m;continue}if(p!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}s.editListPreviousSegmentDurations=l,s.editListOffset=d,c=!0}}}break;case"mdhd":{let s=this.currentTrack;if(!s)break;let a=R(e);e.skip(3),a===0?(e.skip(8),s.timescale=F(e),s.durationInMediaTimescale=F(e)):a===1&&(e.skip(16),s.timescale=F(e),s.durationInMediaTimescale=Se(e));let c=ae(e);if(c>0){s.languageCode="";for(let l=0;l<3;l++)s.languageCode=String.fromCharCode(96+(c&31))+s.languageCode,c>>=5;Jn(s.languageCode)||(s.languageCode=le)}}break;case"hdlr":{let s=this.currentTrack;if(!s)break;e.skip(8);let a=J(e,4);a==="vide"?s.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:a==="soun"&&(s.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{let s=this.currentTrack;if(!s)break;s.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(o,n.contentSize))}break;case"stsd":{let s=this.currentTrack;if(!s||s.info===null||s.sampleTable)break;let a=R(e);e.skip(3);let c=F(e);for(let l=0;l<c;l++){let f=e.filePos,u=Ke(e);if(!u)break;s.internalCodecId=u.name;let m=u.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 '${u.name}').`),e.skip(24),s.info.width=ae(e),s.info.height=ae(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,f+u.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 '${u.name}').`))),e.skip(8);let d=ae(e);e.skip(6);let p=ae(e),h=ae(e);e.skip(4);let x=F(e)/65536;if(a===0&&d>0){if(d===1)e.skip(4),h=8*F(e),e.skip(8);else if(d===2){e.skip(4),x=vo(e),p=F(e),e.skip(4),h=F(e);let y=F(e);if(e.skip(8),m==="lpcm"){let v=h+7>>3,S=!!(y&1),C=!!(y&2),_=y&4?-1:0;h>0&&h<=64&&(S?h===32&&(s.info.codec=C?"pcm-f32be":"pcm-f32"):_&1<<v-1?v===1?s.info.codec="pcm-s8":v===2?s.info.codec=C?"pcm-s16be":"pcm-s16":v===3?s.info.codec=C?"pcm-s24be":"pcm-s24":v===4&&(s.info.codec=C?"pcm-s32be":"pcm-s32"):v===1&&(s.info.codec="pcm-u8")),s.info.codec===null&&console.warn("Unsupported PCM format.")}}}s.info.codec==="opus"&&(x=Ft),s.info.numberOfChannels=p,s.info.sampleRate=x,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,f+u.totalSize-e.filePos))}}}break;case"avcC":{let s=this.currentTrack;if(!s)break;g(s.info),s.info.codecDescription=B(e,n.contentSize)}break;case"hvcC":{let s=this.currentTrack;if(!s)break;g(s.info),s.info.codecDescription=B(e,n.contentSize)}break;case"vpcC":{let s=this.currentTrack;if(!s)break;g(s.info?.type==="video"),e.skip(4);let a=R(e),c=R(e),l=R(e),f=l>>4,u=l>>1&7,m=l&1,d=R(e),p=R(e),h=R(e);s.info.vp9CodecInfo={profile:a,level:c,bitDepth:f,chromaSubsampling:u,videoFullRangeFlag:m,colourPrimaries:d,transferCharacteristics:p,matrixCoefficients:h}}break;case"av1C":{let s=this.currentTrack;if(!s)break;g(s.info?.type==="video"),e.skip(1);let a=R(e),c=a>>5,l=a&31,f=R(e),u=f>>7,m=f>>6&1,d=f>>5&1,p=f>>4&1,h=f>>3&1,x=f>>2&1,y=f&3,v=c===2&&m?d?12:10:m?10:8;s.info.av1CodecInfo={profile:c,level:l,tier:u,bitDepth:v,monochrome:p,chromaSubsamplingX:h,chromaSubsamplingY:x,chromaSamplePosition:y}}break;case"colr":{let s=this.currentTrack;if(!s||(g(s.info?.type==="video"),J(e,4)!=="nclx"))break;let c=ae(e),l=ae(e),f=ae(e),u=!!(R(e)&128);s.info.colorSpace={primaries:Kn[c],transfer:Yn[l],matrix:$n[f],fullRange:u}}break;case"wave":this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"esds":{let s=this.currentTrack;if(!s)break;g(s.info?.type==="audio"),e.skip(4);let a=R(e);g(a===3),ho(e),e.skip(2);let c=R(e),l=(c&128)!==0,f=(c&64)!==0,u=(c&32)!==0;if(l&&e.skip(2),f){let x=R(e);e.skip(x)}u&&e.skip(2);let m=R(e);g(m===4);let d=ho(e),p=e.filePos,h=R(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),d>e.filePos-p){let x=R(e);g(x===5);let y=ho(e);if(s.info.codecDescription=B(e,y),s.info.codec==="aac"){let v=ls(s.info.codecDescription);v.numberOfChannels!==null&&(s.info.numberOfChannels=v.numberOfChannels),v.sampleRate!==null&&(s.info.sampleRate=v.sampleRate)}}}break;case"enda":{let s=this.currentTrack;if(!s)break;g(s.info?.type==="audio"),ae(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;g(s.info?.type==="audio"),e.skip(4);let c=!!(R(e)&1),l=R(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;g(s.info?.type==="audio"),e.skip(1);let a=R(e),c=ae(e),l=F(e),f=un(e),u=R(e),m;u!==0?m=B(e,2+a):m=new Uint8Array(0);let d=new Uint8Array(19+m.byteLength),p=new DataView(d.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,f,!0),p.setUint8(18,u),d.set(m,19),s.info.codecDescription=d,s.info.numberOfChannels=a}break;case"dfLa":{let s=this.currentTrack;if(!s)break;g(s.info?.type==="audio"),e.skip(4);let a=127,c=128,l=e.filePos;for(;e.filePos<i;){let p=R(e),h=mt(e);if((p&a)===ct.STREAMINFO){e.skip(10);let y=F(e),v=y>>>12,S=(y>>9&7)+1;s.info.sampleRate=v,s.info.numberOfChannels=S,e.skip(20)}else e.skip(h);if(p&c)break}let f=e.filePos;e.filePos=l;let u=B(e,f-l),m=new Uint8Array(4+u.byteLength);new DataView(m.buffer).setUint32(0,1716281667,!1),m.set(u,4),s.info.codecDescription=m}break;case"stts":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=F(e),c=0,l=0;for(let f=0;f<a;f++){let u=F(e),m=F(e);s.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:l,count:u,delta:m}),c+=u,l+=u*m}}break;case"ctts":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=F(e),c=0;for(let l=0;l<a;l++){let f=F(e),u=Ye(e);s.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:f,offset:u}),c+=f}}break;case"stsz":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=F(e),c=F(e);if(a===0)for(let l=0;l<c;l++){let f=F(e);s.sampleTable.sampleSizes.push(f)}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=R(e),c=F(e),l=B(e,Math.ceil(c*a/8)),f=new $(l);for(let u=0;u<c;u++){let m=f.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=F(e);for(let c=0;c<a;c++){let l=F(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=F(e);for(let l=0;l<a;l++){let f=F(e)-1,u=F(e),m=F(e);s.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:f,samplesPerChunk:u,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 u=s.sampleTable.sampleToChunk[l+1].startChunkIndex-s.sampleTable.sampleToChunk[l].startChunkIndex;c+=u*s.sampleTable.sampleToChunk[l].samplesPerChunk}}break;case"stco":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=F(e);for(let c=0;c<a;c++){let l=F(e);s.sampleTable.chunkOffsets.push(l)}}break;case"co64":{let s=this.currentTrack;if(!s||!s.sampleTable)break;e.skip(4);let a=F(e);for(let c=0;c<a;c++){let l=Se(e);s.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"mehd":{let s=R(e);e.skip(3);let a=s===1?Se(e):F(e);this.movieDurationInTimescale=a}break;case"trex":{e.skip(4);let s=F(e),a=F(e),c=F(e),l=F(e),f=F(e);this.fragmentTrackDefaults.push({trackId:s,defaultSampleDescriptionIndex:a,defaultSampleDuration:c,defaultSampleSize:l,defaultSampleFlags:f})}break;case"tfra":{let s=R(e);e.skip(3);let a=F(e),c=this.tracks.find(v=>v.id===a);if(!c)break;let l=F(e),f=(l&48)>>4,u=(l&12)>>2,m=l&3,d=[R,ae,mt,F],p=d[f],h=d[u],x=d[m],y=F(e);for(let v=0;v<y;v++){let S=s===1?Se(e):F(e),C=s===1?Se(e):F(e);p(e),h(e),x(e),c.fragmentLookupTable.push({timestamp:S,moofOffset:C})}c.fragmentLookupTable.sort((v,S)=>v.timestamp-S.timestamp);for(let v=0;v<c.fragmentLookupTable.length-1;v++){let S=c.fragmentLookupTable[v],C=c.fragmentLookupTable[v+1];S.timestamp===C.timestamp&&(c.fragmentLookupTable.splice(v+1,1),v--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:n.totalSize,implicitBaseDataOffset:t,trackData:new Map},this.readContiguousBoxes(e.slice(o,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(g(this.currentFragment),this.readContiguousBoxes(e.slice(o,n.contentSize)),this.currentTrack){let s=this.currentFragment.trackData.get(this.currentTrack.id);if(s){let{currentFragmentState:a}=this.currentTrack;g(a),a.startTimestamp!==null&&(Ts(s,a.startTimestamp),s.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{g(this.currentFragment),e.skip(1);let s=mt(e),a=!!(s&1),c=!!(s&2),l=!!(s&8),f=!!(s&16),u=!!(s&32),m=!!(s&65536),d=!!(s&131072),p=F(e),h=this.tracks.find(y=>y.id===p);if(!h)break;let x=this.fragmentTrackDefaults.find(y=>y.trackId===p);this.currentTrack=h,h.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:x?.defaultSampleDescriptionIndex??null,defaultSampleDuration:x?.defaultSampleDuration??null,defaultSampleSize:x?.defaultSampleSize??null,defaultSampleFlags:x?.defaultSampleFlags??null,startTimestamp:null},a?h.currentFragmentState.baseDataOffset=Se(e):d&&(h.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(h.currentFragmentState.sampleDescriptionIndex=F(e)),l&&(h.currentFragmentState.defaultSampleDuration=F(e)),f&&(h.currentFragmentState.defaultSampleSize=F(e)),u&&(h.currentFragmentState.defaultSampleFlags=F(e)),m&&(h.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let s=this.currentTrack;if(!s)break;g(s.currentFragmentState);let a=R(e);e.skip(3);let c=a===0?F(e):Se(e);s.currentFragmentState.startTimestamp=c}break;case"trun":{let s=this.currentTrack;if(!s)break;if(g(this.currentFragment),g(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=R(e),c=mt(e),l=!!(c&1),f=!!(c&4),u=!!(c&256),m=!!(c&512),d=!!(c&1024),p=!!(c&2048),h=F(e),x=s.currentFragmentState.baseDataOffset;l&&(x+=Ye(e));let y=null;f&&(y=F(e));let v=x;if(h===0){this.currentFragment.implicitBaseDataOffset=v;break}let S=0,C={track:s,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(s.id,C);for(let E=0;E<h;E++){let I;u?I=F(e):(g(s.currentFragmentState.defaultSampleDuration!==null),I=s.currentFragmentState.defaultSampleDuration);let M;m?M=F(e):(g(s.currentFragmentState.defaultSampleSize!==null),M=s.currentFragmentState.defaultSampleSize);let L;d?L=F(e):(g(s.currentFragmentState.defaultSampleFlags!==null),L=s.currentFragmentState.defaultSampleFlags),E===0&&y!==null&&(L=y);let V=0;p&&(a===0?V=F(e):V=Ye(e));let te=!(L&65536);C.samples.push({presentationTimestamp:S+V,duration:I,byteOffset:v,byteSize:M,isKeyFrame:te}),v+=M,S+=I}C.presentationTimestamps=C.samples.map((E,I)=>({presentationTimestamp:E.presentationTimestamp,sampleIndex:I})).sort((E,I)=>E.presentationTimestamp-I.presentationTimestamp);for(let E=0;E<C.presentationTimestamps.length;E++){let I=C.presentationTimestamps[E],M=C.samples[I.sampleIndex];if(C.firstKeyFrameTimestamp===null&&M.isKeyFrame&&(C.firstKeyFrameTimestamp=M.presentationTimestamp),E<C.presentationTimestamps.length-1){let L=C.presentationTimestamps[E+1];M.duration=L.presentationTimestamp-I.presentationTimestamp}}let _=C.samples[C.presentationTimestamps[0].sampleIndex],T=C.samples[de(C.presentationTimestamps).sampleIndex];C.startTimestamp=_.presentationTimestamp,C.endTimestamp=T.presentationTimestamp+T.duration,this.currentFragment.implicitBaseDataOffset=v}break;case"udta":{let s=this.iterateContiguousBoxes(e.slice(o,n.contentSize));for(let{boxInfo:a,slice:c}of s){if(a.name!=="meta"&&!this.currentTrack){let l=c.filePos;this.metadataTags.raw??={},a.name[0]==="\xA9"?this.metadataTags.raw[a.name]??=_e(c):this.metadataTags.raw[a.name]??=B(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=ce.decode(B(c,a.contentSize)):this.metadataTags.title??=_e(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=_e(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=_e(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=_e(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=_e(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=_e(c));break;case"\xA9day":if(!this.currentTrack){let l=new Date(_e(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=_e(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=_e(c));break}}}break;case"meta":{if(this.currentTrack)break;let a=F(e)!==0;this.currentMetadataKeys=new Map,a?this.readContiguousBoxes(e.slice(o,n.contentSize)):this.readContiguousBoxes(e.slice(o+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let s=F(e);for(let a=0;a<s;a++){let c=F(e);e.skip(4);let l=ce.decode(B(e,c-8));this.currentMetadataKeys.set(a+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let s=this.iterateContiguousBoxes(e.slice(o,n.contentSize));for(let{boxInfo:a,slice:c}of s){let l=a.name,f=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(f)&&(l=this.currentMetadataKeys.get(f));let u=kc(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=u,l){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof u=="string"&&(this.metadataTags.title??=u);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof u=="string"&&(this.metadataTags.description??=u);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof u=="string"&&(this.metadataTags.artist??=u);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof u=="string"&&(this.metadataTags.album??=u);break;case"aART":case"album_artist":typeof u=="string"&&(this.metadataTags.albumArtist??=u);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof u=="string"&&(this.metadataTags.comment??=u);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof u=="string"&&(this.metadataTags.genre??=u);break;case"\xA9lyr":case"lyrics":typeof u=="string"&&(this.metadataTags.lyrics??=u);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof u=="string"){let m=new Date(u);Number.isNaN(m.getTime())||(this.metadataTags.date??=m)}break;case"covr":case"com.apple.quicktime.artwork":u instanceof st?(this.metadataTags.images??=[],this.metadataTags.images.push({data:u.data,kind:"coverFront",mimeType:u.mimeType})):u instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:u,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof u=="string"){let m=u.split("/"),d=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(d)&&d>0&&(this.metadataTags.trackNumber??=d),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(u instanceof Uint8Array&&u.length>=6){let m=j(u),d=m.getUint16(2,!1),p=m.getUint16(4,!1);d>0&&(this.metadataTags.trackNumber??=d),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(u instanceof Uint8Array&&u.length>=6){let m=j(u),d=m.getUint16(2,!1),p=m.getUint16(4,!1);d>0&&(this.metadataTags.discNumber??=d),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=i,!0}},xo=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,n=>n.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return _t(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),o=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=ks(o,n),s=await this.fetchPacketForSampleIndex(i,t);return!Pc(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=W(c.presentationTimestamps,n,m=>m.presentationTimestamp),f=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,u=l!==-1&&n<c.endTimestamp;return{sampleIndex:f,correctSampleFound:u}},n,n,t)}async getNextPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,t);let o=this.packetToFragmentLocation.get(e);if(o===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(o.fragment,i=>{if(i===o.fragment){let s=i.trackData.get(this.internalTrack.id);if(o.sampleIndex+1<s.samples.length)return{sampleIndex:o.sampleIndex+1,correctSampleFound:!0}}else if(i.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.mapTimestampIntoTimescale(e),o=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=bp(o,n),s=await this.fetchPacketForSampleIndex(i,t);return!Pc(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=Zn(c.presentationTimestamps,m=>c.samples[m.sampleIndex].isKeyFrame&&m.presentationTimestamp<=n),f=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,u=l!==-1&&n<c.endTimestamp;return{sampleIndex:f,correctSampleFound:u}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Tp(i,n);return this.fetchPacketForSampleIndex(s,t)}let o=this.packetToFragmentLocation.get(e);if(o===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(o.fragment,i=>{if(i===o.fragment){let a=i.trackData.get(this.internalTrack.id).samples.findIndex((c,l)=>c.isKeyFrame&&l>o.sampleIndex);if(a!==-1)return{sampleIndex:a,correctSampleFound:!0}}else{let s=i.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){let a=s.samples.findIndex(c=>c.isKeyFrame);return g(a!==-1),{sampleIndex:a,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),o=Sp(n,e);if(!o)return null;let i;if(t.metadataOnly)i=oe;else{let l=this.internalTrack.demuxer.reader.requestSlice(o.sampleOffset,o.sampleSize);l instanceof Promise&&(l=await l),g(l),i=B(l,o.sampleSize)}let s=(o.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=o.duration/this.internalTrack.timescale,c=new Z(i,o.isKeyFrame?"key":"delta",s,a,e,o.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,n){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).samples[t];g(i);let s;if(n.metadataOnly)s=oe;else{let f=this.internalTrack.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);f instanceof Promise&&(f=await f),g(f),s=B(f,i.byteSize)}let a=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=i.duration/this.internalTrack.timescale,l=new Z(s,i.isKeyFrame?"key":"delta",a,c,e.moofOffset+t,i.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:t}),l}async performFragmentedLookup(e,t,n,o,i){let s=this.internalTrack.demuxer,a=null,c=null,l=-1;if(e){let{sampleIndex:x,correctSampleFound:y}=t(e);if(y)return this.fetchPacketInFragment(e,x,i);x!==-1&&(c=e,l=x)}let f=W(this.internalTrack.fragmentLookupTable,n,x=>x.timestamp),u=f!==-1?this.internalTrack.fragmentLookupTable[f]:null,m=W(this.internalTrack.fragmentPositionCache,n,x=>x.startTimestamp),d=m!==-1?this.internalTrack.fragmentPositionCache[m]:null,p=Math.max(u?.moofOffset??0,d?.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 S=a.trackData.get(this.internalTrack.id);if(S&&S.startTimestamp>o)break}let x=s.reader.requestSliceRange(h,Mt,mr);if(x instanceof Promise&&(x=await x),!x)break;let y=h,v=Ke(x);if(!v)break;if(v.name==="moof"){a=await s.readFragment(y);let{sampleIndex:S,correctSampleFound:C}=t(a);if(C)return this.fetchPacketInFragment(a,S,i);S!==-1&&(c=a,l=S)}h=y+v.totalSize}if(u&&(!c||c.moofOffset<u.moofOffset)){let x=this.internalTrack.fragmentLookupTable[f-1];g(!x||x.timestamp<u.timestamp);let y=x?.timestamp??-1/0;return this.performFragmentedLookup(null,t,y,o,i)}return c?this.fetchPacketInFragment(c,l,i):null}},ws=class extends xo{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&&co(e.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&lo(e.data)}return{codec:no(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}},Cs=class extends xo{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:oo(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},ks=(r,e)=>{if(r.presentationTimestamps){let t=W(r.presentationTimestamps,e,n=>n.presentationTimestamp);return t===-1?-1:r.presentationTimestamps[t].sampleIndex}else{let t=W(r.sampleTimingEntries,e,o=>o.startDecodeTimestamp);if(t===-1)return-1;let n=r.sampleTimingEntries[t];return n.startIndex+Math.min(Math.floor((e-n.startDecodeTimestamp)/n.delta),n.count-1)}},bp=(r,e)=>{if(!r.keySampleIndices)return ks(r,e);if(r.presentationTimestamps){let t=W(r.presentationTimestamps,e,n=>n.presentationTimestamp);if(t===-1)return-1;for(let n=t;n>=0;n--){let o=r.presentationTimestamps[n].sampleIndex;if(Ct(r.keySampleIndices,o,s=>s)!==-1)return o}return-1}else{let t=ks(r,e),n=W(r.keySampleIndices,t,o=>o);return r.keySampleIndices[n]??-1}},Sp=(r,e)=>{let t=W(r.sampleTimingEntries,e,y=>y.startIndex),n=r.sampleTimingEntries[t];if(!n||n.startIndex+n.count<=e)return null;let i=n.startDecodeTimestamp+(e-n.startIndex)*n.delta,s=W(r.sampleCompositionTimeOffsets,e,y=>y.startIndex),a=r.sampleCompositionTimeOffsets[s];a&&e-a.startIndex<a.count&&(i+=a.offset);let c=r.sampleSizes[Math.min(e,r.sampleSizes.length-1)],l=W(r.sampleToChunk,e,y=>y.startSampleIndex),f=r.sampleToChunk[l];g(f);let u=f.startChunkIndex+Math.floor((e-f.startSampleIndex)/f.samplesPerChunk),m=r.chunkOffsets[u],d=f.startSampleIndex+(u-f.startChunkIndex)*f.samplesPerChunk,p=0,h=m;if(r.sampleSizes.length===1)h+=c*(e-d),p+=c*f.samplesPerChunk;else for(let y=d;y<d+f.samplesPerChunk;y++){let v=r.sampleSizes[y];y<e&&(h+=v),p+=v}let x=n.delta;if(r.presentationTimestamps){let y=r.presentationTimestampIndexMap[e];g(y!==void 0),y<r.presentationTimestamps.length-1&&(x=r.presentationTimestamps[y+1].presentationTimestamp-i)}return{presentationTimestamp:i,duration:x,sampleOffset:h,sampleSize:c,chunkOffset:m,chunkSize:p,isKeyFrame:r.keySampleIndices?Ct(r.keySampleIndices,e,y=>y)!==-1:!0}},Tp=(r,e)=>{if(!r.keySampleIndices)return e+1;let t=W(r.keySampleIndices,e,n=>n);return r.keySampleIndices[t+1]??-1},Ts=(r,e)=>{r.startTimestamp+=e,r.endTimestamp+=e;for(let t of r.samples)t.presentationTimestamp+=e;for(let t of r.presentationTimestamps)t.presentationTimestamp+=e},wp=r=>{let[e,,,t]=r,n=Math.hypot(e,t),o=e/n,i=t/n,s=-Math.atan2(i,o)*(180/Math.PI);return Number.isFinite(s)?s:0},Pc=r=>r.sampleSizes.length===0;var w;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Duration=17545]="Duration",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.MuxingApp=19840]="MuxingApp",r[r.WritingApp=22337]="WritingApp",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.TrackNumber=215]="TrackNumber",r[r.TrackUID=29637]="TrackUID",r[r.TrackType=131]="TrackType",r[r.FlagEnabled=185]="FlagEnabled",r[r.FlagDefault=136]="FlagDefault",r[r.FlagForced=21930]="FlagForced",r[r.FlagOriginal=21934]="FlagOriginal",r[r.FlagHearingImpaired=21931]="FlagHearingImpaired",r[r.FlagVisualImpaired=21932]="FlagVisualImpaired",r[r.FlagCommentary=21935]="FlagCommentary",r[r.FlagLacing=156]="FlagLacing",r[r.Name=21358]="Name",r[r.Language=2274716]="Language",r[r.LanguageBCP47=2274717]="LanguageBCP47",r[r.CodecID=134]="CodecID",r[r.CodecPrivate=25506]="CodecPrivate",r[r.CodecDelay=22186]="CodecDelay",r[r.SeekPreRoll=22203]="SeekPreRoll",r[r.DefaultDuration=2352003]="DefaultDuration",r[r.Video=224]="Video",r[r.PixelWidth=176]="PixelWidth",r[r.PixelHeight=186]="PixelHeight",r[r.AlphaMode=21440]="AlphaMode",r[r.Audio=225]="Audio",r[r.SamplingFrequency=181]="SamplingFrequency",r[r.Channels=159]="Channels",r[r.BitDepth=25188]="BitDepth",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.Block=161]="Block",r[r.BlockAdditions=30113]="BlockAdditions",r[r.BlockMore=166]="BlockMore",r[r.BlockAdditional=165]="BlockAdditional",r[r.BlockAddID=238]="BlockAddID",r[r.BlockDuration=155]="BlockDuration",r[r.ReferenceBlock=251]="ReferenceBlock",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.Colour=21936]="Colour",r[r.MatrixCoefficients=21937]="MatrixCoefficients",r[r.TransferCharacteristics=21946]="TransferCharacteristics",r[r.Primaries=21947]="Primaries",r[r.Range=21945]="Range",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPoseRoll=30325]="ProjectionPoseRoll",r[r.Attachments=423732329]="Attachments",r[r.AttachedFile=24999]="AttachedFile",r[r.FileDescription=18046]="FileDescription",r[r.FileName=18030]="FileName",r[r.FileMediaType=18016]="FileMediaType",r[r.FileData=18012]="FileData",r[r.FileUID=18094]="FileUID",r[r.Chapters=272869232]="Chapters",r[r.Tags=307544935]="Tags",r[r.Tag=29555]="Tag",r[r.Targets=25536]="Targets",r[r.TargetTypeValue=26826]="TargetTypeValue",r[r.TargetType=25546]="TargetType",r[r.TagTrackUID=25541]="TagTrackUID",r[r.TagEditionUID=25545]="TagEditionUID",r[r.TagChapterUID=25540]="TagChapterUID",r[r.TagAttachmentUID=25542]="TagAttachmentUID",r[r.SimpleTag=26568]="SimpleTag",r[r.TagName=17827]="TagName",r[r.TagLanguage=17530]="TagLanguage",r[r.TagString=17543]="TagString",r[r.TagBinary=17541]="TagBinary",r[r.ContentEncodings=28032]="ContentEncodings",r[r.ContentEncoding=25152]="ContentEncoding",r[r.ContentEncodingOrder=20529]="ContentEncodingOrder",r[r.ContentEncodingScope=20530]="ContentEncodingScope",r[r.ContentCompression=20532]="ContentCompression",r[r.ContentCompAlgo=16980]="ContentCompAlgo",r[r.ContentCompSettings=16981]="ContentCompSettings",r[r.ContentEncryption=20533]="ContentEncryption"})(w||(w={}));var Cp=[w.EBML,w.Segment],dr=[w.SeekHead,w.Info,w.Cluster,w.Tracks,w.Cues,w.Attachments,w.Chapters,w.Tags],fn=[...Cp,...dr];var Ps=8,Te=2,Ie=2*Ps,_s=r=>{let e=R(r);if(r.skip(-1),e===0)return null;let t=1,n=128;for(;(e&n)===0;)t++,n>>=1;return t},pr=r=>{let e=R(r);if(e===0)return null;let t=1,n=128;for(;(e&n)===0;)t++,n>>=1;let o=e&n-1;for(let i=1;i<t;i++)o*=256,o+=R(r);return o},q=(r,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let n=0;n<e;n++)t*=256,t+=R(r);return t},Ic=(r,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let t=0n;for(let n=0;n<e;n++)t<<=8n,t+=BigInt(R(r));return t};var yo=r=>{let e=_s(r);return e===null?null:q(r,e)},Is=r=>{let e=R(r);return e===255?e=null:(r.skip(-1),e=pr(r),e===72057594037927940&&(e=null)),e},Ae=r=>{let e=yo(r);if(e===null)return null;let t=Is(r);return{id:e,size:t}},dt=(r,e)=>{let t=B(r,e),n=0;for(;n<e&&t[n]!==0;)n+=1;return String.fromCharCode(...t.subarray(0,n))},hr=(r,e)=>{let t=B(r,e),n=0;for(;n<e&&t[n]!==0;)n+=1;return ce.decode(t.subarray(0,n))},bo=(r,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?Ac(r):vo(r)},So=async(r,e,t,n)=>{let o=new Set(t),i=e;for(;n===null||i<n;){let s=r.requestSliceRange(i,Te,Ie);if(s instanceof Promise&&(s=await s),!s)break;let a=Ae(s);if(!a)break;if(o.has(a.id))return{pos:i,found:!0};$e(a.size),i=s.filePos+a.size}return{pos:n!==null&&n>i?n:i,found:!1}},As=async(r,e,t,n)=>{let i=new Set(t),s=e;for(;s<n;){let a=r.requestSliceRange(s,0,Math.min(65536,n-s));if(a instanceof Promise&&(a=await a),!a||a.length<Ps)break;for(let c=0;c<a.length-Ps;c++){a.filePos=s;let l=yo(a);if(l!==null&&i.has(l))return s;s++}}return null},Fe={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 $e(r){if(r===null)throw new Error("Undefined element size is used in a place where it is not supported.")}var Fc=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isWebM?"webm":"x-matroska");if(r.codecStrings.length>0){let n=[...new Set(r.codecStrings.filter(Boolean))];t+=`; codecs="${n.join(", ")}"`}return t};var Qe;(function(r){r[r.None=0]="None",r[r.Xiph=1]="Xiph",r[r.FixedSize=2]="FixedSize",r[r.Ebml=3]="Ebml"})(Qe||(Qe={}));var To;(function(r){r[r.Block=1]="Block",r[r.Private=2]="Private",r[r.Next=4]="Next"})(To||(To={}));var mn;(function(r){r[r.Zlib=0]="Zlib",r[r.Bzlib=1]="Bzlib",r[r.lzo1x=2]="lzo1x",r[r.HeaderStripping=3]="HeaderStripping"})(mn||(mn={}));var Fs=[{id:w.SeekHead,flag:"seekHeadSeen"},{id:w.Info,flag:"infoSeen"},{id:w.Tracks,flag:"tracksSeen"},{id:w.Cues,flag:"cuesSeen"}],Ec=10*2**20,wo=class extends me{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(t=>t.inputTrack))}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),t=await Promise.all(e.map(n=>n.getCodecParameterString()));return Fc({isWebM:this.isWebM,hasVideo:this.segments.some(n=>n.tracks.some(o=>o.info?.type==="video")),hasAudio:this.segments.some(n=>n.tracks.some(o=>o.info?.type==="audio")),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let t of this.segments)t.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(let t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,Te,Ie);if(t instanceof Promise&&(t=await t),!t)break;let n=Ae(t);if(!n)break;let o=n.id,i=n.size,s=t.filePos;if(o===w.EBML){$e(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 So(this.reader,s,fn,this.reader.fileSize)).pos-s);let a=de(this.segments);a&&(a.elementEndPos=s+i)}$e(i),e=s+i}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===null?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let a=this.reader.requestSliceRange(n,Te,Ie);if(a instanceof Promise&&(a=await a),!a)break;let c=n,l=Ae(a);if(!l||!dr.includes(l.id)&&l.id!==w.Void){let p=await As(this.reader,c,dr,Math.min(this.currentSegment.elementEndPos??1/0,c+Ec));if(p){n=p;continue}else break}let{id:f,size:u}=l,m=a.filePos,d=Fs.findIndex(p=>p.id===f);if(d!==-1){let p=Fs[d].flag;this.currentSegment[p]=!0,$e(u);let h=this.reader.requestSlice(m,u);h instanceof Promise&&(h=await h),h&&this.readContiguousElements(h)}else if(f===w.Tags||f===w.Attachments){f===w.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,$e(u);let p=this.reader.requestSlice(m,u);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(f===w.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(u===null)break;n=m+u}if(this.currentSegment.seekEntries.sort((a,c)=>a.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(let a of this.currentSegment.seekEntries){let c=Fs.find(p=>p.id===a.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+a.segmentPosition,Te,Ie);if(l instanceof Promise&&(l=await l),!l)continue;let f=Ae(l);if(!f)continue;let{id:u,size:m}=f;if(u!==c.id)continue;$e(m),this.currentSegment[c.flag]=!0;let d=this.reader.requestSlice(l.filePos,m);d instanceof Promise&&(d=await d),d&&this.readContiguousElements(d)}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],f=a.cuePoints[c+1];l.time===f.time&&(a.cuePoints.splice(c+1,1),c--)}}let i=null,s=-1/0;for(let a of this.currentSegment.tracks)a.cuePoints.length>s&&(s=a.cuePoints.length,i=a);for(let a of this.currentSegment.tracks)a.cuePoints.length===0&&(a.cuePoints=i.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let n=this.reader.requestSliceRange(e,Te,Ie);n instanceof Promise&&(n=await n),g(n);let o=e,i=Ae(n);g(i);let s=i.id;g(s===w.Cluster);let a=i.size,c=n.filePos;a===null&&(a=(await So(this.reader,c,fn,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,a);l instanceof Promise&&(l=await l);let f={segment:t,elementStartPos:o,elementEndPos:c+a,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=f,l){let u=this.readContiguousElements(l,fn);f.elementEndPos=u}for(let[,u]of f.trackData){let m=u.track;g(u.blocks.length>0);let d=!1;for(let y=0;y<u.blocks.length;y++){let v=u.blocks[y];v.timestamp+=f.timestamp,d||=v.lacing!==Qe.None}u.presentationTimestamps=u.blocks.map((y,v)=>({timestamp:y.timestamp,blockIndex:v})).sort((y,v)=>y.timestamp-v.timestamp);for(let y=0;y<u.presentationTimestamps.length;y++){let v=u.presentationTimestamps[y],S=u.blocks[v.blockIndex];if(u.firstKeyFrameTimestamp===null&&S.isKeyFrame&&(u.firstKeyFrameTimestamp=S.timestamp),y<u.presentationTimestamps.length-1){let C=u.presentationTimestamps[y+1];S.duration=C.timestamp-S.timestamp}else S.duration===0&&m.defaultDuration!=null&&S.lacing===Qe.None&&(S.duration=m.defaultDuration)}d&&(this.expandLacedBlocks(u.blocks,m),u.presentationTimestamps=u.blocks.map((y,v)=>({timestamp:y.timestamp,blockIndex:v})).sort((y,v)=>y.timestamp-v.timestamp));let p=u.blocks[u.presentationTimestamps[0].blockIndex],h=u.blocks[de(u.presentationTimestamps).blockIndex];u.startTimestamp=p.timestamp,u.endTimestamp=h.timestamp+h.duration;let x=W(m.clusterPositionCache,u.startTimestamp,y=>y.startTimestamp);(x===-1||m.clusterPositionCache[x].elementStartPos!==o)&&m.clusterPositionCache.splice(x+1,0,{elementStartPos:f.elementStartPos,startTimestamp:u.startTimestamp})}return t.lastReadCluster=f,f}getTrackDataInCluster(e,t){let n=e.trackData.get(t);if(!n){let o=e.segment.tracks.find(i=>i.id===t);if(!o)return null;n={track:o,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,n)}return n}expandLacedBlocks(e,t){for(let n=0;n<e.length;n++){let o=e[n];if(o.lacing===Qe.None)continue;o.decoded||(o.data=this.decodeBlockData(t,o.data),o.decoded=!0);let i=gr.tempFromBytes(o.data),s=[],a=R(i)+1;switch(o.lacing){case Qe.Xiph:{let l=0;for(let f=0;f<a-1;f++){let u=0;for(;i.bufferPos<i.length;){let m=R(i);if(u+=m,m<255){s.push(u),l+=u;break}}}s.push(i.length-(i.bufferPos+l))}break;case Qe.FixedSize:{let l=i.length-1,f=Math.floor(l/a);for(let u=0;u<a;u++)s.push(f)}break;case Qe.Ebml:{let l=pr(i);g(l!==null);let f=l;s.push(f);let u=f;for(let m=1;m<a-1;m++){let d=i.bufferPos,p=pr(i);g(p!==null);let h=p,y=(1<<(i.bufferPos-d)*7-1)-1,v=h-y;f+=v,s.push(f),u+=f}s.push(i.length-(i.bufferPos+u))}break;default:g(!1)}g(s.length===a),e.splice(n,1);let c=o.duration||a*(t.defaultDuration??0);for(let l=0;l<a;l++){let f=s[l],u=B(i,f),m=o.timestamp+c*l/a,d=c/a;e.splice(n+l,0,{timestamp:m,duration:d,isKeyFrame:o.isKeyFrame,data:u,lacing:Qe.None,decoded:!0,mainAdditional:o.mainAdditional})}n+=a,n--}}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 n=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,Te,Ie);if(n instanceof Promise&&(n=await n),!n)continue;let o=Ae(n);if(!o||o.id!==t.id)continue;let{size:i}=o;$e(i),g(!this.currentSegment),this.currentSegment=e;let s=this.reader.requestSlice(n.filePos,i);s instanceof Promise&&(s=await s),s&&this.readContiguousElements(s),this.currentSegment=null,t.id===w.Tags?e.tagsSeen=!0:t.id===w.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){let n=e.filePos;for(;e.filePos-n<=e.length-Te;){let o=e.filePos;if(!this.traverseElement(e,t))return o}return e.filePos}traverseElement(e,t){let n=Ae(e);if(!n||t&&t.includes(n.id))return!1;let{id:o,size:i}=n,s=e.filePos;switch($e(i),o){case w.DocType:this.isWebM=dt(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=q(e,i)}break;case w.SeekPosition:{let a=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!a)break;a.segmentPosition=q(e,i)}break;case w.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=q(e,i),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case w.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=bo(e,i)}break;case w.TrackEntry:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...xe},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:le,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(s,i)),this.currentTrack.decodingInstructions.some(a=>a.data?.type!=="decompress"||a.scope!==To.Block||a.data.algorithm!==mn.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===Fe.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Fe.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Fe.vp8?this.currentTrack.info.codec="vp8":c===Fe.vp9?this.currentTrack.info.codec="vp9":c===Fe.av1&&(this.currentTrack.info.codec="av1");let l=this.currentTrack,f=new Ne(this.input,new Es(l));this.currentTrack.inputTrack=f,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){c===Fe.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===Fe.mp3?this.currentTrack.info.codec="mp3":c===Fe.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Ft):c===Fe.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Fe.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,f=new se(this.input,new zs(l));this.currentTrack.inputTrack=f,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case w.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=q(e,i)}break;case w.TrackType:{if(!this.currentTrack)break;let a=q(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;q(e,i)||(this.currentSegment.tracks.pop(),this.currentTrack=null)}break;case w.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!q(e,i)}break;case w.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!q(e,i)}break;case w.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!q(e,i)}break;case w.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!q(e,i)}break;case w.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!q(e,i)}break;case w.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!q(e,i)}break;case w.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=dt(e,i)}break;case w.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=B(e,i)}break;case w.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*q(e,i)/1e9}break;case w.Name:{if(!this.currentTrack)break;this.currentTrack.name=hr(e,i)}break;case w.Language:{if(!this.currentTrack||this.currentTrack.languageCode!==le)break;this.currentTrack.languageCode=dt(e,i),Jn(this.currentTrack.languageCode)||(this.currentTrack.languageCode=le)}break;case w.LanguageBCP47:{if(!this.currentTrack)break;let c=dt(e,i).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=le}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=q(e,i)}break;case w.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=q(e,i)}break;case w.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=q(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=q(e,i),c=$n[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=q(e,i)===2}break;case w.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=q(e,i),c=Yn[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=q(e,i),c=Kn[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=-bo(e,i);try{this.currentTrack.info.rotation=Xn(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=bo(e,i)}break;case w.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=q(e,i)}break;case w.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=q(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=q(e,i);break;case w.CueTrackPositions:{if(this.currentCueTime===null)break;g(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=q(e,i)}break;case w.CueClusterPosition:{let a=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!a)break;g(this.currentSegment),a.clusterPosition=this.currentSegment.dataStartPos+q(e,i)}break;case w.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=q(e,i)}break;case w.SimpleBlock:{if(!this.currentCluster)break;let a=pr(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let l=un(e),f=R(e),u=f>>1&3,m=!!(f&128);c.track.info?.type==="audio"&&c.track.info.codec&&(m=!0);let d=B(e,i-(e.filePos-s)),p=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:m,data:d,lacing:u,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=pr(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let l=un(e),u=R(e)>>1&3,m=B(e,i-(e.filePos-s)),d=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:m,lacing:u,decoded:!d,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=B(e,i)}break;case w.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=q(e,i)}break;case w.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=q(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:q(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=hr(e,i);break;case w.TagString:{if(!this.currentSimpleTagName)break;let a=hr(e,i);this.processTagValue(this.currentSimpleTagName,a)}break;case w.TagBinary:{if(!this.currentSimpleTagName)break;let a=B(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 ro(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 f=c.toLowerCase();f.startsWith("cover.")?l="coverFront":f.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=Ic(e,i)}break;case w.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=hr(e,i)}break;case w.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=dt(e,i)}break;case w.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=B(e,i)}break;case w.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=hr(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:To.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=q(e,i)}break;case w.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=q(e,i)}break;case w.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:mn.Zlib,settings:null},this.readContiguousElements(e.slice(s,i))}break;case w.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=q(e,i)}break;case w.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=B(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){g(e.decodingInstructions.length>0);let n=t;for(let o of e.decodingInstructions)switch(g(o.data),o.data.type){case"decompress":switch(o.data.algorithm){case mn.HeaderStripping:if(o.data.settings&&o.data.settings.length>0){let i=o.data.settings,s=new Uint8Array(i.length+n.length);s.set(i,0),s.set(n,i.length),n=s}break;default:}break;default:}return n}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=t,typeof t=="string")switch(e.toLowerCase()){case"title":n.title??=t;break;case"description":n.description??=t;break;case"artist":n.artist??=t;break;case"album":n.album??=t;break;case"album_artist":n.albumArtist??=t;break;case"genre":n.genre??=t;break;case"comment":n.comment??=t;break;case"lyrics":n.lyrics??=t;break;case"date":{let o=new Date(t);Number.isNaN(o.getTime())||(n.date??=o)}break;case"track_number":case"part_number":{let o=t.split("/"),i=Number.parseInt(o[0],10),s=o[1]&&Number.parseInt(o[1],10);Number.isInteger(i)&&i>0&&(n.trackNumber??=i),s&&Number.isInteger(s)&&s>0&&(n.tracksTotal??=s)}break;case"disc_number":case"disc":{let o=t.split("/"),i=Number.parseInt(o[0],10),s=o[1]&&Number.parseInt(o[1],10);Number.isInteger(i)&&i>0&&(n.discNumber??=i),s&&Number.isInteger(s)&&s>0&&(n.discsTotal??=s)}break}}},Co=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 _t(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,o=>{let i=o.trackData.get(this.internalTrack.id);if(!i)return{blockIndex:-1,correctBlockFound:!1};let s=W(i.presentationTimestamps,n,l=>l.timestamp),a=s!==-1?i.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&n<i.endTimestamp;return{blockIndex:a,correctBlockFound:c}},n,n,t)}async getNextPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,o=>{if(o===n.cluster){let i=o.trackData.get(this.internalTrack.id);if(n.blockIndex+1<i.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(o.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,o=>{let i=o.trackData.get(this.internalTrack.id);if(!i)return{blockIndex:-1,correctBlockFound:!1};let s=Zn(i.presentationTimestamps,l=>i.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=n),a=s!==-1?i.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&n<i.endTimestamp;return{blockIndex:a,correctBlockFound:c}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,o=>{if(o===n.cluster){let s=o.trackData.get(this.internalTrack.id).blocks.findIndex((a,c)=>a.isKeyFrame&&c>n.blockIndex);if(s!==-1)return{blockIndex:s,correctBlockFound:!0}}else{let i=o.trackData.get(this.internalTrack.id);if(i&&i.firstKeyFrameTimestamp!==null){let s=i.blocks.findIndex(a=>a.isKeyFrame);return g(s!==-1),{blockIndex:s,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,n){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).blocks[t];g(i),i.decoded||(i.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,i.data),i.decoded=!0);let s=n.metadataOnly?oe:i.data,a=i.timestamp/this.internalTrack.segment.timestampFactor,c=i.duration/this.internalTrack.segment.timestampFactor,l={};i.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=n.metadataOnly?oe:i.mainAdditional,l.alphaByteLength=i.mainAdditional.byteLength);let f=new Z(s,i.isKeyFrame?"key":"delta",a,c,e.dataStartPos+t,i.data.byteLength,l);return this.packetToClusterLocation.set(f,{cluster:e,blockIndex:t}),f}async performClusterLookup(e,t,n,o,i){let{demuxer:s,segment:a}=this.internalTrack,c=null,l=null,f=-1;if(e){let{blockIndex:y,correctBlockFound:v}=t(e);if(v)return this.fetchPacketInCluster(e,y,i);y!==-1&&(l=e,f=y)}let u=W(this.internalTrack.cuePoints,n,y=>y.time),m=u!==-1?this.internalTrack.cuePoints[u]:null,d=W(this.internalTrack.clusterPositionCache,n,y=>y.startTimestamp),p=d!==-1?this.internalTrack.clusterPositionCache[d]:null,h=Math.max(m?.clusterPosition??0,p?.elementStartPos??0)||null,x;for(e?h===null||e.elementStartPos>=h?(x=e.elementEndPos,c=e):x=h:x=h??a.clusterSeekStartPos;a.elementEndPos===null||x<=a.elementEndPos-Te;){if(c){let I=c.trackData.get(this.internalTrack.id);if(I&&I.startTimestamp>o)break}let y=s.reader.requestSliceRange(x,Te,Ie);if(y instanceof Promise&&(y=await y),!y)break;let v=x,S=Ae(y);if(!S||!dr.includes(S.id)&&S.id!==w.Void){let I=await As(s.reader,v,dr,Math.min(a.elementEndPos??1/0,v+Ec));if(I){x=I;continue}else break}let C=S.id,_=S.size,T=y.filePos;if(C===w.Cluster){c=await s.readCluster(v,a),_=c.elementEndPos-T;let{blockIndex:I,correctBlockFound:M}=t(c);if(M)return this.fetchPacketInCluster(c,I,i);I!==-1&&(l=c,f=I)}_===null&&(g(C!==w.Cluster),_=(await So(s.reader,T,fn,a.elementEndPos)).pos-T);let E=T+_;if(a.elementEndPos===null){let I=s.reader.requestSliceRange(E,Te,Ie);if(I instanceof Promise&&(I=await I),!I)break;if(yo(I)===w.Segment){a.elementEndPos=E;break}}x=E}if(m&&(!l||l.elementStartPos<m.clusterPosition)){let y=this.internalTrack.cuePoints[u-1];g(!y||y.time<m.time);let v=y?.time??-1/0;return this.performClusterLookup(null,t,v,o,i)}return l?this.fetchPacketInCluster(l,f,i):null}},Es=class extends Co{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:no({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?cc(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?uc(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?co(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?lo(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}},zs=class extends Co{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:oo({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 kp=[44100,48e3,32e3],Pp=[-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],zc=1483304551,Dc=1231971951,_p=(r,e,t,n,o)=>e===0?0:e===1?Math.floor(144*t/(n<<r))+o:e===2?Math.floor(144*t/n)+o:(Math.floor(12*t/n)+o)*4,Oc=(r,e)=>r===3?e===3?21:36:e===3?13:21,Rc=(r,e)=>{let t=r>>>24,n=r>>>16&255,o=r>>>8&255,i=r&255;if(t!==255&&n!==255&&o!==255&&i!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((n&224)!==224)return{header:null,bytesAdvanced:1};let s=0,a=0;n&16?s=n&8?0:1:(s=1,a=1);let c=n>>3&3,l=n>>1&3,f=o>>4&15,u=(o>>2&3)%3,m=o>>1&1,d=i>>6&3,p=i>>4&3,h=i>>3&1,x=i>>2&1,y=i&3,v=Pp[s*16*4+l*16+f];if(v===-1)return{header:null,bytesAdvanced:1};let S=v*1e3,C=kp[u]>>s+a,_=_p(s,l,S,C,m);if(e!==null&&e<_)return{header:null,bytesAdvanced:1};let T;return c===3?T=l===3?384:1152:l===3?T=384:l===2?T=1152:T=576,{header:{totalSize:_,mpegVersionId:c,layer:l,bitrate:S,frequencyIndex:u,sampleRate:C,channel:d,modeExtension:p,copyright:h,original:x,emphasis:y,audioSamplesInFrame:T},bytesAdvanced:1}};var ko=r=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=r&e,e>>=8;return t};var vr;(function(r){r[r.Unsynchronisation=128]="Unsynchronisation",r[r.ExtendedHeader=64]="ExtendedHeader",r[r.ExperimentalIndicator=32]="ExperimentalIndicator",r[r.Footer=16]="Footer"})(vr||(vr={}));var yr;(function(r){r[r.ISO_8859_1=0]="ISO_8859_1",r[r.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",r[r.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",r[r.UTF_8=3]="UTF_8"})(yr||(yr={}));var dn=128,Sr=10,br=["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"],Mc=(r,e)=>{let t=r.filePos;e.raw??={},e.raw.TAG??=B(r,dn-3),r.filePos=t;let n=xr(r,30);n&&(e.title??=n);let o=xr(r,30);o&&(e.artist??=o);let i=xr(r,30);i&&(e.album??=i);let s=xr(r,4),a=Number.parseInt(s,10);Number.isInteger(a)&&a>0&&(e.date??=new Date(a,0,1));let c=B(r,30),l;if(c[28]===0&&c[29]!==0){let u=c[29];u>0&&(e.trackNumber??=u),r.skip(-30),l=xr(r,28),r.skip(2)}else r.skip(-30),l=xr(r,30);l&&(e.comment??=l);let f=R(r);f<br.length&&(e.genre??=br[f])},xr=(r,e)=>{let t=B(r,e),n=It(t.indexOf(0),t.length),o=t.subarray(0,n),i="";for(let s=0;s<o.length;s++)i+=String.fromCharCode(o[s]);return i.trimEnd()},Bt=r=>{let e=r.filePos,t=J(r,3),n=R(r),o=R(r),i=R(r),s=F(r);if(t!=="ID3"||n===255||o===255||(s&2155905152)!==0)return r.filePos=e,null;let a=ko(s);return{majorVersion:n,revision:o,flags:i,size:a}},Po=(r,e,t)=>{if(![2,3,4].includes(e.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let n=B(r,e.size),o=new Ds(e,n);if(e.flags&vr.Footer&&o.removeFooter(),e.flags&vr.Unsynchronisation&&e.majorVersion===3&&o.ununsynchronizeAll(),e.flags&vr.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,f=!1;if(e.majorVersion===3?(c=!!(i.flags&64),l=!!(i.flags&128)):e.majorVersion===4&&(c=!!(i.flags&4),l=!!(i.flags&8),f=!!(i.flags&2)||!!(e.flags&vr.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(f&&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("/"),d=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(d)&&d>0&&(t.trackNumber??=d),p&&Number.isInteger(p)&&p>0&&(t.tracksTotal??=p)}break;case"TPOS":case"TPA":{let m=o.readId3V2EncodingAndText(a).split("/"),d=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(d)&&d>0&&(t.discNumber??=d),p&&Number.isInteger(p)&&p>0&&(t.discsTotal??=p)}break;case"TCON":case"TCO":{let u=o.readId3V2EncodingAndText(a),m=/^\((\d+)\)/.exec(u);if(m){let d=Number.parseInt(m[1]);if(br[d]!==void 0){t.genre??=br[d];break}}if(m=/^\d+$/.exec(u),m){let d=Number.parseInt(m[0]);if(br[d]!==void 0){t.genre??=br[d];break}}t.genre??=u}break;case"TDRC":case"TDAT":{let u=o.readId3V2EncodingAndText(a),m=new Date(u);Number.isNaN(m.getTime())||(t.date??=m)}break;case"TYER":case"TYE":{let u=o.readId3V2EncodingAndText(a),m=Number.parseInt(u,10);Number.isInteger(m)&&(t.date??=new Date(m,0,1))}break;case"USLT":case"ULT":{let u=o.readU8();o.pos+=3,o.readId3V2Text(u,a),t.lyrics??=o.readId3V2Text(u,a)}break;case"COMM":case"COM":{let u=o.readU8();o.pos+=3,o.readId3V2Text(u,a),t.comment??=o.readId3V2Text(u,a)}break;case"APIC":case"PIC":{let u=o.readId3V2TextEncoding(),m;if(e.majorVersion===2){let x=o.readAscii(3);m=x==="PNG"?"image/png":x==="JPG"?"image/jpeg":"image/*"}else m=o.readId3V2Text(u,a);let d=o.readU8(),p=o.readId3V2Text(u,a).trimEnd(),h=a-o.pos;if(h>=0){let x=o.readBytes(h);t.images||(t.images=[]),t.images.push({data:x,mimeType:m,kind:d===3?"coverFront":d===4?"coverBack":"unknown",description:p})}}break;default:o.pos+=i.size;break}o.pos=a}},Ds=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t<this.bytes.length;t++){let n=this.bytes[t];e.push(n),n===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let n=[];for(let s=e;s<t;s++){let a=this.bytes[s];n.push(a),a===255&&s!==t-1&&this.bytes[s+1]===0&&s++}let o=this.bytes.subarray(0,e),i=this.bytes.subarray(t);this.bytes=new Uint8Array(o.length+n.length+i.length),this.bytes.set(o,0),this.bytes.set(n,o.length),this.bytes.set(i,o.length+n.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-Sr),this.view=new DataView(this.bytes.buffer)}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+1);return this.pos+=3,e*256+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let n=0;n<e;n++)t+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);if(e==="\0\0\0")return null;let t=this.readU24();return{id:e,size:t,flags:0}}else{let e=this.readAscii(4);if(e==="\0\0\0\0")return null;let t=this.readU32(),n=this.header.majorVersion===4?ko(t):t,o=this.readU16(),i=this.pos,s=a=>{let c=this.pos+a;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=a;let l=this.readAscii(4);if(l!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(l))return!1}return!0};if(!s(n)){let a=this.header.majorVersion===4?t:ko(t);s(a)&&(n=a)}return this.pos=i,{id:e,size:n,flags:o}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let n=this.pos,o=this.readBytes(t-this.pos);switch(e){case yr.ISO_8859_1:{let i="";for(let s=0;s<o.length;s++){let a=o[s];if(a===0){this.pos=n+s+1;break}i+=String.fromCharCode(a)}return i}case yr.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=n+Math.min(s+2,o.length),i.decode(o.subarray(2,s))}else if(o[0]===254&&o[1]===255){let i=new TextDecoder("utf-16be"),s=It(o.findIndex((a,c)=>a===0&&o[c+1]===0&&c%2===0),o.length);return this.pos=n+Math.min(s+2,o.length),i.decode(o.subarray(2,s))}else{let i=It(o.findIndex(s=>s===0),o.length);return this.pos=n+Math.min(i+1,o.length),ce.decode(o.subarray(0,i))}case yr.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=n+Math.min(s+2,o.length),i.decode(o.subarray(0,s))}case yr.UTF_8:{let i=It(o.findIndex(s=>s===0),o.length);return this.pos=n+Math.min(i+1,o.length),ce.decode(o.subarray(0,i))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}};var pn=async(r,e,t)=>{let n=e;for(;t===null||n<t;){let o=r.requestSlice(n,4);if(o instanceof Promise&&(o=await o),!o)break;let i=F(o),s=Rc(i,r.fileSize!==null?r.fileSize-n:null);if(s.header)return{header:s.header,startPos:n};n+=s.bytesAdvanced}return null};var _o=class extends me{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new Me,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 se(this.input,new Os(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,Sr);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}let c=Bt(a);if(!c)break;this.lastLoadedPos=a.filePos+c.size}let e=await pn(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let n=Oc(t.mpegVersionId,t.channel),o=this.reader.requestSlice(e.startPos+n,4);if(o instanceof Promise&&(o=await o),o){let a=F(o);if(a===zc||a===Dc)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 g(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0,n=!1;for(;;){let o=this.reader.requestSlice(t,Sr);if(o instanceof Promise&&(o=await o),!o)break;let i=Bt(o);if(!i)break;n=!0;let s=this.reader.requestSlice(o.filePos,i.size);if(s instanceof Promise&&(s=await s),!s)break;Po(s,i,this.metadataTags),t=o.filePos+i.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=dn){let o=this.reader.requestSlice(this.reader.fileSize-dn,dn);o instanceof Promise&&(o=await o),g(o),J(o,3)==="TAG"&&Mc(o,this.metadataTags)}return this.metadataTags}finally{e()}}},Os=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return g(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 le}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return g(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return g(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...xe}}async getDecoderConfig(){return g(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let o;if(t.metadataOnly)o=oe;else{let i=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(i instanceof Promise&&(i=await i),!i)return null;o=B(i,n.dataSize)}return new Z(o,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let o=Ct(this.demuxer.loadedSamples,e.timestamp,s=>s.timestamp);if(o===-1)throw new Error("Packet was not created from this track.");let i=o+1;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let o=W(this.demuxer.loadedSamples,e,i=>i.timestamp);if(o===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(o,t);if(o>=0&&o+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(o,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Rs=1399285583,Ip=79764919,Uc=new Uint32Array(256);for(let r=0;r<256;r++){let e=r<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^Ip:e<<1;Uc[r]=e>>>0&4294967295}var Nc=r=>{let e=j(r),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let n=0;for(let o=0;o<r.length;o++){let i=r[o];n=(n<<8^Uc[n>>>24^i])>>>0}return e.setUint32(22,t,!0),n},Lc=(r,e,t)=>{let n=0,o=null;if(r.length>0)if(e.codec==="vorbis"){g(e.vorbisInfo);let i=e.vorbisInfo.modeBlockflags.length,a=(1<<Ja(i-1))-1<<1,c=(r[0]&a)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=t,f=e.vorbisInfo.modeBlockflags[c];if(o=e.vorbisInfo.blocksizes[f],f===1){let u=(a|1)+1,m=r[0]&u?1:0;l=e.vorbisInfo.blocksizes[m]}n=l!==null?l+o>>2:0}else e.codec==="opus"&&(n=dc(r).durationInSamples);return{durationInSamples:n,vorbisBlockSize:o}},Vc=r=>{let e="audio/ogg";if(r.codecStrings){let t=[...new Set(r.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};var pt=27,Nt=282,Gc=Nt+65025,Tr=r=>{let e=r.filePos;if(Ut(r)!==Rs)return null;r.skip(1);let n=R(r),o=Hc(r),i=Ut(r),s=Ut(r),a=Ut(r),c=R(r),l=new Uint8Array(c);for(let d=0;d<c;d++)l[d]=R(r);let f=27+c,u=l.reduce((d,p)=>d+p,0),m=f+u;return{headerStartPos:e,totalSize:m,dataStartPos:e+f,dataSize:u,headerType:n,granulePosition:o,serialNumber:i,sequenceNumber:s,checksum:a,lacingValues:l}},qc=(r,e)=>{for(;r.filePos<e-3;){let t=Ut(r),n=t&255,o=t>>>8&255,i=t>>>16&255,s=t>>>24&255,a=79;if(!(n!==a&&o!==a&&i!==a&&s!==a)){if(r.skip(-4),t===Rs)return!0;r.skip(1)}}return!1};var Io=class extends me{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,pt,Nt);if(t instanceof Promise&&(t=await t),!t)break;let n=Tr(t);if(!n||!!!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let t of this.bitstreams){let n=await this.readPacket(t.bosPage,0);n&&(n.data.byteLength>=7&&n.data[0]===1&&n.data[1]===118&&n.data[2]===111&&n.data[3]===114&&n.data[4]===98&&n.data[5]===105&&n.data[6]===115?await this.readVorbisMetadata(n,t):n.data.byteLength>=8&&n.data[0]===79&&n.data[1]===112&&n.data[2]===117&&n.data[3]===115&&n.data[4]===72&&n.data[5]===101&&n.data[6]===97&&n.data[7]===100&&await this.readOpusMetadata(n,t),t.codecInfo.codec!==null&&this.tracks.push(new se(this.input,new Ms(t,this))))}})()}async readVorbisMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let o=await this.readPacket(n.startPage,n.startSegmentIndex);if(!o||(n=await this.findNextPacketStart(o),!n))return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i||o.data[0]!==3||i.data[0]!==5)return;let s=[],a=u=>{for(;s.push(Math.min(255,u)),!(u<255);)u-=255};a(e.data.length),a(o.data.length);let c=new Uint8Array(1+s.length+e.data.length+o.data.length+i.data.length);c[0]=2,c.set(s,1),c.set(e.data,1+s.length),c.set(o.data,1+s.length+e.data.length),c.set(i.data,1+s.length+e.data.length+o.data.length),t.codecInfo.codec="vorbis",t.description=c,t.lastMetadataPacket=i;let l=j(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);let f=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(f&15),1<<(f>>4)],modeBlockflags:pc(i.data).modeBlockflags},tn(o.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let o=await this.readPacket(n.startPage,n.startSegmentIndex);if(!o)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=o;let i=mc(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=Ft,t.codecInfo.opusInfo={preSkip:i.preSkip},tn(o.data.subarray(8),this.metadataTags)}async readPacket(e,t){g(t<e.lacingValues.length);let n=0;for(let u=0;u<t;u++)n+=e.lacingValues[u];let o=e,i=n,s=t,a=[];e:for(;;){let u=this.reader.requestSlice(o.dataStartPos,o.dataSize);u instanceof Promise&&(u=await u),g(u);let m=B(u,o.dataSize);for(;;){if(s===o.lacingValues.length){a.push(m.subarray(n,i));break}let p=o.lacingValues[s];if(i+=p,p<255){a.push(m.subarray(n,i));break e}s++}let d=o.headerStartPos+o.totalSize;for(;;){let p=this.reader.requestSliceRange(d,pt,Nt);if(p instanceof Promise&&(p=await p),!p)return null;let h=Tr(p);if(!h)return null;if(o=h,o.serialNumber===e.serialNumber)break;d=o.headerStartPos+o.totalSize}n=0,i=0,s=0}let c=a.reduce((u,m)=>u+m.length,0),l=new Uint8Array(c),f=0;for(let u=0;u<a.length;u++){let m=a[u];l.set(m,f),f+=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 n=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let o=this.reader.requestSliceRange(n,pt,Nt);if(o instanceof Promise&&(o=await o),!o)return null;let i=Tr(o);if(!i)return null;if(i.serialNumber===e.endPage.serialNumber)return{startPage:i,startSegmentIndex:0};n=i.headerStartPos+i.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(t=>t.getCodecParameterString()));return Vc({codecStrings:e.filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(n=>n.computeDuration()));return Math.max(0,...t)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Ms=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new Me,this.internalSampleRate=e.codecInfo.codec==="opus"?Ft: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 g(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 le}getDisposition(){return{...xe}}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"?(g(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,n){if(!e)return null;let{durationInSamples:o,vorbisBlockSize:i}=Lc(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Z(n.metadataOnly?oe: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){g(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let n=0;this.bitstream.codecInfo.codec==="opus"&&(g(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let o=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(o,{timestampInSamples:n,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let n=this.encodedPacketToMetadata.get(e);if(!n)throw new Error("Packet was not created from this track.");let o=await this.demuxer.findNextPacketStart(n.packet);if(!o)return null;let i=n.timestampInSamples+n.durationInSamples,s=await this.demuxer.readPacket(o.startPage,o.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:i,vorbisLastBlocksize:n.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let n=_t(e*this.internalSampleRate);if(n===0)return this.getFirstPacket(t);if(n<0)return null;g(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 v=i.headerStartPos,S=Math.floor((v+s)/2),C=S;for(;;){let _=Math.min(C+Gc,s-pt),T=this.demuxer.reader.requestSlice(C,_-C);if(T instanceof Promise&&(T=await T),g(T),!qc(T,_)){s=S+pt;continue e}let I=this.demuxer.reader.requestSliceRange(T.filePos,pt,Nt);I instanceof Promise&&(I=await I),g(I);let M=Tr(I);g(M);let L=!1;if(M.serialNumber===this.bitstream.serialNumber)L=!0;else{let te=this.demuxer.reader.requestSlice(M.headerStartPos,M.totalSize);te instanceof Promise&&(te=await te),g(te);let Ee=B(te,M.totalSize);L=Nc(Ee)===M.checksum}if(!L){C=M.headerStartPos+4;continue}if(L&&M.serialNumber!==this.bitstream.serialNumber){C=M.headerStartPos+M.totalSize;continue}if(M.granulePosition===-1){C=M.headerStartPos+M.totalSize;continue}this.granulePositionToTimestampInSamples(M.granulePosition)>n?s=M.headerStartPos:(i=M,a.push(M));continue e}}let c=o.startPage;for(let v of a){if(v.granulePosition===i.granulePosition)break;(!c||v.headerStartPos>c.headerStartPos)&&(c=v)}let l=c,f=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===i.granulePosition);){let v=l.headerStartPos+l.totalSize,S=this.demuxer.reader.requestSliceRange(v,pt,Nt);S instanceof Promise&&(S=await S),g(S);let C=Tr(S);g(C),l=C,l.serialNumber===this.bitstream.serialNumber&&f.push(l)}g(l.granulePosition!==-1);let u=null,m,d,p=l,h=0;if(l.headerStartPos===o.startPage.headerStartPos)m=this.granulePositionToTimestampInSamples(0),d=!0,u=0;else{m=0,d=!1;for(let C=l.lacingValues.length-1;C>=0;C--)if(l.lacingValues[C]<255){u=C+1;break}if(u===null)throw new Error("Invalid page with granule position: no packets end on this page.");h=u-1;let v={data:oe,endPage:p,endSegmentIndex:h};if(await this.demuxer.findNextPacketStart(v)){let C=jc(f,l,u);g(C);let _=Wc(f,C.page,C.segmentIndex);_&&(l=_.page,u=_.segmentIndex)}else for(;;){let C=jc(f,l,u);if(!C)break;let _=Wc(f,C.page,C.segmentIndex);if(!_)break;if(l=_.page,u=_.segmentIndex,C.page.headerStartPos!==p.headerStartPos){p=C.page,h=C.segmentIndex;break}}}let x=null,y=null;for(;l!==null;){g(u!==null);let v=await this.demuxer.readPacket(l,u);if(!v)break;if(!(l.headerStartPos===o.startPage.headerStartPos&&u<o.startSegmentIndex)){let _=this.createEncodedPacketFromOggPacket(v,{timestampInSamples:m,vorbisLastBlocksize:y?.vorbisBlockSize??null},t);g(_);let T=this.encodedPacketToMetadata.get(_);if(g(T),!d&&v.endPage.headerStartPos===p.headerStartPos&&v.endSegmentIndex===h?(m=this.granulePositionToTimestampInSamples(l.granulePosition),d=!0,_=this.createEncodedPacketFromOggPacket(v,{timestampInSamples:m-T.durationInSamples,vorbisLastBlocksize:y?.vorbisBlockSize??null},t),g(_),T=this.encodedPacketToMetadata.get(_),g(T)):m+=T.durationInSamples,x=_,y=T,d&&(Math.max(m,0)>n||Math.max(T.timestampInSamples,0)===n))break}let C=await this.demuxer.findNextPacketStart(v);if(!C)break;l=C.startPage,u=C.startSegmentIndex}return x}async getPacketSequential(e,t){let n=await this.sequentialScanMutex.acquire();try{let o=_t(e*this.internalSampleRate);e=o/this.internalSampleRate;let i=W(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);g(l),this.sequentialScanCache.length>0&&g(de(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return s}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},Wc=(r,e,t)=>{let n=e,o=t;e:for(;;){for(o--,o;o>=0;o--)if(n.lacingValues[o]<255){o++;break e}if(g(o===-1),!(n.headerType&1)){o=0;break}let s=os(r,a=>a.headerStartPos<n.headerStartPos);if(!s)return null;n=s,o=n.lacingValues.length}if(g(o!==-1),o===n.lacingValues.length){let i=r[r.indexOf(n)+1];g(i),n=i,o=0}return{page:n,segmentIndex:o}},jc=(r,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};let n=os(r,o=>o.headerStartPos<e.headerStartPos);return n?{page:n,segmentIndex:n.lacingValues.length-1}:null};var Ze;(function(r){r[r.PCM=1]="PCM",r[r.IEEE_FLOAT=3]="IEEE_FLOAT",r[r.ALAW=6]="ALAW",r[r.MULAW=7]="MULAW",r[r.EXTENSIBLE=65534]="EXTENSIBLE"})(Ze||(Ze={}));var Ao=class extends me{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),g(e);let t=J(e,4),n=t!=="RIFX",o=t==="RF64",i=Je(e,n),s=o?this.reader.fileSize:Math.min(i+8,this.reader.fileSize??1/0);if(J(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,f=e.filePos;for(;s===null||f<s;){let m=this.reader.requestSlice(f,8);if(m instanceof Promise&&(m=await m),!m)break;let d=J(m,4),p=Je(m,n),h=m.filePos;if(o&&c===0&&d!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(d==="fmt ")await this.parseFmtChunk(h,p,n);else if(d==="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(d==="ds64"){let x=this.reader.requestSlice(h,p);if(x instanceof Promise&&(x=await x),!x)break;let y=Us(x,n);l=Us(x,n),s=Math.min(y+8,this.reader.fileSize??1/0)}else d==="LIST"?await this.parseListChunk(h,p,n):(d==="ID3 "||d==="id3 ")&&await this.parseId3Chunk(h,p);f=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 u=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/u)*u,this.tracks.push(new se(this.input,new Bs(this)))})()}async parseFmtChunk(e,t,n){let o=this.reader.requestSlice(e,t);if(o instanceof Promise&&(o=await o),!o)return;let i=Cr(o,n),s=Cr(o,n),a=Je(o,n);o.skip(4);let c=Cr(o,n),l;if(t===14?l=8:l=Cr(o,n),t>=18&&i!==357){let f=Cr(o,n),u=t-18;if(Math.min(u,f)>=22&&i===Ze.EXTENSIBLE){o.skip(6);let d=B(o,16);i=d[0]|d[1]<<8}}(i===Ze.MULAW||i===Ze.ALAW)&&(l=8),this.audioInfo={format:i,numberOfChannels:s,sampleRate:a,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}}async parseListChunk(e,t,n){let o=this.reader.requestSlice(e,t);if(o instanceof Promise&&(o=await o),!o)return;let i=J(o,4);if(i!=="INFO"&&i!=="INF0")return;let s=o.filePos;for(;s<=e+t-8;){o.filePos=s;let a=J(o,4),c=Je(o,n),l=B(o,c),f=0;for(let m=0;m<l.length&&l[m]!==0;m++)f++;let u=String.fromCharCode(...l.subarray(0,f));switch(this.metadataTags.raw??={},this.metadataTags.raw[a]=u,a){case"INAM":case"TITL":this.metadataTags.title??=u;break;case"TIT3":this.metadataTags.description??=u;break;case"IART":this.metadataTags.artist??=u;break;case"IPRD":this.metadataTags.album??=u;break;case"IPRT":case"ITRK":case"TRCK":{let m=u.split("/"),d=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(d)&&d>0&&(this.metadataTags.trackNumber??=d),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{let m=new Date(u);Number.isNaN(m.getTime())||(this.metadataTags.date??=m)}break;case"YEAR":{let m=Number.parseInt(u,10);Number.isInteger(m)&&m>0&&(this.metadataTags.date??=new Date(m,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=u;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=u;break}s+=8+c+(c&1)}}async parseId3Chunk(e,t){let n=this.reader.requestSlice(e,t);if(n instanceof Promise&&(n=await n),!n)return;let o=Bt(n);if(o){let i=n.slice(e+10,o.size);Po(i,o,this.metadataTags)}}getCodec(){if(g(this.audioInfo),this.audioInfo.format===Ze.MULAW)return"ulaw";if(this.audioInfo.format===Ze.ALAW)return"alaw";if(this.audioInfo.format===Ze.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}return this.audioInfo.format===Ze.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 g(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},wr=2048,Bs=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(g(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 g(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return le}getDisposition(){return{...xe}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){g(this.demuxer.audioInfo);let n=e*wr*this.demuxer.audioInfo.blockSizeInBytes;if(n>=this.demuxer.dataSize)return null;let o=Math.min(wr*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-n);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,o);if(c instanceof Promise&&(c=await c),!c)return null}let i;if(t.metadataOnly)i=oe;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,o);c instanceof Promise&&(c=await c),g(c),i=B(c,o)}let s=e*wr/this.demuxer.audioInfo.sampleRate,a=o/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,s),new Z(i,"key",s,a,e,o)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){g(this.demuxer.audioInfo);let n=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/wr,(this.demuxer.dataSize-1)/(wr*this.demuxer.audioInfo.blockSizeInBytes))),o=await this.getPacketAtIndex(n,t);if(o)return o;if(n===0)return null;g(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){g(this.demuxer.audioInfo);let n=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/wr);return this.getPacketAtIndex(n+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var kr=7,Pr=9,hn=r=>{let e=r.filePos,t=B(r,9),n=new $(t);if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let s=n.readBits(1),a=n.readBits(2)+1,c=n.readBits(4);if(c===15)return null;n.skipBits(1);let l=n.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let f=n.readBits(13);n.skipBits(11);let u=n.readBits(2)+1;if(u!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let m=null;return s===1?r.filePos-=2:m=n.readBits(16),{objectType:a,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:f,numberOfAacFrames:u,crcCheck:m,startPos:e}};var Ns=1024,Fo=class extends me{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new Me,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();g(this.firstFrameHeader),this.tracks=[new se(this.input,new Ls(this))]})()}async advanceReader(){let e=this.reader.requestSliceRange(this.lastLoadedPos,kr,Pr);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=hn(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);let n=en[t.samplingFrequencyIndex];g(n!==void 0);let o=Ns/n,i=t.crcCheck?Pr:kr,s={timestamp:this.nextTimestampInSamples/n,duration:o,dataStart:t.startPos+i,dataSize:t.frameLength-i};this.loadedSamples.push(s),this.nextTimestampInSamples+=Ns,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 g(e),e.computeDuration()}async getMetadataTags(){return{}}},Ls=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/Ns}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return le}getCodec(){return"aac"}getInternalCodecId(){return g(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){g(this.demuxer.firstFrameHeader);let e=cs[this.demuxer.firstFrameHeader.channelConfiguration];return g(e!==void 0),e}getSampleRate(){g(this.demuxer.firstFrameHeader);let e=en[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return g(e!==void 0),e}getDisposition(){return{...xe}}async getDecoderConfig(){g(this.demuxer.firstFrameHeader);let e=new Uint8Array(3),t=new $(e),{objectType:n,samplingFrequencyIndex:o,channelConfiguration:i}=this.demuxer.firstFrameHeader;return n>31?(t.writeBits(5,31),t.writeBits(6,n-32)):t.writeBits(5,n),t.writeBits(4,o),t.writeBits(4,i),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:e.subarray(0,Math.ceil((t.pos-1)/8))}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let o;if(t.metadataOnly)o=oe;else{let i=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(i instanceof Promise&&(i=await i),!i)return null;o=B(i,n.dataSize)}return new Z(o,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let o=Ct(this.demuxer.loadedSamples,e.timestamp,s=>s.timestamp);if(o===-1)throw new Error("Packet was not created from this track.");let i=o+1;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let o=W(this.demuxer.loadedSamples,e,i=>i.timestamp);if(o===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(o,t);if(o>=0&&o+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(o,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Xc=r=>r===0?null:r===1?192:r>=2&&r<=5?144*2**r:r===6?"uncommon-u8":r===7?"uncommon-u16":r>=8&&r<=15?2**r:null,Kc=(r,e)=>{switch(r){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},Yc=r=>{let e=0,t=new $(B(r,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);let n=[],o=e-1,i=new $(B(r,o)),s=8-e-1;for(let c=0;c<s;c++)n.unshift(t.readBits(1));for(let c=0;c<o;c++)for(let l=0;l<8;l++){let f=i.readBits(1);l<2||n.unshift(f)}return n.reduce((c,l,f)=>c|l<<f,0)},$c=(r,e)=>{if(e==="uncommon-u16")return ae(r)+1;if(e==="uncommon-u8")return R(r)+1;if(typeof e=="number")return e;we(e),g(!1)},Qc=(r,e)=>e==="uncommon-u16"?ae(r):e==="uncommon-u16-10"?ae(r)*10:e==="uncommon-u8"?R(r):typeof e=="number"?e:null,Zc=r=>{let t=0;for(let n of r){t^=n;for(let o=0;o<8;o++)(t&128)!==0?t=t<<1^7:t<<=1,t&=255}return t};var Eo=class extends me{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 Me,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),g(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),g(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.`);g(t);let n=R(t),o=mt(t),i=(n&128)!==0;switch(n&127){case ct.STREAMINFO:{let a=this.reader.requestSlice(e,o);if(a instanceof Promise&&(a=await a),g(a),a===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let c=B(a,34),l=new $(c),f=l.readBits(16),u=l.readBits(16),m=l.readBits(24),d=l.readBits(24),p=l.readBits(20),h=l.readBits(3)+1;l.readBits(5);let x=l.readBits(36);l.skipBits(128);let y=new Uint8Array(42);y.set(new Uint8Array([102,76,97,67]),0),y.set(new Uint8Array([128,0,0,34]),4),y.set(c,8),this.audioInfo={numberOfChannels:h,sampleRate:p,totalSamples:x,minimumBlockSize:f,maximumBlockSize:u,minimumFrameSize:m,maximumFrameSize:d,description:y},this.track=new se(this.input,new Vs(this));break}case ct.VORBIS_COMMENT:{let a=this.reader.requestSlice(e,o);a instanceof Promise&&(a=await a),g(a),tn(B(a,o),this.metadataTags);break}case ct.PICTURE:{let a=this.reader.requestSlice(e,o);a instanceof Promise&&(a=await a),g(a);let c=F(a),l=F(a),f=ce.decode(B(a,l)),u=F(a),m=ce.decode(B(a,u));a.skip(16);let d=F(a),p=B(a,d);this.metadataTags.images??=[],this.metadataTags.images.push({data:p,mimeType:f,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}){g(this.audioInfo);let n=6,i=this.audioInfo.maximumFrameSize+16,s=await this.reader.requestSliceRange(e,this.audioInfo.minimumFrameSize,i);if(!s)return null;let a=this.readFlacFrameHeader({slice:s,isFirstPacket:t});if(!a)return null;for(s.filePos=e+this.audioInfo.minimumFrameSize;;){if(s.filePos>s.end-n)return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:s.end-e,isLastFrame:!0};if(R(s)===255){let l=s.filePos,f=R(s),u=this.blockingBit===1?249:248;if(f!==u){s.filePos=l;continue}s.skip(-2);let m=s.filePos-e,d=this.readFlacFrameHeader({slice:s,isFirstPacket:!1});if(!d){s.filePos=l;continue}if(this.blockingBit===0){if(d.num-a.num!==1){s.filePos=l;continue}}else if(d.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 n=e.filePos,o=B(e,4),i=new $(o);if(i.readBits(15)!==32764)return null;if(this.blockingBit===null){g(t);let x=i.readBits(1);this.blockingBit=x}else if(this.blockingBit===1){if(g(!t),i.readBits(1)!==1)return null}else if(this.blockingBit===0){if(g(!t),i.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");let a=Xc(i.readBits(4));if(!a)return null;g(this.audioInfo);let c=Kc(i.readBits(4),this.audioInfo.sampleRate);if(!c||(i.readBits(4),i.readBits(3),i.readBits(1)!==0))return null;let f=Yc(e),u=$c(e,a),m=Qc(e,c);if(m===null||m!==this.audioInfo.sampleRate)return null;let d=e.filePos-n,p=R(e);e.skip(-d),e.skip(-1);let h=Zc(B(e,d));return p!==h?null:{num:f,blockSize:u,sampleRate:m}}async advanceReader(){await this.readMetadata(),g(this.lastLoadedPos!==null),g(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],i={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(i),t.isLastFrame){this.lastSampleLoaded=!0;return}}},Vs=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return g(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 g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return le}getTimeResolution(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...xe}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return g(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(g(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");let n=await this.demuxer.readingMutex.acquire();try{for(;;){let o=W(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(o===-1){await this.demuxer.advanceReader();continue}let i=this.demuxer.loadedSamples[o],s=i.blockOffset/this.demuxer.audioInfo.sampleRate,a=i.blockSize/this.demuxer.audioInfo.sampleRate;if(s+a<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(o,t)}}finally{n()}}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let o=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&o>=this.demuxer.loadedSamples.length)return null;for(;o>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(o,t)}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let n=this.demuxer.loadedSamples[e];if(!n)return null;let o;if(t.metadataOnly)o=oe;else{let a=this.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(a instanceof Promise&&(a=await a),!a)return null;o=B(a,n.byteSize)}g(this.demuxer.audioInfo);let i=n.blockOffset/this.demuxer.audioInfo.sampleRate,s=n.blockSize/this.demuxer.audioInfo.sampleRate;return new Z(o,"key",i,s,e,n.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}};var Ce=class{},gn=class extends Ce{async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);return t instanceof Promise&&(t=await t),!t||(t.skip(4),J(t,4)!=="ftyp")?null:J(t,4)}_createDemuxer(e){return new go(e)}},zo=class extends gn{async _canReadInput(e){let t=await this._getMajorBrand(e);return!!t&&t!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},Do=class extends gn{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},xn=class extends Ce{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,Ie);if(n instanceof Promise&&(n=await n),!n)return!1;let o=_s(n);if(o===null||o<1||o>8||q(n,o)!==w.EBML)return!1;let s=Is(n);if(s===null)return!1;let a=e._reader.requestSlice(n.filePos,s);if(a instanceof Promise&&(a=await a),!a)return!1;let c=n.filePos;for(;a.filePos<=c+s-Te;){let l=Ae(a);if(!l)break;let{id:f,size:u}=l,m=a.filePos;if(u===null)return!1;switch(f){case w.EBMLVersion:if(q(a,u)!==1)return!1;break;case w.EBMLReadVersion:if(q(a,u)!==1)return!1;break;case w.DocType:if(dt(a,u)!==t)return!1;break;case w.DocTypeVersion:if(q(a,u)>4)return!1;break}a.filePos=m+u}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new wo(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},Oo=class extends xn{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},Ro=class extends Ce{async _canReadInput(e){let t=e._reader.requestSlice(0,10);if(t instanceof Promise&&(t=await t),!t)return!1;let n=0,o=!1;for(;;){let l=e._reader.requestSlice(n,Sr);if(l instanceof Promise&&(l=await l),!l)break;let f=Bt(l);if(!f)break;o=!0,n=l.filePos+f.size}let i=await pn(e._reader,n,n+4096);if(!i)return!1;if(o)return!0;n=i.startPos+i.header.totalSize;let s=await pn(e._reader,n,n+4);if(!s)return!1;let a=i.header,c=s.header;return!(a.channel!==c.channel||a.sampleRate!==c.sampleRate)}_createDemuxer(e){return new _o(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},Mo=class extends Ce{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let n=J(t,4);return n!=="RIFF"&&n!=="RIFX"&&n!=="RF64"?!1:(t.skip(4),J(t,4)==="WAVE")}_createDemuxer(e){return new Ao(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},Bo=class extends Ce{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?J(t,4)==="OggS":!1}_createDemuxer(e){return new Io(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},Uo=class extends Ce{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?J(t,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Eo(e)}},No=class extends Ce{async _canReadInput(e){let t=e._reader.requestSliceRange(0,kr,Pr);if(t instanceof Promise&&(t=await t),!t)return!1;let n=hn(t);if(!n||(t=e._reader.requestSliceRange(n.frameLength,kr,Pr),t instanceof Promise&&(t=await t),!t))return!1;let o=hn(t);return o?n.objectType===o.objectType&&n.samplingFrequencyIndex===o.samplingFrequencyIndex&&n.channelConfiguration===o.channelConfiguration:!1}_createDemuxer(e){return new Fo(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},Jc=new zo,el=new Do,tl=new xn,rl=new Oo,nl=new Ro,ol=new Mo,il=new Bo,sl=new No,al=new Uo,ge=[Jc,el,tl,rl,ol,il,al,nl,sl];var Lt=class{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new ie;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new ie;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}};var vn=class extends Lt{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&&(!Jr(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 Lo({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:ll.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&&!it()?t=this._blob.slice(e.currentPos).stream().getReader():t=null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){let{done:n,value:o}=await t.read();if(n)throw this._orchestrator.forgetWorker(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}else{let n=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+n.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(n))}e.running=!1,e.aborted&&await t?.cancel()}_dispose(){this._orchestrator.dispose()}},cl=.5*2**20,Ap=((r,e,t)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))){let o=null;try{typeof window<"u"&&typeof window.location<"u"&&(o=new URL(t instanceof Request?t.url:t,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&o!==null&&o!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(r-2),16)}),yn=class extends Lt{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&&(!Jr(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??Ap,this._orchestrator=new Lo({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:ll.network})}async _retrieveSize(){let e=new AbortController,t=await as(this._options.fetchFn??fetch,this._url,ss(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:e.signal}),this._getRetryDelay,()=>this._disposed);if(!t.ok)throw new Error(`Error fetching ${String(this._url)}: ${t.status} ${t.statusText}`);let n,o;if(t.status===206)o=this._getTotalLengthFromRangeResponse(t),n=this._orchestrator.createWorker(0,Math.min(o,cl));else{let i=t.headers.get("Content-Length");if(i)o=Number(i),n=this._orchestrator.createWorker(0,o),this._orchestrator.options.maxCacheSize=1/0,console.warn("HTTP server did not respond with 206 Partial Content, meaning the entire remote resource now has to be downloaded. For efficient media file streaming across a network, please make sure your server supports range requests.");else throw new Error(`HTTP response (status ${t.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=o,this._existingResponses.set(n,{response:t,abortController:e}),this._orchestrator.runWorker(n),o}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;;){let t=this._existingResponses.get(e);this._existingResponses.delete(e);let n=t?.abortController,o=t?.response;if(n||(n=new AbortController,o=await as(this._options.fetchFn??fetch,this._url,ss(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:n.signal}),this._getRetryDelay,()=>this._disposed)),g(o),!o.ok)throw new Error(`Error fetching ${String(this._url)}: ${o.status} ${o.statusText}`);if(e.currentPos>0&&o.status!==206)throw new Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!o.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let i=o.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){n.abort(),e.running=!1;return}let s;try{s=await i.read()}catch(l){if(this._disposed)throw l;let f=this._getRetryDelay(1,l,this._url);if(f!==null){console.error("Error while reading response stream. Attempting to resume.",l),await new Promise(u=>setTimeout(u,1e3*f));break}else throw l}if(e.aborted)continue;let{done:a,value:c}=s;if(a){if(e.currentPos>=e.targetPos){this._orchestrator.forgetWorker(e),e.running=!1;return}break}this.onread?.(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}}}_getTotalLengthFromRangeResponse(e){let t=e.headers.get("Content-Range");if(t){let o=/\/(\d+)/.exec(t);if(o)return Number(o[1])}let n=e.headers.get("Content-Length");if(n)return Number(n);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}};var ll={none:(r,e)=>({start:r,end:e}),fileSystem:(r,e)=>(r=Math.floor((r-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:r,end:e}),network:(r,e,t)=>{r=Math.max(0,Math.floor((r-65536)/65536)*65536);for(let o of t){let s=Math.max((o.startPos+o.targetPos)/2,o.targetPos-8388608);if(eo(r,e,s,o.targetPos)){let a=o.targetPos-o.startPos,c=Math.ceil((a+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(a+1)),f=Math.min(l,c);e=Math.max(e,o.startPos+f)}}return e=Math.max(e,r+cl),{start:r,end:e}}},Lo=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){g(this.fileSize!==null);let n=this.options.prefetchProfile(e,t,this.workers),o=Math.max(n.start,0),i=Math.min(n.end,this.fileSize);g(o<=e&&t<=i);let s=null,a=W(this.cache,e,v=>v.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=W(this.cache,o,v=>v.start),f=s?null:new Uint8Array(t-e),u=0,m=o,d=[];if(l!==-1){for(let v=l;v<this.cache.length;v++){let S=this.cache[v];if(S.start>=i)break;if(S.end<=o)continue;let C=Math.max(o,S.start),_=Math.min(i,S.end);if(g(C<=_),m<C&&d.push({start:m,end:C}),m=_,f){let T=Math.max(e,S.start),E=Math.min(t,S.end);if(T<E){let I=T-e;f.set(S.bytes.subarray(T-S.start,E-S.start),I),I===u&&(u=E-e)}}S.age=this.nextAge++}m<i&&d.push({start:m,end:i})}else d.push({start:o,end:i});if(f&&u>=f.length&&(s={bytes:f,view:j(f),offset:e}),d.length===0)return g(s),s;let{promise:p,resolve:h,reject:x}=pe(),y=[];for(let v of d){let S=Math.max(e,v.start),C=Math.min(t,v.end);S===v.start&&C===v.end?y.push(v):S<C&&y.push({start:S,end:C})}for(let v of d){let S=f&&{start:e,bytes:f,holes:y,resolve:h,reject:x},C=!1;for(let _ of this.workers)if(eo(v.start-131072,v.start,_.currentPos,_.targetPos)){_.targetPos=Math.max(_.targetPos,v.end),C=!0,S&&!_.pendingSlices.includes(S)&&_.pendingSlices.push(S),_.running||this.runWorker(_);break}if(!C){let _=this.createWorker(v.start,v.end);S&&(_.pendingSlices=[S]),this.runWorker(_)}}return s||(g(f),s=p.then(v=>({bytes:v,view:j(v),offset:e}))),s}createWorker(e,t){let n={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(n);this.workers.length>this.options.maxWorkerCount;){let o=0,i=this.workers[0];for(let s=1;s<this.workers.length;s++){let a=this.workers[s];a.age<i.age&&(o=s,i=a)}if(i.running&&i.pendingSlices.length>0)break;i.aborted=!0,this.workers.splice(o,1)}return n}runWorker(e){g(!e.running),g(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(n=>n.reject(t)),e.pendingSlices.length=0;else throw t})}supplyWorkerData(e,t){g(!e.aborted);let n=e.currentPos,o=n+t.length;this.insertIntoCache({start:n,end:o,bytes:t,view:j(t),age:this.nextAge++}),e.currentPos+=t.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let i=0;i<e.pendingSlices.length;i++){let s=e.pendingSlices[i],a=Math.max(n,s.start),c=Math.min(o,s.start+s.bytes.length);a<c&&s.bytes.set(t.subarray(a-n,c-n),a-s.start);for(let l=0;l<s.holes.length;l++){let f=s.holes[l];n<=f.start&&o>f.start&&(f.start=o),f.end<=f.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||eo(n,o,s.currentPos,s.targetPos)&&(this.workers.splice(i,1),i--)}}forgetWorker(e){let t=this.workers.indexOf(e);g(t!==-1),this.workers.splice(t,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=W(this.cache,e.start,n=>n.start)+1;if(t>0){let n=this.cache[t-1];if(n.end>=e.end)return;if(n.end>e.start){let o=new Uint8Array(e.end-n.start);o.set(n.bytes,0),o.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=o,n.view=j(o),n.end=e.end,t--,e=n}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let n=t+1;n<this.cache.length;n++){let o=this.cache[n];if(e.end<=o.start)break;if(e.end>=o.end){this.cache.splice(n,1),this.currentCacheSize-=o.bytes.length,n--;continue}let i=new Uint8Array(o.end-e.start);i.set(e.bytes,0),i.set(o.bytes,o.start-e.start),this.currentCacheSize-=e.end-o.start,e.bytes=i,e.view=j(i),e.end=o.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let n=0,o=this.cache[0];for(let i=1;i<this.cache.length;i++){let s=this.cache[i];s.age<o.age&&(n=i,o=s)}if(this.currentCacheSize-o.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(n,1),this.currentCacheSize-=o.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}};to();var fe=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 Ce)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Lt))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 Vo(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(),g(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()}},ie=class extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}};var Vo=class{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new ie;if(this.fileSize!==null&&e+t>this.fileSize)return null;let n=e+t,o=this.source._read(e,n);return o instanceof Promise?o.then(i=>i?new gr(i.bytes,i.view,i.offset,e,n):null):o?new gr(o.bytes,o.view,o.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new ie;if(this.fileSize!==null)return this.requestSlice(e,Pt(this.fileSize-e,t,n));{let o=this.requestSlice(e,n),i=s=>{if(s)return s;let a=l=>(g(l!==null),this.requestSlice(e,Pt(l-e,t,n))),c=this.source._retrieveSize();return c instanceof Promise?c.then(a):a(c)};return o instanceof Promise?o.then(i):i(o)}}},gr=class r{constructor(e,t,n,o,i){this.bytes=e,this.view=t,this.offset=n,this.start=o,this.end=i,this.bufferPos=o-n}static tempFromBytes(e){return new r(e,j(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new r(this.bytes,this.view,this.offset,e,e+t)}},ve=(r,e)=>{if(r.filePos<r.start||r.filePos+e>r.end)throw new RangeError(`Tried reading [${r.filePos}, ${r.filePos+e}), but slice is [${r.start}, ${r.end}). This is likely an internal error, please report it alongside the file that caused it.`)},B=(r,e)=>{ve(r,e);let t=r.bytes.subarray(r.bufferPos,r.bufferPos+e);return r.bufferPos+=e,t},R=r=>(ve(r,1),r.view.getUint8(r.bufferPos++)),Cr=(r,e)=>{ve(r,2);let t=r.view.getUint16(r.bufferPos,e);return r.bufferPos+=2,t},ae=r=>{ve(r,2);let e=r.view.getUint16(r.bufferPos,!1);return r.bufferPos+=2,e},mt=r=>{ve(r,3);let e=kt(r.view,r.bufferPos,!1);return r.bufferPos+=3,e},un=r=>{ve(r,2);let e=r.view.getInt16(r.bufferPos,!1);return r.bufferPos+=2,e},Je=(r,e)=>{ve(r,4);let t=r.view.getUint32(r.bufferPos,e);return r.bufferPos+=4,t},F=r=>{ve(r,4);let e=r.view.getUint32(r.bufferPos,!1);return r.bufferPos+=4,e},Ut=r=>{ve(r,4);let e=r.view.getUint32(r.bufferPos,!0);return r.bufferPos+=4,e},Ye=r=>{ve(r,4);let e=r.view.getInt32(r.bufferPos,!1);return r.bufferPos+=4,e},Fp=r=>{ve(r,4);let e=r.view.getInt32(r.bufferPos,!0);return r.bufferPos+=4,e},Us=(r,e)=>{let t,n;return e?(t=Je(r,!0),n=Je(r,!0)):(n=Je(r,!1),t=Je(r,!1)),n*4294967296+t},Se=r=>{let e=F(r),t=F(r);return e*4294967296+t},_c=r=>{let e=Ye(r),t=F(r);return e*4294967296+t},Hc=r=>{let e=Ut(r);return Fp(r)*4294967296+e},Ac=r=>{ve(r,4);let e=r.view.getFloat32(r.bufferPos,!1);return r.bufferPos+=4,e},vo=r=>{ve(r,8);let e=r.view.getFloat64(r.bufferPos,!1);return r.bufferPos+=8,e},J=(r,e)=>{ve(r,e);let t="";for(let n=0;n<e;n++)t+=String.fromCharCode(r.bytes[r.bufferPos++]);return t};var Go=class{count=0};var ul={extension:{type:_n.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await import("./browserAll-PTRBXBRP.js")}};var fl={extension:{type:_n.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await import("./webworkerAll-JENRT6BT.js")}};var qo;function ml(r){return qo!==void 0||(qo=(()=>{let e={stencil:!0,failIfMajorPerformanceCaveat:r??An.defaultOptions.failIfMajorPerformanceCaveat};try{if(!Hr.get().getWebGLRenderingContext())return!1;let n=Hr.get().createCanvas().getContext("webgl",e),o=!!n?.getContextAttributes()?.stencil;if(n){let i=n.getExtension("WEBGL_lose_context");i&&i.loseContext()}return n=null,o}catch{return!1}})()),qo}var Ho;async function dl(r={}){return Ho!==void 0||(Ho=await(async()=>{let e=Hr.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(r)).requestDevice(),!0}catch{return!1}})()),Ho}var pl=["webgl","webgpu","canvas"];async function Gs(r){let e=[];r.preference?(e.push(r.preference),pl.forEach(i=>{i!==r.preference&&e.push(i)})):e=pl.slice();let t,n={};for(let i=0;i<e.length;i++){let s=e[i];if(s==="webgpu"&&await dl()){let{WebGPURenderer:a}=await import("./WebGPURenderer-MGFAJCYY.js");t=a,n={...r,...r.webgpu};break}else if(s==="webgl"&&ml(r.failIfMajorPerformanceCaveat??An.defaultOptions.failIfMajorPerformanceCaveat)){let{WebGLRenderer:a}=await import("./WebGLRenderer-RSJAHIG2.js");t=a,n={...r,...r.webgl};break}else if(s==="canvas")throw n={...r},new Error("CanvasRenderer is not yet implemented")}if(delete n.webgpu,delete n.webgl,!t)throw new Error("No available renderer for the current environment");let o=new t;return await o.init(n),o}var hl=`
2363
2363
  in vec2 vTextureCoord;
2364
2364
 
2365
2365
  out vec4 finalColor;
@@ -2439,7 +2439,7 @@ fn mainFragment(
2439
2439
  var sample = textureSample(uTexture, uSampler, uv);
2440
2440
 
2441
2441
  return sample * alphaUniforms.uAlpha;
2442
- }`;var gl=class xl extends k{constructor(e){e={...xl.defaultOptions,...e};let t=A.from({vertex:{source:qs,entryPoint:"mainVertex"},fragment:{source:qs,entryPoint:"mainFragment"}}),n=P.from({vertex:Jt,fragment:hl,name:"alpha-filter"}),{alpha:o,...i}=e,s=new Zt({uAlpha:{value:o,type:"f32"}});super({...i,gpuProgram:t,glProgram:n,resources:{alphaUniforms:s}})}get alpha(){return this.resources.alphaUniforms.uniforms.uAlpha}set alpha(e){this.resources.alphaUniforms.uniforms.uAlpha=e}};gl.defaultOptions={alpha:1};var bn=gl;var Wo={5:[.153388,.221461,.250301],7:[.071303,.131514,.189879,.214607],9:[.028532,.067234,.124009,.179044,.20236],11:[.0093,.028002,.065984,.121703,.175713,.198596],13:[.002406,.009255,.027867,.065666,.121117,.174868,.197641],15:[489e-6,.002403,.009246,.02784,.065602,.120999,.174697,.197448]};var Ep=["in vec2 vBlurTexCoords[%size%];","uniform sampler2D uTexture;","out vec4 finalColor;","void main(void)","{"," finalColor = vec4(0.0);"," %blur%","}"].join(`
2442
+ }`;var gl=class xl extends k{constructor(e){e={...xl.defaultOptions,...e};let t=A.from({vertex:{source:qs,entryPoint:"mainVertex"},fragment:{source:qs,entryPoint:"mainFragment"}}),n=P.from({vertex:tr,fragment:hl,name:"alpha-filter"}),{alpha:o,...i}=e,s=new er({uAlpha:{value:o,type:"f32"}});super({...i,gpuProgram:t,glProgram:n,resources:{alphaUniforms:s}})}get alpha(){return this.resources.alphaUniforms.uniforms.uAlpha}set alpha(e){this.resources.alphaUniforms.uniforms.uAlpha=e}};gl.defaultOptions={alpha:1};var bn=gl;var Wo={5:[.153388,.221461,.250301],7:[.071303,.131514,.189879,.214607],9:[.028532,.067234,.124009,.179044,.20236],11:[.0093,.028002,.065984,.121703,.175713,.198596],13:[.002406,.009255,.027867,.065666,.121117,.174868,.197641],15:[489e-6,.002403,.009246,.02784,.065602,.120999,.174697,.197448]};var Ep=["in vec2 vBlurTexCoords[%size%];","uniform sampler2D uTexture;","out vec4 finalColor;","void main(void)","{"," finalColor = vec4(0.0);"," %blur%","}"].join(`
2443
2443
  `);function vl(r){let e=Wo[r],t=e.length,n=Ep,o="",i="finalColor += texture(uTexture, vBlurTexCoords[%index%]) * %value%;",s;for(let a=0;a<r;a++){let c=i.replace("%index%",a.toString());s=a,a>=t&&(s=r-a-1),c=c.replace("%value%",e[s].toString()),o+=c,o+=`
2444
2444
  `}return n=n.replace("%blur%",o),n=n.replace("%size%",r.toString()),n}var zp=`
2445
2445
  in vec2 aPosition;
@@ -2558,7 +2558,7 @@ fn mainFragment(
2558
2558
  }`;function Tl(r,e){let t=Wo[e],n=t.length,o=[],i=[],s=[];for(let u=0;u<e;u++){o[u]=`@location(${u}) offset${u}: vec2<f32>,`,r?i[u]=`filteredCord + vec2(${u-n+1} * pixelStrength, 0.0),`:i[u]=`filteredCord + vec2(0.0, ${u-n+1} * pixelStrength),`;let m=u<n?u:e-u-1,d=t[m].toString();s[u]=`finalColor += textureSample(uTexture, uSampler, offset${u}) * ${d};`}let a=o.join(`
2559
2559
  `),c=i.join(`
2560
2560
  `),l=s.join(`
2561
- `),f=Sl.replace("%blur-struct%",a).replace("%blur-vertex-out%",c).replace("%blur-fragment-in%",a).replace("%blur-sampling%",l).replace("%dimension%",r?"z":"w");return A.from({vertex:{source:f,entryPoint:"mainVertex"},fragment:{source:f,entryPoint:"mainFragment"}})}var wl=class Cl extends k{constructor(e){e={...Cl.defaultOptions,...e};let t=bl(e.horizontal,e.kernelSize),n=Tl(e.horizontal,e.kernelSize);super({glProgram:t,gpuProgram:n,resources:{blurUniforms:{uStrength:{value:0,type:"f32"}}},...e}),this.horizontal=e.horizontal,this._quality=0,this.quality=e.quality,this.blur=e.strength,this._uniforms=this.resources.blurUniforms.uniforms}apply(e,t,n,o){if(this._uniforms.uStrength=this.strength/this.passes,this.passes===1)e.applyFilter(this,t,n,o);else{let i=Q.getSameSizeTexture(t),s=t,a=i;this._state.blend=!1;let c=e.renderer.type===In.WEBGPU;for(let l=0;l<this.passes-1;l++){e.applyFilter(this,s,a,l===0?!0:c);let f=a;a=s,s=f}this._state.blend=!0,e.applyFilter(this,s,n,o),Q.returnTexture(i)}}get blur(){return this.strength}set blur(e){this.padding=1+Math.abs(e)*2,this.strength=e}get quality(){return this._quality}set quality(e){this._quality=e,this.passes=e}};wl.defaultOptions={strength:8,quality:4,kernelSize:5};var ht=wl;var gt=class extends k{constructor(...e){let t=e[0]??{};typeof t=="number"&&(U(Gr,"BlurFilter constructor params are now options object. See params: { strength, quality, resolution, kernelSize }"),t={strength:t},e[1]!==void 0&&(t.quality=e[1]),e[2]!==void 0&&(t.resolution=e[2]||"inherit"),e[3]!==void 0&&(t.kernelSize=e[3])),t={...ht.defaultOptions,...t};let{strength:n,strengthX:o,strengthY:i,quality:s,...a}=t;super({...a,compatibleRenderers:In.BOTH,resources:{}}),this._repeatEdgePixels=!1,this.blurXFilter=new ht({horizontal:!0,...t}),this.blurYFilter=new ht({horizontal:!1,...t}),this.quality=s,this.strengthX=o??n,this.strengthY=i??n,this.repeatEdgePixels=!1}apply(e,t,n,o){let i=Math.abs(this.blurXFilter.strength),s=Math.abs(this.blurYFilter.strength);if(i&&s){let a=Q.getSameSizeTexture(t);this.blurXFilter.blendMode="normal",this.blurXFilter.apply(e,t,a,!0),this.blurYFilter.blendMode=this.blendMode,this.blurYFilter.apply(e,a,n,o),Q.returnTexture(a)}else s?(this.blurYFilter.blendMode=this.blendMode,this.blurYFilter.apply(e,t,n,o)):(this.blurXFilter.blendMode=this.blendMode,this.blurXFilter.apply(e,t,n,o))}updatePadding(){this._repeatEdgePixels?this.padding=0:this.padding=Math.max(Math.abs(this.blurXFilter.blur),Math.abs(this.blurYFilter.blur))*2}get strength(){if(this.strengthX!==this.strengthY)throw new Error("BlurFilter's strengthX and strengthY are different");return this.strengthX}set strength(e){this.blurXFilter.blur=this.blurYFilter.blur=e,this.updatePadding()}get quality(){return this.blurXFilter.quality}set quality(e){this.blurXFilter.quality=this.blurYFilter.quality=e}get strengthX(){return this.blurXFilter.blur}set strengthX(e){this.blurXFilter.blur=e,this.updatePadding()}get strengthY(){return this.blurYFilter.blur}set strengthY(e){this.blurYFilter.blur=e,this.updatePadding()}get blur(){return U("8.3.0","BlurFilter.blur is deprecated, please use BlurFilter.strength instead."),this.strength}set blur(e){U("8.3.0","BlurFilter.blur is deprecated, please use BlurFilter.strength instead."),this.strength=e}get blurX(){return U("8.3.0","BlurFilter.blurX is deprecated, please use BlurFilter.strengthX instead."),this.strengthX}set blurX(e){U("8.3.0","BlurFilter.blurX is deprecated, please use BlurFilter.strengthX instead."),this.strengthX=e}get blurY(){return U("8.3.0","BlurFilter.blurY is deprecated, please use BlurFilter.strengthY instead."),this.strengthY}set blurY(e){U("8.3.0","BlurFilter.blurY is deprecated, please use BlurFilter.strengthY instead."),this.strengthY=e}get repeatEdgePixels(){return this._repeatEdgePixels}set repeatEdgePixels(e){this._repeatEdgePixels=e,this.updatePadding()}};gt.defaultOptions={strength:8,quality:4,kernelSize:5};var kl=`
2561
+ `),f=Sl.replace("%blur-struct%",a).replace("%blur-vertex-out%",c).replace("%blur-fragment-in%",a).replace("%blur-sampling%",l).replace("%dimension%",r?"z":"w");return A.from({vertex:{source:f,entryPoint:"mainVertex"},fragment:{source:f,entryPoint:"mainFragment"}})}var wl=class Cl extends k{constructor(e){e={...Cl.defaultOptions,...e};let t=bl(e.horizontal,e.kernelSize),n=Tl(e.horizontal,e.kernelSize);super({glProgram:t,gpuProgram:n,resources:{blurUniforms:{uStrength:{value:0,type:"f32"}}},...e}),this.horizontal=e.horizontal,this._quality=0,this.quality=e.quality,this.blur=e.strength,this._uniforms=this.resources.blurUniforms.uniforms}apply(e,t,n,o){if(this._uniforms.uStrength=this.strength/this.passes,this.passes===1)e.applyFilter(this,t,n,o);else{let i=Q.getSameSizeTexture(t),s=t,a=i;this._state.blend=!1;let c=e.renderer.type===In.WEBGPU;for(let l=0;l<this.passes-1;l++){e.applyFilter(this,s,a,l===0?!0:c);let f=a;a=s,s=f}this._state.blend=!0,e.applyFilter(this,s,n,o),Q.returnTexture(i)}}get blur(){return this.strength}set blur(e){this.padding=1+Math.abs(e)*2,this.strength=e}get quality(){return this._quality}set quality(e){this._quality=e,this.passes=e}};wl.defaultOptions={strength:8,quality:4,kernelSize:5};var ht=wl;var gt=class extends k{constructor(...e){let t=e[0]??{};typeof t=="number"&&(U(qr,"BlurFilter constructor params are now options object. See params: { strength, quality, resolution, kernelSize }"),t={strength:t},e[1]!==void 0&&(t.quality=e[1]),e[2]!==void 0&&(t.resolution=e[2]||"inherit"),e[3]!==void 0&&(t.kernelSize=e[3])),t={...ht.defaultOptions,...t};let{strength:n,strengthX:o,strengthY:i,quality:s,...a}=t;super({...a,compatibleRenderers:In.BOTH,resources:{}}),this._repeatEdgePixels=!1,this.blurXFilter=new ht({horizontal:!0,...t}),this.blurYFilter=new ht({horizontal:!1,...t}),this.quality=s,this.strengthX=o??n,this.strengthY=i??n,this.repeatEdgePixels=!1}apply(e,t,n,o){let i=Math.abs(this.blurXFilter.strength),s=Math.abs(this.blurYFilter.strength);if(i&&s){let a=Q.getSameSizeTexture(t);this.blurXFilter.blendMode="normal",this.blurXFilter.apply(e,t,a,!0),this.blurYFilter.blendMode=this.blendMode,this.blurYFilter.apply(e,a,n,o),Q.returnTexture(a)}else s?(this.blurYFilter.blendMode=this.blendMode,this.blurYFilter.apply(e,t,n,o)):(this.blurXFilter.blendMode=this.blendMode,this.blurXFilter.apply(e,t,n,o))}updatePadding(){this._repeatEdgePixels?this.padding=0:this.padding=Math.max(Math.abs(this.blurXFilter.blur),Math.abs(this.blurYFilter.blur))*2}get strength(){if(this.strengthX!==this.strengthY)throw new Error("BlurFilter's strengthX and strengthY are different");return this.strengthX}set strength(e){this.blurXFilter.blur=this.blurYFilter.blur=e,this.updatePadding()}get quality(){return this.blurXFilter.quality}set quality(e){this.blurXFilter.quality=this.blurYFilter.quality=e}get strengthX(){return this.blurXFilter.blur}set strengthX(e){this.blurXFilter.blur=e,this.updatePadding()}get strengthY(){return this.blurYFilter.blur}set strengthY(e){this.blurYFilter.blur=e,this.updatePadding()}get blur(){return U("8.3.0","BlurFilter.blur is deprecated, please use BlurFilter.strength instead."),this.strength}set blur(e){U("8.3.0","BlurFilter.blur is deprecated, please use BlurFilter.strength instead."),this.strength=e}get blurX(){return U("8.3.0","BlurFilter.blurX is deprecated, please use BlurFilter.strengthX instead."),this.strengthX}set blurX(e){U("8.3.0","BlurFilter.blurX is deprecated, please use BlurFilter.strengthX instead."),this.strengthX=e}get blurY(){return U("8.3.0","BlurFilter.blurY is deprecated, please use BlurFilter.strengthY instead."),this.strengthY}set blurY(e){U("8.3.0","BlurFilter.blurY is deprecated, please use BlurFilter.strengthY instead."),this.strengthY=e}get repeatEdgePixels(){return this._repeatEdgePixels}set repeatEdgePixels(e){this._repeatEdgePixels=e,this.updatePadding()}};gt.defaultOptions={strength:8,quality:4,kernelSize:5};var kl=`
2562
2562
  in vec2 vTextureCoord;
2563
2563
  in vec4 vColor;
2564
2564
 
@@ -2730,7 +2730,7 @@ fn mainFragment(
2730
2730
  rgb.b *= result.a;
2731
2731
 
2732
2732
  return vec4(rgb, result.a);
2733
- }`;var Nt=class extends k{constructor(e={}){let t=new Zt({uColorMatrix:{value:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],type:"f32",size:20},uAlpha:{value:1,type:"f32"}}),n=A.from({vertex:{source:Hs,entryPoint:"mainVertex"},fragment:{source:Hs,entryPoint:"mainFragment"}}),o=P.from({vertex:Jt,fragment:kl,name:"color-matrix-filter"});super({...e,gpuProgram:n,glProgram:o,resources:{colorMatrixUniforms:t}}),this.alpha=1}_loadMatrix(e,t=!1){let n=e;t&&(this._multiply(n,this.matrix,e),n=this._colorMatrix(n)),this.resources.colorMatrixUniforms.uniforms.uColorMatrix=n,this.resources.colorMatrixUniforms.update()}_multiply(e,t,n){return e[0]=t[0]*n[0]+t[1]*n[5]+t[2]*n[10]+t[3]*n[15],e[1]=t[0]*n[1]+t[1]*n[6]+t[2]*n[11]+t[3]*n[16],e[2]=t[0]*n[2]+t[1]*n[7]+t[2]*n[12]+t[3]*n[17],e[3]=t[0]*n[3]+t[1]*n[8]+t[2]*n[13]+t[3]*n[18],e[4]=t[0]*n[4]+t[1]*n[9]+t[2]*n[14]+t[3]*n[19]+t[4],e[5]=t[5]*n[0]+t[6]*n[5]+t[7]*n[10]+t[8]*n[15],e[6]=t[5]*n[1]+t[6]*n[6]+t[7]*n[11]+t[8]*n[16],e[7]=t[5]*n[2]+t[6]*n[7]+t[7]*n[12]+t[8]*n[17],e[8]=t[5]*n[3]+t[6]*n[8]+t[7]*n[13]+t[8]*n[18],e[9]=t[5]*n[4]+t[6]*n[9]+t[7]*n[14]+t[8]*n[19]+t[9],e[10]=t[10]*n[0]+t[11]*n[5]+t[12]*n[10]+t[13]*n[15],e[11]=t[10]*n[1]+t[11]*n[6]+t[12]*n[11]+t[13]*n[16],e[12]=t[10]*n[2]+t[11]*n[7]+t[12]*n[12]+t[13]*n[17],e[13]=t[10]*n[3]+t[11]*n[8]+t[12]*n[13]+t[13]*n[18],e[14]=t[10]*n[4]+t[11]*n[9]+t[12]*n[14]+t[13]*n[19]+t[14],e[15]=t[15]*n[0]+t[16]*n[5]+t[17]*n[10]+t[18]*n[15],e[16]=t[15]*n[1]+t[16]*n[6]+t[17]*n[11]+t[18]*n[16],e[17]=t[15]*n[2]+t[16]*n[7]+t[17]*n[12]+t[18]*n[17],e[18]=t[15]*n[3]+t[16]*n[8]+t[17]*n[13]+t[18]*n[18],e[19]=t[15]*n[4]+t[16]*n[9]+t[17]*n[14]+t[18]*n[19]+t[19],e}_colorMatrix(e){let t=new Float32Array(e);return t[4]/=255,t[9]/=255,t[14]/=255,t[19]/=255,t}brightness(e,t){let n=[e,0,0,0,0,0,e,0,0,0,0,0,e,0,0,0,0,0,1,0];this._loadMatrix(n,t)}tint(e,t){let[n,o,i]=Y.shared.setValue(e).toArray(),s=[n,0,0,0,0,0,o,0,0,0,0,0,i,0,0,0,0,0,1,0];this._loadMatrix(s,t)}greyscale(e,t){let n=[e,e,e,0,0,e,e,e,0,0,e,e,e,0,0,0,0,0,1,0];this._loadMatrix(n,t)}grayscale(e,t){this.greyscale(e,t)}blackAndWhite(e){let t=[.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0];this._loadMatrix(t,e)}hue(e,t){e=(e||0)/180*Math.PI;let n=Math.cos(e),o=Math.sin(e),i=Math.sqrt,s=1/3,a=i(s),c=n+(1-n)*s,l=s*(1-n)-a*o,f=s*(1-n)+a*o,u=s*(1-n)+a*o,m=n+s*(1-n),d=s*(1-n)-a*o,p=s*(1-n)-a*o,h=s*(1-n)+a*o,x=n+s*(1-n),y=[c,l,f,0,0,u,m,d,0,0,p,h,x,0,0,0,0,0,1,0];this._loadMatrix(y,t)}contrast(e,t){let n=(e||0)+1,o=-.5*(n-1),i=[n,0,0,0,o,0,n,0,0,o,0,0,n,0,o,0,0,0,1,0];this._loadMatrix(i,t)}saturate(e=0,t){let n=e*2/3+1,o=(n-1)*-.5,i=[n,o,o,0,0,o,n,o,0,0,o,o,n,0,0,0,0,0,1,0];this._loadMatrix(i,t)}desaturate(){this.saturate(-1)}negative(e){let t=[-1,0,0,1,0,0,-1,0,1,0,0,0,-1,1,0,0,0,0,1,0];this._loadMatrix(t,e)}sepia(e){let t=[.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0];this._loadMatrix(t,e)}technicolor(e){let t=[1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0];this._loadMatrix(t,e)}polaroid(e){let t=[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0];this._loadMatrix(t,e)}toBGR(e){let t=[0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0];this._loadMatrix(t,e)}kodachrome(e){let t=[1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0];this._loadMatrix(t,e)}browni(e){let t=[.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0];this._loadMatrix(t,e)}vintage(e){let t=[.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0];this._loadMatrix(t,e)}colorTone(e,t,n,o,i){e||(e=.2),t||(t=.15),n||(n=16770432),o||(o=3375104);let s=Y.shared,[a,c,l]=s.setValue(n).toArray(),[f,u,m]=s.setValue(o).toArray(),d=[.3,.59,.11,0,0,a,c,l,e,0,f,u,m,t,0,a-f,c-u,l-m,0,0];this._loadMatrix(d,i)}night(e,t){e||(e=.1);let n=[e*-2,-e,0,0,0,-e,0,e,0,0,0,e,e*2,0,0,0,0,0,1,0];this._loadMatrix(n,t)}predator(e,t){let n=[11.224130630493164*e,-4.794486999511719*e,-2.8746118545532227*e,0*e,.40342438220977783*e,-3.6330697536468506*e,9.193157196044922*e,-2.951810836791992*e,0*e,-1.316135048866272*e,-3.2184197902679443*e,-4.2375030517578125*e,7.476448059082031*e,0*e,.8044459223747253*e,0,0,0,1,0];this._loadMatrix(n,t)}lsd(e){let t=[2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0];this._loadMatrix(t,e)}reset(){let e=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];this._loadMatrix(e,!1)}get matrix(){return this.resources.colorMatrixUniforms.uniforms.uColorMatrix}set matrix(e){this.resources.colorMatrixUniforms.uniforms.uColorMatrix=e}get alpha(){return this.resources.colorMatrixUniforms.uniforms.uAlpha}set alpha(e){this.resources.colorMatrixUniforms.uniforms.uAlpha=e}};var Pl=`
2733
+ }`;var Vt=class extends k{constructor(e={}){let t=new er({uColorMatrix:{value:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],type:"f32",size:20},uAlpha:{value:1,type:"f32"}}),n=A.from({vertex:{source:Hs,entryPoint:"mainVertex"},fragment:{source:Hs,entryPoint:"mainFragment"}}),o=P.from({vertex:tr,fragment:kl,name:"color-matrix-filter"});super({...e,gpuProgram:n,glProgram:o,resources:{colorMatrixUniforms:t}}),this.alpha=1}_loadMatrix(e,t=!1){let n=e;t&&(this._multiply(n,this.matrix,e),n=this._colorMatrix(n)),this.resources.colorMatrixUniforms.uniforms.uColorMatrix=n,this.resources.colorMatrixUniforms.update()}_multiply(e,t,n){return e[0]=t[0]*n[0]+t[1]*n[5]+t[2]*n[10]+t[3]*n[15],e[1]=t[0]*n[1]+t[1]*n[6]+t[2]*n[11]+t[3]*n[16],e[2]=t[0]*n[2]+t[1]*n[7]+t[2]*n[12]+t[3]*n[17],e[3]=t[0]*n[3]+t[1]*n[8]+t[2]*n[13]+t[3]*n[18],e[4]=t[0]*n[4]+t[1]*n[9]+t[2]*n[14]+t[3]*n[19]+t[4],e[5]=t[5]*n[0]+t[6]*n[5]+t[7]*n[10]+t[8]*n[15],e[6]=t[5]*n[1]+t[6]*n[6]+t[7]*n[11]+t[8]*n[16],e[7]=t[5]*n[2]+t[6]*n[7]+t[7]*n[12]+t[8]*n[17],e[8]=t[5]*n[3]+t[6]*n[8]+t[7]*n[13]+t[8]*n[18],e[9]=t[5]*n[4]+t[6]*n[9]+t[7]*n[14]+t[8]*n[19]+t[9],e[10]=t[10]*n[0]+t[11]*n[5]+t[12]*n[10]+t[13]*n[15],e[11]=t[10]*n[1]+t[11]*n[6]+t[12]*n[11]+t[13]*n[16],e[12]=t[10]*n[2]+t[11]*n[7]+t[12]*n[12]+t[13]*n[17],e[13]=t[10]*n[3]+t[11]*n[8]+t[12]*n[13]+t[13]*n[18],e[14]=t[10]*n[4]+t[11]*n[9]+t[12]*n[14]+t[13]*n[19]+t[14],e[15]=t[15]*n[0]+t[16]*n[5]+t[17]*n[10]+t[18]*n[15],e[16]=t[15]*n[1]+t[16]*n[6]+t[17]*n[11]+t[18]*n[16],e[17]=t[15]*n[2]+t[16]*n[7]+t[17]*n[12]+t[18]*n[17],e[18]=t[15]*n[3]+t[16]*n[8]+t[17]*n[13]+t[18]*n[18],e[19]=t[15]*n[4]+t[16]*n[9]+t[17]*n[14]+t[18]*n[19]+t[19],e}_colorMatrix(e){let t=new Float32Array(e);return t[4]/=255,t[9]/=255,t[14]/=255,t[19]/=255,t}brightness(e,t){let n=[e,0,0,0,0,0,e,0,0,0,0,0,e,0,0,0,0,0,1,0];this._loadMatrix(n,t)}tint(e,t){let[n,o,i]=Y.shared.setValue(e).toArray(),s=[n,0,0,0,0,0,o,0,0,0,0,0,i,0,0,0,0,0,1,0];this._loadMatrix(s,t)}greyscale(e,t){let n=[e,e,e,0,0,e,e,e,0,0,e,e,e,0,0,0,0,0,1,0];this._loadMatrix(n,t)}grayscale(e,t){this.greyscale(e,t)}blackAndWhite(e){let t=[.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0];this._loadMatrix(t,e)}hue(e,t){e=(e||0)/180*Math.PI;let n=Math.cos(e),o=Math.sin(e),i=Math.sqrt,s=1/3,a=i(s),c=n+(1-n)*s,l=s*(1-n)-a*o,f=s*(1-n)+a*o,u=s*(1-n)+a*o,m=n+s*(1-n),d=s*(1-n)-a*o,p=s*(1-n)-a*o,h=s*(1-n)+a*o,x=n+s*(1-n),y=[c,l,f,0,0,u,m,d,0,0,p,h,x,0,0,0,0,0,1,0];this._loadMatrix(y,t)}contrast(e,t){let n=(e||0)+1,o=-.5*(n-1),i=[n,0,0,0,o,0,n,0,0,o,0,0,n,0,o,0,0,0,1,0];this._loadMatrix(i,t)}saturate(e=0,t){let n=e*2/3+1,o=(n-1)*-.5,i=[n,o,o,0,0,o,n,o,0,0,o,o,n,0,0,0,0,0,1,0];this._loadMatrix(i,t)}desaturate(){this.saturate(-1)}negative(e){let t=[-1,0,0,1,0,0,-1,0,1,0,0,0,-1,1,0,0,0,0,1,0];this._loadMatrix(t,e)}sepia(e){let t=[.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0];this._loadMatrix(t,e)}technicolor(e){let t=[1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0];this._loadMatrix(t,e)}polaroid(e){let t=[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0];this._loadMatrix(t,e)}toBGR(e){let t=[0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0];this._loadMatrix(t,e)}kodachrome(e){let t=[1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0];this._loadMatrix(t,e)}browni(e){let t=[.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0];this._loadMatrix(t,e)}vintage(e){let t=[.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0];this._loadMatrix(t,e)}colorTone(e,t,n,o,i){e||(e=.2),t||(t=.15),n||(n=16770432),o||(o=3375104);let s=Y.shared,[a,c,l]=s.setValue(n).toArray(),[f,u,m]=s.setValue(o).toArray(),d=[.3,.59,.11,0,0,a,c,l,e,0,f,u,m,t,0,a-f,c-u,l-m,0,0];this._loadMatrix(d,i)}night(e,t){e||(e=.1);let n=[e*-2,-e,0,0,0,-e,0,e,0,0,0,e,e*2,0,0,0,0,0,1,0];this._loadMatrix(n,t)}predator(e,t){let n=[11.224130630493164*e,-4.794486999511719*e,-2.8746118545532227*e,0*e,.40342438220977783*e,-3.6330697536468506*e,9.193157196044922*e,-2.951810836791992*e,0*e,-1.316135048866272*e,-3.2184197902679443*e,-4.2375030517578125*e,7.476448059082031*e,0*e,.8044459223747253*e,0,0,0,1,0];this._loadMatrix(n,t)}lsd(e){let t=[2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0];this._loadMatrix(t,e)}reset(){let e=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];this._loadMatrix(e,!1)}get matrix(){return this.resources.colorMatrixUniforms.uniforms.uColorMatrix}set matrix(e){this.resources.colorMatrixUniforms.uniforms.uColorMatrix=e}get alpha(){return this.resources.colorMatrixUniforms.uniforms.uAlpha}set alpha(e){this.resources.colorMatrixUniforms.uniforms.uAlpha=e}};var Pl=`
2734
2734
  in vec2 vTextureCoord;
2735
2735
  in vec4 vColor;
2736
2736
 
@@ -2864,7 +2864,7 @@ fn mainFragment(
2864
2864
  sample.b *= sample.a;
2865
2865
 
2866
2866
  return sample;
2867
- }`;var _l=class Il extends k{constructor(e={}){e={...Il.defaultOptions,...e};let t=A.from({vertex:{source:Ws,entryPoint:"mainVertex"},fragment:{source:Ws,entryPoint:"mainFragment"}}),n=P.from({vertex:Jt,fragment:Pl,name:"noise-filter"}),{noise:o,seed:i,...s}=e;super({...s,gpuProgram:t,glProgram:n,resources:{noiseUniforms:new Zt({uNoise:{value:1,type:"f32"},uSeed:{value:1,type:"f32"}})}}),this.noise=o,this.seed=i??Math.random()}get noise(){return this.resources.noiseUniforms.uniforms.uNoise}set noise(e){this.resources.noiseUniforms.uniforms.uNoise=e}get seed(){return this.resources.noiseUniforms.uniforms.uSeed}set seed(e){this.resources.noiseUniforms.uniforms.uSeed=e}};_l.defaultOptions={noise:.5};var js=_l;var jo=class extends wa{constructor(e,t){let{text:n,resolution:o,style:i,anchor:s,width:a,height:c,roundPixels:l,...f}=e;super({...f}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=t,this.text=n??"",this.style=i,this.resolution=o??null,this.allowChildren=!1,this._anchor=new Vr({_onUpdate:()=>{this.onViewUpdate()}}),s&&(this.anchor=s),this.roundPixels=l??!1,a!==void 0&&(this.width=a),c!==void 0&&(this.height=c)}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}set text(e){e=e.toString(),this._text!==e&&(this._text=e,this.onViewUpdate())}get text(){return this._text}set resolution(e){this._autoResolution=e===null,this._resolution=e,this.onViewUpdate()}get resolution(){return this._resolution}get style(){return this._style}set style(e){e||(e={}),this._style?.off("update",this.onViewUpdate,this),e instanceof this._styleClass?this._style=e:this._style=new this._styleClass(e),this._style.on("update",this.onViewUpdate,this),this.onViewUpdate()}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(e){this._setWidth(e,this.bounds.width)}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(e){this._setHeight(e,this.bounds.height)}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this.bounds.width,e.height=Math.abs(this.scale.y)*this.bounds.height,e}setSize(e,t){typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,this.bounds.width),t!==void 0&&this._setHeight(t,this.bounds.height)}containsPoint(e){let t=this.bounds.width,n=this.bounds.height,o=-t*this.anchor.x,i=0;return e.x>=o&&e.x<=o+t&&(i=-n*this.anchor.y,e.y>=i&&e.y<=i+n)}onViewUpdate(){this.didViewUpdate||(this._didTextUpdate=!0),super.onViewUpdate()}destroy(e=!1){super.destroy(e),this.owner=null,this._bounds=null,this._anchor=null,(typeof e=="boolean"?e:e?.style)&&this._style.destroy(e),this._style=null,this._text=null}get styleKey(){return`${this._text}:${this._style.styleKey}:${this._resolution}`}};function Al(r,e){let t=r[0]??{};return(typeof t=="string"||r[1])&&(U(Gr,`use new ${e}({ text: "hi!", style }) instead`),t={text:t,style:r[1]}),t}var Sn=class extends jo{constructor(...e){let t=Al(e,"Text");super(t,Ca),this.renderPipeId="text",t.textureStyle&&(this.textureStyle=t.textureStyle instanceof zi?t.textureStyle:new zi(t.textureStyle))}updateBounds(){let e=this._bounds,t=this._anchor,n=0,o=0;if(this._style.trim){let{frame:i,canvasAndContext:s}=Ri.getCanvasAndContext({text:this.text,style:this._style,resolution:1});Ri.returnCanvasAndContext(s),n=i.width,o=i.height}else{let i=ka.measureText(this._text,this._style);n=i.width,o=i.height}e.minX=-t._x*n,e.maxX=e.minX+n,e.minY=-t._y*o,e.maxY=e.minY+o}};Ta.add(ul,fl);var si={};qd(si,{AdjustmentFilter:()=>Rl,AdvancedBloomFilter:()=>Zl,AsciiFilter:()=>nu,BackdropBlurFilter:()=>Xo,BevelFilter:()=>uu,BloomFilter:()=>du,BulgePinchFilter:()=>yu,CRTFilter:()=>Qu,ColorGradientFilter:()=>wu,ColorMapFilter:()=>Iu,ColorOverlayFilter:()=>Du,ColorReplaceFilter:()=>Uu,ConvolutionFilter:()=>Hu,CrossHatchFilter:()=>Zo,DotFilter:()=>rf,DropShadowFilter:()=>cf,EmbossFilter:()=>Er,GlitchFilter:()=>hf,GlowFilter:()=>bf,GodrayFilter:()=>_f,GrayscaleFilter:()=>ei,HslAdjustmentFilter:()=>Of,KawaseBlurFilter:()=>Pr,MotionBlurFilter:()=>Nf,MultiColorReplaceFilter:()=>Hf,OldFilmFilter:()=>Yf,OutlineFilter:()=>Zf,PixelateFilter:()=>Dr,RGBSplitFilter:()=>gm,RadialBlurFilter:()=>im,ReflectionFilter:()=>um,ShockwaveFilter:()=>Sm,SimpleLightmapFilter:()=>Pm,SimplexNoiseFilter:()=>Em,TiltShiftAxisFilter:()=>Or,TiltShiftFilter:()=>ii,TwistFilter:()=>Vm,ZoomBlurFilter:()=>Xm,angleFromCssOrientation:()=>Js,angleFromDirectionalValue:()=>ea,colorAsStringFromCssStop:()=>Qs,offsetsFromCssColorStops:()=>Zs,parseCssGradient:()=>Yo,stopsFromCssStops:()=>$s,trimCssGradient:()=>ta,typeFromCssType:()=>Ys,vertex:()=>z,wgslVertex:()=>D});var z=`in vec2 aPosition;
2867
+ }`;var _l=class Il extends k{constructor(e={}){e={...Il.defaultOptions,...e};let t=A.from({vertex:{source:Ws,entryPoint:"mainVertex"},fragment:{source:Ws,entryPoint:"mainFragment"}}),n=P.from({vertex:tr,fragment:Pl,name:"noise-filter"}),{noise:o,seed:i,...s}=e;super({...s,gpuProgram:t,glProgram:n,resources:{noiseUniforms:new er({uNoise:{value:1,type:"f32"},uSeed:{value:1,type:"f32"}})}}),this.noise=o,this.seed=i??Math.random()}get noise(){return this.resources.noiseUniforms.uniforms.uNoise}set noise(e){this.resources.noiseUniforms.uniforms.uNoise=e}get seed(){return this.resources.noiseUniforms.uniforms.uSeed}set seed(e){this.resources.noiseUniforms.uniforms.uSeed=e}};_l.defaultOptions={noise:.5};var js=_l;var jo=class extends wa{constructor(e,t){let{text:n,resolution:o,style:i,anchor:s,width:a,height:c,roundPixels:l,...f}=e;super({...f}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=t,this.text=n??"",this.style=i,this.resolution=o??null,this.allowChildren=!1,this._anchor=new Gr({_onUpdate:()=>{this.onViewUpdate()}}),s&&(this.anchor=s),this.roundPixels=l??!1,a!==void 0&&(this.width=a),c!==void 0&&(this.height=c)}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}set text(e){e=e.toString(),this._text!==e&&(this._text=e,this.onViewUpdate())}get text(){return this._text}set resolution(e){this._autoResolution=e===null,this._resolution=e,this.onViewUpdate()}get resolution(){return this._resolution}get style(){return this._style}set style(e){e||(e={}),this._style?.off("update",this.onViewUpdate,this),e instanceof this._styleClass?this._style=e:this._style=new this._styleClass(e),this._style.on("update",this.onViewUpdate,this),this.onViewUpdate()}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(e){this._setWidth(e,this.bounds.width)}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(e){this._setHeight(e,this.bounds.height)}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this.bounds.width,e.height=Math.abs(this.scale.y)*this.bounds.height,e}setSize(e,t){typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,this.bounds.width),t!==void 0&&this._setHeight(t,this.bounds.height)}containsPoint(e){let t=this.bounds.width,n=this.bounds.height,o=-t*this.anchor.x,i=0;return e.x>=o&&e.x<=o+t&&(i=-n*this.anchor.y,e.y>=i&&e.y<=i+n)}onViewUpdate(){this.didViewUpdate||(this._didTextUpdate=!0),super.onViewUpdate()}destroy(e=!1){super.destroy(e),this.owner=null,this._bounds=null,this._anchor=null,(typeof e=="boolean"?e:e?.style)&&this._style.destroy(e),this._style=null,this._text=null}get styleKey(){return`${this._text}:${this._style.styleKey}:${this._resolution}`}};function Al(r,e){let t=r[0]??{};return(typeof t=="string"||r[1])&&(U(qr,`use new ${e}({ text: "hi!", style }) instead`),t={text:t,style:r[1]}),t}var Sn=class extends jo{constructor(...e){let t=Al(e,"Text");super(t,Ca),this.renderPipeId="text",t.textureStyle&&(this.textureStyle=t.textureStyle instanceof zi?t.textureStyle:new zi(t.textureStyle))}updateBounds(){let e=this._bounds,t=this._anchor,n=0,o=0;if(this._style.trim){let{frame:i,canvasAndContext:s}=Ri.getCanvasAndContext({text:this.text,style:this._style,resolution:1});Ri.returnCanvasAndContext(s),n=i.width,o=i.height}else{let i=ka.measureText(this._text,this._style);n=i.width,o=i.height}e.minX=-t._x*n,e.maxX=e.minX+n,e.minY=-t._y*o,e.maxY=e.minY+o}};Ta.add(ul,fl);var si={};qd(si,{AdjustmentFilter:()=>Rl,AdvancedBloomFilter:()=>Zl,AsciiFilter:()=>nu,BackdropBlurFilter:()=>Xo,BevelFilter:()=>uu,BloomFilter:()=>du,BulgePinchFilter:()=>yu,CRTFilter:()=>Qu,ColorGradientFilter:()=>wu,ColorMapFilter:()=>Iu,ColorOverlayFilter:()=>Du,ColorReplaceFilter:()=>Uu,ConvolutionFilter:()=>Hu,CrossHatchFilter:()=>Zo,DotFilter:()=>rf,DropShadowFilter:()=>cf,EmbossFilter:()=>zr,GlitchFilter:()=>hf,GlowFilter:()=>bf,GodrayFilter:()=>_f,GrayscaleFilter:()=>ei,HslAdjustmentFilter:()=>Of,KawaseBlurFilter:()=>_r,MotionBlurFilter:()=>Nf,MultiColorReplaceFilter:()=>Hf,OldFilmFilter:()=>Yf,OutlineFilter:()=>Zf,PixelateFilter:()=>Or,RGBSplitFilter:()=>gm,RadialBlurFilter:()=>im,ReflectionFilter:()=>um,ShockwaveFilter:()=>Sm,SimpleLightmapFilter:()=>Pm,SimplexNoiseFilter:()=>Em,TiltShiftAxisFilter:()=>Rr,TiltShiftFilter:()=>ii,TwistFilter:()=>Vm,ZoomBlurFilter:()=>Xm,angleFromCssOrientation:()=>Js,angleFromDirectionalValue:()=>ea,colorAsStringFromCssStop:()=>Qs,offsetsFromCssColorStops:()=>Zs,parseCssGradient:()=>Yo,stopsFromCssStops:()=>$s,trimCssGradient:()=>ta,typeFromCssType:()=>Ys,vertex:()=>z,wgslVertex:()=>D});var z=`in vec2 aPosition;
2868
2868
  out vec2 vTextureCoord;
2869
2869
 
2870
2870
  uniform vec4 uInputSize;
@@ -3127,7 +3127,7 @@ fn mainFragment(
3127
3127
  color *= 0.25;
3128
3128
 
3129
3129
  return color;
3130
- }`;var Rp=Object.defineProperty,Mp=(r,e,t)=>e in r?Rp(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Lt=(r,e,t)=>(Mp(r,typeof e!="symbol"?e+"":e,t),t),Ll=class Vl extends k{constructor(...e){let t=e[0]??{};(typeof t=="number"||Array.isArray(t))&&(U("6.0.0","KawaseBlurFilter constructor params are now options object. See params: { strength, quality, clamp, pixelSize }"),t={strength:t},e[1]!==void 0&&(t.quality=e[1]),e[2]!==void 0&&(t.clamp=e[2])),t={...Vl.DEFAULT_OPTIONS,...t};let n=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:t?.clamp?Nl:Bl,entryPoint:"mainFragment"}}),o=P.from({vertex:z,fragment:t?.clamp?Ul:Ml,name:"kawase-blur-filter"});super({gpuProgram:n,glProgram:o,resources:{kawaseBlurUniforms:{uOffset:{value:new Float32Array(2),type:"vec2<f32>"}}}}),Lt(this,"uniforms"),Lt(this,"_pixelSize",{x:0,y:0}),Lt(this,"_clamp"),Lt(this,"_kernels",[]),Lt(this,"_blur"),Lt(this,"_quality"),this.uniforms=this.resources.kawaseBlurUniforms.uniforms,this.pixelSize=t.pixelSize??{x:1,y:1},Array.isArray(t.strength)?this.kernels=t.strength:typeof t.strength=="number"&&(this._blur=t.strength,this.quality=t.quality??3),this._clamp=!!t.clamp}apply(e,t,n,o){let i=this.pixelSizeX/t.source.width,s=this.pixelSizeY/t.source.height,a;if(this._quality===1||this._blur===0)a=this._kernels[0]+.5,this.uniforms.uOffset[0]=a*i,this.uniforms.uOffset[1]=a*s,e.applyFilter(this,t,n,o);else{let c=Q.getSameSizeTexture(t),l=t,f=c,u,m=this._quality-1;for(let d=0;d<m;d++)a=this._kernels[d]+.5,this.uniforms.uOffset[0]=a*i,this.uniforms.uOffset[1]=a*s,e.applyFilter(this,l,f,!0),u=l,l=f,f=u;a=this._kernels[m]+.5,this.uniforms.uOffset[0]=a*i,this.uniforms.uOffset[1]=a*s,e.applyFilter(this,l,n,o),Q.returnTexture(c)}}get strength(){return this._blur}set strength(e){this._blur=e,this._generateKernels()}get quality(){return this._quality}set quality(e){this._quality=Math.max(1,Math.round(e)),this._generateKernels()}get kernels(){return this._kernels}set kernels(e){Array.isArray(e)&&e.length>0?(this._kernels=e,this._quality=e.length,this._blur=Math.max(...e)):(this._kernels=[0],this._quality=1)}get pixelSize(){return this._pixelSize}set pixelSize(e){if(typeof e=="number"){this.pixelSizeX=this.pixelSizeY=e;return}if(Array.isArray(e)){this.pixelSizeX=e[0],this.pixelSizeY=e[1];return}this._pixelSize=e}get pixelSizeX(){return this.pixelSize.x}set pixelSizeX(e){this.pixelSize.x=e}get pixelSizeY(){return this.pixelSize.y}set pixelSizeY(e){this.pixelSize.y=e}get clamp(){return this._clamp}_updatePadding(){this.padding=Math.ceil(this._kernels.reduce((e,t)=>e+t+.5,0))}_generateKernels(){let e=this._blur,t=this._quality,n=[e];if(e>0){let o=e,i=e/t;for(let s=1;s<t;s++)o-=i,n.push(o)}this._kernels=n,this._updatePadding()}};Lt(Ll,"DEFAULT_OPTIONS",{strength:4,quality:3,clamp:!1,pixelSize:{x:1,y:1}});var Pr=Ll;var Gl=`in vec2 vTextureCoord;
3130
+ }`;var Rp=Object.defineProperty,Mp=(r,e,t)=>e in r?Rp(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Gt=(r,e,t)=>(Mp(r,typeof e!="symbol"?e+"":e,t),t),Ll=class Vl extends k{constructor(...e){let t=e[0]??{};(typeof t=="number"||Array.isArray(t))&&(U("6.0.0","KawaseBlurFilter constructor params are now options object. See params: { strength, quality, clamp, pixelSize }"),t={strength:t},e[1]!==void 0&&(t.quality=e[1]),e[2]!==void 0&&(t.clamp=e[2])),t={...Vl.DEFAULT_OPTIONS,...t};let n=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:t?.clamp?Nl:Bl,entryPoint:"mainFragment"}}),o=P.from({vertex:z,fragment:t?.clamp?Ul:Ml,name:"kawase-blur-filter"});super({gpuProgram:n,glProgram:o,resources:{kawaseBlurUniforms:{uOffset:{value:new Float32Array(2),type:"vec2<f32>"}}}}),Gt(this,"uniforms"),Gt(this,"_pixelSize",{x:0,y:0}),Gt(this,"_clamp"),Gt(this,"_kernels",[]),Gt(this,"_blur"),Gt(this,"_quality"),this.uniforms=this.resources.kawaseBlurUniforms.uniforms,this.pixelSize=t.pixelSize??{x:1,y:1},Array.isArray(t.strength)?this.kernels=t.strength:typeof t.strength=="number"&&(this._blur=t.strength,this.quality=t.quality??3),this._clamp=!!t.clamp}apply(e,t,n,o){let i=this.pixelSizeX/t.source.width,s=this.pixelSizeY/t.source.height,a;if(this._quality===1||this._blur===0)a=this._kernels[0]+.5,this.uniforms.uOffset[0]=a*i,this.uniforms.uOffset[1]=a*s,e.applyFilter(this,t,n,o);else{let c=Q.getSameSizeTexture(t),l=t,f=c,u,m=this._quality-1;for(let d=0;d<m;d++)a=this._kernels[d]+.5,this.uniforms.uOffset[0]=a*i,this.uniforms.uOffset[1]=a*s,e.applyFilter(this,l,f,!0),u=l,l=f,f=u;a=this._kernels[m]+.5,this.uniforms.uOffset[0]=a*i,this.uniforms.uOffset[1]=a*s,e.applyFilter(this,l,n,o),Q.returnTexture(c)}}get strength(){return this._blur}set strength(e){this._blur=e,this._generateKernels()}get quality(){return this._quality}set quality(e){this._quality=Math.max(1,Math.round(e)),this._generateKernels()}get kernels(){return this._kernels}set kernels(e){Array.isArray(e)&&e.length>0?(this._kernels=e,this._quality=e.length,this._blur=Math.max(...e)):(this._kernels=[0],this._quality=1)}get pixelSize(){return this._pixelSize}set pixelSize(e){if(typeof e=="number"){this.pixelSizeX=this.pixelSizeY=e;return}if(Array.isArray(e)){this.pixelSizeX=e[0],this.pixelSizeY=e[1];return}this._pixelSize=e}get pixelSizeX(){return this.pixelSize.x}set pixelSizeX(e){this.pixelSize.x=e}get pixelSizeY(){return this.pixelSize.y}set pixelSizeY(e){this.pixelSize.y=e}get clamp(){return this._clamp}_updatePadding(){this.padding=Math.ceil(this._kernels.reduce((e,t)=>e+t+.5,0))}_generateKernels(){let e=this._blur,t=this._quality,n=[e];if(e>0){let o=e,i=e/t;for(let s=1;s<t;s++)o-=i,n.push(o)}this._kernels=n,this._updatePadding()}};Gt(Ll,"DEFAULT_OPTIONS",{strength:4,quality:3,clamp:!1,pixelSize:{x:1,y:1}});var _r=Ll;var Gl=`in vec2 vTextureCoord;
3131
3131
  out vec4 finalColor;
3132
3132
 
3133
3133
  uniform sampler2D uTexture;
@@ -3210,7 +3210,7 @@ fn mainFragment(
3210
3210
 
3211
3211
  return select(vec4<f32>(0.), color, brightness > extractBrightnessUniforms.uThreshold);
3212
3212
  }
3213
- `;var Bp=Object.defineProperty,Up=(r,e,t)=>e in r?Bp(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,jl=(r,e,t)=>(Up(r,typeof e!="symbol"?e+"":e,t),t),Xl=class Kl extends k{constructor(e){e={...Kl.DEFAULT_OPTIONS,...e};let t=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:Wl,entryPoint:"mainFragment"}}),n=P.from({vertex:z,fragment:Hl,name:"extract-brightness-filter"});super({gpuProgram:t,glProgram:n,resources:{extractBrightnessUniforms:{uThreshold:{value:e.threshold,type:"f32"}}}}),jl(this,"uniforms"),this.uniforms=this.resources.extractBrightnessUniforms.uniforms}get threshold(){return this.uniforms.uThreshold}set threshold(e){this.uniforms.uThreshold=e}};jl(Xl,"DEFAULT_OPTIONS",{threshold:.5});var Yl=Xl;var Np=Object.defineProperty,Lp=(r,e,t)=>e in r?Np(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,_r=(r,e,t)=>(Lp(r,typeof e!="symbol"?e+"":e,t),t),$l=class Ql extends k{constructor(e){e={...Ql.DEFAULT_OPTIONS,...e};let t=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:ql,entryPoint:"mainFragment"}}),n=P.from({vertex:z,fragment:Gl,name:"advanced-bloom-filter"});super({gpuProgram:t,glProgram:n,resources:{advancedBloomUniforms:{uBloomScale:{value:e.bloomScale,type:"f32"},uBrightness:{value:e.brightness,type:"f32"}},uMapTexture:ne.WHITE}}),_r(this,"uniforms"),_r(this,"bloomScale",1),_r(this,"brightness",1),_r(this,"_extractFilter"),_r(this,"_blurFilter"),this.uniforms=this.resources.advancedBloomUniforms.uniforms,this._extractFilter=new Yl({threshold:e.threshold}),this._blurFilter=new Pr({strength:e.kernels??e.blur,quality:e.kernels?void 0:e.quality}),Object.assign(this,e)}apply(e,t,n,o){let i=Q.getSameSizeTexture(t);this._extractFilter.apply(e,t,i,!0);let s=Q.getSameSizeTexture(t);this._blurFilter.apply(e,i,s,!0),this.uniforms.uBloomScale=this.bloomScale,this.uniforms.uBrightness=this.brightness,this.resources.uMapTexture=s.source,e.applyFilter(this,t,n,o),Q.returnTexture(s),Q.returnTexture(i)}get threshold(){return this._extractFilter.threshold}set threshold(e){this._extractFilter.threshold=e}get kernels(){return this._blurFilter.kernels}set kernels(e){this._blurFilter.kernels=e}get blur(){return this._blurFilter.strength}set blur(e){this._blurFilter.strength=e}get quality(){return this._blurFilter.quality}set quality(e){this._blurFilter.quality=e}get pixelSize(){return this._blurFilter.pixelSize}set pixelSize(e){typeof e=="number"&&(e={x:e,y:e}),Array.isArray(e)&&(e={x:e[0],y:e[1]}),this._blurFilter.pixelSize=e}get pixelSizeX(){return this._blurFilter.pixelSizeX}set pixelSizeX(e){this._blurFilter.pixelSizeX=e}get pixelSizeY(){return this._blurFilter.pixelSizeY}set pixelSizeY(e){this._blurFilter.pixelSizeY=e}};_r($l,"DEFAULT_OPTIONS",{threshold:.5,bloomScale:1,brightness:1,blur:8,quality:4,pixelSize:{x:1,y:1}});var Zl=$l;var Jl=`precision highp float;
3213
+ `;var Bp=Object.defineProperty,Up=(r,e,t)=>e in r?Bp(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,jl=(r,e,t)=>(Up(r,typeof e!="symbol"?e+"":e,t),t),Xl=class Kl extends k{constructor(e){e={...Kl.DEFAULT_OPTIONS,...e};let t=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:Wl,entryPoint:"mainFragment"}}),n=P.from({vertex:z,fragment:Hl,name:"extract-brightness-filter"});super({gpuProgram:t,glProgram:n,resources:{extractBrightnessUniforms:{uThreshold:{value:e.threshold,type:"f32"}}}}),jl(this,"uniforms"),this.uniforms=this.resources.extractBrightnessUniforms.uniforms}get threshold(){return this.uniforms.uThreshold}set threshold(e){this.uniforms.uThreshold=e}};jl(Xl,"DEFAULT_OPTIONS",{threshold:.5});var Yl=Xl;var Np=Object.defineProperty,Lp=(r,e,t)=>e in r?Np(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ir=(r,e,t)=>(Lp(r,typeof e!="symbol"?e+"":e,t),t),$l=class Ql extends k{constructor(e){e={...Ql.DEFAULT_OPTIONS,...e};let t=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:ql,entryPoint:"mainFragment"}}),n=P.from({vertex:z,fragment:Gl,name:"advanced-bloom-filter"});super({gpuProgram:t,glProgram:n,resources:{advancedBloomUniforms:{uBloomScale:{value:e.bloomScale,type:"f32"},uBrightness:{value:e.brightness,type:"f32"}},uMapTexture:ne.WHITE}}),Ir(this,"uniforms"),Ir(this,"bloomScale",1),Ir(this,"brightness",1),Ir(this,"_extractFilter"),Ir(this,"_blurFilter"),this.uniforms=this.resources.advancedBloomUniforms.uniforms,this._extractFilter=new Yl({threshold:e.threshold}),this._blurFilter=new _r({strength:e.kernels??e.blur,quality:e.kernels?void 0:e.quality}),Object.assign(this,e)}apply(e,t,n,o){let i=Q.getSameSizeTexture(t);this._extractFilter.apply(e,t,i,!0);let s=Q.getSameSizeTexture(t);this._blurFilter.apply(e,i,s,!0),this.uniforms.uBloomScale=this.bloomScale,this.uniforms.uBrightness=this.brightness,this.resources.uMapTexture=s.source,e.applyFilter(this,t,n,o),Q.returnTexture(s),Q.returnTexture(i)}get threshold(){return this._extractFilter.threshold}set threshold(e){this._extractFilter.threshold=e}get kernels(){return this._blurFilter.kernels}set kernels(e){this._blurFilter.kernels=e}get blur(){return this._blurFilter.strength}set blur(e){this._blurFilter.strength=e}get quality(){return this._blurFilter.quality}set quality(e){this._blurFilter.quality=e}get pixelSize(){return this._blurFilter.pixelSize}set pixelSize(e){typeof e=="number"&&(e={x:e,y:e}),Array.isArray(e)&&(e={x:e[0],y:e[1]}),this._blurFilter.pixelSize=e}get pixelSizeX(){return this._blurFilter.pixelSizeX}set pixelSizeX(e){this._blurFilter.pixelSizeX=e}get pixelSizeY(){return this._blurFilter.pixelSizeY}set pixelSizeY(e){this._blurFilter.pixelSizeY=e}};Ir($l,"DEFAULT_OPTIONS",{threshold:.5,bloomScale:1,brightness:1,blur:8,quality:4,pixelSize:{x:1,y:1}});var Zl=$l;var Jl=`precision highp float;
3214
3214
  in vec2 vTextureCoord;
3215
3215
  out vec4 finalColor;
3216
3216
 
@@ -3508,7 +3508,7 @@ fn mainFragment(
3508
3508
  color = vec4<f32>(mix(color.rgb, shadow.rgb, clamp((color.a - shadowSample) * shadow.a, 0.0, 1.0)), color.a);
3509
3509
 
3510
3510
  return vec4<f32>(color.rgb * color.a, color.a);
3511
- }`;var jp=Object.defineProperty,Xp=(r,e,t)=>e in r?jp(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ir=(r,e,t)=>(Xp(r,typeof e!="symbol"?e+"":e,t),t),cu=class lu extends k{constructor(e){e={...lu.DEFAULT_OPTIONS,...e};let t=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:au,entryPoint:"mainFragment"}}),n=P.from({vertex:z,fragment:su,name:"bevel-filter"});super({gpuProgram:t,glProgram:n,resources:{bevelUniforms:{uLightColor:{value:new Float32Array(3),type:"vec3<f32>"},uLightAlpha:{value:e.lightAlpha,type:"f32"},uShadowColor:{value:new Float32Array(3),type:"vec3<f32>"},uShadowAlpha:{value:e.shadowAlpha,type:"f32"},uTransform:{value:new Float32Array(2),type:"vec2<f32>"}}},padding:1}),Ir(this,"uniforms"),Ir(this,"_thickness"),Ir(this,"_rotation"),Ir(this,"_lightColor"),Ir(this,"_shadowColor"),this.uniforms=this.resources.bevelUniforms.uniforms,this._lightColor=new Y,this._shadowColor=new Y,this.lightColor=e.lightColor??16777215,this.shadowColor=e.shadowColor??0,Object.assign(this,e)}get rotation(){return this._rotation/Ge}set rotation(e){this._rotation=e*Ge,this._updateTransform()}get thickness(){return this._thickness}set thickness(e){this._thickness=e,this._updateTransform()}get lightColor(){return this._lightColor.value}set lightColor(e){this._lightColor.setValue(e);let[t,n,o]=this._lightColor.toArray();this.uniforms.uLightColor[0]=t,this.uniforms.uLightColor[1]=n,this.uniforms.uLightColor[2]=o}get lightAlpha(){return this.uniforms.uLightAlpha}set lightAlpha(e){this.uniforms.uLightAlpha=e}get shadowColor(){return this._shadowColor.value}set shadowColor(e){this._shadowColor.setValue(e);let[t,n,o]=this._shadowColor.toArray();this.uniforms.uShadowColor[0]=t,this.uniforms.uShadowColor[1]=n,this.uniforms.uShadowColor[2]=o}get shadowAlpha(){return this.uniforms.uShadowAlpha}set shadowAlpha(e){this.uniforms.uShadowAlpha=e}_updateTransform(){this.uniforms.uTransform[0]=this.thickness*Math.cos(this._rotation),this.uniforms.uTransform[1]=this.thickness*Math.sin(this._rotation)}};Ir(cu,"DEFAULT_OPTIONS",{rotation:45,thickness:2,lightColor:16777215,lightAlpha:.7,shadowColor:0,shadowAlpha:.7});var uu=cu;var Kp=Object.defineProperty,Yp=(r,e,t)=>e in r?Kp(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ko=(r,e,t)=>(Yp(r,typeof e!="symbol"?e+"":e,t),t),fu=class mu extends bn{constructor(...e){let t=e[0]??{};if(typeof t=="number"||Array.isArray(t)||"x"in t&&"y"in t){U("6.0.0","BloomFilter constructor params are now options object. See params: { strength, quality, resolution, kernelSize }");let n=t;Array.isArray(n)&&(n={x:n[0],y:n[1]}),t={strength:n},e[1]!==void 0&&(t.quality=e[1]),e[2]!==void 0&&(t.resolution=e[2]),e[3]!==void 0&&(t.kernelSize=e[3])}t={...mu.DEFAULT_OPTIONS,...t},super(),Ko(this,"_blurXFilter"),Ko(this,"_blurYFilter"),Ko(this,"_strength"),this._strength={x:2,y:2},t.strength&&(typeof t.strength=="number"?(this._strength.x=t.strength,this._strength.y=t.strength):(this._strength.x=t.strength.x,this._strength.y=t.strength.y)),this._blurXFilter=new ht({...t,horizontal:!0,strength:this.strengthX}),this._blurYFilter=new ht({...t,horizontal:!1,strength:this.strengthY}),this._blurYFilter.blendMode="screen",Object.assign(this,t)}apply(e,t,n,o){let i=Q.getSameSizeTexture(t);e.applyFilter(this,t,n,o),this._blurXFilter.apply(e,t,i,!0),this._blurYFilter.apply(e,i,n,!1),Q.returnTexture(i)}get strength(){return this._strength}set strength(e){this._strength=typeof e=="number"?{x:e,y:e}:e,this._updateStrength()}get strengthX(){return this.strength.x}set strengthX(e){this.strength.x=e,this._updateStrength()}get strengthY(){return this.strength.y}set strengthY(e){this.strength.y=e,this._updateStrength()}_updateStrength(){this._blurXFilter.blur=this.strengthX,this._blurYFilter.blur=this.strengthY}get blur(){return U("6.0.0","BloomFilter.blur is deprecated, please use BloomFilter.strength instead"),this.strengthX}set blur(e){U("6.0.0","BloomFilter.blur is deprecated, please use BloomFilter.strength instead"),this.strength=e}get blurX(){return U("6.0.0","BloomFilter.blurX is deprecated, please use BloomFilter.strengthX instead"),this.strengthX}set blurX(e){U("6.0.0","BloomFilter.blurX is deprecated, please use BloomFilter.strengthX instead"),this.strengthX=e}get blurY(){return U("6.0.0","BloomFilter.blurY is deprecated, please use BloomFilter.strengthY instead"),this.strengthY}set blurY(e){U("6.0.0","BloomFilter.blurY is deprecated, please use BloomFilter.strengthY instead"),this.strengthY=e}};Ko(fu,"DEFAULT_OPTIONS",{strength:{x:2,y:2},quality:4,resolution:1,kernelSize:5});var du=fu;var pu=`precision highp float;
3511
+ }`;var jp=Object.defineProperty,Xp=(r,e,t)=>e in r?jp(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ar=(r,e,t)=>(Xp(r,typeof e!="symbol"?e+"":e,t),t),cu=class lu extends k{constructor(e){e={...lu.DEFAULT_OPTIONS,...e};let t=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:au,entryPoint:"mainFragment"}}),n=P.from({vertex:z,fragment:su,name:"bevel-filter"});super({gpuProgram:t,glProgram:n,resources:{bevelUniforms:{uLightColor:{value:new Float32Array(3),type:"vec3<f32>"},uLightAlpha:{value:e.lightAlpha,type:"f32"},uShadowColor:{value:new Float32Array(3),type:"vec3<f32>"},uShadowAlpha:{value:e.shadowAlpha,type:"f32"},uTransform:{value:new Float32Array(2),type:"vec2<f32>"}}},padding:1}),Ar(this,"uniforms"),Ar(this,"_thickness"),Ar(this,"_rotation"),Ar(this,"_lightColor"),Ar(this,"_shadowColor"),this.uniforms=this.resources.bevelUniforms.uniforms,this._lightColor=new Y,this._shadowColor=new Y,this.lightColor=e.lightColor??16777215,this.shadowColor=e.shadowColor??0,Object.assign(this,e)}get rotation(){return this._rotation/Ge}set rotation(e){this._rotation=e*Ge,this._updateTransform()}get thickness(){return this._thickness}set thickness(e){this._thickness=e,this._updateTransform()}get lightColor(){return this._lightColor.value}set lightColor(e){this._lightColor.setValue(e);let[t,n,o]=this._lightColor.toArray();this.uniforms.uLightColor[0]=t,this.uniforms.uLightColor[1]=n,this.uniforms.uLightColor[2]=o}get lightAlpha(){return this.uniforms.uLightAlpha}set lightAlpha(e){this.uniforms.uLightAlpha=e}get shadowColor(){return this._shadowColor.value}set shadowColor(e){this._shadowColor.setValue(e);let[t,n,o]=this._shadowColor.toArray();this.uniforms.uShadowColor[0]=t,this.uniforms.uShadowColor[1]=n,this.uniforms.uShadowColor[2]=o}get shadowAlpha(){return this.uniforms.uShadowAlpha}set shadowAlpha(e){this.uniforms.uShadowAlpha=e}_updateTransform(){this.uniforms.uTransform[0]=this.thickness*Math.cos(this._rotation),this.uniforms.uTransform[1]=this.thickness*Math.sin(this._rotation)}};Ar(cu,"DEFAULT_OPTIONS",{rotation:45,thickness:2,lightColor:16777215,lightAlpha:.7,shadowColor:0,shadowAlpha:.7});var uu=cu;var Kp=Object.defineProperty,Yp=(r,e,t)=>e in r?Kp(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ko=(r,e,t)=>(Yp(r,typeof e!="symbol"?e+"":e,t),t),fu=class mu extends bn{constructor(...e){let t=e[0]??{};if(typeof t=="number"||Array.isArray(t)||"x"in t&&"y"in t){U("6.0.0","BloomFilter constructor params are now options object. See params: { strength, quality, resolution, kernelSize }");let n=t;Array.isArray(n)&&(n={x:n[0],y:n[1]}),t={strength:n},e[1]!==void 0&&(t.quality=e[1]),e[2]!==void 0&&(t.resolution=e[2]),e[3]!==void 0&&(t.kernelSize=e[3])}t={...mu.DEFAULT_OPTIONS,...t},super(),Ko(this,"_blurXFilter"),Ko(this,"_blurYFilter"),Ko(this,"_strength"),this._strength={x:2,y:2},t.strength&&(typeof t.strength=="number"?(this._strength.x=t.strength,this._strength.y=t.strength):(this._strength.x=t.strength.x,this._strength.y=t.strength.y)),this._blurXFilter=new ht({...t,horizontal:!0,strength:this.strengthX}),this._blurYFilter=new ht({...t,horizontal:!1,strength:this.strengthY}),this._blurYFilter.blendMode="screen",Object.assign(this,t)}apply(e,t,n,o){let i=Q.getSameSizeTexture(t);e.applyFilter(this,t,n,o),this._blurXFilter.apply(e,t,i,!0),this._blurYFilter.apply(e,i,n,!1),Q.returnTexture(i)}get strength(){return this._strength}set strength(e){this._strength=typeof e=="number"?{x:e,y:e}:e,this._updateStrength()}get strengthX(){return this.strength.x}set strengthX(e){this.strength.x=e,this._updateStrength()}get strengthY(){return this.strength.y}set strengthY(e){this.strength.y=e,this._updateStrength()}_updateStrength(){this._blurXFilter.blur=this.strengthX,this._blurYFilter.blur=this.strengthY}get blur(){return U("6.0.0","BloomFilter.blur is deprecated, please use BloomFilter.strength instead"),this.strengthX}set blur(e){U("6.0.0","BloomFilter.blur is deprecated, please use BloomFilter.strength instead"),this.strength=e}get blurX(){return U("6.0.0","BloomFilter.blurX is deprecated, please use BloomFilter.strengthX instead"),this.strengthX}set blurX(e){U("6.0.0","BloomFilter.blurX is deprecated, please use BloomFilter.strengthX instead"),this.strengthX=e}get blurY(){return U("6.0.0","BloomFilter.blurY is deprecated, please use BloomFilter.strengthY instead"),this.strengthY}set blurY(e){U("6.0.0","BloomFilter.blurY is deprecated, please use BloomFilter.strengthY instead"),this.strengthY=e}};Ko(fu,"DEFAULT_OPTIONS",{strength:{x:2,y:2},quality:4,resolution:1,kernelSize:5});var du=fu;var pu=`precision highp float;
3512
3512
  in vec2 vTextureCoord;
3513
3513
  out vec4 finalColor;
3514
3514
 
@@ -3980,7 +3980,7 @@ const PI_2: f32 = PI * 2.0;
3980
3980
  const TYPE_LINEAR: i32 = 0;
3981
3981
  const TYPE_RADIAL: i32 = 1;
3982
3982
  const TYPE_CONIC: i32 = 2;
3983
- const MAX_STOPS: i32 = 32;`;var Vt=Vt||{};Vt.stringify=(function(){var r={"visit_linear-gradient":function(e){return r.visit_gradient(e)},"visit_repeating-linear-gradient":function(e){return r.visit_gradient(e)},"visit_radial-gradient":function(e){return r.visit_gradient(e)},"visit_repeating-radial-gradient":function(e){return r.visit_gradient(e)},visit_gradient:function(e){var t=r.visit(e.orientation);return t&&(t+=", "),e.type+"("+t+r.visit(e.colorStops)+")"},visit_shape:function(e){var t=e.value,n=r.visit(e.at),o=r.visit(e.style);return o&&(t+=" "+o),n&&(t+=" at "+n),t},"visit_default-radial":function(e){var t="",n=r.visit(e.at);return n&&(t+=n),t},"visit_extent-keyword":function(e){var t=e.value,n=r.visit(e.at);return n&&(t+=" at "+n),t},"visit_position-keyword":function(e){return e.value},visit_position:function(e){return r.visit(e.value.x)+" "+r.visit(e.value.y)},"visit_%":function(e){return e.value+"%"},visit_em:function(e){return e.value+"em"},visit_px:function(e){return e.value+"px"},visit_literal:function(e){return r.visit_color(e.value,e)},visit_hex:function(e){return r.visit_color("#"+e.value,e)},visit_rgb:function(e){return r.visit_color("rgb("+e.value.join(", ")+")",e)},visit_rgba:function(e){return r.visit_color("rgba("+e.value.join(", ")+")",e)},visit_color:function(e,t){var n=e,o=r.visit(t.length);return o&&(n+=" "+o),n},visit_angular:function(e){return e.value+"deg"},visit_directional:function(e){return"to "+e.value},visit_array:function(e){var t="",n=e.length;return e.forEach(function(o,i){t+=r.visit(o),i<n-1&&(t+=", ")}),t},visit:function(e){if(!e)return"";var t="";if(e instanceof Array)return r.visit_array(e,t);if(e.type){var n=r["visit_"+e.type];if(n)return n(e);throw Error("Missing visitor visit_"+e.type)}else throw Error("Invalid node.")}};return function(e){return r.visit(e)}})();var Vt=Vt||{};Vt.parse=(function(){var r={linearGradient:/^(\-(webkit|o|ms|moz)\-)?(linear\-gradient)/i,repeatingLinearGradient:/^(\-(webkit|o|ms|moz)\-)?(repeating\-linear\-gradient)/i,radialGradient:/^(\-(webkit|o|ms|moz)\-)?(radial\-gradient)/i,repeatingRadialGradient:/^(\-(webkit|o|ms|moz)\-)?(repeating\-radial\-gradient)/i,sideOrCorner:/^to (left (top|bottom)|right (top|bottom)|left|right|top|bottom)/i,extentKeywords:/^(closest\-side|closest\-corner|farthest\-side|farthest\-corner|contain|cover)/,positionKeywords:/^(left|center|right|top|bottom)/i,pixelValue:/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))px/,percentageValue:/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))\%/,emValue:/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))em/,angleValue:/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))deg/,startCall:/^\(/,endCall:/^\)/,comma:/^,/,hexColor:/^\#([0-9a-fA-F]+)/,literalColor:/^([a-zA-Z]+)/,rgbColor:/^rgb/i,rgbaColor:/^rgba/i,number:/^(([0-9]*\.[0-9]+)|([0-9]+\.?))/},e="";function t(N){var K=new Error(e+": "+N);throw K.source=e,K}function n(){var N=o();return e.length>0&&t("Invalid input not EOF"),N}function o(){return S(i)}function i(){return s("linear-gradient",r.linearGradient,c)||s("repeating-linear-gradient",r.repeatingLinearGradient,c)||s("radial-gradient",r.radialGradient,u)||s("repeating-radial-gradient",r.repeatingRadialGradient,u)}function s(N,K,re){return a(K,function(nt){var Sa=re();return Sa&&(rt(r.comma)||t("Missing comma before color stops")),{type:N,orientation:Sa,colorStops:S(C)}})}function a(N,K){var re=rt(N);if(re){rt(r.startCall)||t("Missing (");var nt=K(re);return rt(r.endCall)||t("Missing )"),nt}}function c(){return l()||f()}function l(){return be("directional",r.sideOrCorner,1)}function f(){return be("angular",r.angleValue,1)}function u(){var N,K=m(),re;return K&&(N=[],N.push(K),re=e,rt(r.comma)&&(K=m(),K?N.push(K):e=re)),N}function m(){var N=d()||p();if(N)N.at=x();else{var K=h();if(K){N=K;var re=x();re&&(N.at=re)}else{var nt=y();nt&&(N={type:"default-radial",at:nt})}}return N}function d(){var N=be("shape",/^(circle)/i,0);return N&&(N.style=Ee()||h()),N}function p(){var N=be("shape",/^(ellipse)/i,0);return N&&(N.style=V()||h()),N}function h(){return be("extent-keyword",r.extentKeywords,1)}function x(){if(be("position",/^at/,0)){var N=y();return N||t("Missing positioning value"),N}}function y(){var N=v();if(N.x||N.y)return{type:"position",value:N}}function v(){return{x:V(),y:V()}}function S(N){var K=N(),re=[];if(K)for(re.push(K);rt(r.comma);)K=N(),K?re.push(K):t("One extra comma");return re}function C(){var N=_();return N||t("Expected color definition"),N.length=V(),N}function _(){return E()||M()||I()||T()}function T(){return be("literal",r.literalColor,0)}function E(){return be("hex",r.hexColor,1)}function I(){return a(r.rgbColor,function(){return{type:"rgb",value:S(L)}})}function M(){return a(r.rgbaColor,function(){return{type:"rgba",value:S(L)}})}function L(){return rt(r.number)[1]}function V(){return be("%",r.percentageValue,1)||te()||Ee()}function te(){return be("position-keyword",r.positionKeywords,1)}function Ee(){return be("px",r.pixelValue,1)||be("em",r.emValue,1)}function be(N,K,re){var nt=rt(K);if(nt)return{type:N,value:nt[re]}}function rt(N){var K,re;return re=/^[\n\r\t\s]+/.exec(e),re&&ba(re[0].length),K=N.exec(e),K&&ba(K[0].length),K}function ba(N){e=e.substr(N)}return function(N){return e=N.toString(),n()}})();var Tu=Vt.parse;Vt.stringify;function Yo(r){let e=Tu(ta(r));if(e.length===0)throw new Error("Invalid CSS gradient.");if(e.length!==1)throw new Error("Unsupported CSS gradient (multiple gradients is not supported).");let t=e[0],n=Ys(t.type),o=$s(t.colorStops),i=Js(t.orientation);return{type:n,stops:o,angle:i}}function Ys(r){let e={"linear-gradient":0,"radial-gradient":1};if(!(r in e))throw new Error(`Unsupported gradient type "${r}"`);return e[r]}function $s(r){let e=Zs(r),t=[],n=new Y;for(let o=0;o<r.length;o++){let i=Qs(r[o]),s=n.setValue(i).toArray();t.push({offset:e[o],color:s.slice(0,3),alpha:s[3]})}return t}function Qs(r){switch(r.type){case"hex":return`#${r.value}`;case"literal":return r.value;default:return`${r.type}(${r.value.join(",")})`}}function Zs(r){let e=[];for(let i=0;i<r.length;i++){let s=r[i],a=-1;s.type==="literal"&&s.length&&"type"in s.length&&s.length.type==="%"&&"value"in s.length&&(a=parseFloat(s.length.value)/100),e.push(a)}let n=i=>{for(let s=i;s<e.length;s++)if(e[s]!==-1)return{indexDelta:s-i,offset:e[s]};return{indexDelta:e.length-1-i,offset:1}},o=0;for(let i=0;i<e.length;i++){let s=e[i];if(s!==-1)o=s;else if(i===0)e[i]=0;else if(i+1===e.length)e[i]=1;else{let a=n(i),l=(a.offset-o)/(1+a.indexDelta);for(let f=0;f<=a.indexDelta;f++)e[i+f]=o+(f+1)*l;i+=a.indexDelta,o=e[i]}}return e.map(Zp)}function Zp(r){return r.toString().length>6?parseFloat(r.toString().substring(0,6)):r}function Js(r){if(typeof r>"u")return 0;if("type"in r&&"value"in r)switch(r.type){case"angular":return parseFloat(r.value);case"directional":return ea(r.value)}return 0}function ea(r){let e={left:270,top:0,bottom:180,right:90,"left top":315,"top left":315,"left bottom":225,"bottom left":225,"right top":45,"top right":45,"right bottom":135,"bottom right":135};if(!(r in e))throw new Error(`Unsupported directional value "${r}"`);return e[r]}function ta(r){let e=r.replace(/\s{2,}/gu," ");return e=e.replace(/;/g,""),e=e.replace(/ ,/g,","),e=e.replace(/\( /g,"("),e=e.replace(/ \)/g,")"),e.trim()}var Jp=Object.defineProperty,eh=(r,e,t)=>e in r?Jp(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Gt=(r,e,t)=>(eh(r,typeof e!="symbol"?e+"":e,t),t),ra=90;function th(r){return[...r].sort((e,t)=>e.offset-t.offset)}var Ar=class $o extends k{constructor(e){if(e&&"css"in e?e={...Yo(e.css||""),alpha:e.alpha??$o.defaults.alpha,maxColors:e.maxColors??$o.defaults.maxColors}:e={...$o.defaults,...e},!e.stops||e.stops.length<2)throw new Error("ColorGradientFilter requires at least 2 color stops.");let t=A.from({vertex:{source:Ks,entryPoint:"mainVertex"},fragment:{source:Ks,entryPoint:"mainFragment"}}),n=P.from({vertex:Su,fragment:bu,name:"color-gradient-filter"}),o=32;super({gpuProgram:t,glProgram:n,resources:{baseUniforms:{uOptions:{value:[e.type,e.angle??ra,e.alpha,e.replace?1:0],type:"vec4<f32>"},uCounts:{value:[e.stops.length,e.maxColors],type:"vec2<f32>"}},stopsUniforms:{uColors:{value:new Float32Array(o*3),type:"vec3<f32>",size:o},uStops:{value:new Float32Array(o*4),type:"vec4<f32>",size:o}}}}),Gt(this,"baseUniforms"),Gt(this,"stopsUniforms"),Gt(this,"_stops",[]),this.baseUniforms=this.resources.baseUniforms.uniforms,this.stopsUniforms=this.resources.stopsUniforms.uniforms,Object.assign(this,e)}get stops(){return this._stops}set stops(e){let t=th(e),n=new Y,o,i,s;for(let a=0;a<t.length;a++){n.setValue(t[a].color);let c=a*3;[o,i,s]=n.toArray(),this.stopsUniforms.uColors[c]=o,this.stopsUniforms.uColors[c+1]=i,this.stopsUniforms.uColors[c+2]=s,this.stopsUniforms.uStops[a*4]=t[a].offset,this.stopsUniforms.uStops[a*4+1]=t[a].alpha}this.baseUniforms.uCounts[0]=t.length,this._stops=t}get type(){return this.baseUniforms.uOptions[0]}set type(e){this.baseUniforms.uOptions[0]=e}get angle(){return this.baseUniforms.uOptions[1]+ra}set angle(e){this.baseUniforms.uOptions[1]=e-ra}get alpha(){return this.baseUniforms.uOptions[2]}set alpha(e){this.baseUniforms.uOptions[2]=e}get maxColors(){return this.baseUniforms.uCounts[1]}set maxColors(e){this.baseUniforms.uCounts[1]=e}get replace(){return this.baseUniforms.uOptions[3]>.5}set replace(e){this.baseUniforms.uOptions[3]=e?1:0}};Gt(Ar,"LINEAR",0);Gt(Ar,"RADIAL",1);Gt(Ar,"CONIC",2);Gt(Ar,"defaults",{type:Ar.LINEAR,stops:[{offset:0,color:16711680,alpha:1},{offset:1,color:255,alpha:1}],alpha:1,angle:90,maxColors:0,replace:!1});var wu=Ar;var Cu=`in vec2 vTextureCoord;
3983
+ const MAX_STOPS: i32 = 32;`;var qt=qt||{};qt.stringify=(function(){var r={"visit_linear-gradient":function(e){return r.visit_gradient(e)},"visit_repeating-linear-gradient":function(e){return r.visit_gradient(e)},"visit_radial-gradient":function(e){return r.visit_gradient(e)},"visit_repeating-radial-gradient":function(e){return r.visit_gradient(e)},visit_gradient:function(e){var t=r.visit(e.orientation);return t&&(t+=", "),e.type+"("+t+r.visit(e.colorStops)+")"},visit_shape:function(e){var t=e.value,n=r.visit(e.at),o=r.visit(e.style);return o&&(t+=" "+o),n&&(t+=" at "+n),t},"visit_default-radial":function(e){var t="",n=r.visit(e.at);return n&&(t+=n),t},"visit_extent-keyword":function(e){var t=e.value,n=r.visit(e.at);return n&&(t+=" at "+n),t},"visit_position-keyword":function(e){return e.value},visit_position:function(e){return r.visit(e.value.x)+" "+r.visit(e.value.y)},"visit_%":function(e){return e.value+"%"},visit_em:function(e){return e.value+"em"},visit_px:function(e){return e.value+"px"},visit_literal:function(e){return r.visit_color(e.value,e)},visit_hex:function(e){return r.visit_color("#"+e.value,e)},visit_rgb:function(e){return r.visit_color("rgb("+e.value.join(", ")+")",e)},visit_rgba:function(e){return r.visit_color("rgba("+e.value.join(", ")+")",e)},visit_color:function(e,t){var n=e,o=r.visit(t.length);return o&&(n+=" "+o),n},visit_angular:function(e){return e.value+"deg"},visit_directional:function(e){return"to "+e.value},visit_array:function(e){var t="",n=e.length;return e.forEach(function(o,i){t+=r.visit(o),i<n-1&&(t+=", ")}),t},visit:function(e){if(!e)return"";var t="";if(e instanceof Array)return r.visit_array(e,t);if(e.type){var n=r["visit_"+e.type];if(n)return n(e);throw Error("Missing visitor visit_"+e.type)}else throw Error("Invalid node.")}};return function(e){return r.visit(e)}})();var qt=qt||{};qt.parse=(function(){var r={linearGradient:/^(\-(webkit|o|ms|moz)\-)?(linear\-gradient)/i,repeatingLinearGradient:/^(\-(webkit|o|ms|moz)\-)?(repeating\-linear\-gradient)/i,radialGradient:/^(\-(webkit|o|ms|moz)\-)?(radial\-gradient)/i,repeatingRadialGradient:/^(\-(webkit|o|ms|moz)\-)?(repeating\-radial\-gradient)/i,sideOrCorner:/^to (left (top|bottom)|right (top|bottom)|left|right|top|bottom)/i,extentKeywords:/^(closest\-side|closest\-corner|farthest\-side|farthest\-corner|contain|cover)/,positionKeywords:/^(left|center|right|top|bottom)/i,pixelValue:/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))px/,percentageValue:/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))\%/,emValue:/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))em/,angleValue:/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))deg/,startCall:/^\(/,endCall:/^\)/,comma:/^,/,hexColor:/^\#([0-9a-fA-F]+)/,literalColor:/^([a-zA-Z]+)/,rgbColor:/^rgb/i,rgbaColor:/^rgba/i,number:/^(([0-9]*\.[0-9]+)|([0-9]+\.?))/},e="";function t(N){var K=new Error(e+": "+N);throw K.source=e,K}function n(){var N=o();return e.length>0&&t("Invalid input not EOF"),N}function o(){return S(i)}function i(){return s("linear-gradient",r.linearGradient,c)||s("repeating-linear-gradient",r.repeatingLinearGradient,c)||s("radial-gradient",r.radialGradient,u)||s("repeating-radial-gradient",r.repeatingRadialGradient,u)}function s(N,K,re){return a(K,function(nt){var Sa=re();return Sa&&(rt(r.comma)||t("Missing comma before color stops")),{type:N,orientation:Sa,colorStops:S(C)}})}function a(N,K){var re=rt(N);if(re){rt(r.startCall)||t("Missing (");var nt=K(re);return rt(r.endCall)||t("Missing )"),nt}}function c(){return l()||f()}function l(){return be("directional",r.sideOrCorner,1)}function f(){return be("angular",r.angleValue,1)}function u(){var N,K=m(),re;return K&&(N=[],N.push(K),re=e,rt(r.comma)&&(K=m(),K?N.push(K):e=re)),N}function m(){var N=d()||p();if(N)N.at=x();else{var K=h();if(K){N=K;var re=x();re&&(N.at=re)}else{var nt=y();nt&&(N={type:"default-radial",at:nt})}}return N}function d(){var N=be("shape",/^(circle)/i,0);return N&&(N.style=Ee()||h()),N}function p(){var N=be("shape",/^(ellipse)/i,0);return N&&(N.style=V()||h()),N}function h(){return be("extent-keyword",r.extentKeywords,1)}function x(){if(be("position",/^at/,0)){var N=y();return N||t("Missing positioning value"),N}}function y(){var N=v();if(N.x||N.y)return{type:"position",value:N}}function v(){return{x:V(),y:V()}}function S(N){var K=N(),re=[];if(K)for(re.push(K);rt(r.comma);)K=N(),K?re.push(K):t("One extra comma");return re}function C(){var N=_();return N||t("Expected color definition"),N.length=V(),N}function _(){return E()||M()||I()||T()}function T(){return be("literal",r.literalColor,0)}function E(){return be("hex",r.hexColor,1)}function I(){return a(r.rgbColor,function(){return{type:"rgb",value:S(L)}})}function M(){return a(r.rgbaColor,function(){return{type:"rgba",value:S(L)}})}function L(){return rt(r.number)[1]}function V(){return be("%",r.percentageValue,1)||te()||Ee()}function te(){return be("position-keyword",r.positionKeywords,1)}function Ee(){return be("px",r.pixelValue,1)||be("em",r.emValue,1)}function be(N,K,re){var nt=rt(K);if(nt)return{type:N,value:nt[re]}}function rt(N){var K,re;return re=/^[\n\r\t\s]+/.exec(e),re&&ba(re[0].length),K=N.exec(e),K&&ba(K[0].length),K}function ba(N){e=e.substr(N)}return function(N){return e=N.toString(),n()}})();var Tu=qt.parse;qt.stringify;function Yo(r){let e=Tu(ta(r));if(e.length===0)throw new Error("Invalid CSS gradient.");if(e.length!==1)throw new Error("Unsupported CSS gradient (multiple gradients is not supported).");let t=e[0],n=Ys(t.type),o=$s(t.colorStops),i=Js(t.orientation);return{type:n,stops:o,angle:i}}function Ys(r){let e={"linear-gradient":0,"radial-gradient":1};if(!(r in e))throw new Error(`Unsupported gradient type "${r}"`);return e[r]}function $s(r){let e=Zs(r),t=[],n=new Y;for(let o=0;o<r.length;o++){let i=Qs(r[o]),s=n.setValue(i).toArray();t.push({offset:e[o],color:s.slice(0,3),alpha:s[3]})}return t}function Qs(r){switch(r.type){case"hex":return`#${r.value}`;case"literal":return r.value;default:return`${r.type}(${r.value.join(",")})`}}function Zs(r){let e=[];for(let i=0;i<r.length;i++){let s=r[i],a=-1;s.type==="literal"&&s.length&&"type"in s.length&&s.length.type==="%"&&"value"in s.length&&(a=parseFloat(s.length.value)/100),e.push(a)}let n=i=>{for(let s=i;s<e.length;s++)if(e[s]!==-1)return{indexDelta:s-i,offset:e[s]};return{indexDelta:e.length-1-i,offset:1}},o=0;for(let i=0;i<e.length;i++){let s=e[i];if(s!==-1)o=s;else if(i===0)e[i]=0;else if(i+1===e.length)e[i]=1;else{let a=n(i),l=(a.offset-o)/(1+a.indexDelta);for(let f=0;f<=a.indexDelta;f++)e[i+f]=o+(f+1)*l;i+=a.indexDelta,o=e[i]}}return e.map(Zp)}function Zp(r){return r.toString().length>6?parseFloat(r.toString().substring(0,6)):r}function Js(r){if(typeof r>"u")return 0;if("type"in r&&"value"in r)switch(r.type){case"angular":return parseFloat(r.value);case"directional":return ea(r.value)}return 0}function ea(r){let e={left:270,top:0,bottom:180,right:90,"left top":315,"top left":315,"left bottom":225,"bottom left":225,"right top":45,"top right":45,"right bottom":135,"bottom right":135};if(!(r in e))throw new Error(`Unsupported directional value "${r}"`);return e[r]}function ta(r){let e=r.replace(/\s{2,}/gu," ");return e=e.replace(/;/g,""),e=e.replace(/ ,/g,","),e=e.replace(/\( /g,"("),e=e.replace(/ \)/g,")"),e.trim()}var Jp=Object.defineProperty,eh=(r,e,t)=>e in r?Jp(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ht=(r,e,t)=>(eh(r,typeof e!="symbol"?e+"":e,t),t),ra=90;function th(r){return[...r].sort((e,t)=>e.offset-t.offset)}var Fr=class $o extends k{constructor(e){if(e&&"css"in e?e={...Yo(e.css||""),alpha:e.alpha??$o.defaults.alpha,maxColors:e.maxColors??$o.defaults.maxColors}:e={...$o.defaults,...e},!e.stops||e.stops.length<2)throw new Error("ColorGradientFilter requires at least 2 color stops.");let t=A.from({vertex:{source:Ks,entryPoint:"mainVertex"},fragment:{source:Ks,entryPoint:"mainFragment"}}),n=P.from({vertex:Su,fragment:bu,name:"color-gradient-filter"}),o=32;super({gpuProgram:t,glProgram:n,resources:{baseUniforms:{uOptions:{value:[e.type,e.angle??ra,e.alpha,e.replace?1:0],type:"vec4<f32>"},uCounts:{value:[e.stops.length,e.maxColors],type:"vec2<f32>"}},stopsUniforms:{uColors:{value:new Float32Array(o*3),type:"vec3<f32>",size:o},uStops:{value:new Float32Array(o*4),type:"vec4<f32>",size:o}}}}),Ht(this,"baseUniforms"),Ht(this,"stopsUniforms"),Ht(this,"_stops",[]),this.baseUniforms=this.resources.baseUniforms.uniforms,this.stopsUniforms=this.resources.stopsUniforms.uniforms,Object.assign(this,e)}get stops(){return this._stops}set stops(e){let t=th(e),n=new Y,o,i,s;for(let a=0;a<t.length;a++){n.setValue(t[a].color);let c=a*3;[o,i,s]=n.toArray(),this.stopsUniforms.uColors[c]=o,this.stopsUniforms.uColors[c+1]=i,this.stopsUniforms.uColors[c+2]=s,this.stopsUniforms.uStops[a*4]=t[a].offset,this.stopsUniforms.uStops[a*4+1]=t[a].alpha}this.baseUniforms.uCounts[0]=t.length,this._stops=t}get type(){return this.baseUniforms.uOptions[0]}set type(e){this.baseUniforms.uOptions[0]=e}get angle(){return this.baseUniforms.uOptions[1]+ra}set angle(e){this.baseUniforms.uOptions[1]=e-ra}get alpha(){return this.baseUniforms.uOptions[2]}set alpha(e){this.baseUniforms.uOptions[2]=e}get maxColors(){return this.baseUniforms.uCounts[1]}set maxColors(e){this.baseUniforms.uCounts[1]=e}get replace(){return this.baseUniforms.uOptions[3]>.5}set replace(e){this.baseUniforms.uOptions[3]=e?1:0}};Ht(Fr,"LINEAR",0);Ht(Fr,"RADIAL",1);Ht(Fr,"CONIC",2);Ht(Fr,"defaults",{type:Fr.LINEAR,stops:[{offset:0,color:16711680,alpha:1},{offset:1,color:255,alpha:1}],alpha:1,angle:90,maxColors:0,replace:!1});var wu=Fr;var Cu=`in vec2 vTextureCoord;
3984
3984
  out vec4 finalColor;
3985
3985
 
3986
3986
  uniform sampler2D uTexture;
@@ -4606,7 +4606,7 @@ fn mainFragment(
4606
4606
  color *= dropShadowUniforms.uAlpha;
4607
4607
 
4608
4608
  return color;
4609
- }`;var hh=Object.defineProperty,gh=(r,e,t)=>e in r?hh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Fr=(r,e,t)=>(gh(r,typeof e!="symbol"?e+"":e,t),t),sf=class af extends k{constructor(e){e={...af.DEFAULT_OPTIONS,...e};let t=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:of,entryPoint:"mainFragment"}}),n=P.from({vertex:z,fragment:nf,name:"drop-shadow-filter"});super({gpuProgram:t,glProgram:n,resources:{dropShadowUniforms:{uAlpha:{value:e.alpha,type:"f32"},uColor:{value:new Float32Array(3),type:"vec3<f32>"},uOffset:{value:e.offset,type:"vec2<f32>"}}},resolution:e.resolution}),Fr(this,"uniforms"),Fr(this,"shadowOnly",!1),Fr(this,"_color"),Fr(this,"_blurFilter"),Fr(this,"_basePass"),this.uniforms=this.resources.dropShadowUniforms.uniforms,this._color=new Y,this.color=e.color??0,this._blurFilter=new Pr({strength:e.kernels??e.blur,quality:e.kernels?void 0:e.quality}),this._basePass=new k({gpuProgram:A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:`
4609
+ }`;var hh=Object.defineProperty,gh=(r,e,t)=>e in r?hh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Er=(r,e,t)=>(gh(r,typeof e!="symbol"?e+"":e,t),t),sf=class af extends k{constructor(e){e={...af.DEFAULT_OPTIONS,...e};let t=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:of,entryPoint:"mainFragment"}}),n=P.from({vertex:z,fragment:nf,name:"drop-shadow-filter"});super({gpuProgram:t,glProgram:n,resources:{dropShadowUniforms:{uAlpha:{value:e.alpha,type:"f32"},uColor:{value:new Float32Array(3),type:"vec3<f32>"},uOffset:{value:e.offset,type:"vec2<f32>"}}},resolution:e.resolution}),Er(this,"uniforms"),Er(this,"shadowOnly",!1),Er(this,"_color"),Er(this,"_blurFilter"),Er(this,"_basePass"),this.uniforms=this.resources.dropShadowUniforms.uniforms,this._color=new Y,this.color=e.color??0,this._blurFilter=new _r({strength:e.kernels??e.blur,quality:e.kernels?void 0:e.quality}),this._basePass=new k({gpuProgram:A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:`
4610
4610
  @group(0) @binding(1) var uTexture: texture_2d<f32>;
4611
4611
  @group(0) @binding(2) var uSampler: sampler;
4612
4612
  @fragment
@@ -4624,7 +4624,7 @@ fn mainFragment(
4624
4624
  void main(void){
4625
4625
  finalColor = texture(uTexture, vTextureCoord);
4626
4626
  }
4627
- `,name:"drop-shadow-filter"}),resources:{}}),Object.assign(this,e)}apply(e,t,n,o){let i=Q.getSameSizeTexture(t);e.applyFilter(this,t,i,!0),this._blurFilter.apply(e,i,n,o),this.shadowOnly||e.applyFilter(this._basePass,t,n,!1),Q.returnTexture(i)}get offset(){return this.uniforms.uOffset}set offset(e){this.uniforms.uOffset=e,this._updatePadding()}get offsetX(){return this.offset.x}set offsetX(e){this.offset.x=e,this._updatePadding()}get offsetY(){return this.offset.y}set offsetY(e){this.offset.y=e,this._updatePadding()}get color(){return this._color.value}set color(e){this._color.setValue(e);let[t,n,o]=this._color.toArray();this.uniforms.uColor[0]=t,this.uniforms.uColor[1]=n,this.uniforms.uColor[2]=o}get alpha(){return this.uniforms.uAlpha}set alpha(e){this.uniforms.uAlpha=e}get blur(){return this._blurFilter.strength}set blur(e){this._blurFilter.strength=e,this._updatePadding()}get quality(){return this._blurFilter.quality}set quality(e){this._blurFilter.quality=e,this._updatePadding()}get kernels(){return this._blurFilter.kernels}set kernels(e){this._blurFilter.kernels=e}get pixelSize(){return this._blurFilter.pixelSize}set pixelSize(e){typeof e=="number"&&(e={x:e,y:e}),Array.isArray(e)&&(e={x:e[0],y:e[1]}),this._blurFilter.pixelSize=e}get pixelSizeX(){return this._blurFilter.pixelSizeX}set pixelSizeX(e){this._blurFilter.pixelSizeX=e}get pixelSizeY(){return this._blurFilter.pixelSizeY}set pixelSizeY(e){this._blurFilter.pixelSizeY=e}_updatePadding(){let e=Math.max(Math.abs(this.offsetX),Math.abs(this.offsetY));this.padding=e+this.blur*2+this.quality*4}};Fr(sf,"DEFAULT_OPTIONS",{offset:{x:4,y:4},color:0,alpha:.5,shadowOnly:!1,kernels:void 0,blur:2,quality:3,pixelSize:{x:1,y:1},resolution:1});var cf=sf;var lf=`precision highp float;
4627
+ `,name:"drop-shadow-filter"}),resources:{}}),Object.assign(this,e)}apply(e,t,n,o){let i=Q.getSameSizeTexture(t);e.applyFilter(this,t,i,!0),this._blurFilter.apply(e,i,n,o),this.shadowOnly||e.applyFilter(this._basePass,t,n,!1),Q.returnTexture(i)}get offset(){return this.uniforms.uOffset}set offset(e){this.uniforms.uOffset=e,this._updatePadding()}get offsetX(){return this.offset.x}set offsetX(e){this.offset.x=e,this._updatePadding()}get offsetY(){return this.offset.y}set offsetY(e){this.offset.y=e,this._updatePadding()}get color(){return this._color.value}set color(e){this._color.setValue(e);let[t,n,o]=this._color.toArray();this.uniforms.uColor[0]=t,this.uniforms.uColor[1]=n,this.uniforms.uColor[2]=o}get alpha(){return this.uniforms.uAlpha}set alpha(e){this.uniforms.uAlpha=e}get blur(){return this._blurFilter.strength}set blur(e){this._blurFilter.strength=e,this._updatePadding()}get quality(){return this._blurFilter.quality}set quality(e){this._blurFilter.quality=e,this._updatePadding()}get kernels(){return this._blurFilter.kernels}set kernels(e){this._blurFilter.kernels=e}get pixelSize(){return this._blurFilter.pixelSize}set pixelSize(e){typeof e=="number"&&(e={x:e,y:e}),Array.isArray(e)&&(e={x:e[0],y:e[1]}),this._blurFilter.pixelSize=e}get pixelSizeX(){return this._blurFilter.pixelSizeX}set pixelSizeX(e){this._blurFilter.pixelSizeX=e}get pixelSizeY(){return this._blurFilter.pixelSizeY}set pixelSizeY(e){this._blurFilter.pixelSizeY=e}_updatePadding(){let e=Math.max(Math.abs(this.offsetX),Math.abs(this.offsetY));this.padding=e+this.blur*2+this.quality*4}};Er(sf,"DEFAULT_OPTIONS",{offset:{x:4,y:4},color:0,alpha:.5,shadowOnly:!1,kernels:void 0,blur:2,quality:3,pixelSize:{x:1,y:1},resolution:1});var cf=sf;var lf=`precision highp float;
4628
4628
  in vec2 vTextureCoord;
4629
4629
  out vec4 finalColor;
4630
4630
 
@@ -4685,7 +4685,7 @@ fn mainFragment(
4685
4685
  let blendColor: vec4<f32> = textureSample(uTexture, uSampler, uv);
4686
4686
 
4687
4687
  return vec4<f32>(color.rgb * blendColor.a, blendColor.a);
4688
- }`;var xh=Object.defineProperty,vh=(r,e,t)=>e in r?xh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,yh=(r,e,t)=>(vh(r,typeof e!="symbol"?e+"":e,t),t),Er=class extends k{constructor(e=5){let t=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:uf,entryPoint:"mainFragment"}}),n=P.from({vertex:z,fragment:lf,name:"emboss-filter"});super({gpuProgram:t,glProgram:n,resources:{embossUniforms:{uStrength:{value:e,type:"f32"}}}}),yh(this,"uniforms"),this.uniforms=this.resources.embossUniforms.uniforms}get strength(){return this.uniforms.uStrength}set strength(e){this.uniforms.uStrength=e}};var ff=`precision highp float;
4688
+ }`;var xh=Object.defineProperty,vh=(r,e,t)=>e in r?xh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,yh=(r,e,t)=>(vh(r,typeof e!="symbol"?e+"":e,t),t),zr=class extends k{constructor(e=5){let t=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:uf,entryPoint:"mainFragment"}}),n=P.from({vertex:z,fragment:lf,name:"emboss-filter"});super({gpuProgram:t,glProgram:n,resources:{embossUniforms:{uStrength:{value:e,type:"f32"}}}}),yh(this,"uniforms"),this.uniforms=this.resources.embossUniforms.uniforms}get strength(){return this.uniforms.uStrength}set strength(e){this.uniforms.uStrength=e}};var ff=`precision highp float;
4689
4689
  in vec2 vTextureCoord;
4690
4690
  out vec4 finalColor;
4691
4691
 
@@ -4914,7 +4914,7 @@ const TRANSPARENT: i32 = 0;
4914
4914
  const ORIGINAL: i32 = 1;
4915
4915
  const LOOP: i32 = 2;
4916
4916
  const CLAMP: i32 = 3;
4917
- const MIRROR: i32 = 4;`;var bh=Object.defineProperty,Sh=(r,e,t)=>e in r?bh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Le=(r,e,t)=>(Sh(r,typeof e!="symbol"?e+"":e,t),t),df=class pf extends k{constructor(e){e={...pf.defaults,...e};let t=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:mf,entryPoint:"mainFragment"}}),n=P.from({vertex:z,fragment:ff,name:"glitch-filter"}),o=document.createElement("canvas");o.width=4,o.height=e.sampleSize??512;let i=new ne({source:new Qt({resource:o})});super({gpuProgram:t,glProgram:n,resources:{glitchUniforms:{uSeed:{value:e?.seed??0,type:"f32"},uDimensions:{value:new Float32Array(2),type:"vec2<f32>"},uAspect:{value:1,type:"f32"},uFillMode:{value:e?.fillMode??0,type:"f32"},uOffset:{value:e?.offset??100,type:"f32"},uDirection:{value:e?.direction??0,type:"f32"},uRed:{value:{x:0,y:0},type:"vec2<f32>"},uGreen:{value:{x:0,y:0},type:"vec2<f32>"},uBlue:{value:{x:0,y:0},type:"vec2<f32>"}},uDisplacementMap:i.source,uDisplacementSampler:i.source.style}}),Le(this,"uniforms"),Le(this,"average",!1),Le(this,"minSize",8),Le(this,"sampleSize",512),Le(this,"_canvas"),Le(this,"texture"),Le(this,"_slices",0),Le(this,"_sizes",new Float32Array(1)),Le(this,"_offsets",new Float32Array(1)),this.uniforms=this.resources.glitchUniforms.uniforms,this._canvas=o,this.texture=i,Object.assign(this,e)}apply(e,t,n,o){let{width:i,height:s}=t.frame;this.uniforms.uDimensions[0]=i,this.uniforms.uDimensions[1]=s,this.uniforms.uAspect=s/i,e.applyFilter(this,t,n,o)}_randomizeSizes(){let e=this._sizes,t=this._slices-1,n=this.sampleSize,o=Math.min(this.minSize/n,.9/this._slices);if(this.average){let i=this._slices,s=1;for(let a=0;a<t;a++){let c=s/(i-a),l=Math.max(c*(1-Math.random()*.6),o);e[a]=l,s-=l}e[t]=s}else{let i=1,s=Math.sqrt(1/this._slices);for(let a=0;a<t;a++){let c=Math.max(s*i*Math.random(),o);e[a]=c,i-=c}e[t]=i}this.shuffle()}shuffle(){let e=this._sizes,t=this._slices-1;for(let n=t;n>0;n--){let o=Math.random()*n>>0,i=e[n];e[n]=e[o],e[o]=i}}_randomizeOffsets(){for(let e=0;e<this._slices;e++)this._offsets[e]=Math.random()*(Math.random()<.5?-1:1)}refresh(){this._randomizeSizes(),this._randomizeOffsets(),this.redraw()}redraw(){let e=this.sampleSize,t=this.texture,n=this._canvas.getContext("2d");n.clearRect(0,0,8,e);let o,i=0;for(let s=0;s<this._slices;s++){o=Math.floor(this._offsets[s]*256);let a=this._sizes[s]*e,c=o>0?o:0,l=o<0?-o:0;n.fillStyle=`rgba(${c}, ${l}, 0, 1)`,n.fillRect(0,i>>0,e,a+1>>0),i+=a}t.source.update()}set sizes(e){let t=Math.min(this._slices,e.length);for(let n=0;n<t;n++)this._sizes[n]=e[n]}get sizes(){return this._sizes}set offsets(e){let t=Math.min(this._slices,e.length);for(let n=0;n<t;n++)this._offsets[n]=e[n]}get offsets(){return this._offsets}get slices(){return this._slices}set slices(e){this._slices!==e&&(this._slices=e,this._sizes=new Float32Array(e),this._offsets=new Float32Array(e),this.refresh())}get offset(){return this.uniforms.uOffset}set offset(e){this.uniforms.uOffset=e}get seed(){return this.uniforms.uSeed}set seed(e){this.uniforms.uSeed=e}get fillMode(){return this.uniforms.uFillMode}set fillMode(e){this.uniforms.uFillMode=e}get direction(){return this.uniforms.uDirection/Ge}set direction(e){this.uniforms.uDirection=e*Ge}get red(){return this.uniforms.uRed}set red(e){Array.isArray(e)&&(e={x:e[0],y:e[1]}),this.uniforms.uRed=e}get green(){return this.uniforms.uGreen}set green(e){Array.isArray(e)&&(e={x:e[0],y:e[1]}),this.uniforms.uGreen=e}get blue(){return this.uniforms.uBlue}set blue(e){Array.isArray(e)&&(e={x:e[0],y:e[1]}),this.uniforms.uBlue=e}destroy(){this.texture?.destroy(!0),this.texture=this._canvas=this.red=this.green=this.blue=this._sizes=this._offsets=null}};Le(df,"defaults",{slices:5,offset:100,direction:0,fillMode:0,average:!1,seed:0,red:{x:0,y:0},green:{x:0,y:0},blue:{x:0,y:0},minSize:8,sampleSize:512});var hf=df;var gf=`precision highp float;
4917
+ const MIRROR: i32 = 4;`;var bh=Object.defineProperty,Sh=(r,e,t)=>e in r?bh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Le=(r,e,t)=>(Sh(r,typeof e!="symbol"?e+"":e,t),t),df=class pf extends k{constructor(e){e={...pf.defaults,...e};let t=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:mf,entryPoint:"mainFragment"}}),n=P.from({vertex:z,fragment:ff,name:"glitch-filter"}),o=document.createElement("canvas");o.width=4,o.height=e.sampleSize??512;let i=new ne({source:new Jt({resource:o})});super({gpuProgram:t,glProgram:n,resources:{glitchUniforms:{uSeed:{value:e?.seed??0,type:"f32"},uDimensions:{value:new Float32Array(2),type:"vec2<f32>"},uAspect:{value:1,type:"f32"},uFillMode:{value:e?.fillMode??0,type:"f32"},uOffset:{value:e?.offset??100,type:"f32"},uDirection:{value:e?.direction??0,type:"f32"},uRed:{value:{x:0,y:0},type:"vec2<f32>"},uGreen:{value:{x:0,y:0},type:"vec2<f32>"},uBlue:{value:{x:0,y:0},type:"vec2<f32>"}},uDisplacementMap:i.source,uDisplacementSampler:i.source.style}}),Le(this,"uniforms"),Le(this,"average",!1),Le(this,"minSize",8),Le(this,"sampleSize",512),Le(this,"_canvas"),Le(this,"texture"),Le(this,"_slices",0),Le(this,"_sizes",new Float32Array(1)),Le(this,"_offsets",new Float32Array(1)),this.uniforms=this.resources.glitchUniforms.uniforms,this._canvas=o,this.texture=i,Object.assign(this,e)}apply(e,t,n,o){let{width:i,height:s}=t.frame;this.uniforms.uDimensions[0]=i,this.uniforms.uDimensions[1]=s,this.uniforms.uAspect=s/i,e.applyFilter(this,t,n,o)}_randomizeSizes(){let e=this._sizes,t=this._slices-1,n=this.sampleSize,o=Math.min(this.minSize/n,.9/this._slices);if(this.average){let i=this._slices,s=1;for(let a=0;a<t;a++){let c=s/(i-a),l=Math.max(c*(1-Math.random()*.6),o);e[a]=l,s-=l}e[t]=s}else{let i=1,s=Math.sqrt(1/this._slices);for(let a=0;a<t;a++){let c=Math.max(s*i*Math.random(),o);e[a]=c,i-=c}e[t]=i}this.shuffle()}shuffle(){let e=this._sizes,t=this._slices-1;for(let n=t;n>0;n--){let o=Math.random()*n>>0,i=e[n];e[n]=e[o],e[o]=i}}_randomizeOffsets(){for(let e=0;e<this._slices;e++)this._offsets[e]=Math.random()*(Math.random()<.5?-1:1)}refresh(){this._randomizeSizes(),this._randomizeOffsets(),this.redraw()}redraw(){let e=this.sampleSize,t=this.texture,n=this._canvas.getContext("2d");n.clearRect(0,0,8,e);let o,i=0;for(let s=0;s<this._slices;s++){o=Math.floor(this._offsets[s]*256);let a=this._sizes[s]*e,c=o>0?o:0,l=o<0?-o:0;n.fillStyle=`rgba(${c}, ${l}, 0, 1)`,n.fillRect(0,i>>0,e,a+1>>0),i+=a}t.source.update()}set sizes(e){let t=Math.min(this._slices,e.length);for(let n=0;n<t;n++)this._sizes[n]=e[n]}get sizes(){return this._sizes}set offsets(e){let t=Math.min(this._slices,e.length);for(let n=0;n<t;n++)this._offsets[n]=e[n]}get offsets(){return this._offsets}get slices(){return this._slices}set slices(e){this._slices!==e&&(this._slices=e,this._sizes=new Float32Array(e),this._offsets=new Float32Array(e),this.refresh())}get offset(){return this.uniforms.uOffset}set offset(e){this.uniforms.uOffset=e}get seed(){return this.uniforms.uSeed}set seed(e){this.uniforms.uSeed=e}get fillMode(){return this.uniforms.uFillMode}set fillMode(e){this.uniforms.uFillMode=e}get direction(){return this.uniforms.uDirection/Ge}set direction(e){this.uniforms.uDirection=e*Ge}get red(){return this.uniforms.uRed}set red(e){Array.isArray(e)&&(e={x:e[0],y:e[1]}),this.uniforms.uRed=e}get green(){return this.uniforms.uGreen}set green(e){Array.isArray(e)&&(e={x:e[0],y:e[1]}),this.uniforms.uGreen=e}get blue(){return this.uniforms.uBlue}set blue(e){Array.isArray(e)&&(e={x:e[0],y:e[1]}),this.uniforms.uBlue=e}destroy(){this.texture?.destroy(!0),this.texture=this._canvas=this.red=this.green=this.blue=this._sizes=this._offsets=null}};Le(df,"defaults",{slices:5,offset:100,direction:0,fillMode:0,average:!1,seed:0,red:{x:0,y:0},green:{x:0,y:0},blue:{x:0,y:0},minSize:8,sampleSize:512});var hf=df;var gf=`precision highp float;
4918
4918
  in vec2 vTextureCoord;
4919
4919
  out vec4 finalColor;
4920
4920
 
@@ -5410,7 +5410,7 @@ fn turb(P: vec3<f32>, rep: vec3<f32>, lacunarity: f32, gain: f32) -> f32
5410
5410
  totalgain *= gain;
5411
5411
  }
5412
5412
  return abs(sum);
5413
- }`;var Ch=Object.defineProperty,kh=(r,e,t)=>e in r?Ch(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,zr=(r,e,t)=>(kh(r,typeof e!="symbol"?e+"":e,t),t),kf=class Pf extends k{constructor(e){e={...Pf.DEFAULT_OPTIONS,...e};let t=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:Tf.replace("${PERLIN}",Cf),entryPoint:"mainFragment"}}),n=P.from({vertex:z,fragment:Sf.replace("${PERLIN}",wf),name:"god-ray-filter"});super({gpuProgram:t,glProgram:n,resources:{godrayUniforms:{uLight:{value:new Float32Array(2),type:"vec2<f32>"},uParallel:{value:0,type:"f32"},uAspect:{value:0,type:"f32"},uTime:{value:e.time,type:"f32"},uRay:{value:new Float32Array(3),type:"vec3<f32>"},uDimensions:{value:new Float32Array(2),type:"vec2<f32>"}}}}),zr(this,"uniforms"),zr(this,"time",0),zr(this,"_angleLight",[0,0]),zr(this,"_angle",0),zr(this,"_center"),this.uniforms=this.resources.godrayUniforms.uniforms,Object.assign(this,e)}apply(e,t,n,o){let i=t.frame.width,s=t.frame.height;this.uniforms.uLight[0]=this.parallel?this._angleLight[0]:this._center.x,this.uniforms.uLight[1]=this.parallel?this._angleLight[1]:this._center.y,this.uniforms.uDimensions[0]=i,this.uniforms.uDimensions[1]=s,this.uniforms.uAspect=s/i,this.uniforms.uTime=this.time,e.applyFilter(this,t,n,o)}get angle(){return this._angle}set angle(e){this._angle=e;let t=e*Ge;this._angleLight[0]=Math.cos(t),this._angleLight[1]=Math.sin(t)}get parallel(){return this.uniforms.uParallel>.5}set parallel(e){this.uniforms.uParallel=e?1:0}get center(){return this._center}set center(e){Array.isArray(e)&&(e={x:e[0],y:e[1]}),this._center=e}get centerX(){return this.center.x}set centerX(e){this.center.x=e}get centerY(){return this.center.y}set centerY(e){this.center.y=e}get gain(){return this.uniforms.uRay[0]}set gain(e){this.uniforms.uRay[0]=e}get lacunarity(){return this.uniforms.uRay[1]}set lacunarity(e){this.uniforms.uRay[1]=e}get alpha(){return this.uniforms.uRay[2]}set alpha(e){this.uniforms.uRay[2]=e}};zr(kf,"DEFAULT_OPTIONS",{angle:30,gain:.5,lacunarity:2.5,parallel:!0,time:0,center:{x:0,y:0},alpha:1});var _f=kf;var If=`in vec2 vTextureCoord;
5413
+ }`;var Ch=Object.defineProperty,kh=(r,e,t)=>e in r?Ch(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Dr=(r,e,t)=>(kh(r,typeof e!="symbol"?e+"":e,t),t),kf=class Pf extends k{constructor(e){e={...Pf.DEFAULT_OPTIONS,...e};let t=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:Tf.replace("${PERLIN}",Cf),entryPoint:"mainFragment"}}),n=P.from({vertex:z,fragment:Sf.replace("${PERLIN}",wf),name:"god-ray-filter"});super({gpuProgram:t,glProgram:n,resources:{godrayUniforms:{uLight:{value:new Float32Array(2),type:"vec2<f32>"},uParallel:{value:0,type:"f32"},uAspect:{value:0,type:"f32"},uTime:{value:e.time,type:"f32"},uRay:{value:new Float32Array(3),type:"vec3<f32>"},uDimensions:{value:new Float32Array(2),type:"vec2<f32>"}}}}),Dr(this,"uniforms"),Dr(this,"time",0),Dr(this,"_angleLight",[0,0]),Dr(this,"_angle",0),Dr(this,"_center"),this.uniforms=this.resources.godrayUniforms.uniforms,Object.assign(this,e)}apply(e,t,n,o){let i=t.frame.width,s=t.frame.height;this.uniforms.uLight[0]=this.parallel?this._angleLight[0]:this._center.x,this.uniforms.uLight[1]=this.parallel?this._angleLight[1]:this._center.y,this.uniforms.uDimensions[0]=i,this.uniforms.uDimensions[1]=s,this.uniforms.uAspect=s/i,this.uniforms.uTime=this.time,e.applyFilter(this,t,n,o)}get angle(){return this._angle}set angle(e){this._angle=e;let t=e*Ge;this._angleLight[0]=Math.cos(t),this._angleLight[1]=Math.sin(t)}get parallel(){return this.uniforms.uParallel>.5}set parallel(e){this.uniforms.uParallel=e?1:0}get center(){return this._center}set center(e){Array.isArray(e)&&(e={x:e[0],y:e[1]}),this._center=e}get centerX(){return this.center.x}set centerX(e){this.center.x=e}get centerY(){return this.center.y}set centerY(e){this.center.y=e}get gain(){return this.uniforms.uRay[0]}set gain(e){this.uniforms.uRay[0]=e}get lacunarity(){return this.uniforms.uRay[1]}set lacunarity(e){this.uniforms.uRay[1]=e}get alpha(){return this.uniforms.uRay[2]}set alpha(e){this.uniforms.uRay[2]=e}};Dr(kf,"DEFAULT_OPTIONS",{angle:30,gain:.5,lacunarity:2.5,parallel:!0,time:0,center:{x:0,y:0},alpha:1});var _f=kf;var If=`in vec2 vTextureCoord;
5414
5414
 
5415
5415
  out vec4 finalColor;
5416
5416
 
@@ -5643,7 +5643,7 @@ fn mainFragment(
5643
5643
  return select(color / f32(uKernelSize), textureSample(uTexture, uSampler, uv), uKernelSize == 0);
5644
5644
  }
5645
5645
 
5646
- const MAX_KERNEL_SIZE: i32 = 2048;`;var Ih=Object.defineProperty,Ah=(r,e,t)=>e in r?Ih(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,sa=(r,e,t)=>(Ah(r,typeof e!="symbol"?e+"":e,t),t),Bf=class Uf extends k{constructor(...e){let t=e[0]??{};if(Array.isArray(t)||"x"in t&&"y"in t||t instanceof Vr){U("6.0.0","MotionBlurFilter constructor params are now options object. See params: { velocity, kernelSize, offset }");let i="x"in t?t.x:t[0],s="y"in t?t.y:t[1];t={velocity:{x:i,y:s}},e[1]!==void 0&&(t.kernelSize=e[1]),e[2]!==void 0&&(t.offset=e[2])}t={...Uf.DEFAULT_OPTIONS,...t};let n=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:Mf,entryPoint:"mainFragment"}}),o=P.from({vertex:z,fragment:Rf,name:"motion-blur-filter"});super({gpuProgram:n,glProgram:o,resources:{motionBlurUniforms:{uVelocity:{value:{x:0,y:0},type:"vec2<f32>"},uKernelSize:{value:Math.trunc(t.kernelSize??5),type:"i32"},uOffset:{value:t.offset,type:"f32"}}}}),sa(this,"uniforms"),sa(this,"_kernelSize"),this.uniforms=this.resources.motionBlurUniforms.uniforms,Object.assign(this,t)}get velocity(){return this.uniforms.uVelocity}set velocity(e){Array.isArray(e)&&(e={x:e[0],y:e[1]}),this.uniforms.uVelocity=e,this._updateDirty()}get velocityX(){return this.velocity.x}set velocityX(e){this.velocity.x=e,this._updateDirty()}get velocityY(){return this.velocity.y}set velocityY(e){this.velocity.y=e,this._updateDirty()}get kernelSize(){return this._kernelSize}set kernelSize(e){this._kernelSize=e,this._updateDirty()}get offset(){return this.uniforms.uOffset}set offset(e){this.uniforms.uOffset=e}_updateDirty(){this.padding=(Math.max(Math.abs(this.velocityX),Math.abs(this.velocityY))>>0)+1,this.uniforms.uKernelSize=this.velocityX!==0||this.velocityY!==0?this._kernelSize:0}};sa(Bf,"DEFAULT_OPTIONS",{velocity:{x:0,y:0},kernelSize:5,offset:0});var Nf=Bf;var Lf=`in vec2 vTextureCoord;
5646
+ const MAX_KERNEL_SIZE: i32 = 2048;`;var Ih=Object.defineProperty,Ah=(r,e,t)=>e in r?Ih(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,sa=(r,e,t)=>(Ah(r,typeof e!="symbol"?e+"":e,t),t),Bf=class Uf extends k{constructor(...e){let t=e[0]??{};if(Array.isArray(t)||"x"in t&&"y"in t||t instanceof Gr){U("6.0.0","MotionBlurFilter constructor params are now options object. See params: { velocity, kernelSize, offset }");let i="x"in t?t.x:t[0],s="y"in t?t.y:t[1];t={velocity:{x:i,y:s}},e[1]!==void 0&&(t.kernelSize=e[1]),e[2]!==void 0&&(t.offset=e[2])}t={...Uf.DEFAULT_OPTIONS,...t};let n=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:Mf,entryPoint:"mainFragment"}}),o=P.from({vertex:z,fragment:Rf,name:"motion-blur-filter"});super({gpuProgram:n,glProgram:o,resources:{motionBlurUniforms:{uVelocity:{value:{x:0,y:0},type:"vec2<f32>"},uKernelSize:{value:Math.trunc(t.kernelSize??5),type:"i32"},uOffset:{value:t.offset,type:"f32"}}}}),sa(this,"uniforms"),sa(this,"_kernelSize"),this.uniforms=this.resources.motionBlurUniforms.uniforms,Object.assign(this,t)}get velocity(){return this.uniforms.uVelocity}set velocity(e){Array.isArray(e)&&(e={x:e[0],y:e[1]}),this.uniforms.uVelocity=e,this._updateDirty()}get velocityX(){return this.velocity.x}set velocityX(e){this.velocity.x=e,this._updateDirty()}get velocityY(){return this.velocity.y}set velocityY(e){this.velocity.y=e,this._updateDirty()}get kernelSize(){return this._kernelSize}set kernelSize(e){this._kernelSize=e,this._updateDirty()}get offset(){return this.uniforms.uOffset}set offset(e){this.uniforms.uOffset=e}_updateDirty(){this.padding=(Math.max(Math.abs(this.velocityX),Math.abs(this.velocityY))>>0)+1,this.uniforms.uKernelSize=this.velocityX!==0||this.velocityY!==0?this._kernelSize:0}};sa(Bf,"DEFAULT_OPTIONS",{velocity:{x:0,y:0},kernelSize:5,offset:0});var Nf=Bf;var Lf=`in vec2 vTextureCoord;
5647
5647
  out vec4 finalColor;
5648
5648
 
5649
5649
  const int MAX_COLORS = \${MAX_COLORS};
@@ -6100,7 +6100,7 @@ fn outlineMaxAlphaAtPos(uv: vec2<f32>) -> f32 {
6100
6100
  return maxAlpha;
6101
6101
  }
6102
6102
 
6103
- const DOUBLE_PI: f32 = 3.14159265358979323846264 * 2.;`;var Oh=Object.defineProperty,Rh=(r,e,t)=>e in r?Oh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ht=(r,e,t)=>(Rh(r,typeof e!="symbol"?e+"":e,t),t),ri=class qt extends k{constructor(...e){let t=e[0]??{};typeof t=="number"&&(U("6.0.0","OutlineFilter constructor params are now options object. See params: { thickness, color, quality, alpha, knockout }"),t={thickness:t},e[1]!==void 0&&(t.color=e[1]),e[2]!==void 0&&(t.quality=e[2]),e[3]!==void 0&&(t.alpha=e[3]),e[4]!==void 0&&(t.knockout=e[4])),t={...qt.DEFAULT_OPTIONS,...t};let n=t.quality??.1,o=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:Qf,entryPoint:"mainFragment"}}),i=P.from({vertex:z,fragment:$f.replace(/\$\{ANGLE_STEP\}/,qt.getAngleStep(n).toFixed(7)),name:"outline-filter"});super({gpuProgram:o,glProgram:i,resources:{outlineUniforms:{uThickness:{value:new Float32Array(2),type:"vec2<f32>"},uColor:{value:new Float32Array(3),type:"vec3<f32>"},uAlpha:{value:t.alpha,type:"f32"},uAngleStep:{value:0,type:"f32"},uKnockout:{value:t.knockout?1:0,type:"f32"}}}}),Ht(this,"uniforms"),Ht(this,"_thickness"),Ht(this,"_quality"),Ht(this,"_color"),this.uniforms=this.resources.outlineUniforms.uniforms,this.uniforms.uAngleStep=qt.getAngleStep(n),this._color=new Y,this.color=t.color??0,Object.assign(this,t)}apply(e,t,n,o){this.uniforms.uThickness[0]=this.thickness/t.source.width,this.uniforms.uThickness[1]=this.thickness/t.source.height,e.applyFilter(this,t,n,o)}static getAngleStep(e){return parseFloat((Math.PI*2/Math.max(e*qt.MAX_SAMPLES,qt.MIN_SAMPLES)).toFixed(7))}get thickness(){return this._thickness}set thickness(e){this._thickness=this.padding=e}get color(){return this._color.value}set color(e){this._color.setValue(e);let[t,n,o]=this._color.toArray();this.uniforms.uColor[0]=t,this.uniforms.uColor[1]=n,this.uniforms.uColor[2]=o}get alpha(){return this.uniforms.uAlpha}set alpha(e){this.uniforms.uAlpha=e}get quality(){return this._quality}set quality(e){this._quality=e,this.uniforms.uAngleStep=qt.getAngleStep(e)}get knockout(){return this.uniforms.uKnockout===1}set knockout(e){this.uniforms.uKnockout=e?1:0}};Ht(ri,"DEFAULT_OPTIONS",{thickness:1,color:0,alpha:1,quality:.1,knockout:!1});Ht(ri,"MIN_SAMPLES",1);Ht(ri,"MAX_SAMPLES",100);var Zf=ri;var Jf=`precision highp float;
6103
+ const DOUBLE_PI: f32 = 3.14159265358979323846264 * 2.;`;var Oh=Object.defineProperty,Rh=(r,e,t)=>e in r?Oh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,jt=(r,e,t)=>(Rh(r,typeof e!="symbol"?e+"":e,t),t),ri=class Wt extends k{constructor(...e){let t=e[0]??{};typeof t=="number"&&(U("6.0.0","OutlineFilter constructor params are now options object. See params: { thickness, color, quality, alpha, knockout }"),t={thickness:t},e[1]!==void 0&&(t.color=e[1]),e[2]!==void 0&&(t.quality=e[2]),e[3]!==void 0&&(t.alpha=e[3]),e[4]!==void 0&&(t.knockout=e[4])),t={...Wt.DEFAULT_OPTIONS,...t};let n=t.quality??.1,o=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:Qf,entryPoint:"mainFragment"}}),i=P.from({vertex:z,fragment:$f.replace(/\$\{ANGLE_STEP\}/,Wt.getAngleStep(n).toFixed(7)),name:"outline-filter"});super({gpuProgram:o,glProgram:i,resources:{outlineUniforms:{uThickness:{value:new Float32Array(2),type:"vec2<f32>"},uColor:{value:new Float32Array(3),type:"vec3<f32>"},uAlpha:{value:t.alpha,type:"f32"},uAngleStep:{value:0,type:"f32"},uKnockout:{value:t.knockout?1:0,type:"f32"}}}}),jt(this,"uniforms"),jt(this,"_thickness"),jt(this,"_quality"),jt(this,"_color"),this.uniforms=this.resources.outlineUniforms.uniforms,this.uniforms.uAngleStep=Wt.getAngleStep(n),this._color=new Y,this.color=t.color??0,Object.assign(this,t)}apply(e,t,n,o){this.uniforms.uThickness[0]=this.thickness/t.source.width,this.uniforms.uThickness[1]=this.thickness/t.source.height,e.applyFilter(this,t,n,o)}static getAngleStep(e){return parseFloat((Math.PI*2/Math.max(e*Wt.MAX_SAMPLES,Wt.MIN_SAMPLES)).toFixed(7))}get thickness(){return this._thickness}set thickness(e){this._thickness=this.padding=e}get color(){return this._color.value}set color(e){this._color.setValue(e);let[t,n,o]=this._color.toArray();this.uniforms.uColor[0]=t,this.uniforms.uColor[1]=n,this.uniforms.uColor[2]=o}get alpha(){return this.uniforms.uAlpha}set alpha(e){this.uniforms.uAlpha=e}get quality(){return this._quality}set quality(e){this._quality=e,this.uniforms.uAngleStep=Wt.getAngleStep(e)}get knockout(){return this.uniforms.uKnockout===1}set knockout(e){this.uniforms.uKnockout=e?1:0}};jt(ri,"DEFAULT_OPTIONS",{thickness:1,color:0,alpha:1,quality:.1,knockout:!1});jt(ri,"MIN_SAMPLES",1);jt(ri,"MAX_SAMPLES",100);var Zf=ri;var Jf=`precision highp float;
6104
6104
  in vec2 vTextureCoord;
6105
6105
  out vec4 finalColor;
6106
6106
 
@@ -6190,7 +6190,7 @@ fn pixelate(coord: vec2<f32>, size: vec2<f32>) -> vec2<f32>
6190
6190
  return floor( coord / size ) * size;
6191
6191
  }
6192
6192
 
6193
- `;var Dr=class extends k{constructor(e=10){let t=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:em,entryPoint:"mainFragment"}}),n=P.from({vertex:z,fragment:Jf,name:"pixelate-filter"});super({gpuProgram:t,glProgram:n,resources:{pixelateUniforms:{uSize:{value:new Float32Array(2),type:"vec2<f32>"}}}}),this.size=e}get size(){return this.resources.pixelateUniforms.uniforms.uSize}set size(e){e instanceof Fi?(this.sizeX=e.x,this.sizeY=e.y):Array.isArray(e)?this.resources.pixelateUniforms.uniforms.uSize=e:this.sizeX=this.sizeY=e}get sizeX(){return this.resources.pixelateUniforms.uniforms.uSize[0]}set sizeX(e){this.resources.pixelateUniforms.uniforms.uSize[0]=e}get sizeY(){return this.resources.pixelateUniforms.uniforms.uSize[1]}set sizeY(e){this.resources.pixelateUniforms.uniforms.uSize[1]=e}};var tm=`precision highp float;
6193
+ `;var Or=class extends k{constructor(e=10){let t=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:em,entryPoint:"mainFragment"}}),n=P.from({vertex:z,fragment:Jf,name:"pixelate-filter"});super({gpuProgram:t,glProgram:n,resources:{pixelateUniforms:{uSize:{value:new Float32Array(2),type:"vec2<f32>"}}}}),this.size=e}get size(){return this.resources.pixelateUniforms.uniforms.uSize}set size(e){e instanceof Fi?(this.sizeX=e.x,this.sizeY=e.y):Array.isArray(e)?this.resources.pixelateUniforms.uniforms.uSize=e:this.sizeX=this.sizeY=e}get sizeX(){return this.resources.pixelateUniforms.uniforms.uSize[0]}set sizeX(e){this.resources.pixelateUniforms.uniforms.uSize[0]=e}get sizeY(){return this.resources.pixelateUniforms.uniforms.uSize[1]}set sizeY(e){this.resources.pixelateUniforms.uniforms.uSize[1]=e}};var tm=`precision highp float;
6194
6194
  in vec2 vTextureCoord;
6195
6195
  out vec4 finalColor;
6196
6196
 
@@ -6951,7 +6951,7 @@ fn mainFragment(
6951
6951
  fn random(position: vec4<f32>, scale: vec3<f32>, seed: f32) -> f32
6952
6952
  {
6953
6953
  return fract(sin(dot(position.xyz + seed, scale)) * 43758.5453 + seed);
6954
- }`;var Yh=Object.defineProperty,$h=(r,e,t)=>e in r?Yh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ua=(r,e,t)=>($h(r,typeof e!="symbol"?e+"":e,t),t),Om=class Rm extends k{constructor(e){let{width:t,height:n}=Bi.defaultOptions;e={...Rm.DEFAULT_OPTIONS,start:{x:0,y:n/2},end:{x:t,y:n/2},...e};let o=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:Dm,entryPoint:"mainFragment"}}),i=P.from({vertex:z,fragment:zm,name:"tilt-shift-axis-filter"});super({gpuProgram:o,glProgram:i,resources:{tiltShiftUniforms:{uBlur:{value:new Float32Array([e.blur,e.gradientBlur]),type:"vec2<f32>"},uStart:{value:e.start,type:"vec2<f32>"},uEnd:{value:e.end,type:"vec2<f32>"},uDelta:{value:new Float32Array([0,0]),type:"vec2<f32>"}}}}),ua(this,"uniforms"),ua(this,"_tiltAxis"),this.uniforms=this.resources.tiltShiftUniforms.uniforms,this._tiltAxis=e.axis}updateDelta(){if(this.uniforms.uDelta[0]=0,this.uniforms.uDelta[1]=0,this._tiltAxis===void 0)return;let e=this.uniforms.uEnd,t=this.uniforms.uStart,n=e.x-t.x,o=e.y-t.y,i=Math.sqrt(n*n+o*o),s=this._tiltAxis==="vertical";this.uniforms.uDelta[0]=s?-o/i:n/i,this.uniforms.uDelta[1]=s?n/i:o/i}};ua(Om,"DEFAULT_OPTIONS",{blur:100,gradientBlur:600});var Or=Om;var Qh=Object.defineProperty,Zh=(r,e,t)=>e in r?Qh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Jh=(r,e,t)=>(Zh(r,typeof e!="symbol"?e+"":e,t),t),ii=class extends Or{constructor(e){e={...Or.DEFAULT_OPTIONS,...e},super({...e,axis:"horizontal"}),Jh(this,"_tiltShiftYFilter"),this._tiltShiftYFilter=new Or({...e,axis:"vertical"}),this.updateDelta(),Object.assign(this,e)}apply(e,t,n,o){let i=Q.getSameSizeTexture(t);e.applyFilter(this,t,i,!0),e.applyFilter(this._tiltShiftYFilter,i,n,o),Q.returnTexture(i)}updateDelta(){super.updateDelta(),this._tiltShiftYFilter.updateDelta()}get blur(){return this.uniforms.uBlur[0]}set blur(e){this.uniforms.uBlur[0]=this._tiltShiftYFilter.uniforms.uBlur[0]=e}get gradientBlur(){return this.uniforms.uBlur[1]}set gradientBlur(e){this.uniforms.uBlur[1]=this._tiltShiftYFilter.uniforms.uBlur[1]=e}get start(){return this.uniforms.uStart}set start(e){this.uniforms.uStart=this._tiltShiftYFilter.uniforms.uStart=e,this.updateDelta()}get startX(){return this.start.x}set startX(e){this.start.x=e,this.updateDelta()}get startY(){return this.start.y}set startY(e){this.start.y=e,this.updateDelta()}get end(){return this.uniforms.uEnd}set end(e){this.uniforms.uEnd=this._tiltShiftYFilter.uniforms.uEnd=e,this.updateDelta()}get endX(){return this.end.x}set endX(e){this.end.x=e,this.updateDelta()}get endY(){return this.end.y}set endY(e){this.end.y=e,this.updateDelta()}};var Mm=`precision highp float;
6954
+ }`;var Yh=Object.defineProperty,$h=(r,e,t)=>e in r?Yh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ua=(r,e,t)=>($h(r,typeof e!="symbol"?e+"":e,t),t),Om=class Rm extends k{constructor(e){let{width:t,height:n}=Bi.defaultOptions;e={...Rm.DEFAULT_OPTIONS,start:{x:0,y:n/2},end:{x:t,y:n/2},...e};let o=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:Dm,entryPoint:"mainFragment"}}),i=P.from({vertex:z,fragment:zm,name:"tilt-shift-axis-filter"});super({gpuProgram:o,glProgram:i,resources:{tiltShiftUniforms:{uBlur:{value:new Float32Array([e.blur,e.gradientBlur]),type:"vec2<f32>"},uStart:{value:e.start,type:"vec2<f32>"},uEnd:{value:e.end,type:"vec2<f32>"},uDelta:{value:new Float32Array([0,0]),type:"vec2<f32>"}}}}),ua(this,"uniforms"),ua(this,"_tiltAxis"),this.uniforms=this.resources.tiltShiftUniforms.uniforms,this._tiltAxis=e.axis}updateDelta(){if(this.uniforms.uDelta[0]=0,this.uniforms.uDelta[1]=0,this._tiltAxis===void 0)return;let e=this.uniforms.uEnd,t=this.uniforms.uStart,n=e.x-t.x,o=e.y-t.y,i=Math.sqrt(n*n+o*o),s=this._tiltAxis==="vertical";this.uniforms.uDelta[0]=s?-o/i:n/i,this.uniforms.uDelta[1]=s?n/i:o/i}};ua(Om,"DEFAULT_OPTIONS",{blur:100,gradientBlur:600});var Rr=Om;var Qh=Object.defineProperty,Zh=(r,e,t)=>e in r?Qh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Jh=(r,e,t)=>(Zh(r,typeof e!="symbol"?e+"":e,t),t),ii=class extends Rr{constructor(e){e={...Rr.DEFAULT_OPTIONS,...e},super({...e,axis:"horizontal"}),Jh(this,"_tiltShiftYFilter"),this._tiltShiftYFilter=new Rr({...e,axis:"vertical"}),this.updateDelta(),Object.assign(this,e)}apply(e,t,n,o){let i=Q.getSameSizeTexture(t);e.applyFilter(this,t,i,!0),e.applyFilter(this._tiltShiftYFilter,i,n,o),Q.returnTexture(i)}updateDelta(){super.updateDelta(),this._tiltShiftYFilter.updateDelta()}get blur(){return this.uniforms.uBlur[0]}set blur(e){this.uniforms.uBlur[0]=this._tiltShiftYFilter.uniforms.uBlur[0]=e}get gradientBlur(){return this.uniforms.uBlur[1]}set gradientBlur(e){this.uniforms.uBlur[1]=this._tiltShiftYFilter.uniforms.uBlur[1]=e}get start(){return this.uniforms.uStart}set start(e){this.uniforms.uStart=this._tiltShiftYFilter.uniforms.uStart=e,this.updateDelta()}get startX(){return this.start.x}set startX(e){this.start.x=e,this.updateDelta()}get startY(){return this.start.y}set startY(e){this.start.y=e,this.updateDelta()}get end(){return this.uniforms.uEnd}set end(e){this.uniforms.uEnd=this._tiltShiftYFilter.uniforms.uEnd=e,this.updateDelta()}get endX(){return this.end.x}set endX(e){this.end.x=e,this.updateDelta()}get endY(){return this.end.y}set endY(e){this.end.y=e,this.updateDelta()}};var Mm=`precision highp float;
6955
6955
  in vec2 vTextureCoord;
6956
6956
  out vec4 finalColor;
6957
6957
 
@@ -7269,7 +7269,7 @@ fn rand(co: vec2<f32>, seed: f32) -> f32
7269
7269
  let dt: f32 = dot(co + seed, vec2<f32>(a, b));
7270
7270
  let sn: f32 = modulo(dt, 3.14159);
7271
7271
  return fract(sin(sn) * c + seed);
7272
- }`;var r0=Object.defineProperty,n0=(r,e,t)=>e in r?r0(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Hm=(r,e,t)=>(n0(r,typeof e!="symbol"?e+"":e,t),t),Wm=class jm extends k{constructor(e){e={...jm.DEFAULT_OPTIONS,...e};let t=e.maxKernelSize??32,n=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:qm.replace("${MAX_KERNEL_SIZE}",t.toFixed(1)),entryPoint:"mainFragment"}}),o=P.from({vertex:z,fragment:Gm.replace("${MAX_KERNEL_SIZE}",t.toFixed(1)),name:"zoom-blur-filter"});super({gpuProgram:n,glProgram:o,resources:{zoomBlurUniforms:{uStrength:{value:e.strength,type:"f32"},uCenter:{value:{x:0,y:0},type:"vec2<f32>"},uRadii:{value:new Float32Array(2),type:"vec2<f32>"}}}}),Hm(this,"uniforms"),this.uniforms=this.resources.zoomBlurUniforms.uniforms,Object.assign(this,e)}get strength(){return this.uniforms.uStrength}set strength(e){this.uniforms.uStrength=e}get center(){return this.uniforms.uCenter}set center(e){Array.isArray(e)&&(e={x:e[0],y:e[1]}),this.uniforms.uCenter=e}get centerX(){return this.uniforms.uCenter.x}set centerX(e){this.uniforms.uCenter.x=e}get centerY(){return this.uniforms.uCenter.y}set centerY(e){this.uniforms.uCenter.y=e}get innerRadius(){return this.uniforms.uRadii[0]}set innerRadius(e){this.uniforms.uRadii[0]=e}get radius(){return this.uniforms.uRadii[1]}set radius(e){this.uniforms.uRadii[1]=e<0||e===1/0?-1:e}};Hm(Wm,"DEFAULT_OPTIONS",{strength:.1,center:{x:0,y:0},innerRadius:0,radius:-1,maxKernelSize:32});var Xm=Wm;var o0={AlphaFilter:bn,BlurFilter:gt,ColorMatrixFilter:Nt,NoiseFilter:js,...si};function Km(r){return o0[r]}var fa=r=>{let[e,t,n]=r,[o,i]=e,[s,a]=t,c=n*Math.PI/180,l=Math.cos(c),f=Math.sin(c);return[l*s,f*s,-f*a,l*a,o,i]},Ym=([r,e,t,n,o,i])=>new Ei(r,e,t,n,o,i);var ma=(r,e)=>{let[t,n,o,i,s,a]=r,[c,l,f,u,m,d]=e;return[t*c+o*l,n*c+i*l,t*f+o*u,n*f+i*u,t*m+o*d+s,n*m+i*d+a]};var $m=[1,0,0,1,0,0];var td=Hd(Zm(),1);var Jm=`
7272
+ }`;var r0=Object.defineProperty,n0=(r,e,t)=>e in r?r0(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Hm=(r,e,t)=>(n0(r,typeof e!="symbol"?e+"":e,t),t),Wm=class jm extends k{constructor(e){e={...jm.DEFAULT_OPTIONS,...e};let t=e.maxKernelSize??32,n=A.from({vertex:{source:D,entryPoint:"mainVertex"},fragment:{source:qm.replace("${MAX_KERNEL_SIZE}",t.toFixed(1)),entryPoint:"mainFragment"}}),o=P.from({vertex:z,fragment:Gm.replace("${MAX_KERNEL_SIZE}",t.toFixed(1)),name:"zoom-blur-filter"});super({gpuProgram:n,glProgram:o,resources:{zoomBlurUniforms:{uStrength:{value:e.strength,type:"f32"},uCenter:{value:{x:0,y:0},type:"vec2<f32>"},uRadii:{value:new Float32Array(2),type:"vec2<f32>"}}}}),Hm(this,"uniforms"),this.uniforms=this.resources.zoomBlurUniforms.uniforms,Object.assign(this,e)}get strength(){return this.uniforms.uStrength}set strength(e){this.uniforms.uStrength=e}get center(){return this.uniforms.uCenter}set center(e){Array.isArray(e)&&(e={x:e[0],y:e[1]}),this.uniforms.uCenter=e}get centerX(){return this.uniforms.uCenter.x}set centerX(e){this.uniforms.uCenter.x=e}get centerY(){return this.uniforms.uCenter.y}set centerY(e){this.uniforms.uCenter.y=e}get innerRadius(){return this.uniforms.uRadii[0]}set innerRadius(e){this.uniforms.uRadii[0]=e}get radius(){return this.uniforms.uRadii[1]}set radius(e){this.uniforms.uRadii[1]=e<0||e===1/0?-1:e}};Hm(Wm,"DEFAULT_OPTIONS",{strength:.1,center:{x:0,y:0},innerRadius:0,radius:-1,maxKernelSize:32});var Xm=Wm;var o0={AlphaFilter:bn,BlurFilter:gt,ColorMatrixFilter:Vt,NoiseFilter:js,...si};function Km(r){return o0[r]}var fa=r=>{let[e,t,n]=r,[o,i]=e,[s,a]=t,c=n*Math.PI/180,l=Math.cos(c),f=Math.sin(c);return[l*s,f*s,-f*a,l*a,o,i]},Ym=([r,e,t,n,o,i])=>new Ei(r,e,t,n,o,i);var ma=(r,e)=>{let[t,n,o,i,s,a]=r,[c,l,f,u,m,d]=e;return[t*c+o*l,n*c+i*l,t*f+o*u,n*f+i*u,t*m+o*d+s,n*m+i*d+a]};var $m=[1,0,0,1,0,0];var td=Hd(Zm(),1);var Jm=`
7273
7273
  in vec2 aPosition;
7274
7274
  varying vec2 _uv; // gl-transition
7275
7275
  uniform mat3 projectionMatrix;
@@ -7322,7 +7322,7 @@ fn rand(co: vec2<f32>, seed: f32) -> f32
7322
7322
  vec2 uv = vTextureCoord.xy;
7323
7323
  gl_FragColor = transition(vTextureCoord);
7324
7324
  }
7325
- `;function rd({name:r,renderer:e}){let t=td.default.find(c=>c.name===r),n=new $t,o=new ne,i=new Qt({}),s=new Qt({}),a=new k({glProgram:new P({vertex:Jm,fragment:ed(t.glsl)}),resources:{from:i,to:s,uniforms:{...da.basics,...da.custom(t)}}});return n.filters=[a],{render({width:c,height:l,from:f,to:u,progress:m}){return(n.width!==c||n.height!==l)&&(n.setSize({width:c,height:l}),o.source.resize(c,l)),i.resource=f,s.resource=u,i.update(),s.update(),a.resources.uniforms.uniforms.progress=m,e.render({container:n,target:o,clear:!1,width:c,height:l}),o}}}var ai=class{pixi;onPointerDown=ke();onPointerMove=ke();onPointerUp=ke();onDispose=ke();static async setup(){let e=await Gs({width:1920,height:1080,preference:"webgl",background:"black",preferWebGLVersion:2}),t=new Oi;return t.interactive=!0,new this({renderer:e,stage:t})}constructor(e){this.pixi=e}#e=new Map;#t=new Map;#r=new WeakMap;async composite(e){let{stage:t,renderer:n}=this.pixi;this.#d(this.#m(e));let{dispose:o}=await this.#n(e,t);n.render(t);let i=new VideoFrame(n.canvas,{timestamp:0,duration:0});return o(),i}getActiveObject(e){return this.#t.get(e)?.sprite}async#n(e,t){if(Array.isArray(e)){let n=[];for(let o of[...e].reverse()){let i=await this.#n(o,t);n.push(i.dispose)}return{dispose:()=>n.forEach(o=>o())}}switch(e.kind){case"text":return this.#o(e,t);case"image":return this.#c(e,t);case"transition":return this.#i(e,t);case"gap":return this.pixi?.renderer.clear(),{dispose:()=>{}};default:return console.warn("Unknown layer kind",e.kind),{dispose:()=>{}}}}#o(e,t){let n=this.#f(e);return n.text=e.content,e.style&&(n.style=e.style),this.#s(n,e.matrix),this.#a(n,e.alpha),this.#l(n,e.crop),this.#u(n,e.filters),t.addChild(n),{dispose:()=>{}}}#c(e,t){let n=this.#f(e);n.texture&&n.texture!==ne.EMPTY&&n.texture.destroy(!0);let o=ne.from(e.frame);return n.texture=o,this.#s(n,e.matrix),this.#a(n,e.alpha),this.#l(n,e.crop),this.#u(n,e.filters),t.addChild(n),{dispose:()=>{e.frame.close()}}}#i({from:e,to:t,progress:n,name:o},i){let a=(this.#e.get(o)??(this.#e.set(o,rd({name:"circle",renderer:this.pixi.renderer})),this.#e.get(o))).render({from:e,to:t,progress:n,width:e.displayWidth,height:e.displayHeight}),c=new $t(a);return i.addChild(c),{dispose:()=>c.destroy(!1)}}#s(e,t){if(!t)return;let n=Ym(t);e.setFromMatrix(n)}#a(e,t){e.alpha=t??1}#l(e,t){let n=this.#r.get(e);if(n&&(e.mask===n&&(e.mask=null),n.removeFromParent(),n.clear()),!t||t.every(h=>h===0))return;let[o,i,s,a]=t,c=e.mask;e.mask=null;let l=e.getLocalBounds();e.mask=c;let f=l.x+l.width*a,u=l.y+l.height*o,m=l.width*Math.max(0,1-a-i),d=l.height*Math.max(0,1-o-s),p=n??new Mi;p.clear(),p.beginFill(16777215),p.drawRect(f,u,m,d),p.endFill(),e.addChild(p),e.mask=p,this.#r.set(e,p)}#u(e,t){if(!t?.length){e.filters=null;return}e.filters=t.map(n=>{switch(n.type){case"ColorMatrixFilter":{let{matrix:o,...i}=n.params??{},s=new Nt(i);return o&&(s.matrix=o),s}case"EmbossFilter":return new Er(n.params?.strength);case"PixelateFilter":return new Dr(n.params?.size);default:{let o=Km(n.type);return o?new o(n.params):void 0}}}).filter(n=>!!n)}#f(e){let t=this.#t.get(e.id);if(t)return t.sprite;switch(e.kind){case"text":{let n=new Sn({text:e.content,style:e.style});n.eventMode="static";let o=a=>this.onPointerDown.publish({event:a,id:e.id,object:n}),i=a=>this.onPointerUp.publish({event:a,id:e.id,object:n}),s=a=>this.onPointerUp.publish({event:a,id:e.id,object:n});return n.on("pointerdown",o),n.on("pointerup",i),n.on("pointermove",s),this.#t.set(e.id,{sprite:n,dispose:()=>{this.onDispose.publish({id:e.id,object:n}),n.off("pointermove",s),n.off("pointerdown",o),n.off("pointerup",i)}}).get(e.id)?.sprite}case"image":{let n=new $t;n.eventMode="static";let o=a=>this.onPointerDown.publish({event:a,id:e.id,object:n}),i=a=>this.onPointerUp.publish({event:a,id:e.id,object:n}),s=a=>this.onPointerUp.publish({event:a,id:e.id,object:n});return n.on("pointerdown",o),n.on("pointermove",s),n.on("pointerup",i),this.#t.set(e.id,{sprite:n,dispose:()=>{this.onDispose.publish({id:e.id,object:n}),n.off("pointerdown",o),n.off("pointermove",s),n.off("pointerup",i)}}).get(e.id)?.sprite}}}#m(e){let t=new Set,n=o=>{if(Array.isArray(o))for(let i of o)n(i);else t.add(o.id)};return n(e),t}#d(e){for(let t of this.#t.keys())if(!e.has(t)){let{sprite:n,dispose:o}=this.#t.get(t);o(),n.destroy(!0),this.#t.delete(t)}}};var nd=r=>ir.host(e=>({async world(){r.count++}}));async function ye(r){return r instanceof Blob?new vn(r):new yn(r)}var ci=class{machina;thread;compositor;static async setup(e){let t=new Go,n=await ir.thread({label:"OmnitoolDriver",workerUrl:e?.workerUrl??"/node_modules/@omnimedia/omnitool/x/driver/driver.worker.bundle.min.js",setupHost:nd(t)}),o=await ai.setup();return new this(t,n,o)}constructor(e,t,n){this.machina=e,this.thread=t,this.compositor=n}async hello(){return this.thread.work.hello()}async getAudioDuration(e){let n=await new fe({source:await ye(e),formats:ge}).getPrimaryAudioTrack();if(!n)throw new Error("primary audio track not found");return await n.computeDuration()}async getVideoDuration(e){return await(await new fe({source:await ye(e),formats:ge}).getPrimaryVideoTrack())?.computeDuration()}decodeVideo(e){let t=null,{port1:n,port2:o}=new MessageChannel,i=new TransformStream({async transform(s,a){let c=await e.onFrame?.(s)??s;t?.close(),a.enqueue(c),t=c}});return this.thread.work.decodeVideo[rr]({transfer:[i.writable,o]})({source:e.source,cancel:o,video:i.writable,start:e.start,end:e.end}),{readable:i.readable,cancel(){n.postMessage("close"),n.close()}}}decodeAudio(e){let t=new TransformStream,{port1:n,port2:o}=new MessageChannel;return this.thread.work.decodeAudio[rr]({transfer:[t.writable,o]})({source:e.source,cancel:o,audio:t.writable,start:e.start,end:e.end}),{readable:t.readable,cancel(){n.postMessage("close"),n.close()}}}encode({audio:e,video:t,config:n}){let{readable:o,writable:i}=new TransformStream,s=[e,t,i].filter(En.happy),a=this.thread.work.encode[rr]({transfer:s})({audio:e,video:t,config:n,writable:i});return{readable:o,done:a}}async composite(e){return await this.compositor.composite(e)}};var b=(r,e,t,n)=>({type:"number",min:r,max:e,default:t,...n===void 0?{}:{step:n}}),tt=r=>({type:"color",default:r}),Ve=r=>({type:"boolean",default:r}),li=(r,e)=>({type:"choice",options:r,default:e}),ee=r=>({type:"object",properties:r}),s0=r=>({type:"array",items:r}),od=[3,5,7,9,11,13,15,17,19,21,23,25],a0={TRANSPARENT:0,ORIGINAL:1,LOOP:2,CLAMP:3,MIRROR:4},H=()=>(r,e={})=>({type:r,schema:e}),ui={adjustment:H()("AdjustmentFilter",{gamma:b(0,5,1),saturation:b(0,5,1),contrast:b(0,5,1),brightness:b(0,5,1),red:b(0,5,1),green:b(0,5,1),blue:b(0,5,1),alpha:b(0,1,1,.01)}),advancedBloom:H()("AdvancedBloomFilter",{threshold:b(.1,.9,.5,.01),bloomScale:b(.5,1.5,1,.01),brightness:b(.5,1.5,1,.01),blur:b(0,20,8,.1),quality:b(1,20,4,1)}),alpha:H()("AlphaFilter",{alpha:b(0,1,1,.01)}),ascii:H()("AsciiFilter",{size:b(2,20,8,1),color:tt("#ffffff"),replaceColor:Ve(!1)}),backdropBlur:H()("BackdropBlurFilter",{strength:b(0,100,8,.1),quality:b(1,10,4,1)}),bevel:H()("BevelFilter",{rotation:b(0,360,45,1),thickness:b(0,10,2,.1),lightColor:tt("#ffffff"),lightAlpha:b(0,1,.7,.01),shadowColor:tt("#000000"),shadowAlpha:b(0,1,.7,.01)}),bloom:H()("BloomFilter",{strength:ee({x:b(0,20,2,.1),y:b(0,20,2,.1)}),quality:b(1,20,4,1),resolution:b(.25,4,1,.01),kernelSize:li([5,7,9,11,13,15],5)}),blur:H()("BlurFilter",{strength:b(0,100,8,.1),quality:b(1,10,4,1)}),bulgePinch:H()("BulgePinchFilter",{radius:b(0,1e3,100,1),strength:b(-1,1,1,.01),center:ee({x:b(0,1,.5,.01),y:b(0,1,.5,.01)})}),colorGradient:H()("ColorGradientFilter"),colorMatrix:H()("ColorMatrixFilter"),colorOverlay:H()("ColorOverlayFilter",{color:tt("#ff0000"),alpha:b(0,1,.5,.01)}),colorReplace:H()("ColorReplaceFilter",{originalColor:tt("#ff0000"),targetColor:tt("#000000"),tolerance:b(0,1,.4,.01)}),convolution:H()("ConvolutionFilter",{width:b(0,500,300,1),height:b(0,500,300,1),matrix:s0([b(0,1,0),b(0,1,.5,.01),b(0,1,0),b(0,1,.5,.01),b(0,1,1,.01),b(0,1,.5,.01),b(0,1,0),b(0,1,.5,.01),b(0,1,0)])}),crossHatch:H()("CrossHatchFilter"),crt:H()("CRTFilter",{curvature:b(0,10,1,.01),lineWidth:b(0,5,3,.01),lineContrast:b(0,1,.3,.01),verticalLine:Ve(!1),noise:b(0,1,.2,.01),noiseSize:b(1,10,1,.1),vignetting:b(0,1,.3,.01),vignettingAlpha:b(0,1,1,.01),vignettingBlur:b(0,1,.3,.01),seed:b(0,1,0,.01),time:b(.5,20,.5,.01)}),dot:H()("DotFilter",{scale:b(.3,1,1,.01),angle:b(0,5,5,.01),grayscale:Ve(!0)}),dropShadow:H()("DropShadowFilter",{blur:b(0,20,2,.1),quality:b(1,20,3,1),alpha:b(0,1,.5,.01),offset:ee({x:b(-50,50,4,1),y:b(-50,50,4,1)}),color:tt("#000000"),shadowOnly:Ve(!1)}),emboss:H()("EmbossFilter",{strength:b(0,20,5,.1)}),glitch:H()("GlitchFilter",{slices:b(0,64,5,1),seed:b(0,1,.5,.01),offset:b(-400,400,100,1),direction:b(-180,180,0,1),fillMode:li(a0,"LOOP"),average:Ve(!1),minSize:b(0,64,8,1),sampleSize:b(1,2048,512,1),red:ee({x:b(-50,50,2,1),y:b(-50,50,2,1)}),blue:ee({x:b(-50,50,10,1),y:b(-50,50,-4,1)}),green:ee({x:b(-50,50,-10,1),y:b(-50,50,4,1)})}),glow:H()("GlowFilter",{distance:b(0,20,15,.1),innerStrength:b(0,20,0,.1),outerStrength:b(0,20,2,.1),color:tt("#ffffff"),quality:b(0,1,.2,.01),alpha:b(0,1,1,.01),knockout:Ve(!1)}),godray:H()("GodrayFilter",{time:b(0,1,0,.01),gain:b(0,1,.6,.01),lacunarity:b(0,5,2.75,.01),alpha:b(0,1,1,.01),parallel:Ve(!0),angle:b(-60,60,30,1),center:ee({x:b(-100,2012,956,1),y:b(-1e3,-100,-100,1)})}),grayscale:H()("GrayscaleFilter"),hslAdjustment:H()("HslAdjustmentFilter",{hue:b(-180,180,0,1),saturation:b(-1,1,0,.01),lightness:b(-1,1,0,.01),colorize:Ve(!1),alpha:b(0,1,1,.01)}),kawaseBlur:H()("KawaseBlurFilter",{strength:b(0,20,4,.1),quality:b(1,20,3,1),pixelSize:ee({x:b(0,10,1,.1),y:b(0,10,1,.1)})}),motionBlur:H()("MotionBlurFilter",{velocity:ee({x:b(-90,90,40,1),y:b(-90,90,40,1)}),kernelSize:li(od,15),offset:b(-150,150,0,1)}),multiColorReplace:H()("MultiColorReplaceFilter"),noise:H()("NoiseFilter",{noise:b(0,1,.5,.01),seed:b(.01,10,.5,.01)}),oldFilm:H()("OldFilmFilter",{sepia:b(0,1,.3,.01),noise:b(0,1,.3,.01),noiseSize:b(1,10,1,.1),scratch:b(-1,1,.5,.01),scratchDensity:b(0,1,.3,.01),scratchWidth:b(1,20,1,.1),vignetting:b(0,1,.3,.01),vignettingAlpha:b(0,1,1,.01),vignettingBlur:b(0,1,.3,.01)}),outline:H()("OutlineFilter",{thickness:b(0,10,4,.1),color:tt("#000000"),alpha:b(0,1,1,.01),knockout:Ve(!1)}),pixelate:H()("PixelateFilter",{size:ee({x:b(4,40,10,1),y:b(4,40,10,1)})}),radialBlur:H()("RadialBlurFilter",{angle:b(-180,180,20,1),radius:b(-1,1912,300,1),center:ee({x:b(0,1912,956,1),y:b(0,920,460,1)}),kernelSize:li(od,15)}),reflection:H()("ReflectionFilter",{mirror:Ve(!0),boundary:b(0,1,.5,.01),amplitude:ee({start:b(0,50,0,.1),end:b(0,50,20,.1)}),waveLength:ee({start:b(10,200,30,1),end:b(10,200,100,1)}),alpha:ee({start:b(0,1,1,.01),end:b(0,1,1,.01)}),time:b(0,20,0,.01)}),rgbSplit:H()("RGBSplitFilter",{red:ee({x:b(-20,20,-10,1),y:b(-20,20,0,1)}),blue:ee({x:b(-20,20,0,1),y:b(-20,20,0,1)}),green:ee({x:b(-20,20,0,1),y:b(-20,20,10,1)})}),shockwave:H()("ShockwaveFilter",{speed:b(500,2e3,500,1),amplitude:b(1,100,30,1),wavelength:b(2,400,160,1),brightness:b(.2,2,1,.01),radius:b(100,2e3,-1,1),center:ee({x:b(0,1912,956,1),y:b(0,920,460,1)})}),simplexNoise:H()("SimplexNoiseFilter",{strength:b(0,1,.5,.01),noiseScale:b(0,50,10,.1),offsetX:b(0,5,0,.01),offsetY:b(0,5,0,.01),offsetZ:b(0,5,0,.01),step:b(-1,1,-1,.01)}),tiltShift:H()("TiltShiftFilter",{blur:b(0,200,100,.1),gradientBlur:b(0,1e3,600,1),start:ee({x:b(0,1912,0,1),y:b(0,920,460,1)}),end:ee({x:b(0,1912,1912,1),y:b(0,920,460,1)})}),twist:H()("TwistFilter",{angle:b(-10,10,4,.01),radius:b(0,1912,200,1),offset:ee({x:b(0,1912,956,1),y:b(0,920,460,1)})}),zoomBlur:H()("ZoomBlurFilter",{strength:b(.01,.5,.1,.01),center:ee({x:b(0,1912,956,1),y:b(0,920,460,1)}),innerRadius:b(0,956,80,1),radius:b(0,956,-1,1)})};var G;(function(r){r[r.Sequence=0]="Sequence",r[r.Stack=1]="Stack",r[r.Video=2]="Video",r[r.Audio=3]="Audio",r[r.Text=4]="Text",r[r.Gap=5]="Gap",r[r.Spatial=6]="Spatial",r[r.Animation=7]="Animation",r[r.Transition=8]="Transition",r[r.TextStyle=9]="TextStyle",r[r.Filter=10]="Filter",r[r.Caption=11]="Caption",r[r.Image=12]="Image"})(G||(G={}));var fi;(function(r){r[r.Crossfade=0]="Crossfade"})(fi||(fi={}));var mi=class{datafile;duration=0;isImage=!1;hasVideo=!1;hasAudio=!1;constructor(e){this.datafile=e}static async analyze(e){let t=new this(e);if(this.#e(e))return t.isImage=!0,t;let n=await this.duration(e.url)*1e3;t.duration=n;let{video:o,audio:i}=await this.#t(e.url);return t.hasAudio=i,t.hasVideo=o,t}static#e(e){return e.blob.type.startsWith("image/")}static async duration(e){let n=await new fe({formats:ge,source:await ye(e)}).computeDuration();return Number(n.toFixed(5))}static async#t(e){let t=new fe({formats:ge,source:await ye(e)});return{audio:!!await t.getPrimaryAudioTrack(),video:!!await t.getPrimaryVideoTrack()}}};var di=class{#e=new zn;async store(e){let t=await mi.analyze(e),{hash:n}=t.datafile.checksum,{filename:o,bytes:i,url:s,blob:a}=t.datafile;if(this.#e.has(n)){let c=this.#e.require(n);c.filename=o}else this.#e.set(n,{kind:"media",filename:o,bytes:i,url:s,blob:a,duration:t.duration});return t}require(e){return this.#e.require(e)}};var pi=class r{videoTrack;options;#e;#t=new Map;#r=[0,0];constructor(e,t){this.videoTrack=e,this.options=t,this.#e=new cn(e,t.canvasSinkOptions)}static async init(e,t){let o=await new fe({formats:ge,source:await ye(e)}).getPrimaryVideoTrack();if(o)return new r(o,{frequency:t.frequency??1,canvasSinkOptions:t.canvasSinkOptions??{width:80,height:50,fit:"fill"},onChange:t.onChange,onPlaceholders:t.onPlaceholders});throw new Error("Source has no video track")}set frequency(e){e!==this.options.frequency&&(this.options.frequency=e,this.#a())}get frequency(){return this.options.frequency}#n([e,t],n=1){let o=t-e;return[e-o*n,t+o*n]}async#o(){let[e,t]=this.#r,n=new Set,o=await this.videoTrack.computeDuration();for(let i=Math.max(0,e);i<=t;i+=this.options.frequency)i>=0&&i<=o&&n.add(i);this.options.onPlaceholders?.([...n])}async#c(){let[e,t]=this.#r,n=new Set,o=await this.videoTrack.computeDuration();for(let c=Math.max(0,e);c<=t;c+=this.options.frequency)c>=0&&c<=o&&n.add(c);let i=[...n].filter(c=>!this.#t.has(c)),s=0;for await(let c of this.#e.canvasesAtTimestamps(i))if(c){let l=i[s++];this.#t.set(l,c)}for(let c of this.#t.keys())n.has(c)||this.#t.delete(c);let a=[...this.#t.entries()].map(([c,l])=>({time:c,canvas:l}));this.options.onChange(a)}set range(e){let[t,n]=e,o=n-t,[i,s]=this.#r,a=i+o,c=s-o,l=t<a,f=n>c;!l&&!f||(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)}};var xt={slideIn:{type:"motion",label:"Slide in",defaults:{duration:700,from:[-400,0],to:[0,0],terp:"easeOut"},transform:{from:{position:[-400,0]},to:{position:[0,0]}}},slideOut:{type:"motion",label:"Slide out",defaults:{duration:700,from:[0,0],to:[400,0],terp:"easeIn"},transform:{from:{position:[0,0]},to:{position:[400,0]}}},spinIn:{type:"motion",label:"Spin in",defaults:{duration:700,from:[0,0],to:[0,0],terp:"easeOut"},transform:{from:{scale:[0,0],rotation:-180},to:{scale:[1,1],rotation:0}}},spinOut:{type:"motion",label:"Spin out",defaults:{duration:700,from:[0,0],to:[0,0],terp:"easeIn"},transform:{from:{scale:[1,1],rotation:0},to:{scale:[0,0],rotation:180}}},zoomIn:{type:"motion",label:"Zoom in",defaults:{duration:700,from:[0,0],to:[0,0],terp:"easeOut"},transform:{from:{scale:[0,0]},to:{scale:[1,1]}}},zoomOut:{type:"motion",label:"Zoom out",defaults:{duration:700,from:[0,0],to:[0,0],terp:"easeIn"},transform:{from:{scale:[1,1]},to:{scale:[0,0]}}},bounceIn:{type:"motion",label:"Bounce in",defaults:{duration:700,from:[0,0],to:[0,0],terp:"bounce"},transform:{from:{scale:[0,0]},to:{scale:[1,1]}}},bounceOut:{type:"motion",label:"Bounce out",defaults:{duration:700,from:[0,0],to:[0,0],terp:"bounce"},transform:{from:{scale:[1,1]},to:{scale:[0,0]}}},fadeIn:{type:"scalar",label:"Fade in",defaults:{duration:700,from:0,to:1,terp:"easeIn"}},fadeOut:{type:"scalar",label:"Fade out",defaults:{duration:700,from:1,to:0,terp:"easeOut"}}};var Tn={transform:{type:"transform",defaultTerp:"linear",channels:[{path:"position.x",type:"number",default:0,unit:"pixel"},{path:"position.y",type:"number",default:0,unit:"pixel"},{path:"scale.x",type:"number",default:1,unit:"scale"},{path:"scale.y",type:"number",default:1,unit:"scale"},{path:"rotation",type:"number",default:0,unit:"degree"}]},opacity:{type:"scalar",defaultTerp:"linear",channels:[{type:"number",default:1,unit:"ratio",range:[0,1]}]}},c0={...Tn};function id(r,e,t){let n=Object.entries(xt).map(([o,i])=>{let s=i.type==="motion"?a=>{let c=a?.offset??0;return e(a?.terp??i.defaults.terp,[[c,t({...i.transform.from,...a?.from===void 0?{}:{position:a.from}})],[c+(a?.duration??i.defaults.duration),t({...i.transform.to,...a?.to===void 0?{}:{position:a.to}})]])}:a=>{let c=a?.offset??0;return r(a?.terp??i.defaults.terp,[[c,a?.from??i.defaults.from],[c+(a?.duration??i.defaults.duration),a?.to??i.defaults.to]])};return[o,s]});return Object.fromEntries(n)}var hi={default:{styles:{fontFamily:"Arial",fontSize:56,fill:"#ffffff",align:"center",wordWrap:!0,wordWrapWidth:1440},transform:{position:[240,860]}}},l0={maxChars:42,maxDuration:3500,maxSilence:750};function pa(r,e){let{maxChars:t,maxDuration:n,maxSilence:o}={...l0,...e},i=[],s=null;for(let{timestamp:[a,c],text:l}of r.chunks){let[f,u]=[a*1e3,c*1e3],m=l.trim();if(!Number.isFinite(f)||!Number.isFinite(u)||!m)continue;if(!s){s={text:m,timestamp:[f,u]};continue}let[d,p]=s.timestamp,h=`${s.text} ${m}`.trim();h.length>t||u-d>n||f-p>o?(i.push(s),s={text:m,timestamp:[f,u]}):s={text:h,timestamp:[d,u]}}return s&&i.push(s),i}function sd(r,e){let t=pa(r,e);return Math.max(0,...t.map(n=>n.timestamp[1]))}var ad=()=>({model:"onnx-community/whisper-tiny_timestamped",dtype:"auto",device:"webgpu",chunkLength:20,strideLength:3});async function cd(r,e){let t=await e.arrayBuffer(),o=await new AudioContext({sampleRate:16e3}).decodeAudioData(t),i;if(o.numberOfChannels===2){let a=Math.sqrt(2),c=o.getChannelData(0),l=o.getChannelData(1);i=new Float32Array(c.length);for(let f=0;f<o.length;++f)i[f]=a*(c[f]+l[f])/2}else i=o.getChannelData(0);let s=await r.getAudioDuration(e);return{audio:i,duration:s}}async function ld({driver:r,spec:e,workerUrl:t,onLoading:n}){let o=Vi(),i=Vi(),s=await ir.thread({label:"OmnitoolSpeechTranscriber",workerUrl:t,setupHost:()=>({loading:async a=>n(a),deliverReport:async a=>o.pub(a),deliverTranscription:async a=>i.pub(a)})});return await s.work.prepare(e),{transcribe:_a(async a=>{let{source:c,language:l}=a,{audio:f,duration:u}=await cd(r,c),m=Ia(o(a.onReport),i(a.onTranscription)),d=await s.work.transcribe({duration:u,language:l,audio:f.buffer});return m(),d}),dispose:()=>s.terminate()}}function ud(r,e){let t=typeof window<"u"&&window.devicePixelRatio||1,n=document.createElement("canvas");n.width=e.width*t,n.height=e.height*t,n.style.width=`${e.width}px`,n.style.height=`${e.height}px`;let o=n.getContext("2d");if(!o)return n;o.scale(t,t),o.fillStyle=e.color;let i=e.height/2,s=Math.max(1,e.width),a=r.length/s;for(let c=0;c<s;c++){let l=Math.floor(c*a),f=Math.max(l+1,Math.floor((c+1)*a)),u=0;for(let d=l;d<f&&d<r.length;d++)r[d]>u&&(u=r[d]);let m=u*e.height;o.fillRect(c,i-m/2,1,m)}return n}var ha=[2048,1024,512,256,128,64,32];async function fd(r,e){let t=await r.getAudioDuration(e)??0,n=r.decodeAudio({source:e}).readable,o=ha[ha.length-1],i=[],s=0,a=0,c=0;for await(let u of n){c||=u.sampleRate;let m=u.numberOfFrames,d=new Float32Array(m);u.copyTo(d,{planeIndex:0});for(let p=0;p<d.length;p++){let h=Math.abs(d[p]);h>s&&(s=h),a++,a>=o&&(i.push(s),s=0,a=0)}u.close()}a>0&&i.push(s);let l=new Float32Array(i),f=ha.map(u=>{let m=Math.max(1,Math.round(u/o)),d=m===1?l:u0(l,m);return{samplesPerPeak:u,peaks:d,peaksPerSecond:c>0?c/u:0}});return{duration:t,levels:f}}function u0(r,e){let t=new Float32Array(Math.ceil(r.length/e));for(let n=0;n<t.length;n++){let o=0,i=n*e,s=Math.min(i+e,r.length);for(let a=i;a<s;a++)r[a]>o&&(o=r[a]);t[n]=o}return t}var f0=4096,gi=class r{#e=new Map;#t=[0,0];#r=[0,0];#n;#o;#c;#i=!1;color;duration;tileSize;tileHeight;preloadMargin;constructor(e,t,n){this.#o=e,this.duration=t,this.tileSize=n.tileSize??1,this.#n=n.zoom??(n.tileWidth??256)/this.tileSize,this.tileHeight=n.tileHeight??96,this.preloadMargin=n.preloadMargin??2,this.color=n.color??"rgb(3, 148, 129)",this.#c=n.onChange}static async init(e,t,n={}){let{duration:o,levels:i}=await fd(e,t);return new r(i,o,n)}set zoom(e){let t=Math.max(1,e);t!==this.#n&&(this.#n=t,this.#e.clear(),this.#a())}get zoom(){return this.#n}get range(){return this.#r}#s([e,t],n=1){let o=t-e;return[Math.max(0,e-o*n),Math.min(this.duration,t+o*n)]}set range(e){this.#r=e;let[t,n]=e,o=n-t,[i,s]=this.#t,a=i>0,c=s<this.duration,l=!a||t>=i+o,f=!c||n<=s-o;l&&f||(this.#t=this.#s(e,this.preloadMargin),this.#a())}#a(){this.#i||(this.#i=!0,queueMicrotask(()=>{this.#i=!1,this.#l()}))}#l(){let[e,t]=this.#t,n=new Set,o=this.#f(),i=Math.max(0,Math.floor(e/this.tileSize)*this.tileSize),s=Math.min(this.duration,t);for(let a=i;a<=s;a+=this.tileSize)n.add(a);for(let a of n)if(!this.#e.has(a)){let c=Math.min(a+this.tileSize,this.duration);this.#e.set(a,this.#u(a,c,o))}for(let a of this.#e.keys())n.has(a)||this.#e.delete(a);this.#p()}#u(e,t,n){let o=this.#m(n,e,t);return{startTime:e,endTime:t,peaks:o,canvas:ud(o,{width:this.#d(e,t),height:this.tileHeight,color:this.color})}}#f(){return this.#o.find(e=>e.peaksPerSecond>=this.#n)??this.#o[this.#o.length-1]}#m(e,t,n){if(!e.peaksPerSecond)return new Float32Array;let o=Math.max(0,Math.floor(t*e.peaksPerSecond)),i=Math.max(o+1,Math.min(e.peaks.length,Math.ceil(n*e.peaksPerSecond)));return e.peaks.slice(o,i)}#d(e,t){return Math.min(f0,Math.max(1,Math.ceil((t-e)*this.#n)))}#p(){this.#c&&this.#c([...this.#e.values()].sort((e,t)=>e.startTime-t.startTime))}getTiles(){return this.#e}};var X=r=>r;var Rr=r=>r;var md=()=>{let r=!1,e=Rr(60),t=1e3/e,n=0,o=0,i=ke(),s=null,a=l=>{if(requestAnimationFrame(a),!!r)for(n=l;l-o>=t;)o+=t,s?.(),s=null,i()};async function*c(){for(n=performance.now(),o=n,requestAnimationFrame(a);;)await new Promise(l=>s=l),yield}return{play(){r||(r=!0,n=performance.now(),o=n)},pause(){r=!1},setFPS(l){e=l,t=1e3/e},isPlaying(){return r},ticks:c,onTick:i}},dd=async(r,e)=>{let t=X(1e3/r.fps),n=r.duration/1e3,o=Math.ceil(n*r.fps);for(let i=0;i<o;i++){let s=X(i*t);await e(s,i)}};var wn=r=>r;var ga=class{keys;index;constructor(e,t){this.keys=e,this.index=t}near(e){return this.keys[Math.max(0,Math.min(this.keys.length-1,this.index+e))][1]}},pd=r=>r,Cn=r=>pd((e,t)=>r(e,t.near(0),t.near(1))),kn=(r,e,t)=>e+(t-e)*r,m0={linear:Cn(kn),ease:Cn((r,e,t)=>{let n=r<.5?4*r*r*r:1-Math.pow(-2*r+2,3)/2;return kn(n,e,t)}),easeIn:Cn((r,e,t)=>kn(r*r*r,e,t)),easeOut:Cn((r,e,t)=>kn(1-Math.pow(1-r,3),e,t)),bounce:Cn((r,e,t)=>{let i=r<.36363636363636365?7.5625*r*r:r<.7272727272727273?7.5625*(r-.5454545454545454)**2+.75:r<.9090909090909091?7.5625*(r-.8181818181818182)**2+.9375:7.5625*(r-.9545454545454546)**2+.984375;return kn(i,e,t)}),catmullRom:pd((r,e)=>{let t=e.near(-1),n=e.near(0),o=e.near(1),i=e.near(2),s=r*r,a=s*r;return .5*(2*n+(-t+o)*r+(2*t-5*n+4*o-i)*s+(-t+3*n-3*o+i)*a)})},hd=(r,e,t,n)=>{let o=m0[r];if(!o)throw new Error(`unknown terp "${r}"`);return o(e,new ga(t,n))};var Mr=(r,e,t,n=0)=>{if(e.length===0)return n;if(e.length===1)return e[0][1];let o=[...e].sort((u,m)=>u[0]-m[0]);if(r<=o[0][0])return o[0][1];let i=o[o.length-1];if(r>=i[0])return i[1];let s=0;for(let u=0;u<o.length-1;u++){let m=o[u],d=o[u+1];if(r>=m[0]&&r<=d[0]){s=u;break}}let[a]=o[s],[c]=o[s+1],l=c-a,f=l===0?0:(r-a)/l;return hd(t,f,o,s)},gd=(r,e)=>[[Mr(r,e.track.position.x,e.terp),Mr(r,e.track.position.y,e.terp)],[Mr(r,e.track.scale.x,e.terp,1),Mr(r,e.track.scale.y,e.terp,1)],Mr(r,e.track.rotation,e.terp)],xd=(r,e)=>Mr(r,e.track,e.terp);function d0(r){return"duration"in r}function yd(r){let e=[],t=new Map(r.timeline.items.map(n=>[n.id,n]));return xa(r.timeline.rootId,t,r.from,{sequence:()=>{},stack:()=>{},video:(n,o,i)=>e.push({item:n,localTime:o,ancestors:i}),image:(n,o,i)=>e.push({item:n,localTime:o,ancestors:i}),text:(n,o,i)=>e.push({item:n,localTime:o,ancestors:i}),caption:(n,o,i)=>e.push({item:n,localTime:o,ancestors:i}),audio:(n,o,i)=>e.push({item:n,localTime:o,ancestors:i})}),e}function bd(r,e,t,n){let o=$m;for(let i of e)o=vd(r,i.item,o,i.localTime);return vd(r,t,o,n)}function vd(r,e,t,n){let o=t;if("spatialId"in e&&e.spatialId){let i=r.get(e.spatialId);if(i?.enabled){let s=fa(i.transform);o=ma(s,o)}}if("animationIds"in e&&e.animationIds)for(let i of e.animationIds){let s=r.get(i),a=s?.anims.transform;if(s?.enabled&&a&&p0(a,n)){let c=fa(gd(n,a));o=ma(c,o)}}return o}function xa(r,e,t,n,o=[]){let i=e.get(r);if(i)switch(i.kind){case G.Stack:n.stack(i,t,o);for(let s of i.childrenIds)xa(s,e,t,n,[...o,{item:i,localTime:t}]);break;case G.Sequence:{n.sequence(i,t,o);let s=X(0);for(let a of i.childrenIds){let c=e.get(a);if(!c)continue;let l=Ur(c.id,e);if(l<=0)continue;let f=X(s+l);if(t>=f){s=f;continue}let u=X(Math.max(0,t-s));xa(a,e,u,n,[...o,{item:i,localTime:t}]),s=f}break}case G.Video:n.video(i,t,o);break;case G.Image:n.image(i,t,o);break;case G.Text:n.text(i,t,o);break;case G.Caption:n.caption(i,t,o);break;case G.Audio:n.audio(i,t,o);break}}function Wt(r,e){return Ur(r,new Map(e.items.map(t=>[t.id,t])))}function Ur(r,e){let t=e.get(r);if(!t)return X(0);switch(t.kind){case G.Sequence:{let n=t.childrenIds.map(i=>e.get(i)).filter(Boolean),o=X(0);for(let i=0;i<n.length;i++){let s=n[i];if(s.kind===G.Transition){let a=n[i-1],c=n[i+1];if(a&&c&&a.kind!==G.Transition&&c.kind!==G.Transition){let l=Ur(a.id,e),f=Ur(c.id,e),u=Math.max(0,Math.min(s.duration,l,f));o=X(o-u)}continue}o=X(o+Ur(s.id,e))}return o}case G.Stack:{let n=X(0);for(let o of t.childrenIds){let i=Ur(o,e);i>n&&(n=i)}return n}default:return d0(t)?t.duration:X(0)}}function Sd(r,e,t){if(!("animationIds"in e)||e.animationIds===void 0)return 1;let n=1;for(let o of e.animationIds){let i=r.items.get(o),s=i?.anims.opacity;i?.enabled&&s&&Br(s.track,t)&&(n=xd(t,s))}return n}function Br(r,e){if(r.length===0)return!1;let t=r[0][0],n=r[0][0];for(let[o]of r)t=Math.min(t,o),n=Math.max(n,o);return e>=t&&e<=n}function p0(r,e){return Br(r.track.position.x,e)||Br(r.track.position.y,e)||Br(r.track.scale.x,e)||Br(r.track.scale.y,e)||Br(r.track.rotation,e)}var xi=class{resolveMedia;#e=new Map;constructor(e){this.resolveMedia=e}async getSink(e){let t=this.#e.get(e);if(t)return t.sink;let n=new fe({formats:ge,source:await ye(this.resolveMedia(e))}),o=await n.getPrimaryVideoTrack(),s=!!o&&await o.canDecode()&&o?new ut(o):null;return this.#e.set(e,{input:n,sink:s}),s}};var vi=class{resolveMedia;#e=new Map;constructor(e){this.resolveMedia=e}async getFrame(e,t){let n=await this.#t(e);return new VideoFrame(n.bitmap,{timestamp:Math.round(t*1e3)})}async#t(e){let t=this.#e.get(e);if(t)return t;let n=this.resolveMedia(e),o=n instanceof Blob?n:await fetch(n).then(s=>s.blob()),i={bitmap:await createImageBitmap(o)};return this.#e.set(e,i),i}disposeAll(){for(let e of this.#e.values())e.bitmap.close();this.#e.clear()}dispose(e){this.#e.get(e)?.bitmap.close(),this.#e.delete(e)}};async function Td(r,e,t,n){let[o,i]=await Promise.all([t,n]),s=o.find(l=>l.kind==="image")?.frame,a=i.find(l=>l.kind==="image")?.frame,c=[...o.filter(l=>l.kind!=="image"),...i.filter(l=>l.kind!=="image")];return s&&a?[{id:r.id,kind:"transition",name:"circle",progress:e,from:s,to:a},...c]:c}async function wd(r,e,t,n){let o=h0(r,e,t);if(!o)return[];let i=[...n,{item:e,localTime:t}];return o.isTransitioning?Td(o.transition,o.progress,jt(r,o.outgoing,o.outgoingTime,i),jt(r,o.incoming,o.incomingTime,i)):jt(r,o.item,o.localTime,i)}function h0(r,e,t){let n=e.childrenIds.map(i=>r.items.get(i)).filter(i=>!!i),o=X(0);for(let i=0;i<n.length;i++){let s=n[i];if(s.kind===G.Transition)continue;let a=o,c=Wt(s.id,r.timeline),l=X(a+c),f=n[i+1];if(!(f?.kind===G.Transition)){if(t<l)return{isTransitioning:!1,item:s,localTime:X(t-a)};o=l;continue}let m=f,d=n[i+2];if(!d||d.kind===G.Transition){o=l;continue}let p=Wt(d.id,r.timeline),h=Math.max(0,Math.min(m.duration,c,p)),x=X(l-h);if(t<x)return{isTransitioning:!1,item:s,localTime:X(t-a)};if(t<l){let y=X(t-x),v=X(t-a);return{isTransitioning:!0,incoming:d,outgoing:s,outgoingTime:v,incomingTime:y,progress:h>0?y/h:1,transition:m}}o=x,i++}return null}async function jt(r,e,t,n){let o=bd(r.items,n,e,t),i=Sd(r,e,t),s="spatialId"in e&&e.spatialId?r.items.get(e.spatialId)?.crop:void 0,a="filterIds"in e&&e.filterIds?e.filterIds.map(c=>r.items.get(c)).filter(c=>!!c?.enabled).map(c=>({type:c.type,params:c.params})):void 0;switch(e.kind){case G.Stack:{let c=[...n,{item:e,localTime:t}];return(await Promise.all(e.childrenIds.map(f=>r.items.get(f)).filter(f=>!!f).map(f=>jt(r,f,t,c)))).flat()}case G.Sequence:return wd(r,e,t,n);case G.Video:{if(t<0||t>=e.duration)return[];let c=await r.videoSampler(e,t);return c?[{kind:"image",frame:c,matrix:o,alpha:i,crop:s,filters:a,id:e.id}]:[]}case G.Image:{if(t<0||t>=e.duration)return[];let c=await r.imageSampler(e,t);return c?[{kind:"image",frame:c,matrix:o,alpha:i,crop:s,filters:a,id:e.id}]:[]}case G.Text:{if(t<0||t>=e.duration)return[];let c=e.styleId?r.items.get(e.styleId)?.style:void 0;return[{id:e.id,kind:"text",content:e.content,style:c,matrix:o,alpha:i,crop:s,filters:a}]}case G.Caption:{if(t<0||t>=e.duration)return[];let c=e.start+t,l=pa(e.transcript,e).find(u=>{let[m,d]=u.timestamp;return c>=m&&c<d});if(!l)return[];let f=e.styleId?r.items.get(e.styleId)?.style:void 0;return[{id:e.id,kind:"text",content:l.text,style:f,matrix:o,alpha:i,crop:s,filters:a}]}case G.Gap:return[{id:e.id,kind:"gap"}];default:return[]}}function Cd(r){return async(e,t)=>{let n=await r.getSink(e.mediaHash),o=e.start+t,i=await n?.getSample(o/1e3),s=i?.toVideoFrame();return i?.close(),s??void 0}}function kd(r){return async(e,t)=>await r.getFrame(e.mediaHash,t)}function yi(r,e){let t=new vi(r),n=new xi(r),o=kd(t),i=e??Cd(n);return{async sample(s,a){let c=new Map(s.items.map(f=>[f.id,f])),l=c.get(s.rootId);return l?jt({imageSampler:o,videoSampler:i,timeline:s,items:c},l,a,[]):[]}}}var bi=class{driver;resolveMedia;timeline;#e=new Map;#t;constructor(e,t,n){this.driver=e,this.resolveMedia=t,this.timeline=n,this.#t=yi(this.resolveMedia,(o,i)=>{let s=Pd(X(o.start+i)),a=this.#e.get(o.id);if(!a){let c=this.resolveMedia(o.mediaHash),l=Pd(X(o.start+o.duration));a=this.createCursor(c,s,l),this.#e.set(o.id,a)}return a.next(s)})}sample(e){return this.#t.sample(this.timeline,e)}async cancel(){await Promise.all([...this.#e.values()].map(e=>e.cancel())),this.#e.clear()}},Xt=class extends bi{#e=-1/0;next(e){if(e<this.#e)throw new Error(`Forward-only cursor regression: ${e}ms < ${this.#e}ms`);return this.#e=e,this.sample(e)}createCursor(e,t,n){let o=this.driver.decodeVideo({source:e,start:t/1e6,end:n/1e6}),i=o.readable.getReader(),s=null,a=null,c=!1,l=async()=>{if(c)return null;let{done:f,value:u}=await i.read();if(f)return c=!0,null;let m=new VideoFrame(u);return u.close(),m};return{async next(f){if(s??=await l(),!!s)for(;;){a??=l();let u=await a;if(!u)return new VideoFrame(s);let m=s.timestamp??-1/0,d=u.timestamp??m;if(d<f){s.close(),s=u,a=null;continue}if(Math.abs(d-f)<Math.abs(m-f)){s.close(),s=u,a=null;continue}return new VideoFrame(s)}},async cancel(){let f=a;a=null,c=!0,(await f?.catch(()=>null))?.close(),s?.close(),s=null,o.cancel()}}}},Pn=class extends bi{#e=1/0;next(e){if(e>this.#e)throw new Error(`Reverse-only cursor regression: ${e}ms > ${this.#e}ms`);return this.#e=e,this.sample(e)}createCursor(e,t,n){let s=[],a=1/0,c=-1/0,l=null,f=null,u=null,m=0,d=Promise.resolve(),p=null,h=!1,x=()=>{for(let T of s)T.close();s=[]},y=()=>{m++===0&&(d=new Promise(T=>p=T))},v=()=>{--m===0&&(p?.(),p=null)},S=async()=>{if(f)return f;l=new fe({source:await ye(e),formats:ge});let T=await l.getPrimaryVideoTrack();return f=T&&await T.canDecode()?new ut(T):null,f},C=async T=>{y();let E=Math.min(n,T+1),I=Math.max(t,E-1e6),M=[],L=await S();if(L)for await(let V of L.samples(I/1e6,E/1e6))M.push(V.toVideoFrame()),V.close();return v(),{frames:M,windowStart:I,windowEnd:E}},_=async T=>{x();let E=await C(T);s=E.frames,a=E.windowStart,c=E.windowEnd};return{async next(T){if(h)return;if(T<a||T>c)if(u){let M=await u;if(u=null,h){for(let L of M.frames)L.close();return}if(T>=M.windowStart&&T<=M.windowEnd)x(),s=M.frames,a=M.windowStart,c=M.windowEnd;else{for(let L of M.frames)L.close();await _(T)}}else await _(T);!u&&T<a+5e5&&a>t&&(u=C(a-1));let E,I=1/0;for(let M of s){let L=Math.abs((M.timestamp??T)-T);L<I&&(E=M,I=L)}return E?new VideoFrame(E):void 0},async cancel(){h=!0;let T=u;u=null;let E=await T?.catch(()=>null);if(E)for(let I of E.frames)I.close();await d,x(),l?.dispose(),l=null,f=null}}}},Pd=r=>Math.round(r*1e3);async function _d(r,e,t){return(await Promise.all(e.map(async({item:o,localTime:i})=>{if(o.kind!==G.Audio)return;let s=await r.getSink(o.mediaHash);if(!s)return;let a=o.start+i,c=wn((t-a)/1e3),l=s.samples(a/1e3),f=await l.next();if(f.done)return;let u=f.value,m=l.next();return{offset:c,gain:o.gain??1,get currentSample(){return u},timelineTime:()=>wn(c+u.timestamp),output:()=>({sample:u,timestamp:c+u.timestamp,gain:o.gain??1}),advance:async()=>{let d=await m;return d.done?!1:(u=d.value,m=l.next(),!0)}}}))).filter(o=>!!o)}var Si=class{resolveMedia;#e=new Map;constructor(e){this.resolveMedia=e}async getSink(e){let t=this.#e.get(e);if(t)return t.sink;let n=new fe({formats:ge,source:await ye(this.resolveMedia(e))}),o=await n.getPrimaryAudioTrack(),s=!!o&&await o.canDecode()&&o?new ln(o):null;return this.#e.set(e,{input:n,sink:s}),s}};function Id(r){let e={index:0,stream:r[0],time:r[0].timelineTime()};for(let[t,n]of r.entries()){let o=n.timelineTime();o<e.time&&(e={time:o,stream:n,index:t})}return e}function Ti(r){let e=new Si(r);return{async*sampleAudio(t,n){let o=yd({timeline:t,from:n}),i=await _d(e,o,n);for(;i.length>0;){let{stream:s,index:a}=Id(i);yield s.output(),await s.advance()||i.splice(a,1)}}}}var wi=class{driver;timeline;resolveMedia;audioSampler;seekVisualSampler;playVisualSampler=null;reversePlayVisualSampler=null;#e=X(0);#t=null;#r=1;#n=md();onTick=this.#n.onTick;audioContext=new AudioContext({sampleRate:48e3});audioGain=this.audioContext.createGain();audioNodes=new Set;#o=null;constructor(e,t,n){this.driver=e,this.timeline=t,this.resolveMedia=n,this.audioGain.connect(this.audioContext.destination),this.audioGain.gain.value=.7**2,this.seekVisualSampler=yi(this.resolveMedia),this.audioSampler=Ti(this.resolveMedia),this.#c()}update(e){this.timeline=e}get isPlaying(){return this.#n.isPlaying()}async#c(){for await(let e of this.#n.ticks()){let t=this.currentTime,n=this.#r>=0?await this.playVisualSampler?.next(t)??[]:await this.reversePlayVisualSampler?.next(t)??[];(await this.driver.composite(n)).close(),(this.#r>=0?t>=this.duration:t<=0)&&this.pause()}}async seek(e){return this.pause(),this.#e=e,await this.seekVisualSampler.sample(this.timeline,e)}async start(){this.#n.isPlaying()||(await this.audioContext.resume(),this.#e=this.currentTime,this.#t=this.audioContext.currentTime,this.#s(),this.playVisualSampler=new Xt(this.driver,this.resolveMedia,this.timeline),this.reversePlayVisualSampler=new Pn(this.driver,this.resolveMedia,this.timeline),this.#n.play(),this.#a())}pause(){this.#e=this.currentTime,this.#n.pause(),this.#s(),this.playVisualSampler&&(this.playVisualSampler.cancel(),this.playVisualSampler=null),this.reversePlayVisualSampler&&(this.reversePlayVisualSampler.cancel(),this.reversePlayVisualSampler=null)}get duration(){return Wt(this.timeline.rootId,this.timeline)}get currentTime(){if(!this.#n.isPlaying()||this.#t===null)return this.#e;let e=(this.audioContext.currentTime-this.#t)*1e3,t=this.#e+e*this.#r;return X(Math.max(0,Math.min(this.duration,t)))}get playbackRate(){return this.#r}set playbackRate(e){if(!Number.isFinite(e)||e===0)throw new Error(`Invalid playback rate "${e}".`);this.#e=this.currentTime,this.#t=this.#n.isPlaying()?this.audioContext.currentTime:null;let t=this.#r<0;this.#r=e,this.#n.isPlaying()&&(t&&e>0?(this.playVisualSampler?.cancel(),this.playVisualSampler=new Xt(this.driver,this.resolveMedia,this.timeline)):!t&&e<0&&(this.reversePlayVisualSampler?.cancel(),this.reversePlayVisualSampler=new Pn(this.driver,this.resolveMedia,this.timeline)),this.#i())}setFps(e){this.#n.setFPS(e)}#i(){this.#s(),this.#a()}#s(){this.#o?.abort(),this.#o=null;for(let e of this.audioNodes)e.stop();this.audioNodes.clear()}async#a(){if(this.#r!==1)return;let e=wn(this.#e/1e3);this.#o=new AbortController;let t=this.#o.signal,n=this.audioContext;if(this.#t!==null)for await(let{sample:o,timestamp:i}of this.audioSampler.sampleAudio(this.timeline,X(e*1e3))){if(t.aborted||!this.#n.isPlaying())return;for(;i-(n.currentTime-this.#t+e)>.75;)await new Promise(c=>setTimeout(c,25));let s=n.createBufferSource();s.buffer=o.toAudioBuffer(),s.connect(this.audioGain),s.onended=()=>this.audioNodes.delete(s),this.audioNodes.add(s);let a=this.#t+i-e;a>=n.currentTime?s.start(a):s.start(n.currentTime,n.currentTime-a)}}};var Ci=class{driver;canvas;playback;#e=null;#t=null;constructor(e,t,n){this.driver=e,this.playback=new wi(e,n,t),this.canvas=e.compositor.pixi.renderer.canvas}async play(){await this.playback.start()}pause(){this.playback.pause()}seek(e){return this.#e=e,this.#t??=this.#r().finally(()=>this.#t=null)}setFPS(e){this.playback.setFps(Rr(e))}get isSeeking(){return this.#t!==null}get isPlaying(){return this.playback.isPlaying}get duration(){return this.playback.duration}get currentTime(){return this.playback.currentTime}get playbackRate(){return this.playback.playbackRate}set playbackRate(e){this.playback.playbackRate=e}async update(e){this.playback.update(e),this.isPlaying||await this.seek(this.currentTime)}async#r(){for(;this.#e!==null;){let e=this.#e;this.#e=null;let t=await this.playback.seek(X(e));(await this.driver.composite(t)).close()}}};var Kt=class{state;constructor(e){this.state=e}require(e){return e===void 0?void 0:this.state.timeline.items.find(n=>n.id===e)}get timeline(){return this.state.timeline}getId(){return ze.toInteger(ze.random())}#e(e){this.state.timeline=e(this.state.timeline)}register(e){this.#e(t=>({...t,items:[...t.items,e]}))}textStyle=e=>{let t={id:this.getId(),kind:G.TextStyle,style:e};return this.register(t),t};spatial=(e,t)=>{let n={id:this.getId(),kind:G.Spatial,transform:e??this.transform(),crop:t,enabled:!0};return this.register(n),n};#t=e=>{let t={id:this.getId(),kind:G.Animation,anims:e,enabled:!0};return this.register(t),t};#r=(e,t)=>{let n={...e,animationIds:[...e.animationIds??[],t.id]};return this.set(e.id,n),n};anim={scalar:(e,t)=>({terp:e,track:t}),vec2:(e,t)=>{let n={x:[],y:[]};for(let[o,[i,s]]of t)n.x.push([o,i]),n.y.push([o,s]);return{terp:e,track:n}},transform:(e,t)=>{let n={position:{x:[],y:[]},scale:{x:[],y:[]},rotation:[]};for(let[o,[i,s,a]]of t)n.position.x.push([o,i[0]]),n.position.y.push([o,i[1]]),n.scale.x.push([o,s[0]]),n.scale.y.push([o,s[1]]),n.rotation.push([o,a]);return{terp:e,track:n}}};#n=id((e,t)=>({terp:e,track:t}),(e,t)=>this.anim.transform(e,t),e=>this.transform(e));#o=e=>{let t=o=>{let i={id:this.getId(),kind:G.Filter,type:e,params:o,enabled:!0};return this.register(i),i},n=((o,i)=>{let s=t(i),a={...o,filterIds:[...o.filterIds??[],s.id]};return this.set(o.id,a),a});return n.make=t,n};#c=()=>{let e=Object.entries(ui).map(([t,n])=>[t,this.#o(n.type)]);return Object.fromEntries(e)};filter=this.#c();#i=(e,t,n)=>e==="transform"?this.anim.transform(t,n):this.anim.scalar(t,n);#s=e=>{let t=(o,i)=>this.#t({[e]:this.#i(e,o,i)}),n=((o,i,s)=>{let a=t(i,s);return this.#r(o,a)});return n.make=t,n};#a=e=>{let t=o=>{let i=xt[e],s=this.#n[e](o);return this.#t(i.type==="motion"?{transform:s}:{opacity:s})},n=((o,i)=>{let s=t(i);return this.#r(o,s)});return n.make=t,n};#l=()=>{let e=Object.keys(Tn).map(t=>[t,this.#s(t)]);return Object.fromEntries(e)};#u=()=>{let e=Object.keys(xt).map(t=>[t,this.#a(t)]);return Object.fromEntries(e)};animate={...this.#l(),presets:this.#u()};sequence=(...e)=>{let t={id:this.getId(),kind:G.Sequence,childrenIds:e.map(n=>n.id)};return this.register(t),t};stack=(...e)=>{let t={kind:G.Stack,id:this.getId(),childrenIds:e.map(n=>n.id)};return this.register(t),t};video=(e,t)=>{if(!e.hasVideo)throw new Error(`Video clip error: media "${e.datafile.filename}" has no video track.`);let n={kind:G.Video,id:this.getId(),mediaHash:e.datafile.checksum.hash,start:t?.start??0,duration:t?.duration??e.duration};return this.register(n),n};image=(e,t)=>{if(!e.isImage)throw new Error(`Image error: media "${e.datafile.filename}" is not an image.`);let n={kind:G.Image,id:this.getId(),mediaHash:e.datafile.checksum.hash,duration:t?.duration??2e3};return this.register(n),n};audio=(e,t)=>{if(!e.hasAudio)throw new Error(`Audio clip error: media "${e.datafile.filename}" has no audio track.`);let n={kind:G.Audio,id:this.getId(),mediaHash:e.datafile.checksum.hash,start:t?.start??0,duration:t?.duration??e.duration,gain:t?.gain??1};return this.register(n),n};text=(e,t)=>{let n={id:this.getId(),content:e,kind:G.Text,duration:t?.duration??2e3};return t?.styles&&(n.styleId=this.textStyle(t.styles).id),this.register(n),n};#f=(e,t,n)=>{let o=n?.start??0,i=n?.duration??Math.max(0,sd(e,n)-o),s={id:this.getId(),kind:G.Caption,transcript:e,itemId:n?.itemId,start:o,duration:i,maxChars:n?.maxChars,maxDuration:n?.maxDuration,maxSilence:n?.maxSilence};return s.styleId=this.textStyle(n?.styles??t.styles).id,s.spatialId=this.spatial(this.transform(t.transform)).id,this.register(s),s};#m=e=>{let t=(o,i)=>this.#f(o,e,i),n=((o,i,s)=>{let a=t(i,{...s,itemId:o.id,start:s?.start??o.start,duration:s?.duration??o.duration});return this.stack(a,o)});return n.make=t,n};#d=()=>{let e=Object.entries(hi).map(([t,n])=>[t,this.#m(n)]);return Object.fromEntries(e)};captions=Object.assign(this.#m(hi.default),{presets:this.#d()});gap=e=>{let t={id:this.getId(),kind:G.Gap,duration:e};return this.register(t),t};transition={crossfade:e=>{let t={id:this.getId(),kind:G.Transition,effect:fi.Crossfade,duration:e};return this.register(t),t}};transform=e=>{let t=[e?.position?.[0]??0,e?.position?.[1]??0],n=[e?.scale?.[0]??1,e?.scale?.[1]??1],o=e?.rotation??0;return[t,n,o]};addChildren(e,...t){this.#e(n=>(n.items.find(({id:i})=>i===e.id).childrenIds.push(...t.map(i=>i.id)),n))}set=(e,t)=>{this.#e(n=>({...n,items:n.items.map(o=>o.id===e?{...o,...t}:o)}))}};function g0(r){let e=((t,n)=>o=>r(o)(t(o),n));return e.make=t=>n=>r(n).make(t),e}function x0(){let e=Object.keys(ui).map(t=>[t,g0(n=>n.filter[t])]);return Object.fromEntries(e)}var KF=x0();function v0(r){let e=((t,n,o)=>i=>r(i)(t(i),n,o));return e.make=(t,n)=>o=>r(o).make(t,n),e}function y0(){let r=Object.keys(Tn).map(e=>[e,v0(t=>t.animate[e])]);return Object.fromEntries(r)}function b0(r){let e=((t,n)=>o=>o.animate.presets[r](t(o),n));return e.make=t=>n=>n.animate.presets[r].make(t),e}function S0(){let r=Object.keys(xt).map(e=>[e,b0(e)]);return Object.fromEntries(r)}var YF={...y0(),presets:S0()};var ki=class{#e;#t;constructor(e={}){this.#e=e.chunkFrames??1024,this.#t=e.clamp??!0}async*mix(e){let t=this.#e,n=null,o=null,i=[],s=0,a=0;for await(let c of e){if(o===null)o=c.planes.length,n=c.sampleRate;else{if(c.planes.length!==o)throw new Error("Channel count changed");if(c.sampleRate!==n)throw new Error("Sample rate changed")}let l=Math.round(c.timestamp*n),f=c.planes[0]?.length??0;for(;s+t<=l;)yield this.#r(i,s,o,n),s+=t;i.push({startFrame:l,endFrame:l+f,data:c.planes}),a=Math.max(a,l+f)}if(o!==null&&n!==null)for(;s<a;)yield this.#r(i,s,o,n),s+=t}#r(e,t,n,o){let i=this.#e,s=new Float32Array(n*i),a=t+i;for(let c=0;c<n;c++){let l=c*i,f=s.subarray(l,l+i);for(let u of e){let m=u.data[c];if(!m)continue;let d=Math.max(t,u.startFrame),p=Math.min(a,u.endFrame);if(d>=p)continue;let h=d-t,x=d-u.startFrame,y=p-d;for(let v=0;v<y;v++)f[h+v]+=m[x+v]}if(this.#t)for(let u=0;u<i;u++){let m=f[u];f[u]=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:n,frames:i,startFrame:t}}};var T0=(r,e,t)=>{if(e===t)return r;let n=t/e,o=Math.max(1,Math.round(r.length*n)),i=new Float32Array(o);for(let s=0;s<o;s++){let a=s/n,c=Math.floor(a),l=Math.min(c+1,r.length-1),f=a-c;i[s]=r[c]*(1-f)+r[l]*f}return i},Ad=(r,e)=>{let t=r.numberOfChannels,n=new Array(t),o=0;for(let i=0;i<t;i++){let s=new Float32Array(r.numberOfFrames);r.copyTo(s,{planeIndex:i,format:"f32-planar"});let a=T0(s,r.sampleRate,e);n[i]=a,o=a.length}return{data:n,frames:o}};var Fd=(r,e)=>{if(e!==1)for(let t of r)for(let n=0;n<t.length;n++)t[n]*=e};function Ed({timeline:r,resolveMedia:e}){let t=new ki,n=w0(r,e),o=new TransformStream,i=o.writable.getWriter();async function s(){for await(let a of t.mix(n)){let c=new AudioData({format:"f32-planar",sampleRate:a.sampleRate,numberOfFrames:a.frames,numberOfChannels:a.channels,timestamp:Math.round(a.startFrame/a.sampleRate*1e6),data:new Float32Array(a.planar)});await i.write(c)}await i.close()}return s(),o.readable}async function*w0(r,e){let t=Ti(e);for await(let{sample:n,timestamp:o,gain:i}of t.sampleAudio(r,X(0))){let{data:s}=Ad(n,48e3);Fd(s,i),yield{planes:s,sampleRate:48e3,timestamp:o},n.close()}}function zd({timeline:r,fps:e,driver:t,resolveMedia:n}){let o=new TransformStream,i=o.writable.getWriter(),s=new Xt(t,n,r),a=1/e,c=Wt(r.rootId,r);async function l(){await dd({fps:e,duration:c},async(f,u)=>{let m=await s.next(f),d=await t.composite(m),p=new VideoFrame(d,{timestamp:Math.round(u*a*1e6),duration:Math.round(a*1e6)});await i.write(p),d.close()}),await i.close()}return l(),o.readable}function Dd(r){let e=Ed({...r}),t=zd({...r});return r.driver.encode({video:t,audio:e,config:{audio:{codec:"opus",bitrate:128e3},video:{codec:"vp9",bitrate:1e6}}})}var Pi=class{driver;resources=new di;constructor(e){this.driver=e}load=async e=>Object.fromEntries(await Promise.all(Object.entries(e).map(async([t,n])=>[t,await this.resources.store(await n)])));timeline=e=>{let t=new Kt({timeline:{format:"timeline",info:"https://omniclip.app/",version:0,items:[],rootId:0}}),n=e(t);return t.timeline.rootId=n.id,t.timeline};playback=async e=>new Ci(this.driver,t=>this.resources.require(t).url,e);render=async(e,t=30)=>Dd({timeline:e,fps:Rr(t),driver:this.driver,resolveMedia:n=>this.resources.require(n).url})};var _i=class{data;bytes;hash;nickname;constructor(e,t,n,o){this.data=e,this.bytes=t,this.hash=n,this.nickname=o}static async make(e){let t=new Uint8Array(e),n=new Uint8Array(await crypto.subtle.digest("SHA-256",t)),o=Fn.fromBytes(n),i=Pa.sigil.fromBytes(n);return new this(e,n,o,i)}};var Ii=class{url;bytes;blob;filename;checksum;constructor(e,t,n,o,i){this.url=e,this.bytes=t,this.blob=n,this.filename=o,this.checksum=i}static async make(e,t){let n=await e.arrayBuffer(),o=new Uint8Array(n),i=await _i.make(o),s=t??i.nickname,a=URL.createObjectURL(e);return new this(a,o,e,s,i)}static async load(e){}};async function Rd(r,e,t){let n=t.querySelector(".play"),o=t.querySelector(".stop"),i=t.querySelector(".scrub"),s=t.querySelector(".playhead"),a=t.querySelector(".timecode"),c=t.querySelector(".player-canvas"),l=new Kt({timeline:r}),f=await e.playback(r);c.replaceChildren(f.canvas),n.disabled=!1,o.disabled=!1,n.addEventListener("click",()=>f.play()),o.addEventListener("click",()=>f.pause()),i.max=String(Math.ceil(f.duration));let u=!1;f.playback.onTick.on(()=>d(f.currentTime,f.duration));let m=(p,h)=>{a.textContent=`${Od(p)} / ${Od(h)}`};i.addEventListener("input",async()=>{u=!0;let p=Math.max(0,Math.min(+i.value,f.duration));m(p,f.duration),await f.seek(p)}),i.addEventListener("change",async()=>{u=!1;let p=Math.max(0,Math.min(+i.value,f.duration));await f.seek(p)});let d=(p,h)=>{let x=Math.max(0,Math.min(p,h));u||(i.value=String(Math.round(x)));let y=h?x/h*100:0;s.style.left=`${y}%`,m(x,h)};await f.update(l.timeline)}function Od(r){let e=Math.max(0,r),t=Math.floor(e/1e3),n=Math.floor(t/60),o=t%60,i=Math.floor(e%1e3);return`${n}:${String(o).padStart(2,"0")}.${String(i).padStart(3,"0")}`}async function Bd(r,e,t){let n=t.querySelector(".waveform-canvas"),o=t.querySelector(".width");n.replaceChildren(),n.style.position="relative",n.style.height="96px",n.style.overflow="hidden";let i=await gi.init(r,e,{tileHeight:96,onChange:()=>s()}),s=()=>{let a=+o.value,c=Md(a,i.duration);i.zoom=c,n.style.width=`${a}px`,n.replaceChildren(...[...i.getTiles().values()].map(l=>(l.canvas.style.position="absolute",l.canvas.style.top="0",l.canvas.style.left=`${l.startTime*Md(a,i.duration)}px`,l.canvas.style.height="100%",l.canvas)))};o.oninput=s,i.range=[0,i.duration]}function Md(r,e){return e>0?r/e:0}async function va(r,e){let t=await ld({driver:r,spec:ad(),workerUrl:new URL("/features/speech/transcribe/worker.bundle.min.js",import.meta.url),onLoading:a=>console.log("transcriber loading",a)}),n=new Pi(r),{videoA:o}=await n.load({videoA:Ii.make(e)}),i=await t.transcribe({source:e,language:"english",onReport:a=>console.log("transcriber report",a),onTranscription:a=>console.log("transcribing",a)});return{timeline:n.timeline(a=>{let c=a.text("content",{duration:3e3}),l=a.animate.opacity.make("easeIn",[[0,0],[700,1],[2200,1],[3e3,.35]]),f=a.textStyle({fill:"green",fontSize:100}),u=a.spatial(a.transform({position:[240,160],scale:[1.4,1.4],rotation:.08}),[.15,.1,.05,.2]),m=a.spatial(),d=a.animate.transform.make("linear",[[0,a.transform({position:[-320,80],scale:[.7,.7]})],[1e3,a.transform({position:[120,80],scale:[1,1]})],[2e3,a.transform({position:[200,40],scale:[1.35,1.35],rotation:8})],[3e3,a.transform({position:[320,0],scale:[1.15,1.15],rotation:0})]]),p=a.video(o,{duration:6e3,start:3e3});return a.set(c.id,{styleId:f.id,spatialId:m.id,animationIds:[l.id,d.id]}),a.set(p.id,{spatialId:u.id}),a.sequence(a.stack(c,a.captions(p,i,{maxChars:34,maxDuration:2800,maxSilence:450,styles:{fontFamily:"Arial",fontSize:64,fill:"#ffffff",align:"center",wordWrap:!0,wordWrapWidth:1280,stroke:{color:"#000000",width:6}}}),a.audio(o,{start:3e3})),a.gap(500),a.video(o,{duration:7e3,start:5e3}))}),omni:n}}async function Ud(r,e){let t=e.querySelector(".range"),n=e.querySelector(".range-view"),o=e.querySelector(".range-size"),i=e.querySelector(".frequency"),s=e.querySelector(".frequency-view"),a=e.querySelector(".filmstrip"),c=1/10,l=.5;a.replaceChildren();let f=await pi.init(r,{onChange(u){let m=u.sort((d,p)=>d.time-p.time);a.replaceChildren(...m.map(({time:d,canvas:p})=>C0(d,p.canvas)))},frequency:c,canvasSinkOptions:{width:80,height:50,fit:"fill"}});o.oninput=()=>{l=+o.value;let u=+t.value,m=u+l;f.range=[u,m],n.textContent=`visible time range: [${u}, ${m}]`},t.oninput=()=>{let u=+t.value,m=u+l;f.range=[u,m],n.textContent=`visible time range: [${u}, ${m}]`},i.oninput=()=>{f.frequency=1/+i.value,s.textContent=`frame every ${f.frequency.toFixed(3)} second (${i.value} frames per second)`},f.range=[10,10.5]}function C0(r,e){let t=document.createElement("div");t.style.position="relative",t.style.display="inline-block",t.style.marginRight="4px",t.appendChild(e);let n=document.createElement("div");return n.textContent=`${r.toFixed(2)}s`,n.style.position="absolute",n.style.top="2px",n.style.right="4px",n.style.fontSize="10px",n.style.color="white",n.style.background="rgba(0,0,0,0.6)",n.style.padding="2px 4px",n.style.borderRadius="4px",n.style.pointerEvents="none",t.appendChild(n),t}function Nd(r,e){let t={width:1920,height:1080},n=document.createElement("canvas");n.width=t.width,n.height=t.height;let o=n.getContext("2d");async function i(){let s=r.decodeVideo({source:e,async onFrame(m){let d=await r.composite([{id:0,kind:"image",frame:m},{id:1,kind:"text",content:"omnitool",style:{fontSize:50,fill:"green"}}]);return m.close(),o?.drawImage(d,0,0),d}}),a=r.decodeAudio({source:e}),{readable:c,done:l}=r.encode({video:s.readable,audio:a.readable,config:{audio:{codec:"opus",bitrate:128e3},video:{codec:"vp9",bitrate:1e6}}}),u=await(await window.showSaveFilePicker()).createWritable();await Promise.all([c.pipeTo(u),l])}return{canvas:n,run:i}}var Nr=await ci.setup({workerUrl:new URL("../driver/driver.worker.bundle.min.js",import.meta.url)}),k0=document.querySelector("[data-demo='transcode']"),P0=document.querySelector("[data-demo='filmstrip']"),_0=document.querySelector("[data-demo='waveform']"),Ld=document.querySelector("[data-demo='playback']"),Yt=document.querySelector("[data-demo='export']"),Vd=Yt.querySelector("[data-action='export']"),Ai=null;await Nr.thread.work.hello(),Nr.machina.count===1?console.log("\u2705 driver works"):console.error("\u274C FAIL driver call didn't work");var Lr=(r,e)=>{let t=r.querySelector(".progress"),n=r.querySelector(".status");!t||!n||(e==="running"?(t.removeAttribute("value"),n.textContent="running"):e==="done"?(t.value=1,n.textContent="done"):(t.value=0,n.textContent="idle"))},ya=(r,e)=>{let t=r.querySelector("input[type='file']"),n=r.querySelector("[data-action='run']");n.disabled=!0,t.addEventListener("input",()=>{n.disabled=!t.files?.length}),n.addEventListener("click",async()=>{let o=t.files?.[0];if(o){n.disabled=!0,Lr(r,"running");try{await e(o,r),Lr(r,"done")}finally{n.disabled=!1}}})};ya(k0,async(r,e)=>{let t=e.querySelector(".demo-preview"),n=Nd(Nr,r);t.replaceChildren(n.canvas),await n.run()});ya(P0,async(r,e)=>{await Ud(r,e)});ya(_0,async(r,e)=>{await Bd(Nr,r,e)});{let r=Ld.querySelector("input[type='file']");r.addEventListener("input",async()=>{let e=r.files?.[0];if(!e)return;let{timeline:t,omni:n}=await va(Nr,e);await Rd(t,n,Ld)})}{let r=Yt.querySelector("input[type='file']");r.addEventListener("input",async()=>{let e=r.files?.[0];if(!e)return;Lr(Yt,"running");let{timeline:t,omni:n}=await va(Nr,e);Ai={timeline:t,omni:n},Vd.disabled=!1;let o=Yt.querySelector(".demo-preview"),i=await n.playback(t);await i.seek(0),o.replaceChildren(i.canvas),Lr(Yt,"done")})}Vd.addEventListener("click",async()=>{Ai&&(Lr(Yt,"running"),await Ai.omni.render(Ai.timeline),Lr(Yt,"done"))});
7325
+ `;function rd({name:r,renderer:e}){let t=td.default.find(c=>c.name===r),n=new Zt,o=new ne,i=new Jt({}),s=new Jt({}),a=new k({glProgram:new P({vertex:Jm,fragment:ed(t.glsl)}),resources:{from:i,to:s,uniforms:{...da.basics,...da.custom(t)}}});return n.filters=[a],{render({width:c,height:l,from:f,to:u,progress:m}){return(n.width!==c||n.height!==l)&&(n.setSize({width:c,height:l}),o.source.resize(c,l)),i.resource=f,s.resource=u,i.update(),s.update(),a.resources.uniforms.uniforms.progress=m,e.render({container:n,target:o,clear:!1,width:c,height:l}),o}}}var ai=class{pixi;onPointerDown=ke();onPointerMove=ke();onPointerUp=ke();onDispose=ke();static async setup(){let e=await Gs({width:1920,height:1080,preference:"webgl",background:"black",preferWebGLVersion:2}),t=new Oi;return t.interactive=!0,new this({renderer:e,stage:t})}constructor(e){this.pixi=e}#e=new Map;#t=new Map;#r=new WeakMap;async composite(e){let{stage:t,renderer:n}=this.pixi;this.#d(this.#m(e));let{dispose:o}=await this.#n(e,t);n.render(t);let i=new VideoFrame(n.canvas,{timestamp:0,duration:0});return o(),i}getActiveObject(e){return this.#t.get(e)?.sprite}async#n(e,t){if(Array.isArray(e)){let n=[];for(let o of[...e].reverse()){let i=await this.#n(o,t);n.push(i.dispose)}return{dispose:()=>n.forEach(o=>o())}}switch(e.kind){case"text":return this.#o(e,t);case"image":return this.#c(e,t);case"transition":return this.#i(e,t);case"gap":return this.pixi?.renderer.clear(),{dispose:()=>{}};default:return console.warn("Unknown layer kind",e.kind),{dispose:()=>{}}}}#o(e,t){let n=this.#f(e);return n.text=e.content,e.style&&(n.style=e.style),this.#s(n,e.matrix),this.#a(n,e.alpha),this.#l(n,e.crop),this.#u(n,e.filters),t.addChild(n),{dispose:()=>{}}}#c(e,t){let n=this.#f(e);n.texture&&n.texture!==ne.EMPTY&&n.texture.destroy(!0);let o=ne.from(e.frame);return n.texture=o,this.#s(n,e.matrix),this.#a(n,e.alpha),this.#l(n,e.crop),this.#u(n,e.filters),t.addChild(n),{dispose:()=>{e.frame.close()}}}#i({from:e,to:t,progress:n,name:o},i){let a=(this.#e.get(o)??(this.#e.set(o,rd({name:"circle",renderer:this.pixi.renderer})),this.#e.get(o))).render({from:e,to:t,progress:n,width:e.displayWidth,height:e.displayHeight}),c=new Zt(a);return i.addChild(c),{dispose:()=>c.destroy(!1)}}#s(e,t){if(!t)return;let n=Ym(t);e.setFromMatrix(n)}#a(e,t){e.alpha=t??1}#l(e,t){let n=this.#r.get(e);if(n&&(e.mask===n&&(e.mask=null),n.removeFromParent(),n.clear()),!t||t.every(h=>h===0))return;let[o,i,s,a]=t,c=e.mask;e.mask=null;let l=e.getLocalBounds();e.mask=c;let f=l.x+l.width*a,u=l.y+l.height*o,m=l.width*Math.max(0,1-a-i),d=l.height*Math.max(0,1-o-s),p=n??new Mi;p.clear(),p.beginFill(16777215),p.drawRect(f,u,m,d),p.endFill(),e.addChild(p),e.mask=p,this.#r.set(e,p)}#u(e,t){if(!t?.length){e.filters=null;return}e.filters=t.map(n=>{switch(n.type){case"ColorMatrixFilter":{let{matrix:o,...i}=n.params??{},s=new Vt(i);return o&&(s.matrix=o),s}case"EmbossFilter":return new zr(n.params?.strength);case"PixelateFilter":return new Or(n.params?.size);default:{let o=Km(n.type);return o?new o(n.params):void 0}}}).filter(n=>!!n)}#f(e){let t=this.#t.get(e.id);if(t)return t.sprite;switch(e.kind){case"text":{let n=new Sn({text:e.content,style:e.style});n.eventMode="static";let o=a=>this.onPointerDown.publish({event:a,id:e.id,object:n}),i=a=>this.onPointerUp.publish({event:a,id:e.id,object:n}),s=a=>this.onPointerUp.publish({event:a,id:e.id,object:n});return n.on("pointerdown",o),n.on("pointerup",i),n.on("pointermove",s),this.#t.set(e.id,{sprite:n,dispose:()=>{this.onDispose.publish({id:e.id,object:n}),n.off("pointermove",s),n.off("pointerdown",o),n.off("pointerup",i)}}).get(e.id)?.sprite}case"image":{let n=new Zt;n.eventMode="static";let o=a=>this.onPointerDown.publish({event:a,id:e.id,object:n}),i=a=>this.onPointerUp.publish({event:a,id:e.id,object:n}),s=a=>this.onPointerUp.publish({event:a,id:e.id,object:n});return n.on("pointerdown",o),n.on("pointermove",s),n.on("pointerup",i),this.#t.set(e.id,{sprite:n,dispose:()=>{this.onDispose.publish({id:e.id,object:n}),n.off("pointerdown",o),n.off("pointermove",s),n.off("pointerup",i)}}).get(e.id)?.sprite}}}#m(e){let t=new Set,n=o=>{if(Array.isArray(o))for(let i of o)n(i);else t.add(o.id)};return n(e),t}#d(e){for(let t of this.#t.keys())if(!e.has(t)){let{sprite:n,dispose:o}=this.#t.get(t);o(),n.destroy(!0),this.#t.delete(t)}}};var nd=r=>wt.host(e=>({async world(){r.count++}}));async function ye(r){return r instanceof Blob?new vn(r):new yn(r)}var ci=class{machina;thread;compositor;static async setup(e){let t=new Go,n=await wt.thread({label:"OmnitoolDriver",workerUrl:e?.workerUrl??"/node_modules/@omnimedia/omnitool/x/driver/driver.worker.bundle.min.js",setupHost:nd(t)}),o=await ai.setup();return new this(t,n,o)}constructor(e,t,n){this.machina=e,this.thread=t,this.compositor=n}async hello(){return this.thread.work.hello()}async getAudioDuration(e){let n=await new fe({source:await ye(e),formats:ge}).getPrimaryAudioTrack();if(!n)throw new Error("primary audio track not found");return await n.computeDuration()}async getVideoDuration(e){return await(await new fe({source:await ye(e),formats:ge}).getPrimaryVideoTrack())?.computeDuration()}decodeVideo(e){let t=null,{port1:n,port2:o}=new MessageChannel,i=new TransformStream({async transform(s,a){let c=await e.onFrame?.(s)??s;t?.close(),a.enqueue(c),t=c}});return this.thread.work.decodeVideo[yt]({transfer:[i.writable,o]})({source:e.source,cancel:o,video:i.writable,start:e.start,end:e.end}),{readable:i.readable,cancel(){n.postMessage("close"),n.close()}}}decodeAudio(e){let t=new TransformStream,{port1:n,port2:o}=new MessageChannel;return this.thread.work.decodeAudio[yt]({transfer:[t.writable,o]})({source:e.source,cancel:o,audio:t.writable,start:e.start,end:e.end}),{readable:t.readable,cancel(){n.postMessage("close"),n.close()}}}encode({audio:e,video:t,config:n}){let{readable:o,writable:i}=new TransformStream,s=[e,t,i].filter(En.happy),a=this.thread.work.encode[yt]({transfer:s})({audio:e,video:t,config:n,writable:i});return{readable:o,done:a}}async composite(e){return await this.compositor.composite(e)}};var b=(r,e,t,n)=>({type:"number",min:r,max:e,default:t,...n===void 0?{}:{step:n}}),tt=r=>({type:"color",default:r}),Ve=r=>({type:"boolean",default:r}),li=(r,e)=>({type:"choice",options:r,default:e}),ee=r=>({type:"object",properties:r}),s0=r=>({type:"array",items:r}),od=[3,5,7,9,11,13,15,17,19,21,23,25],a0={TRANSPARENT:0,ORIGINAL:1,LOOP:2,CLAMP:3,MIRROR:4},H=()=>(r,e={})=>({type:r,schema:e}),ui={adjustment:H()("AdjustmentFilter",{gamma:b(0,5,1),saturation:b(0,5,1),contrast:b(0,5,1),brightness:b(0,5,1),red:b(0,5,1),green:b(0,5,1),blue:b(0,5,1),alpha:b(0,1,1,.01)}),advancedBloom:H()("AdvancedBloomFilter",{threshold:b(.1,.9,.5,.01),bloomScale:b(.5,1.5,1,.01),brightness:b(.5,1.5,1,.01),blur:b(0,20,8,.1),quality:b(1,20,4,1)}),alpha:H()("AlphaFilter",{alpha:b(0,1,1,.01)}),ascii:H()("AsciiFilter",{size:b(2,20,8,1),color:tt("#ffffff"),replaceColor:Ve(!1)}),backdropBlur:H()("BackdropBlurFilter",{strength:b(0,100,8,.1),quality:b(1,10,4,1)}),bevel:H()("BevelFilter",{rotation:b(0,360,45,1),thickness:b(0,10,2,.1),lightColor:tt("#ffffff"),lightAlpha:b(0,1,.7,.01),shadowColor:tt("#000000"),shadowAlpha:b(0,1,.7,.01)}),bloom:H()("BloomFilter",{strength:ee({x:b(0,20,2,.1),y:b(0,20,2,.1)}),quality:b(1,20,4,1),resolution:b(.25,4,1,.01),kernelSize:li([5,7,9,11,13,15],5)}),blur:H()("BlurFilter",{strength:b(0,100,8,.1),quality:b(1,10,4,1)}),bulgePinch:H()("BulgePinchFilter",{radius:b(0,1e3,100,1),strength:b(-1,1,1,.01),center:ee({x:b(0,1,.5,.01),y:b(0,1,.5,.01)})}),colorGradient:H()("ColorGradientFilter"),colorMatrix:H()("ColorMatrixFilter"),colorOverlay:H()("ColorOverlayFilter",{color:tt("#ff0000"),alpha:b(0,1,.5,.01)}),colorReplace:H()("ColorReplaceFilter",{originalColor:tt("#ff0000"),targetColor:tt("#000000"),tolerance:b(0,1,.4,.01)}),convolution:H()("ConvolutionFilter",{width:b(0,500,300,1),height:b(0,500,300,1),matrix:s0([b(0,1,0),b(0,1,.5,.01),b(0,1,0),b(0,1,.5,.01),b(0,1,1,.01),b(0,1,.5,.01),b(0,1,0),b(0,1,.5,.01),b(0,1,0)])}),crossHatch:H()("CrossHatchFilter"),crt:H()("CRTFilter",{curvature:b(0,10,1,.01),lineWidth:b(0,5,3,.01),lineContrast:b(0,1,.3,.01),verticalLine:Ve(!1),noise:b(0,1,.2,.01),noiseSize:b(1,10,1,.1),vignetting:b(0,1,.3,.01),vignettingAlpha:b(0,1,1,.01),vignettingBlur:b(0,1,.3,.01),seed:b(0,1,0,.01),time:b(.5,20,.5,.01)}),dot:H()("DotFilter",{scale:b(.3,1,1,.01),angle:b(0,5,5,.01),grayscale:Ve(!0)}),dropShadow:H()("DropShadowFilter",{blur:b(0,20,2,.1),quality:b(1,20,3,1),alpha:b(0,1,.5,.01),offset:ee({x:b(-50,50,4,1),y:b(-50,50,4,1)}),color:tt("#000000"),shadowOnly:Ve(!1)}),emboss:H()("EmbossFilter",{strength:b(0,20,5,.1)}),glitch:H()("GlitchFilter",{slices:b(0,64,5,1),seed:b(0,1,.5,.01),offset:b(-400,400,100,1),direction:b(-180,180,0,1),fillMode:li(a0,"LOOP"),average:Ve(!1),minSize:b(0,64,8,1),sampleSize:b(1,2048,512,1),red:ee({x:b(-50,50,2,1),y:b(-50,50,2,1)}),blue:ee({x:b(-50,50,10,1),y:b(-50,50,-4,1)}),green:ee({x:b(-50,50,-10,1),y:b(-50,50,4,1)})}),glow:H()("GlowFilter",{distance:b(0,20,15,.1),innerStrength:b(0,20,0,.1),outerStrength:b(0,20,2,.1),color:tt("#ffffff"),quality:b(0,1,.2,.01),alpha:b(0,1,1,.01),knockout:Ve(!1)}),godray:H()("GodrayFilter",{time:b(0,1,0,.01),gain:b(0,1,.6,.01),lacunarity:b(0,5,2.75,.01),alpha:b(0,1,1,.01),parallel:Ve(!0),angle:b(-60,60,30,1),center:ee({x:b(-100,2012,956,1),y:b(-1e3,-100,-100,1)})}),grayscale:H()("GrayscaleFilter"),hslAdjustment:H()("HslAdjustmentFilter",{hue:b(-180,180,0,1),saturation:b(-1,1,0,.01),lightness:b(-1,1,0,.01),colorize:Ve(!1),alpha:b(0,1,1,.01)}),kawaseBlur:H()("KawaseBlurFilter",{strength:b(0,20,4,.1),quality:b(1,20,3,1),pixelSize:ee({x:b(0,10,1,.1),y:b(0,10,1,.1)})}),motionBlur:H()("MotionBlurFilter",{velocity:ee({x:b(-90,90,40,1),y:b(-90,90,40,1)}),kernelSize:li(od,15),offset:b(-150,150,0,1)}),multiColorReplace:H()("MultiColorReplaceFilter"),noise:H()("NoiseFilter",{noise:b(0,1,.5,.01),seed:b(.01,10,.5,.01)}),oldFilm:H()("OldFilmFilter",{sepia:b(0,1,.3,.01),noise:b(0,1,.3,.01),noiseSize:b(1,10,1,.1),scratch:b(-1,1,.5,.01),scratchDensity:b(0,1,.3,.01),scratchWidth:b(1,20,1,.1),vignetting:b(0,1,.3,.01),vignettingAlpha:b(0,1,1,.01),vignettingBlur:b(0,1,.3,.01)}),outline:H()("OutlineFilter",{thickness:b(0,10,4,.1),color:tt("#000000"),alpha:b(0,1,1,.01),knockout:Ve(!1)}),pixelate:H()("PixelateFilter",{size:ee({x:b(4,40,10,1),y:b(4,40,10,1)})}),radialBlur:H()("RadialBlurFilter",{angle:b(-180,180,20,1),radius:b(-1,1912,300,1),center:ee({x:b(0,1912,956,1),y:b(0,920,460,1)}),kernelSize:li(od,15)}),reflection:H()("ReflectionFilter",{mirror:Ve(!0),boundary:b(0,1,.5,.01),amplitude:ee({start:b(0,50,0,.1),end:b(0,50,20,.1)}),waveLength:ee({start:b(10,200,30,1),end:b(10,200,100,1)}),alpha:ee({start:b(0,1,1,.01),end:b(0,1,1,.01)}),time:b(0,20,0,.01)}),rgbSplit:H()("RGBSplitFilter",{red:ee({x:b(-20,20,-10,1),y:b(-20,20,0,1)}),blue:ee({x:b(-20,20,0,1),y:b(-20,20,0,1)}),green:ee({x:b(-20,20,0,1),y:b(-20,20,10,1)})}),shockwave:H()("ShockwaveFilter",{speed:b(500,2e3,500,1),amplitude:b(1,100,30,1),wavelength:b(2,400,160,1),brightness:b(.2,2,1,.01),radius:b(100,2e3,-1,1),center:ee({x:b(0,1912,956,1),y:b(0,920,460,1)})}),simplexNoise:H()("SimplexNoiseFilter",{strength:b(0,1,.5,.01),noiseScale:b(0,50,10,.1),offsetX:b(0,5,0,.01),offsetY:b(0,5,0,.01),offsetZ:b(0,5,0,.01),step:b(-1,1,-1,.01)}),tiltShift:H()("TiltShiftFilter",{blur:b(0,200,100,.1),gradientBlur:b(0,1e3,600,1),start:ee({x:b(0,1912,0,1),y:b(0,920,460,1)}),end:ee({x:b(0,1912,1912,1),y:b(0,920,460,1)})}),twist:H()("TwistFilter",{angle:b(-10,10,4,.01),radius:b(0,1912,200,1),offset:ee({x:b(0,1912,956,1),y:b(0,920,460,1)})}),zoomBlur:H()("ZoomBlurFilter",{strength:b(.01,.5,.1,.01),center:ee({x:b(0,1912,956,1),y:b(0,920,460,1)}),innerRadius:b(0,956,80,1),radius:b(0,956,-1,1)})};var G;(function(r){r[r.Sequence=0]="Sequence",r[r.Stack=1]="Stack",r[r.Video=2]="Video",r[r.Audio=3]="Audio",r[r.Text=4]="Text",r[r.Gap=5]="Gap",r[r.Spatial=6]="Spatial",r[r.Animation=7]="Animation",r[r.Transition=8]="Transition",r[r.TextStyle=9]="TextStyle",r[r.Filter=10]="Filter",r[r.Caption=11]="Caption",r[r.Image=12]="Image"})(G||(G={}));var fi;(function(r){r[r.Crossfade=0]="Crossfade"})(fi||(fi={}));var mi=class{datafile;duration=0;isImage=!1;hasVideo=!1;hasAudio=!1;constructor(e){this.datafile=e}static async analyze(e){let t=new this(e);if(this.#e(e))return t.isImage=!0,t;let n=await this.duration(e.url)*1e3;t.duration=n;let{video:o,audio:i}=await this.#t(e.url);return t.hasAudio=i,t.hasVideo=o,t}static#e(e){return e.blob.type.startsWith("image/")}static async duration(e){let n=await new fe({formats:ge,source:await ye(e)}).computeDuration();return Number(n.toFixed(5))}static async#t(e){let t=new fe({formats:ge,source:await ye(e)});return{audio:!!await t.getPrimaryAudioTrack(),video:!!await t.getPrimaryVideoTrack()}}};var di=class{#e=new zn;async store(e){let t=await mi.analyze(e),{hash:n}=t.datafile.checksum,{filename:o,bytes:i,url:s,blob:a}=t.datafile;if(this.#e.has(n)){let c=this.#e.require(n);c.filename=o}else this.#e.set(n,{kind:"media",filename:o,bytes:i,url:s,blob:a,duration:t.duration});return t}require(e){return this.#e.require(e)}};var pi=class r{videoTrack;options;#e;#t=new Map;#r=[0,0];constructor(e,t){this.videoTrack=e,this.options=t,this.#e=new cn(e,t.canvasSinkOptions)}static async init(e,t){let o=await new fe({formats:ge,source:await ye(e)}).getPrimaryVideoTrack();if(o)return new r(o,{frequency:t.frequency??1,canvasSinkOptions:t.canvasSinkOptions??{width:80,height:50,fit:"fill"},onChange:t.onChange,onPlaceholders:t.onPlaceholders});throw new Error("Source has no video track")}set frequency(e){e!==this.options.frequency&&(this.options.frequency=e,this.#a())}get frequency(){return this.options.frequency}#n([e,t],n=1){let o=t-e;return[e-o*n,t+o*n]}async#o(){let[e,t]=this.#r,n=new Set,o=await this.videoTrack.computeDuration();for(let i=Math.max(0,e);i<=t;i+=this.options.frequency)i>=0&&i<=o&&n.add(i);this.options.onPlaceholders?.([...n])}async#c(){let[e,t]=this.#r,n=new Set,o=await this.videoTrack.computeDuration();for(let c=Math.max(0,e);c<=t;c+=this.options.frequency)c>=0&&c<=o&&n.add(c);let i=[...n].filter(c=>!this.#t.has(c)),s=0;for await(let c of this.#e.canvasesAtTimestamps(i))if(c){let l=i[s++];this.#t.set(l,c)}for(let c of this.#t.keys())n.has(c)||this.#t.delete(c);let a=[...this.#t.entries()].map(([c,l])=>({time:c,canvas:l}));this.options.onChange(a)}set range(e){let[t,n]=e,o=n-t,[i,s]=this.#r,a=i+o,c=s-o,l=t<a,f=n>c;!l&&!f||(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)}};var xt={slideIn:{type:"motion",label:"Slide in",defaults:{duration:700,from:[-400,0],to:[0,0],terp:"easeOut"},transform:{from:{position:[-400,0]},to:{position:[0,0]}}},slideOut:{type:"motion",label:"Slide out",defaults:{duration:700,from:[0,0],to:[400,0],terp:"easeIn"},transform:{from:{position:[0,0]},to:{position:[400,0]}}},spinIn:{type:"motion",label:"Spin in",defaults:{duration:700,from:[0,0],to:[0,0],terp:"easeOut"},transform:{from:{scale:[0,0],rotation:-180},to:{scale:[1,1],rotation:0}}},spinOut:{type:"motion",label:"Spin out",defaults:{duration:700,from:[0,0],to:[0,0],terp:"easeIn"},transform:{from:{scale:[1,1],rotation:0},to:{scale:[0,0],rotation:180}}},zoomIn:{type:"motion",label:"Zoom in",defaults:{duration:700,from:[0,0],to:[0,0],terp:"easeOut"},transform:{from:{scale:[0,0]},to:{scale:[1,1]}}},zoomOut:{type:"motion",label:"Zoom out",defaults:{duration:700,from:[0,0],to:[0,0],terp:"easeIn"},transform:{from:{scale:[1,1]},to:{scale:[0,0]}}},bounceIn:{type:"motion",label:"Bounce in",defaults:{duration:700,from:[0,0],to:[0,0],terp:"bounce"},transform:{from:{scale:[0,0]},to:{scale:[1,1]}}},bounceOut:{type:"motion",label:"Bounce out",defaults:{duration:700,from:[0,0],to:[0,0],terp:"bounce"},transform:{from:{scale:[1,1]},to:{scale:[0,0]}}},fadeIn:{type:"scalar",label:"Fade in",defaults:{duration:700,from:0,to:1,terp:"easeIn"}},fadeOut:{type:"scalar",label:"Fade out",defaults:{duration:700,from:1,to:0,terp:"easeOut"}}};var Tn={transform:{type:"transform",defaultTerp:"linear",channels:[{path:"position.x",type:"number",default:0,unit:"pixel"},{path:"position.y",type:"number",default:0,unit:"pixel"},{path:"scale.x",type:"number",default:1,unit:"scale"},{path:"scale.y",type:"number",default:1,unit:"scale"},{path:"rotation",type:"number",default:0,unit:"degree"}]},opacity:{type:"scalar",defaultTerp:"linear",channels:[{type:"number",default:1,unit:"ratio",range:[0,1]}]}},c0={...Tn};function id(r,e,t){let n=Object.entries(xt).map(([o,i])=>{let s=i.type==="motion"?a=>{let c=a?.offset??0;return e(a?.terp??i.defaults.terp,[[c,t({...i.transform.from,...a?.from===void 0?{}:{position:a.from}})],[c+(a?.duration??i.defaults.duration),t({...i.transform.to,...a?.to===void 0?{}:{position:a.to}})]])}:a=>{let c=a?.offset??0;return r(a?.terp??i.defaults.terp,[[c,a?.from??i.defaults.from],[c+(a?.duration??i.defaults.duration),a?.to??i.defaults.to]])};return[o,s]});return Object.fromEntries(n)}var hi={default:{styles:{fontFamily:"Arial",fontSize:56,fill:"#ffffff",align:"center",wordWrap:!0,wordWrapWidth:1440},transform:{position:[240,860]}}},l0={maxChars:42,maxDuration:3500,maxSilence:750};function pa(r,e){let{maxChars:t,maxDuration:n,maxSilence:o}={...l0,...e},i=[],s=null;for(let{timestamp:[a,c],text:l}of r.chunks){let[f,u]=[a*1e3,c*1e3],m=l.trim();if(!Number.isFinite(f)||!Number.isFinite(u)||!m)continue;if(!s){s={text:m,timestamp:[f,u]};continue}let[d,p]=s.timestamp,h=`${s.text} ${m}`.trim();h.length>t||u-d>n||f-p>o?(i.push(s),s={text:m,timestamp:[f,u]}):s={text:h,timestamp:[d,u]}}return s&&i.push(s),i}function sd(r,e){let t=pa(r,e);return Math.max(0,...t.map(n=>n.timestamp[1]))}var ad=()=>({model:"onnx-community/whisper-tiny_timestamped",dtype:"auto",device:"webgpu",chunkLength:20,strideLength:3});async function cd(r,e){let t=await e.arrayBuffer(),o=await new AudioContext({sampleRate:16e3}).decodeAudioData(t),i;if(o.numberOfChannels===2){let a=Math.sqrt(2),c=o.getChannelData(0),l=o.getChannelData(1);i=new Float32Array(c.length);for(let f=0;f<o.length;++f)i[f]=a*(c[f]+l[f])/2}else i=o.getChannelData(0);let s=await r.getAudioDuration(e);return{audio:i,duration:s}}async function ld({driver:r,spec:e,workerUrl:t,onLoading:n}){let o=Vi(),i=Vi(),s=await wt.thread({label:"OmnitoolSpeechTranscriber",workerUrl:t,setupHost:()=>({loading:async a=>n(a),deliverReport:async a=>o.pub(a),deliverTranscription:async a=>i.pub(a)})});return await s.work.prepare(e),{transcribe:_a(async a=>{let{source:c,language:l}=a,{audio:f,duration:u}=await cd(r,c),m=Ia(o(a.onReport),i(a.onTranscription)),d=await s.work.transcribe({duration:u,language:l,audio:f.buffer});return m(),d}),dispose:()=>s.terminate()}}function ud(r,e){let t=typeof window<"u"&&window.devicePixelRatio||1,n=document.createElement("canvas");n.width=e.width*t,n.height=e.height*t,n.style.width=`${e.width}px`,n.style.height=`${e.height}px`;let o=n.getContext("2d");if(!o)return n;o.scale(t,t),o.fillStyle=e.color;let i=e.height/2,s=Math.max(1,e.width),a=r.length/s;for(let c=0;c<s;c++){let l=Math.floor(c*a),f=Math.max(l+1,Math.floor((c+1)*a)),u=0;for(let d=l;d<f&&d<r.length;d++)r[d]>u&&(u=r[d]);let m=u*e.height;o.fillRect(c,i-m/2,1,m)}return n}var ha=[2048,1024,512,256,128,64,32];async function fd(r,e){let t=await r.getAudioDuration(e)??0,n=r.decodeAudio({source:e}).readable,o=ha[ha.length-1],i=[],s=0,a=0,c=0;for await(let u of n){c||=u.sampleRate;let m=u.numberOfFrames,d=new Float32Array(m);u.copyTo(d,{planeIndex:0});for(let p=0;p<d.length;p++){let h=Math.abs(d[p]);h>s&&(s=h),a++,a>=o&&(i.push(s),s=0,a=0)}u.close()}a>0&&i.push(s);let l=new Float32Array(i),f=ha.map(u=>{let m=Math.max(1,Math.round(u/o)),d=m===1?l:u0(l,m);return{samplesPerPeak:u,peaks:d,peaksPerSecond:c>0?c/u:0}});return{duration:t,levels:f}}function u0(r,e){let t=new Float32Array(Math.ceil(r.length/e));for(let n=0;n<t.length;n++){let o=0,i=n*e,s=Math.min(i+e,r.length);for(let a=i;a<s;a++)r[a]>o&&(o=r[a]);t[n]=o}return t}var f0=4096,gi=class r{#e=new Map;#t=[0,0];#r=[0,0];#n;#o;#c;#i=!1;color;duration;tileSize;tileHeight;preloadMargin;constructor(e,t,n){this.#o=e,this.duration=t,this.tileSize=n.tileSize??1,this.#n=n.zoom??(n.tileWidth??256)/this.tileSize,this.tileHeight=n.tileHeight??96,this.preloadMargin=n.preloadMargin??2,this.color=n.color??"rgb(3, 148, 129)",this.#c=n.onChange}static async init(e,t,n={}){let{duration:o,levels:i}=await fd(e,t);return new r(i,o,n)}set zoom(e){let t=Math.max(1,e);t!==this.#n&&(this.#n=t,this.#e.clear(),this.#a())}get zoom(){return this.#n}get range(){return this.#r}#s([e,t],n=1){let o=t-e;return[Math.max(0,e-o*n),Math.min(this.duration,t+o*n)]}set range(e){this.#r=e;let[t,n]=e,o=n-t,[i,s]=this.#t,a=i>0,c=s<this.duration,l=!a||t>=i+o,f=!c||n<=s-o;l&&f||(this.#t=this.#s(e,this.preloadMargin),this.#a())}#a(){this.#i||(this.#i=!0,queueMicrotask(()=>{this.#i=!1,this.#l()}))}#l(){let[e,t]=this.#t,n=new Set,o=this.#f(),i=Math.max(0,Math.floor(e/this.tileSize)*this.tileSize),s=Math.min(this.duration,t);for(let a=i;a<=s;a+=this.tileSize)n.add(a);for(let a of n)if(!this.#e.has(a)){let c=Math.min(a+this.tileSize,this.duration);this.#e.set(a,this.#u(a,c,o))}for(let a of this.#e.keys())n.has(a)||this.#e.delete(a);this.#p()}#u(e,t,n){let o=this.#m(n,e,t);return{startTime:e,endTime:t,peaks:o,canvas:ud(o,{width:this.#d(e,t),height:this.tileHeight,color:this.color})}}#f(){return this.#o.find(e=>e.peaksPerSecond>=this.#n)??this.#o[this.#o.length-1]}#m(e,t,n){if(!e.peaksPerSecond)return new Float32Array;let o=Math.max(0,Math.floor(t*e.peaksPerSecond)),i=Math.max(o+1,Math.min(e.peaks.length,Math.ceil(n*e.peaksPerSecond)));return e.peaks.slice(o,i)}#d(e,t){return Math.min(f0,Math.max(1,Math.ceil((t-e)*this.#n)))}#p(){this.#c&&this.#c([...this.#e.values()].sort((e,t)=>e.startTime-t.startTime))}getTiles(){return this.#e}};var X=r=>r;var Mr=r=>r;var md=()=>{let r=!1,e=Mr(60),t=1e3/e,n=0,o=0,i=ke(),s=null,a=l=>{if(requestAnimationFrame(a),!!r)for(n=l;l-o>=t;)o+=t,s?.(),s=null,i()};async function*c(){for(n=performance.now(),o=n,requestAnimationFrame(a);;)await new Promise(l=>s=l),yield}return{play(){r||(r=!0,n=performance.now(),o=n)},pause(){r=!1},setFPS(l){e=l,t=1e3/e},isPlaying(){return r},ticks:c,onTick:i}},dd=async(r,e)=>{let t=X(1e3/r.fps),n=r.duration/1e3,o=Math.ceil(n*r.fps);for(let i=0;i<o;i++){let s=X(i*t);await e(s,i)}};var wn=r=>r;var ga=class{keys;index;constructor(e,t){this.keys=e,this.index=t}near(e){return this.keys[Math.max(0,Math.min(this.keys.length-1,this.index+e))][1]}},pd=r=>r,Cn=r=>pd((e,t)=>r(e,t.near(0),t.near(1))),kn=(r,e,t)=>e+(t-e)*r,m0={linear:Cn(kn),ease:Cn((r,e,t)=>{let n=r<.5?4*r*r*r:1-Math.pow(-2*r+2,3)/2;return kn(n,e,t)}),easeIn:Cn((r,e,t)=>kn(r*r*r,e,t)),easeOut:Cn((r,e,t)=>kn(1-Math.pow(1-r,3),e,t)),bounce:Cn((r,e,t)=>{let i=r<.36363636363636365?7.5625*r*r:r<.7272727272727273?7.5625*(r-.5454545454545454)**2+.75:r<.9090909090909091?7.5625*(r-.8181818181818182)**2+.9375:7.5625*(r-.9545454545454546)**2+.984375;return kn(i,e,t)}),catmullRom:pd((r,e)=>{let t=e.near(-1),n=e.near(0),o=e.near(1),i=e.near(2),s=r*r,a=s*r;return .5*(2*n+(-t+o)*r+(2*t-5*n+4*o-i)*s+(-t+3*n-3*o+i)*a)})},hd=(r,e,t,n)=>{let o=m0[r];if(!o)throw new Error(`unknown terp "${r}"`);return o(e,new ga(t,n))};var Br=(r,e,t,n=0)=>{if(e.length===0)return n;if(e.length===1)return e[0][1];let o=[...e].sort((u,m)=>u[0]-m[0]);if(r<=o[0][0])return o[0][1];let i=o[o.length-1];if(r>=i[0])return i[1];let s=0;for(let u=0;u<o.length-1;u++){let m=o[u],d=o[u+1];if(r>=m[0]&&r<=d[0]){s=u;break}}let[a]=o[s],[c]=o[s+1],l=c-a,f=l===0?0:(r-a)/l;return hd(t,f,o,s)},gd=(r,e)=>[[Br(r,e.track.position.x,e.terp),Br(r,e.track.position.y,e.terp)],[Br(r,e.track.scale.x,e.terp,1),Br(r,e.track.scale.y,e.terp,1)],Br(r,e.track.rotation,e.terp)],xd=(r,e)=>Br(r,e.track,e.terp);function d0(r){return"duration"in r}function yd(r){let e=[],t=new Map(r.timeline.items.map(n=>[n.id,n]));return xa(r.timeline.rootId,t,r.from,{sequence:()=>{},stack:()=>{},video:(n,o,i)=>e.push({item:n,localTime:o,ancestors:i}),image:(n,o,i)=>e.push({item:n,localTime:o,ancestors:i}),text:(n,o,i)=>e.push({item:n,localTime:o,ancestors:i}),caption:(n,o,i)=>e.push({item:n,localTime:o,ancestors:i}),audio:(n,o,i)=>e.push({item:n,localTime:o,ancestors:i})}),e}function bd(r,e,t,n){let o=$m;for(let i of e)o=vd(r,i.item,o,i.localTime);return vd(r,t,o,n)}function vd(r,e,t,n){let o=t;if("spatialId"in e&&e.spatialId){let i=r.get(e.spatialId);if(i?.enabled){let s=fa(i.transform);o=ma(s,o)}}if("animationIds"in e&&e.animationIds)for(let i of e.animationIds){let s=r.get(i),a=s?.anims.transform;if(s?.enabled&&a&&p0(a,n)){let c=fa(gd(n,a));o=ma(c,o)}}return o}function xa(r,e,t,n,o=[]){let i=e.get(r);if(i)switch(i.kind){case G.Stack:n.stack(i,t,o);for(let s of i.childrenIds)xa(s,e,t,n,[...o,{item:i,localTime:t}]);break;case G.Sequence:{n.sequence(i,t,o);let s=X(0);for(let a of i.childrenIds){let c=e.get(a);if(!c)continue;let l=Nr(c.id,e);if(l<=0)continue;let f=X(s+l);if(t>=f){s=f;continue}let u=X(Math.max(0,t-s));xa(a,e,u,n,[...o,{item:i,localTime:t}]),s=f}break}case G.Video:n.video(i,t,o);break;case G.Image:n.image(i,t,o);break;case G.Text:n.text(i,t,o);break;case G.Caption:n.caption(i,t,o);break;case G.Audio:n.audio(i,t,o);break}}function Xt(r,e){return Nr(r,new Map(e.items.map(t=>[t.id,t])))}function Nr(r,e){let t=e.get(r);if(!t)return X(0);switch(t.kind){case G.Sequence:{let n=t.childrenIds.map(i=>e.get(i)).filter(Boolean),o=X(0);for(let i=0;i<n.length;i++){let s=n[i];if(s.kind===G.Transition){let a=n[i-1],c=n[i+1];if(a&&c&&a.kind!==G.Transition&&c.kind!==G.Transition){let l=Nr(a.id,e),f=Nr(c.id,e),u=Math.max(0,Math.min(s.duration,l,f));o=X(o-u)}continue}o=X(o+Nr(s.id,e))}return o}case G.Stack:{let n=X(0);for(let o of t.childrenIds){let i=Nr(o,e);i>n&&(n=i)}return n}default:return d0(t)?t.duration:X(0)}}function Sd(r,e,t){if(!("animationIds"in e)||e.animationIds===void 0)return 1;let n=1;for(let o of e.animationIds){let i=r.items.get(o),s=i?.anims.opacity;i?.enabled&&s&&Ur(s.track,t)&&(n=xd(t,s))}return n}function Ur(r,e){if(r.length===0)return!1;let t=r[0][0],n=r[0][0];for(let[o]of r)t=Math.min(t,o),n=Math.max(n,o);return e>=t&&e<=n}function p0(r,e){return Ur(r.track.position.x,e)||Ur(r.track.position.y,e)||Ur(r.track.scale.x,e)||Ur(r.track.scale.y,e)||Ur(r.track.rotation,e)}var xi=class{resolveMedia;#e=new Map;constructor(e){this.resolveMedia=e}async getSink(e){let t=this.#e.get(e);if(t)return t.sink;let n=new fe({formats:ge,source:await ye(this.resolveMedia(e))}),o=await n.getPrimaryVideoTrack(),s=!!o&&await o.canDecode()&&o?new ut(o):null;return this.#e.set(e,{input:n,sink:s}),s}};var vi=class{resolveMedia;#e=new Map;constructor(e){this.resolveMedia=e}async getFrame(e,t){let n=await this.#t(e);return new VideoFrame(n.bitmap,{timestamp:Math.round(t*1e3)})}async#t(e){let t=this.#e.get(e);if(t)return t;let n=this.resolveMedia(e),o=n instanceof Blob?n:await fetch(n).then(s=>s.blob()),i={bitmap:await createImageBitmap(o)};return this.#e.set(e,i),i}disposeAll(){for(let e of this.#e.values())e.bitmap.close();this.#e.clear()}dispose(e){this.#e.get(e)?.bitmap.close(),this.#e.delete(e)}};async function Td(r,e,t,n){let[o,i]=await Promise.all([t,n]),s=o.find(l=>l.kind==="image")?.frame,a=i.find(l=>l.kind==="image")?.frame,c=[...o.filter(l=>l.kind!=="image"),...i.filter(l=>l.kind!=="image")];return s&&a?[{id:r.id,kind:"transition",name:"circle",progress:e,from:s,to:a},...c]:c}async function wd(r,e,t,n){let o=h0(r,e,t);if(!o)return[];let i=[...n,{item:e,localTime:t}];return o.isTransitioning?Td(o.transition,o.progress,Kt(r,o.outgoing,o.outgoingTime,i),Kt(r,o.incoming,o.incomingTime,i)):Kt(r,o.item,o.localTime,i)}function h0(r,e,t){let n=e.childrenIds.map(i=>r.items.get(i)).filter(i=>!!i),o=X(0);for(let i=0;i<n.length;i++){let s=n[i];if(s.kind===G.Transition)continue;let a=o,c=Xt(s.id,r.timeline),l=X(a+c),f=n[i+1];if(!(f?.kind===G.Transition)){if(t<l)return{isTransitioning:!1,item:s,localTime:X(t-a)};o=l;continue}let m=f,d=n[i+2];if(!d||d.kind===G.Transition){o=l;continue}let p=Xt(d.id,r.timeline),h=Math.max(0,Math.min(m.duration,c,p)),x=X(l-h);if(t<x)return{isTransitioning:!1,item:s,localTime:X(t-a)};if(t<l){let y=X(t-x),v=X(t-a);return{isTransitioning:!0,incoming:d,outgoing:s,outgoingTime:v,incomingTime:y,progress:h>0?y/h:1,transition:m}}o=x,i++}return null}async function Kt(r,e,t,n){let o=bd(r.items,n,e,t),i=Sd(r,e,t),s="spatialId"in e&&e.spatialId?r.items.get(e.spatialId)?.crop:void 0,a="filterIds"in e&&e.filterIds?e.filterIds.map(c=>r.items.get(c)).filter(c=>!!c?.enabled).map(c=>({type:c.type,params:c.params})):void 0;switch(e.kind){case G.Stack:{let c=[...n,{item:e,localTime:t}];return(await Promise.all(e.childrenIds.map(f=>r.items.get(f)).filter(f=>!!f).map(f=>Kt(r,f,t,c)))).flat()}case G.Sequence:return wd(r,e,t,n);case G.Video:{if(t<0||t>=e.duration)return[];let c=await r.videoSampler(e,t);return c?[{kind:"image",frame:c,matrix:o,alpha:i,crop:s,filters:a,id:e.id}]:[]}case G.Image:{if(t<0||t>=e.duration)return[];let c=await r.imageSampler(e,t);return c?[{kind:"image",frame:c,matrix:o,alpha:i,crop:s,filters:a,id:e.id}]:[]}case G.Text:{if(t<0||t>=e.duration)return[];let c=e.styleId?r.items.get(e.styleId)?.style:void 0;return[{id:e.id,kind:"text",content:e.content,style:c,matrix:o,alpha:i,crop:s,filters:a}]}case G.Caption:{if(t<0||t>=e.duration)return[];let c=e.start+t,l=pa(e.transcript,e).find(u=>{let[m,d]=u.timestamp;return c>=m&&c<d});if(!l)return[];let f=e.styleId?r.items.get(e.styleId)?.style:void 0;return[{id:e.id,kind:"text",content:l.text,style:f,matrix:o,alpha:i,crop:s,filters:a}]}case G.Gap:return[{id:e.id,kind:"gap"}];default:return[]}}function Cd(r){return async(e,t)=>{let n=await r.getSink(e.mediaHash),o=e.start+t,i=await n?.getSample(o/1e3),s=i?.toVideoFrame();return i?.close(),s??void 0}}function kd(r){return async(e,t)=>await r.getFrame(e.mediaHash,t)}function yi(r,e){let t=new vi(r),n=new xi(r),o=kd(t),i=e??Cd(n);return{async sample(s,a){let c=new Map(s.items.map(f=>[f.id,f])),l=c.get(s.rootId);return l?Kt({imageSampler:o,videoSampler:i,timeline:s,items:c},l,a,[]):[]}}}var bi=class{driver;resolveMedia;timeline;#e=new Map;#t;constructor(e,t,n){this.driver=e,this.resolveMedia=t,this.timeline=n,this.#t=yi(this.resolveMedia,(o,i)=>{let s=Pd(X(o.start+i)),a=this.#e.get(o.id);if(!a){let c=this.resolveMedia(o.mediaHash),l=Pd(X(o.start+o.duration));a=this.createCursor(c,s,l),this.#e.set(o.id,a)}return a.next(s)})}sample(e){return this.#t.sample(this.timeline,e)}async cancel(){await Promise.all([...this.#e.values()].map(e=>e.cancel())),this.#e.clear()}},Yt=class extends bi{#e=-1/0;next(e){if(e<this.#e)throw new Error(`Forward-only cursor regression: ${e}ms < ${this.#e}ms`);return this.#e=e,this.sample(e)}createCursor(e,t,n){let o=this.driver.decodeVideo({source:e,start:t/1e6,end:n/1e6}),i=o.readable.getReader(),s=null,a=null,c=!1,l=async()=>{if(c)return null;let{done:f,value:u}=await i.read();if(f)return c=!0,null;let m=new VideoFrame(u);return u.close(),m};return{async next(f){if(s??=await l(),!!s)for(;;){a??=l();let u=await a;if(!u)return new VideoFrame(s);let m=s.timestamp??-1/0,d=u.timestamp??m;if(d<f){s.close(),s=u,a=null;continue}if(Math.abs(d-f)<Math.abs(m-f)){s.close(),s=u,a=null;continue}return new VideoFrame(s)}},async cancel(){let f=a;a=null,c=!0,(await f?.catch(()=>null))?.close(),s?.close(),s=null,o.cancel()}}}},Pn=class extends bi{#e=1/0;next(e){if(e>this.#e)throw new Error(`Reverse-only cursor regression: ${e}ms > ${this.#e}ms`);return this.#e=e,this.sample(e)}createCursor(e,t,n){let s=[],a=1/0,c=-1/0,l=null,f=null,u=null,m=0,d=Promise.resolve(),p=null,h=!1,x=()=>{for(let T of s)T.close();s=[]},y=()=>{m++===0&&(d=new Promise(T=>p=T))},v=()=>{--m===0&&(p?.(),p=null)},S=async()=>{if(f)return f;l=new fe({source:await ye(e),formats:ge});let T=await l.getPrimaryVideoTrack();return f=T&&await T.canDecode()?new ut(T):null,f},C=async T=>{y();let E=Math.min(n,T+1),I=Math.max(t,E-1e6),M=[],L=await S();if(L)for await(let V of L.samples(I/1e6,E/1e6))M.push(V.toVideoFrame()),V.close();return v(),{frames:M,windowStart:I,windowEnd:E}},_=async T=>{x();let E=await C(T);s=E.frames,a=E.windowStart,c=E.windowEnd};return{async next(T){if(h)return;if(T<a||T>c)if(u){let M=await u;if(u=null,h){for(let L of M.frames)L.close();return}if(T>=M.windowStart&&T<=M.windowEnd)x(),s=M.frames,a=M.windowStart,c=M.windowEnd;else{for(let L of M.frames)L.close();await _(T)}}else await _(T);!u&&T<a+5e5&&a>t&&(u=C(a-1));let E,I=1/0;for(let M of s){let L=Math.abs((M.timestamp??T)-T);L<I&&(E=M,I=L)}return E?new VideoFrame(E):void 0},async cancel(){h=!0;let T=u;u=null;let E=await T?.catch(()=>null);if(E)for(let I of E.frames)I.close();await d,x(),l?.dispose(),l=null,f=null}}}},Pd=r=>Math.round(r*1e3);async function _d(r,e,t){return(await Promise.all(e.map(async({item:o,localTime:i})=>{if(o.kind!==G.Audio)return;let s=await r.getSink(o.mediaHash);if(!s)return;let a=o.start+i,c=wn((t-a)/1e3),l=s.samples(a/1e3),f=await l.next();if(f.done)return;let u=f.value,m=l.next();return{offset:c,gain:o.gain??1,get currentSample(){return u},timelineTime:()=>wn(c+u.timestamp),output:()=>({sample:u,timestamp:c+u.timestamp,gain:o.gain??1}),advance:async()=>{let d=await m;return d.done?!1:(u=d.value,m=l.next(),!0)}}}))).filter(o=>!!o)}var Si=class{resolveMedia;#e=new Map;constructor(e){this.resolveMedia=e}async getSink(e){let t=this.#e.get(e);if(t)return t.sink;let n=new fe({formats:ge,source:await ye(this.resolveMedia(e))}),o=await n.getPrimaryAudioTrack(),s=!!o&&await o.canDecode()&&o?new ln(o):null;return this.#e.set(e,{input:n,sink:s}),s}};function Id(r){let e={index:0,stream:r[0],time:r[0].timelineTime()};for(let[t,n]of r.entries()){let o=n.timelineTime();o<e.time&&(e={time:o,stream:n,index:t})}return e}function Ti(r){let e=new Si(r);return{async*sampleAudio(t,n){let o=yd({timeline:t,from:n}),i=await _d(e,o,n);for(;i.length>0;){let{stream:s,index:a}=Id(i);yield s.output(),await s.advance()||i.splice(a,1)}}}}var wi=class{driver;timeline;resolveMedia;audioSampler;seekVisualSampler;playVisualSampler=null;reversePlayVisualSampler=null;#e=X(0);#t=null;#r=1;#n=md();onTick=this.#n.onTick;audioContext=new AudioContext({sampleRate:48e3});audioGain=this.audioContext.createGain();audioNodes=new Set;#o=null;constructor(e,t,n){this.driver=e,this.timeline=t,this.resolveMedia=n,this.audioGain.connect(this.audioContext.destination),this.audioGain.gain.value=.7**2,this.seekVisualSampler=yi(this.resolveMedia),this.audioSampler=Ti(this.resolveMedia),this.#c()}update(e){this.timeline=e}get isPlaying(){return this.#n.isPlaying()}async#c(){for await(let e of this.#n.ticks()){let t=this.currentTime,n=this.#r>=0?await this.playVisualSampler?.next(t)??[]:await this.reversePlayVisualSampler?.next(t)??[];(await this.driver.composite(n)).close(),(this.#r>=0?t>=this.duration:t<=0)&&this.pause()}}async seek(e){return this.pause(),this.#e=e,await this.seekVisualSampler.sample(this.timeline,e)}async start(){this.#n.isPlaying()||(await this.audioContext.resume(),this.#e=this.currentTime,this.#t=this.audioContext.currentTime,this.#s(),this.playVisualSampler=new Yt(this.driver,this.resolveMedia,this.timeline),this.reversePlayVisualSampler=new Pn(this.driver,this.resolveMedia,this.timeline),this.#n.play(),this.#a())}pause(){this.#e=this.currentTime,this.#n.pause(),this.#s(),this.playVisualSampler&&(this.playVisualSampler.cancel(),this.playVisualSampler=null),this.reversePlayVisualSampler&&(this.reversePlayVisualSampler.cancel(),this.reversePlayVisualSampler=null)}get duration(){return Xt(this.timeline.rootId,this.timeline)}get currentTime(){if(!this.#n.isPlaying()||this.#t===null)return this.#e;let e=(this.audioContext.currentTime-this.#t)*1e3,t=this.#e+e*this.#r;return X(Math.max(0,Math.min(this.duration,t)))}get playbackRate(){return this.#r}set playbackRate(e){if(!Number.isFinite(e)||e===0)throw new Error(`Invalid playback rate "${e}".`);this.#e=this.currentTime,this.#t=this.#n.isPlaying()?this.audioContext.currentTime:null;let t=this.#r<0;this.#r=e,this.#n.isPlaying()&&(t&&e>0?(this.playVisualSampler?.cancel(),this.playVisualSampler=new Yt(this.driver,this.resolveMedia,this.timeline)):!t&&e<0&&(this.reversePlayVisualSampler?.cancel(),this.reversePlayVisualSampler=new Pn(this.driver,this.resolveMedia,this.timeline)),this.#i())}setFps(e){this.#n.setFPS(e)}#i(){this.#s(),this.#a()}#s(){this.#o?.abort(),this.#o=null;for(let e of this.audioNodes)e.stop();this.audioNodes.clear()}async#a(){if(this.#r!==1)return;let e=wn(this.#e/1e3);this.#o=new AbortController;let t=this.#o.signal,n=this.audioContext;if(this.#t!==null)for await(let{sample:o,timestamp:i}of this.audioSampler.sampleAudio(this.timeline,X(e*1e3))){if(t.aborted||!this.#n.isPlaying())return;for(;i-(n.currentTime-this.#t+e)>.75;)await new Promise(c=>setTimeout(c,25));let s=n.createBufferSource();s.buffer=o.toAudioBuffer(),s.connect(this.audioGain),s.onended=()=>this.audioNodes.delete(s),this.audioNodes.add(s);let a=this.#t+i-e;a>=n.currentTime?s.start(a):s.start(n.currentTime,n.currentTime-a)}}};var Ci=class{driver;canvas;playback;#e=null;#t=null;constructor(e,t,n){this.driver=e,this.playback=new wi(e,n,t),this.canvas=e.compositor.pixi.renderer.canvas}async play(){await this.playback.start()}pause(){this.playback.pause()}seek(e){return this.#e=e,this.#t??=this.#r().finally(()=>this.#t=null)}setFPS(e){this.playback.setFps(Mr(e))}get isSeeking(){return this.#t!==null}get isPlaying(){return this.playback.isPlaying}get duration(){return this.playback.duration}get currentTime(){return this.playback.currentTime}get playbackRate(){return this.playback.playbackRate}set playbackRate(e){this.playback.playbackRate=e}async update(e){this.playback.update(e),this.isPlaying||await this.seek(this.currentTime)}async#r(){for(;this.#e!==null;){let e=this.#e;this.#e=null;let t=await this.playback.seek(X(e));(await this.driver.composite(t)).close()}}};var $t=class{state;constructor(e){this.state=e}require(e){return e===void 0?void 0:this.state.timeline.items.find(n=>n.id===e)}get timeline(){return this.state.timeline}getId(){return ze.toInteger(ze.random())}#e(e){this.state.timeline=e(this.state.timeline)}register(e){this.#e(t=>({...t,items:[...t.items,e]}))}textStyle=e=>{let t={id:this.getId(),kind:G.TextStyle,style:e};return this.register(t),t};spatial=(e,t)=>{let n={id:this.getId(),kind:G.Spatial,transform:e??this.transform(),crop:t,enabled:!0};return this.register(n),n};#t=e=>{let t={id:this.getId(),kind:G.Animation,anims:e,enabled:!0};return this.register(t),t};#r=(e,t)=>{let n={...e,animationIds:[...e.animationIds??[],t.id]};return this.set(e.id,n),n};anim={scalar:(e,t)=>({terp:e,track:t}),vec2:(e,t)=>{let n={x:[],y:[]};for(let[o,[i,s]]of t)n.x.push([o,i]),n.y.push([o,s]);return{terp:e,track:n}},transform:(e,t)=>{let n={position:{x:[],y:[]},scale:{x:[],y:[]},rotation:[]};for(let[o,[i,s,a]]of t)n.position.x.push([o,i[0]]),n.position.y.push([o,i[1]]),n.scale.x.push([o,s[0]]),n.scale.y.push([o,s[1]]),n.rotation.push([o,a]);return{terp:e,track:n}}};#n=id((e,t)=>({terp:e,track:t}),(e,t)=>this.anim.transform(e,t),e=>this.transform(e));#o=e=>{let t=o=>{let i={id:this.getId(),kind:G.Filter,type:e,params:o,enabled:!0};return this.register(i),i},n=((o,i)=>{let s=t(i),a={...o,filterIds:[...o.filterIds??[],s.id]};return this.set(o.id,a),a});return n.make=t,n};#c=()=>{let e=Object.entries(ui).map(([t,n])=>[t,this.#o(n.type)]);return Object.fromEntries(e)};filter=this.#c();#i=(e,t,n)=>e==="transform"?this.anim.transform(t,n):this.anim.scalar(t,n);#s=e=>{let t=(o,i)=>this.#t({[e]:this.#i(e,o,i)}),n=((o,i,s)=>{let a=t(i,s);return this.#r(o,a)});return n.make=t,n};#a=e=>{let t=o=>{let i=xt[e],s=this.#n[e](o);return this.#t(i.type==="motion"?{transform:s}:{opacity:s})},n=((o,i)=>{let s=t(i);return this.#r(o,s)});return n.make=t,n};#l=()=>{let e=Object.keys(Tn).map(t=>[t,this.#s(t)]);return Object.fromEntries(e)};#u=()=>{let e=Object.keys(xt).map(t=>[t,this.#a(t)]);return Object.fromEntries(e)};animate={...this.#l(),presets:this.#u()};sequence=(...e)=>{let t={id:this.getId(),kind:G.Sequence,childrenIds:e.map(n=>n.id)};return this.register(t),t};stack=(...e)=>{let t={kind:G.Stack,id:this.getId(),childrenIds:e.map(n=>n.id)};return this.register(t),t};video=(e,t)=>{if(!e.hasVideo)throw new Error(`Video clip error: media "${e.datafile.filename}" has no video track.`);let n={kind:G.Video,id:this.getId(),mediaHash:e.datafile.checksum.hash,start:t?.start??0,duration:t?.duration??e.duration};return this.register(n),n};image=(e,t)=>{if(!e.isImage)throw new Error(`Image error: media "${e.datafile.filename}" is not an image.`);let n={kind:G.Image,id:this.getId(),mediaHash:e.datafile.checksum.hash,duration:t?.duration??2e3};return this.register(n),n};audio=(e,t)=>{if(!e.hasAudio)throw new Error(`Audio clip error: media "${e.datafile.filename}" has no audio track.`);let n={kind:G.Audio,id:this.getId(),mediaHash:e.datafile.checksum.hash,start:t?.start??0,duration:t?.duration??e.duration,gain:t?.gain??1};return this.register(n),n};text=(e,t)=>{let n={id:this.getId(),content:e,kind:G.Text,duration:t?.duration??2e3};return t?.styles&&(n.styleId=this.textStyle(t.styles).id),this.register(n),n};#f=(e,t,n)=>{let o=n?.start??0,i=n?.duration??Math.max(0,sd(e,n)-o),s={id:this.getId(),kind:G.Caption,transcript:e,itemId:n?.itemId,start:o,duration:i,maxChars:n?.maxChars,maxDuration:n?.maxDuration,maxSilence:n?.maxSilence};return s.styleId=this.textStyle(n?.styles??t.styles).id,s.spatialId=this.spatial(this.transform(t.transform)).id,this.register(s),s};#m=e=>{let t=(o,i)=>this.#f(o,e,i),n=((o,i,s)=>{let a=t(i,{...s,itemId:o.id,start:s?.start??o.start,duration:s?.duration??o.duration});return this.stack(a,o)});return n.make=t,n};#d=()=>{let e=Object.entries(hi).map(([t,n])=>[t,this.#m(n)]);return Object.fromEntries(e)};captions=Object.assign(this.#m(hi.default),{presets:this.#d()});gap=e=>{let t={id:this.getId(),kind:G.Gap,duration:e};return this.register(t),t};transition={crossfade:e=>{let t={id:this.getId(),kind:G.Transition,effect:fi.Crossfade,duration:e};return this.register(t),t}};transform=e=>{let t=[e?.position?.[0]??0,e?.position?.[1]??0],n=[e?.scale?.[0]??1,e?.scale?.[1]??1],o=e?.rotation??0;return[t,n,o]};addChildren(e,...t){this.#e(n=>(n.items.find(({id:i})=>i===e.id).childrenIds.push(...t.map(i=>i.id)),n))}set=(e,t)=>{this.#e(n=>({...n,items:n.items.map(o=>o.id===e?{...o,...t}:o)}))}};function g0(r){let e=((t,n)=>o=>r(o)(t(o),n));return e.make=t=>n=>r(n).make(t),e}function x0(){let e=Object.keys(ui).map(t=>[t,g0(n=>n.filter[t])]);return Object.fromEntries(e)}var QF=x0();function v0(r){let e=((t,n,o)=>i=>r(i)(t(i),n,o));return e.make=(t,n)=>o=>r(o).make(t,n),e}function y0(){let r=Object.keys(Tn).map(e=>[e,v0(t=>t.animate[e])]);return Object.fromEntries(r)}function b0(r){let e=((t,n)=>o=>o.animate.presets[r](t(o),n));return e.make=t=>n=>n.animate.presets[r].make(t),e}function S0(){let r=Object.keys(xt).map(e=>[e,b0(e)]);return Object.fromEntries(r)}var ZF={...y0(),presets:S0()};var ki=class{#e;#t;constructor(e={}){this.#e=e.chunkFrames??1024,this.#t=e.clamp??!0}async*mix(e){let t=this.#e,n=null,o=null,i=[],s=0,a=0;for await(let c of e){if(o===null)o=c.planes.length,n=c.sampleRate;else{if(c.planes.length!==o)throw new Error("Channel count changed");if(c.sampleRate!==n)throw new Error("Sample rate changed")}let l=Math.round(c.timestamp*n),f=c.planes[0]?.length??0;for(;s+t<=l;)yield this.#r(i,s,o,n),s+=t;i.push({startFrame:l,endFrame:l+f,data:c.planes}),a=Math.max(a,l+f)}if(o!==null&&n!==null)for(;s<a;)yield this.#r(i,s,o,n),s+=t}#r(e,t,n,o){let i=this.#e,s=new Float32Array(n*i),a=t+i;for(let c=0;c<n;c++){let l=c*i,f=s.subarray(l,l+i);for(let u of e){let m=u.data[c];if(!m)continue;let d=Math.max(t,u.startFrame),p=Math.min(a,u.endFrame);if(d>=p)continue;let h=d-t,x=d-u.startFrame,y=p-d;for(let v=0;v<y;v++)f[h+v]+=m[x+v]}if(this.#t)for(let u=0;u<i;u++){let m=f[u];f[u]=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:n,frames:i,startFrame:t}}};var T0=(r,e,t)=>{if(e===t)return r;let n=t/e,o=Math.max(1,Math.round(r.length*n)),i=new Float32Array(o);for(let s=0;s<o;s++){let a=s/n,c=Math.floor(a),l=Math.min(c+1,r.length-1),f=a-c;i[s]=r[c]*(1-f)+r[l]*f}return i},Ad=(r,e)=>{let t=r.numberOfChannels,n=new Array(t),o=0;for(let i=0;i<t;i++){let s=new Float32Array(r.numberOfFrames);r.copyTo(s,{planeIndex:i,format:"f32-planar"});let a=T0(s,r.sampleRate,e);n[i]=a,o=a.length}return{data:n,frames:o}};var Fd=(r,e)=>{if(e!==1)for(let t of r)for(let n=0;n<t.length;n++)t[n]*=e};function Ed({timeline:r,resolveMedia:e}){let t=new ki,n=w0(r,e),o=new TransformStream,i=o.writable.getWriter();async function s(){for await(let a of t.mix(n)){let c=new AudioData({format:"f32-planar",sampleRate:a.sampleRate,numberOfFrames:a.frames,numberOfChannels:a.channels,timestamp:Math.round(a.startFrame/a.sampleRate*1e6),data:new Float32Array(a.planar)});await i.write(c)}await i.close()}return s(),o.readable}async function*w0(r,e){let t=Ti(e);for await(let{sample:n,timestamp:o,gain:i}of t.sampleAudio(r,X(0))){let{data:s}=Ad(n,48e3);Fd(s,i),yield{planes:s,sampleRate:48e3,timestamp:o},n.close()}}function zd({timeline:r,fps:e,driver:t,resolveMedia:n}){let o=new TransformStream,i=o.writable.getWriter(),s=new Yt(t,n,r),a=1/e,c=Xt(r.rootId,r);async function l(){await dd({fps:e,duration:c},async(f,u)=>{let m=await s.next(f),d=await t.composite(m),p=new VideoFrame(d,{timestamp:Math.round(u*a*1e6),duration:Math.round(a*1e6)});await i.write(p),d.close()}),await i.close()}return l(),o.readable}function Dd(r){let e=Ed({...r}),t=zd({...r});return r.driver.encode({video:t,audio:e,config:{audio:{codec:"opus",bitrate:128e3},video:{codec:"vp9",bitrate:1e6}}})}var Pi=class{driver;resources=new di;constructor(e){this.driver=e}load=async e=>Object.fromEntries(await Promise.all(Object.entries(e).map(async([t,n])=>[t,await this.resources.store(await n)])));timeline=e=>{let t=new $t({timeline:{format:"timeline",info:"https://omniclip.app/",version:0,items:[],rootId:0}}),n=e(t);return t.timeline.rootId=n.id,t.timeline};playback=async e=>new Ci(this.driver,t=>this.resources.require(t).url,e);render=async(e,t=30)=>Dd({timeline:e,fps:Mr(t),driver:this.driver,resolveMedia:n=>this.resources.require(n).url})};var _i=class{data;bytes;hash;nickname;constructor(e,t,n,o){this.data=e,this.bytes=t,this.hash=n,this.nickname=o}static async make(e){let t=new Uint8Array(e),n=new Uint8Array(await crypto.subtle.digest("SHA-256",t)),o=Fn.fromBytes(n),i=Pa.sigil.fromBytes(n);return new this(e,n,o,i)}};var Ii=class{url;bytes;blob;filename;checksum;constructor(e,t,n,o,i){this.url=e,this.bytes=t,this.blob=n,this.filename=o,this.checksum=i}static async make(e,t){let n=await e.arrayBuffer(),o=new Uint8Array(n),i=await _i.make(o),s=t??i.nickname,a=URL.createObjectURL(e);return new this(a,o,e,s,i)}static async load(e){}};async function Rd(r,e,t){let n=t.querySelector(".play"),o=t.querySelector(".stop"),i=t.querySelector(".scrub"),s=t.querySelector(".playhead"),a=t.querySelector(".timecode"),c=t.querySelector(".player-canvas"),l=new $t({timeline:r}),f=await e.playback(r);c.replaceChildren(f.canvas),n.disabled=!1,o.disabled=!1,n.addEventListener("click",()=>f.play()),o.addEventListener("click",()=>f.pause()),i.max=String(Math.ceil(f.duration));let u=!1;f.playback.onTick.on(()=>d(f.currentTime,f.duration));let m=(p,h)=>{a.textContent=`${Od(p)} / ${Od(h)}`};i.addEventListener("input",async()=>{u=!0;let p=Math.max(0,Math.min(+i.value,f.duration));m(p,f.duration),await f.seek(p)}),i.addEventListener("change",async()=>{u=!1;let p=Math.max(0,Math.min(+i.value,f.duration));await f.seek(p)});let d=(p,h)=>{let x=Math.max(0,Math.min(p,h));u||(i.value=String(Math.round(x)));let y=h?x/h*100:0;s.style.left=`${y}%`,m(x,h)};await f.update(l.timeline)}function Od(r){let e=Math.max(0,r),t=Math.floor(e/1e3),n=Math.floor(t/60),o=t%60,i=Math.floor(e%1e3);return`${n}:${String(o).padStart(2,"0")}.${String(i).padStart(3,"0")}`}async function Bd(r,e,t){let n=t.querySelector(".waveform-canvas"),o=t.querySelector(".width");n.replaceChildren(),n.style.position="relative",n.style.height="96px",n.style.overflow="hidden";let i=await gi.init(r,e,{tileHeight:96,onChange:()=>s()}),s=()=>{let a=+o.value,c=Md(a,i.duration);i.zoom=c,n.style.width=`${a}px`,n.replaceChildren(...[...i.getTiles().values()].map(l=>(l.canvas.style.position="absolute",l.canvas.style.top="0",l.canvas.style.left=`${l.startTime*Md(a,i.duration)}px`,l.canvas.style.height="100%",l.canvas)))};o.oninput=s,i.range=[0,i.duration]}function Md(r,e){return e>0?r/e:0}async function va(r,e){let t=await ld({driver:r,spec:ad(),workerUrl:new URL("/features/speech/transcribe/worker.bundle.min.js",import.meta.url),onLoading:a=>console.log("transcriber loading",a)}),n=new Pi(r),{videoA:o}=await n.load({videoA:Ii.make(e)}),i=await t.transcribe({source:e,language:"english",onReport:a=>console.log("transcriber report",a),onTranscription:a=>console.log("transcribing",a)});return{timeline:n.timeline(a=>{let c=a.text("content",{duration:3e3}),l=a.animate.opacity.make("easeIn",[[0,0],[700,1],[2200,1],[3e3,.35]]),f=a.textStyle({fill:"green",fontSize:100}),u=a.spatial(a.transform({position:[240,160],scale:[1.4,1.4],rotation:.08}),[.15,.1,.05,.2]),m=a.spatial(),d=a.animate.transform.make("linear",[[0,a.transform({position:[-320,80],scale:[.7,.7]})],[1e3,a.transform({position:[120,80],scale:[1,1]})],[2e3,a.transform({position:[200,40],scale:[1.35,1.35],rotation:8})],[3e3,a.transform({position:[320,0],scale:[1.15,1.15],rotation:0})]]),p=a.video(o,{duration:6e3,start:3e3});return a.set(c.id,{styleId:f.id,spatialId:m.id,animationIds:[l.id,d.id]}),a.set(p.id,{spatialId:u.id}),a.sequence(a.stack(c,a.captions(p,i,{maxChars:34,maxDuration:2800,maxSilence:450,styles:{fontFamily:"Arial",fontSize:64,fill:"#ffffff",align:"center",wordWrap:!0,wordWrapWidth:1280,stroke:{color:"#000000",width:6}}}),a.audio(o,{start:3e3})),a.gap(500),a.video(o,{duration:7e3,start:5e3}))}),omni:n}}async function Ud(r,e){let t=e.querySelector(".range"),n=e.querySelector(".range-view"),o=e.querySelector(".range-size"),i=e.querySelector(".frequency"),s=e.querySelector(".frequency-view"),a=e.querySelector(".filmstrip"),c=1/10,l=.5;a.replaceChildren();let f=await pi.init(r,{onChange(u){let m=u.sort((d,p)=>d.time-p.time);a.replaceChildren(...m.map(({time:d,canvas:p})=>C0(d,p.canvas)))},frequency:c,canvasSinkOptions:{width:80,height:50,fit:"fill"}});o.oninput=()=>{l=+o.value;let u=+t.value,m=u+l;f.range=[u,m],n.textContent=`visible time range: [${u}, ${m}]`},t.oninput=()=>{let u=+t.value,m=u+l;f.range=[u,m],n.textContent=`visible time range: [${u}, ${m}]`},i.oninput=()=>{f.frequency=1/+i.value,s.textContent=`frame every ${f.frequency.toFixed(3)} second (${i.value} frames per second)`},f.range=[10,10.5]}function C0(r,e){let t=document.createElement("div");t.style.position="relative",t.style.display="inline-block",t.style.marginRight="4px",t.appendChild(e);let n=document.createElement("div");return n.textContent=`${r.toFixed(2)}s`,n.style.position="absolute",n.style.top="2px",n.style.right="4px",n.style.fontSize="10px",n.style.color="white",n.style.background="rgba(0,0,0,0.6)",n.style.padding="2px 4px",n.style.borderRadius="4px",n.style.pointerEvents="none",t.appendChild(n),t}function Nd(r,e){let t={width:1920,height:1080},n=document.createElement("canvas");n.width=t.width,n.height=t.height;let o=n.getContext("2d");async function i(){let s=r.decodeVideo({source:e,async onFrame(m){let d=await r.composite([{id:0,kind:"image",frame:m},{id:1,kind:"text",content:"omnitool",style:{fontSize:50,fill:"green"}}]);return m.close(),o?.drawImage(d,0,0),d}}),a=r.decodeAudio({source:e}),{readable:c,done:l}=r.encode({video:s.readable,audio:a.readable,config:{audio:{codec:"opus",bitrate:128e3},video:{codec:"vp9",bitrate:1e6}}}),u=await(await window.showSaveFilePicker()).createWritable();await Promise.all([c.pipeTo(u),l])}return{canvas:n,run:i}}var Lr=await ci.setup({workerUrl:new URL("../driver/driver.worker.bundle.min.js",import.meta.url)}),k0=document.querySelector("[data-demo='transcode']"),P0=document.querySelector("[data-demo='filmstrip']"),_0=document.querySelector("[data-demo='waveform']"),Ld=document.querySelector("[data-demo='playback']"),Qt=document.querySelector("[data-demo='export']"),Vd=Qt.querySelector("[data-action='export']"),Ai=null;await Lr.thread.work.hello(),Lr.machina.count===1?console.log("\u2705 driver works"):console.error("\u274C FAIL driver call didn't work");var Vr=(r,e)=>{let t=r.querySelector(".progress"),n=r.querySelector(".status");!t||!n||(e==="running"?(t.removeAttribute("value"),n.textContent="running"):e==="done"?(t.value=1,n.textContent="done"):(t.value=0,n.textContent="idle"))},ya=(r,e)=>{let t=r.querySelector("input[type='file']"),n=r.querySelector("[data-action='run']");n.disabled=!0,t.addEventListener("input",()=>{n.disabled=!t.files?.length}),n.addEventListener("click",async()=>{let o=t.files?.[0];if(o){n.disabled=!0,Vr(r,"running");try{await e(o,r),Vr(r,"done")}finally{n.disabled=!1}}})};ya(k0,async(r,e)=>{let t=e.querySelector(".demo-preview"),n=Nd(Lr,r);t.replaceChildren(n.canvas),await n.run()});ya(P0,async(r,e)=>{await Ud(r,e)});ya(_0,async(r,e)=>{await Bd(Lr,r,e)});{let r=Ld.querySelector("input[type='file']");r.addEventListener("input",async()=>{let e=r.files?.[0];if(!e)return;let{timeline:t,omni:n}=await va(Lr,e);await Rd(t,n,Ld)})}{let r=Qt.querySelector("input[type='file']");r.addEventListener("input",async()=>{let e=r.files?.[0];if(!e)return;Vr(Qt,"running");let{timeline:t,omni:n}=await va(Lr,e);Ai={timeline:t,omni:n},Vd.disabled=!1;let o=Qt.querySelector(".demo-preview"),i=await n.playback(t);await i.seek(0),o.replaceChildren(i.canvas),Vr(Qt,"done")})}Vd.addEventListener("click",async()=>{Ai&&(Vr(Qt,"running"),await Ai.omni.render(Ai.timeline),Vr(Qt,"done"))});
7326
7326
  /*! Bundled license information:
7327
7327
 
7328
7328
  mediabunny/dist/modules/src/misc.js: